Compare commits

..
Author SHA1 Message Date
MoepchiandClaude Opus 5.5 9c67471b49 gateway: idle timeout applies to sockets opened after a change
Each socket keeps the IDLE_TIMEOUT_MINUTES it was told in its hello.
Raising it from 0 in the admin panel used to drop already connected
pages after a few minutes without asking, since they never learned they
have to send "active".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 23:34:06 +00:00
MoepchiandClaude Opus 5.5 958095fbf4 Streaming out of alpha; "Are you still there?" idle check
- Drop the ALPHA badge, the alpha warning in the stream dialog and the
  "(Alpha)" in the stream button's tooltip.
- New IDLE_TIMEOUT_MINUTES (admin panel / .env, 0 = off). The gateway
  announces it in the hello; after that long without input, talking or
  broadcasting the page asks "Are you still there?" and disconnects all
  tabs if nobody answers within 60 s. The page sends a throttled "active"
  message, and the gateway closes sockets that stay silent for the
  timeout plus 3 minutes, for pages that never ask. The page treats that
  close as deliberate and doesn't reconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 23:28:33 +00:00
MoepchiandClaude Opus 5.5 fc33843179 web: pop-out window opens channel streams by itself
While the stream grid is popped out, every stream in our channel is
watched right away instead of showing a "Watch" tile. Each stream is
auto-opened only once, so closing it or a refused join request leaves
the tile rather than rejoining in a loop. The main window still waits
for a click.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 22:13:41 +00:00
MoepchiandClaude Opus 5.5 e923181e14 web: stream tiles for the channel, clickable tree icons, camera vs. screen
- Streams in our own channel show up in the grid (corner and pop-out)
  as tiles with a "Watch" button, Discord-style, before anyone opens them.
- Stream icons moved to the right side of the client row, next to the
  group icons, and a click opens that stream; 📷 for a camera (setupstream
  type 1), 🖥️ for screen/window. Same icons in tiles and context menu.
- Stream infos and watched streams are keyed by stream id instead of
  clid, since one client can now send screen and camera at once; the
  context menu lists one entry per stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 22:07:50 +00:00
MoepchiandClaude Opus 5.5 ebe162fafb web: broadcast screen and camera at the same time
Publisher state was a single slot; it is now one publisher per source,
each with its own tile (preview, viewers, join requests). The stream
button opens the dialog with the source that is not running yet
preselected and only stops everything once both run.

StreamPublisher used to claim any own notifystreamstarted, so a second
broadcast would have stolen the first one's id. It now only takes an id
while it is starting and has none, and the app starts one publisher at
a time so that stays unambiguous.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 21:55:17 +00:00
MoepchiandClaude Opus 5.5 968a266684 web: size popped-out stream tiles to the window, Discord-style
In the separate window the grid now picks the column count that makes
the 16:9 tiles largest for the current window size and stream count, and
re-picks on resize. The pop-out/back button moved from a bar above the
grid into each tile header: in the corner the bar got pushed out of view
once the tiles overflowed, and "align-content: end" made that overflow
unreachable (now "safe end").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 21:47:06 +00:00
MoepchiandClaude Opus 5.5 8fbd591efa web: Discord-style stream grid, focus and pop-out window
Watched streams and our own broadcast are tiles in one grid (two columns
in the corner), any tile can be enlarged across the grid, and the whole
grid can move into its own browser window via a React portal; closing
that window brings it back.

main.tsx now reloads once when the App chunk (or a lazy chunk) fails to
load, which is what left a black screen right after the last deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 21:38:18 +00:00
MoepchiandClaude Opus 5.5 73ae268dfb web: watch several streams at once
Viewer state was a single slot, so opening a second stream closed the
first. It is now keyed by publisher clid: each stream gets its own
StreamViewer and panel (they already stack bottom-right), "watch" on a
stream that is open is a no-op, and closing one leaves the others running.
StreamViewer already ignored events for other stream ids, so only the app
state changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-30 21:25:59 +00:00
MoepchiandClaude Opus 5.5 f2d9115782 gateway: serialize write-then-rename per file
Every JSON store (ping, store, news, sync, admin auth, config) wrote to one
shared "<file>.tmp" and renamed it. Parallel requests raced on that path:
one rename won, the others failed with ENOENT, and overlapping writes could
leave a mangled file that reads as empty after a restart. Seen live from a
parallel /api/ping probe.

writeFileAtomic() in net.ts queues writes per file, so the last caller's
data always lands last.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-28 00:23:20 +00:00
MoepchiandClaude Opus 5.5 54a580dc39 Connector: cap upload bodies held in memory
A legacy ftupload line had no size check, and every upload body stayed in
memory until the server answered and the transfer finished, which a
client-chosen ftlimit can stretch to days. One client could park any
amount of memory in its connector (measured: +8 MiB per 8 MiB upload,
never released). Legacy uploads now respect MAX_UPLOAD_BYTES, and all
held upload bodies share a budget of 2x MAX_UPLOAD_BYTES per connector,
released when an upload finishes or fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 13:42:11 +00:00
Möpchi abecd4e14d Merge pull request #21 from WebSpeak3/fix/orphan-connectors
Security fixes from the audit
2026-11-25 14:04:48 +01:00
MoepchiandClaude Opus 5.5 d054c9bba4 TS2: cap the reorder window and fragment reassembly
A server could make the connector buffer without bound: packets far
ahead of the next expected one went into the reorder map, fragments
were appended until one arrived with fragment 0. Packets more than 256
ahead are now dropped unacknowledged (a real server resends them), and
a fragmented message over 1 MiB ends the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:52:10 +00:00
MoepchiandClaude Opus 5.5 deff678cfa Store: CSS filter bypasses via comments in strings and vendor prefixes
normalizeCss stripped /* */ without knowing about strings or escapes, so
content:"/*" ... "*/" hid a url() between them from the checks, and
-webkit-image-set( slipped past the function-name boundary. The checks
now run with and without comment stripping and allow a vendor prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:50:25 +00:00
MoepchiandClaude Opus 5.5 512366bc94 Gateway: ALLOWED_SERVERS ignored text after a bracketed host
stripPort("[allowed]evil.tld") returned "allowed", so the allowlist
accepted the host while the connector resolved and contacted evil.tld.
A bracketed host may now only be followed by :port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:49:15 +00:00
MoepchiandClaude Opus 5.5 5f9950a96b Gateway: no orphaned connectors on connect/close races
Message handlers on one WebSocket run concurrently. A connect awaiting the
previous connector's teardown could still spawn a new connector after the
socket closed, or two connects could both spawn and one got lost. Either
way the connector kept running outside MAX_CONNECTIONS and shutdown.

Each connect now detaches the previous connection before awaiting it and
only spawns if it is still the newest connect on an open socket; the
disconnect message and the close handler detach the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:45:41 +00:00
Möpchi 8c0d0a3d1d Merge pull request #20 from WebSpeak3/feature/admin-panel
Admin panel for live gateway settings
2026-11-25 13:43:46 +01:00
24 changed files with 947 additions and 247 deletions

No files matched your search

+52 -5
View File
@@ -63,6 +63,27 @@ async fn ft_pace(limit: &AtomicU64, bytes: usize, started: std::time::Instant) {
tokio::time::sleep(rest).await; tokio::time::sleep(rest).await;
} }
} }
/// Upload bodies held at once (waiting for the server or being sent, which
/// ftlimit can stretch to days). Without a cap a client could park any
/// amount of memory in the connector.
const MAX_UPLOADS_HELD: u64 = 2 * MAX_UPLOAD_BYTES;
static UPLOADS_HELD: AtomicU64 = AtomicU64::new(0);
/// A share of MAX_UPLOADS_HELD, given back when dropped.
struct HeldUpload(u64);
impl Drop for HeldUpload {
fn drop(&mut self) {
UPLOADS_HELD.fetch_sub(self.0, Ordering::Relaxed);
}
}
fn hold_upload(size: u64) -> Option<HeldUpload> {
UPLOADS_HELD
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| (held + size <= MAX_UPLOADS_HELD).then_some(held + size))
.ok()
.map(|_| HeldUpload(size))
}
const UPLOADS_BUSY: &str = "Upload refused: too many uploads in progress, try again when they are done";
/// Half-received chunked uploads per connection - each can hold up to /// Half-received chunked uploads per connection - each can hold up to
/// MAX_UPLOAD_BYTES until it completes. /// MAX_UPLOAD_BYTES until it completes.
const MAX_PARTIAL_UPLOADS: usize = 4; const MAX_PARTIAL_UPLOADS: usize = 4;
@@ -1201,7 +1222,7 @@ async fn run(args: Args) -> Result<()> {
// (StreamItem::FileDownload/FileUpload below); these just remember which // (StreamItem::FileDownload/FileUpload below); these just remember which
// request that stream belongs to. // request that stream belongs to.
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new(); let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new(); let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>, HeldUpload)> = HashMap::new();
// Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far). // Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far).
let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new(); let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new();
// Set by "permissionlist" while waiting to emit the full permission // Set by "permissionlist" while waiting to emit the full permission
@@ -2333,9 +2354,19 @@ async fn run(args: Args) -> Result<()> {
) { ) {
(Ok(cid), Ok(bytes)) => { (Ok(cid), Ok(bytes)) => {
let size = bytes.len() as u64; let size = bytes.len() as u64;
let held = if size > MAX_UPLOAD_BYTES { None } else { hold_upload(size) };
let Some(held) = held else {
let message = if size > MAX_UPLOAD_BYTES {
format!("Upload refused: {path} is larger than {} KiB", MAX_UPLOAD_BYTES >> 10)
} else {
UPLOADS_BUSY.into()
};
emit(&Event::TransferError { message, cid, path: path.to_string() });
continue;
};
match con.upload_file(ChannelId(cid), path, None, size, true, false) { match con.upload_file(ChannelId(cid), path, None, size, true, false) {
Ok(handle) => { Ok(handle) => {
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes)); pending_uploads.insert(handle.0, (cid, path.to_string(), bytes, held));
} }
Err(e) => emit(&Event::TransferError { Err(e) => emit(&Event::TransferError {
message: format!("Upload failed: {e}"), message: format!("Upload failed: {e}"),
@@ -2349,9 +2380,13 @@ async fn run(args: Args) -> Result<()> {
} else if let Some(rest) = l.strip_prefix("ftuploadchunk ") { } else if let Some(rest) = l.strip_prefix("ftuploadchunk ") {
match take_upload_chunk(&mut partial_uploads, rest) { match take_upload_chunk(&mut partial_uploads, rest) {
Ok(Some((cid, path, bytes))) => { Ok(Some((cid, path, bytes))) => {
let Some(held) = hold_upload(bytes.len() as u64) else {
emit(&Event::TransferError { message: UPLOADS_BUSY.into(), cid, path });
continue;
};
match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) { match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) {
Ok(handle) => { Ok(handle) => {
pending_uploads.insert(handle.0, (cid, path, bytes)); pending_uploads.insert(handle.0, (cid, path, bytes, held));
} }
Err(e) => emit(&Event::TransferError { message: format!("Upload failed: {e}"), cid, path }), Err(e) => emit(&Event::TransferError { message: format!("Upload failed: {e}"), cid, path }),
} }
@@ -3244,10 +3279,11 @@ async fn run(args: Args) -> Result<()> {
} }
} }
Some(Ok(StreamItem::FileUpload(handle, result))) => { Some(Ok(StreamItem::FileUpload(handle, result))) => {
if let Some((cid, path, data)) = pending_uploads.remove(&handle.0) { if let Some((cid, path, data, held)) = pending_uploads.remove(&handle.0) {
let seek = result.seek_position as usize; let seek = result.seek_position as usize;
let mut stream = result.stream; let mut stream = result.stream;
tokio::spawn(async move { tokio::spawn(async move {
let _held = held;
let slice = if seek < data.len() { &data[seek..] } else { &[][..] }; let slice = if seek < data.len() { &data[seek..] } else { &[][..] };
for piece in slice.chunks(TRANSFER_CHUNK_BYTES) { for piece in slice.chunks(TRANSFER_CHUNK_BYTES) {
let started = std::time::Instant::now(); let started = std::time::Instant::now();
@@ -3264,7 +3300,7 @@ async fn run(args: Args) -> Result<()> {
Some(Ok(StreamItem::FiletransferFailed(handle, e))) => { Some(Ok(StreamItem::FiletransferFailed(handle, e))) => {
let failed = pending_downloads let failed = pending_downloads
.remove(&handle.0) .remove(&handle.0)
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, _)| (cid, path))); .or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, ..)| (cid, path)));
if let Some((cid, path)) = failed { if let Some((cid, path)) = failed {
emit(&Event::TransferError { message: format!("File transfer failed: {e}"), cid, path }); emit(&Event::TransferError { message: format!("File transfer failed: {e}"), cid, path });
} }
@@ -3331,6 +3367,17 @@ async fn run(args: Args) -> Result<()> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn held_uploads_are_capped_and_released() {
let a = hold_upload(MAX_UPLOAD_BYTES).unwrap();
let b = hold_upload(MAX_UPLOAD_BYTES).unwrap();
assert!(hold_upload(1).is_none());
drop(a);
assert!(hold_upload(MAX_UPLOAD_BYTES).is_some());
drop(b);
assert_eq!(UPLOADS_HELD.load(Ordering::Relaxed), 0);
}
fn chunk(offset: u64, total: u64, data: &[u8]) -> String { fn chunk(offset: u64, total: u64, data: &[u8]) -> String {
format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data)) format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data))
} }
+45
View File
@@ -31,6 +31,10 @@ const KEEPALIVE_EVERY: Duration = Duration::from_secs(3);
const RESEND_AFTER: Duration = Duration::from_secs(1); const RESEND_AFTER: Duration = Duration::from_secs(1);
const MAX_RESENDS: u16 = 10; const MAX_RESENDS: u16 = 10;
const SERVER_TIMEOUT: Duration = Duration::from_secs(20); const SERVER_TIMEOUT: Duration = Duration::from_secs(20);
// Caps what a (hostile) server can make us buffer: packets ahead of the next
// expected one, and the size of one reassembled fragmented message.
const REORDER_WINDOW: u32 = 256;
const MAX_FRAGMENTS_BYTES: usize = 1 << 20;
/// Speex narrowband: 20 ms frames of 160 samples at 8 kHz, 5 per voice packet. /// Speex narrowband: 20 ms frames of 160 samples at 8 kHz, 5 per voice packet.
const SPEEX_FRAME: usize = 160; const SPEEX_FRAME: usize = 160;
const FRAMES_PER_PACKET: usize = 5; const FRAMES_PER_PACKET: usize = 5;
@@ -675,6 +679,10 @@ impl Ts2 {
match u16_at(b, 0) { match u16_at(b, 0) {
0xbef0 if b.len() >= 24 => { 0xbef0 if b.len() >= 24 => {
let seq = u32_at(b, 12); let seq = u32_at(b, 12);
// Too far ahead: no ack, so a real server resends it later.
if seq >= self.next_in && seq - self.next_in >= REORDER_WINDOW {
return Ok(true);
}
let mut ack = Vec::with_capacity(16); let mut ack = Vec::with_capacity(16);
ack.extend_from_slice(&0xbef1u16.to_le_bytes()); ack.extend_from_slice(&0xbef1u16.to_le_bytes());
ack.extend_from_slice(&0u16.to_le_bytes()); ack.extend_from_slice(&0u16.to_le_bytes());
@@ -695,6 +703,9 @@ impl Ts2 {
if self.fragments.is_empty() { if self.fragments.is_empty() {
self.fragment_type = typ; self.fragment_type = typ;
} }
if self.fragments.len() + p.len() - 24 > MAX_FRAGMENTS_BYTES {
bail!("The TeamSpeak 2 server sent an oversized message");
}
self.fragments.extend_from_slice(&p[24..]); self.fragments.extend_from_slice(&p[24..]);
if fragment != 0 { if fragment != 0 {
continue; continue;
@@ -922,6 +933,40 @@ which this gateway does not connect to. (Self-hosting admin? Set ALLOW_PRIVATE_T
mod tests { mod tests {
use super::*; use super::*;
// A hostile server can't make the connector buffer without bound.
#[tokio::test]
async fn reorder_and_fragment_buffers_are_capped() {
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
sock.connect(peer.local_addr().unwrap()).await.unwrap();
let mut ts = Ts2 {
sock, session: 0, client_id: 0, conn_counter: 0, seq: 0, outbox: VecDeque::new(), in_flight: None,
next_in: 1, early: BTreeMap::new(), fragments: Vec::new(), fragment_type: 0, channels: BTreeMap::new(),
players: BTreeMap::new(), lists_done: false, speakers: HashMap::new(), talking: HashSet::new(),
encoder: None, voice_counter: 0, voice_conversation: 0, last_audio_in: None, codec_warned: false,
};
let packet = |seq: u32, fragment: u16, body: usize| {
let mut p = vec![0u8; 24 + body];
p[0..2].copy_from_slice(&0xbef0u16.to_le_bytes());
p[12..16].copy_from_slice(&seq.to_le_bytes());
p[18..20].copy_from_slice(&fragment.to_le_bytes());
p
};
for seq in 2..2000 {
ts.on_datagram(&packet(seq, 0, 100)).await.unwrap();
}
assert!(ts.early.len() < REORDER_WINDOW as usize);
ts.early.clear();
let mut result = Ok(true);
for _ in 0..100 {
result = ts.on_datagram(&packet(ts.next_in, 1, 60_000)).await;
if result.is_err() {
break;
}
}
assert!(result.is_err() && ts.fragments.len() <= MAX_FRAGMENTS_BYTES);
}
#[test] #[test]
fn crc_matches_zlib() { fn crc_matches_zlib() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926); assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
+2 -5
View File
@@ -11,11 +11,10 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import type { TLSSocket } from "node:tls"; import type { TLSSocket } from "node:tls";
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto"; import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { rename, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { promisify } from "node:util"; import { promisify } from "node:util";
import qrcode from "qrcode-generator"; import qrcode from "qrcode-generator";
import { clientIp, createRateLimiter } from "./net.js"; import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
import { describeSettings, updateSettings, validate } from "./config.js"; import { describeSettings, updateSettings, validate } from "./config.js";
const ADMIN_USER = process.env.ADMIN_USER ?? ""; const ADMIN_USER = process.env.ADMIN_USER ?? "";
@@ -36,9 +35,7 @@ try {
} }
const totpSecret = () => auth.totpSecret ?? ENV_TOTP; const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
async function saveAuth(next: typeof auth) { async function saveAuth(next: typeof auth) {
const tmp = `${AUTH_FILE}.${process.pid}.tmp`; await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
await rename(tmp, AUTH_FILE);
auth = next; auth = next;
} }
+3 -4
View File
@@ -11,7 +11,7 @@
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the // Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
// operator's LAN), and the admin credentials themselves. // operator's LAN), and the admin credentials themselves.
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { rename, writeFile } from "node:fs/promises"; import { writeFileAtomic } from "./net.js";
import path from "node:path"; import path from "node:path";
export type SettingKind = "number" | "bool" | "list" | "text" | "secret"; export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
@@ -39,6 +39,7 @@ export const SETTINGS: Setting[] = [
{ group: "Connect dialog", staticOnly: true, key: "DEFAULT_SERVER", kind: "text", help: "Server address prefilled in the connect dialog." }, { group: "Connect dialog", staticOnly: true, key: "DEFAULT_SERVER", kind: "text", help: "Server address prefilled in the connect dialog." },
{ group: "Connect dialog", staticOnly: true, key: "DEFAULT_CHANNEL", kind: "text", help: "Channel prefilled in the connect dialog." }, { group: "Connect dialog", staticOnly: true, key: "DEFAULT_CHANNEL", kind: "text", help: "Channel prefilled in the connect dialog." },
{ group: "Connect dialog", staticOnly: true, key: "SYNC_URL", kind: "text", help: "Own account-sync server (sync-server.js). Empty = the official one." }, { group: "Connect dialog", staticOnly: true, key: "SYNC_URL", kind: "text", help: "Own account-sync server (sync-server.js). Empty = the official one." },
{ group: "Connections & limits", key: "IDLE_TIMEOUT_MINUTES", kind: "number", fallback: "0", help: "Ask \"Are you still there?\" after this many minutes without input in the client; no answer within 60 s disconnects (0 = off)." },
{ group: "Features", key: "FEEDBACK_ENABLED", kind: "bool", fallback: "0", help: "Accept in-app feedback (/api/feedback)." }, { group: "Features", key: "FEEDBACK_ENABLED", kind: "bool", fallback: "0", help: "Accept in-app feedback (/api/feedback)." },
{ group: "Features", key: "STORE_ENABLED", kind: "bool", fallback: "0", help: "Run the Design Store (theme submissions and downloads)." }, { group: "Features", key: "STORE_ENABLED", kind: "bool", fallback: "0", help: "Run the Design Store (theme submissions and downloads)." },
{ group: "Features", key: "LOG_CONNECTIONS", kind: "bool", fallback: "0", help: "Log connects/disconnects (hashed client tags, no plain IPs)." }, { group: "Features", key: "LOG_CONNECTIONS", kind: "bool", fallback: "0", help: "Log connects/disconnects (hashed client tags, no plain IPs)." },
@@ -116,9 +117,7 @@ export async function updateSettings(changes: Record<string, string | null>): Pr
if (value === null) delete next[key]; if (value === null) delete next[key];
else next[key] = value; else next[key] = value;
} }
const tmp = `${CONFIG_FILE}.${process.pid}.tmp`; await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
await rename(tmp, CONFIG_FILE);
overrides = next; overrides = next;
apply(); apply();
} }
+65 -17
View File
@@ -50,8 +50,10 @@ const allowedServers = () =>
// as-is. Deliberately not full URL parsing - `host` here is never a URL. // as-is. Deliberately not full URL parsing - `host` here is never a URL.
function stripPort(host: string): string { function stripPort(host: string): string {
if (host.startsWith("[")) { if (host.startsWith("[")) {
const end = host.indexOf("]"); // Only "[v6]" or "[v6]:port"; anything after "]" would otherwise be
return end === -1 ? host : host.slice(1, end); // ignored here but still reach the connector ("[allowed]evil.tld").
const m = /^\[([^\]]*)\](?::\d+)?$/.exec(host);
return m ? m[1] : host;
} }
const i = host.lastIndexOf(":"); const i = host.lastIndexOf(":");
return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host; return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host;
@@ -622,8 +624,21 @@ const HEARTBEAT_INTERVAL_MS = 20_000;
interface HeartbeatState { interface HeartbeatState {
isAlive: boolean; isAlive: boolean;
/** Last "active" message (user input in the page) or connect. */
lastActive: number;
/** Idle timeout this socket was told in its hello. A later change in the
* admin panel applies to new sockets only: older pages don't know they
* must send "active" and would be dropped without being asked. */
idleMs: number;
} }
/** IDLE_TIMEOUT_MINUTES in ms, 0 = off. Read per check, the admin panel changes it live. */
const idleTimeoutMs = () => Math.max(0, Number(process.env.IDLE_TIMEOUT_MINUTES) || 0) * 60_000;
// The page asks "Are you still there?" after the timeout and waits 60 s; the
// gateway only steps in after that plus slack, for pages that never asked
// (outdated or modified). Throttled "active" messages keep it away.
const IDLE_GRACE_MS = 3 * 60_000;
const heartbeats = new WeakMap<WebSocket, HeartbeatState>(); const heartbeats = new WeakMap<WebSocket, HeartbeatState>();
// Tracked so SIGTERM (below) can tell every live TS3/TeaSpeak session to // Tracked so SIGTERM (below) can tell every live TS3/TeaSpeak session to
@@ -645,6 +660,14 @@ const heartbeatTimer = setInterval(() => {
socket.terminate(); socket.terminate();
continue; continue;
} }
if (state.idleMs > 0 && Date.now() - state.lastActive > state.idleMs + IDLE_GRACE_MS) {
// Close handler disconnects the TS session; the message tells the page
// this was deliberate, so it doesn't auto-reconnect.
socket.send('{"type":"idleTimeout"}');
socket.close(4000, "idle");
heartbeats.delete(socket);
continue;
}
state.isAlive = false; state.isAlive = false;
socket.ping(); socket.ping();
// Protocol pings are invisible to browser JS; this lets the page notice // Protocol pings are invisible to browser JS; this lets the page notice
@@ -708,6 +731,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
// One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens // One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens
// multiple /ws connections in parallel (one per server tab). // multiple /ws connections in parallel (one per server tab).
let connection: Ts3Connection | undefined; let connection: Ts3Connection | undefined;
// Message handlers are async and run concurrently, so a connect can still be
// awaiting when a newer connect or the close arrives. Only the newest
// connect on an open socket may spawn a connector, else one leaks.
let closed = false;
let connectGen = 0;
// Full: accept and say so, since a browser can't read why an upgrade was refused. // Full: accept and say so, since a browser can't read why an upgrade was refused.
if (maxConnections() > 0 && wss.clients.size > maxConnections()) { if (maxConnections() > 0 && wss.clients.size > maxConnections()) {
@@ -723,9 +751,17 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
// pulled, so the browser must not assume a feature exists just because it // pulled, so the browser must not assume a feature exists just because it
// knows about it. A gateway without "hello" (before v0.15) supports the // knows about it. A gateway without "hello" (before v0.15) supports the
// v0.14 feature set, streaming included; anything newer gets a name here. // v0.14 feature set, streaming included; anything newer gets a name here.
socket.send(JSON.stringify({ type: "hello", features: gatewayFeatures(), iceServers: turnServers() })); const idleMs = idleTimeoutMs();
socket.send(
JSON.stringify({
type: "hello",
features: gatewayFeatures(),
iceServers: turnServers(),
idleTimeoutMinutes: idleMs / 60_000,
}),
);
heartbeats.set(socket, { isAlive: true }); heartbeats.set(socket, { isAlive: true, lastActive: Date.now(), idleMs });
socket.on("pong", () => { socket.on("pong", () => {
const state = heartbeats.get(socket); const state = heartbeats.get(socket);
if (state) state.isAlive = true; if (state) state.isAlive = true;
@@ -757,6 +793,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
} }
async function handleMessage(msg: any): Promise<void> { async function handleMessage(msg: any): Promise<void> {
if (msg.type === "active" || msg.type === "connect") {
const state = heartbeats.get(socket);
if (state) state.lastActive = Date.now();
if (msg.type === "active") return;
}
switch (msg.type) { switch (msg.type) {
case "connect": { case "connect": {
if (!isValidHost(msg.host) || !isValidNickname(msg.nickname)) { if (!isValidHost(msg.host) || !isValidNickname(msg.nickname)) {
@@ -791,17 +832,16 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
} }
socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) })); socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) }));
} }
// Replacing a connection on the same socket: tear down the previous // Replacing a connection on the same socket: take the previous one
// connector so we don't leak processes. // out before awaiting its teardown, so no other handler sees it.
if (connection) { const gen = ++connectGen;
try { const prev = connection;
await connection.disconnect();
} catch {
/* ignore */
}
liveConnections.delete(connection);
connection = undefined; connection = undefined;
if (prev) {
liveConnections.delete(prev);
await prev.disconnect().catch(() => {});
} }
if (closed || gen !== connectGen) break;
const options: Ts3ConnectOptions = { const options: Ts3ConnectOptions = {
host: msg.host, host: msg.host,
nickname: msg.nickname, nickname: msg.nickname,
@@ -1095,9 +1135,13 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
break; break;
} }
case "disconnect": { case "disconnect": {
await connection?.disconnect(msg.message ?? ""); // Same as above: detach first, a connect may arrive while this awaits.
if (connection) liveConnections.delete(connection); const current = connection;
connection = undefined; connection = undefined;
if (current) {
liveConnections.delete(current);
await current.disconnect(msg.message ?? "");
}
break; break;
} }
default: default:
@@ -1113,7 +1157,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
if (remaining > 0) connectionsPerIp.set(ip, remaining); if (remaining > 0) connectionsPerIp.set(ip, remaining);
else connectionsPerIp.delete(ip); else connectionsPerIp.delete(ip);
heartbeats.delete(socket); heartbeats.delete(socket);
if (connection) liveConnections.delete(connection); closed = true;
connection?.disconnect(); if (connection) {
liveConnections.delete(connection);
void connection.disconnect().catch(() => {});
connection = undefined;
}
}); });
}); });
+19
View File
@@ -1,4 +1,5 @@
import type { IncomingMessage } from "node:http"; import type { IncomingMessage } from "node:http";
import { rename, writeFile } from "node:fs/promises";
// Behind a reverse proxy / tunnel every request arrives from the proxy's own // Behind a reverse proxy / tunnel every request arrives from the proxy's own
// address, so per-IP limits would lump all users into one bucket. Only set // address, so per-IP limits would lump all users into one bucket. Only set
@@ -38,3 +39,21 @@ export function createRateLimiter(limit: number | (() => number), windowMs: numb
return recent.length > (typeof limit === "function" ? limit() : limit); return recent.length > (typeof limit === "function" ? limit() : limit);
}; };
} }
/** Write-then-rename, one write at a time per file. Concurrent requests used
* to share one `.tmp` path: one rename won, the others failed with ENOENT,
* and overlapping writes could leave a mangled file. Queued, the last caller's
* data always lands last. */
const writeQueues = new Map<string, Promise<void>>();
export function writeFileAtomic(file: string, data: string, mode?: number): Promise<void> {
const run = async () => {
const tmp = `${file}.tmp`;
await writeFile(tmp, data, { encoding: "utf-8", mode });
await rename(tmp, file);
};
const done = (writeQueues.get(file) ?? Promise.resolve()).then(run);
const tail = done.catch(() => {});
writeQueues.set(file, tail);
void tail.then(() => { if (writeQueues.get(file) === tail) writeQueues.delete(file); });
return done;
}
+3 -4
View File
@@ -13,7 +13,8 @@
// //
// Like store.ts, this file has zero private modifications. // Like store.ts, this file has zero private modifications.
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { writeFileAtomic } from "./net.js";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { isAdminRequest, latestPublicTheme } from "./store.js"; import { isAdminRequest, latestPublicTheme } from "./store.js";
@@ -43,9 +44,7 @@ async function load(): Promise<TextItem[]> {
} }
async function save(items: TextItem[]) { async function save(items: TextItem[]) {
const tmp = `${NEWS_DATA_FILE}.tmp`; await writeFileAtomic(NEWS_DATA_FILE!, JSON.stringify(items));
await writeFile(tmp, JSON.stringify(items), "utf-8");
await rename(tmp, NEWS_DATA_FILE!);
cache = items; cache = items;
} }
+3 -5
View File
@@ -4,8 +4,8 @@
// row per instance id: version, first and last seen. No IP addresses, no // row per instance id: version, first and last seen. No IP addresses, no
// request log. The admin view returns counts only. // request log. The admin view returns counts only.
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { clientIp, createRateLimiter } from "./net.js"; import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
import { isAdminRequest } from "./store.js"; import { isAdminRequest } from "./store.js";
const PING_DATA_FILE = process.env.PING_DATA_FILE; const PING_DATA_FILE = process.env.PING_DATA_FILE;
@@ -36,9 +36,7 @@ async function save(instances: Record<string, Instance>) {
// Instances silent for 90 days are gone for good. // Instances silent for 90 days are gone for good.
const cutoff = Date.now() - 90 * DAY_MS; const cutoff = Date.now() - 90 * DAY_MS;
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id]; for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
const tmp = `${PING_DATA_FILE}.tmp`; await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
await writeFile(tmp, JSON.stringify(instances), "utf-8");
await rename(tmp, PING_DATA_FILE!);
} }
function json(res: ServerResponse, status: number, body: unknown) { function json(res: ServerResponse, status: number, body: unknown) {
+14 -12
View File
@@ -11,10 +11,10 @@
// touched. It has zero private modifications, so the overlay just copies it // touched. It has zero private modifications, so the overlay just copies it
// verbatim; only index.ts's small SQLite-persistence sections need patching. // verbatim; only index.ts's small SQLite-persistence sections need patching.
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { timingSafeEqual, randomUUID } from "node:crypto"; import { timingSafeEqual, randomUUID } from "node:crypto";
import path from "node:path"; import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js"; import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*"; const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
// Plain JSON file (whole-array read-modify-write, not JSON-lines like // Plain JSON file (whole-array read-modify-write, not JSON-lines like
@@ -75,9 +75,10 @@ interface StoreTheme {
// Undo what a plain pattern check would miss: comments splitting a keyword // Undo what a plain pattern check would miss: comments splitting a keyword
// (u/**/rl), CSS escapes (\75 rl( is url(), and case. // (u/**/rl), CSS escapes (\75 rl( is url(), and case.
function normalizeCss(css: string): string { // Comment stripping isn't string-aware ("/*" inside content:"..."), so the
return css // checks run on both variants: with and without comments removed.
.replace(/\/\*[\s\S]*?\*\//g, "") function normalizeCss(css: string, stripComments: boolean): string {
return (stripComments ? css.replace(/\/\*[\s\S]*?\*\//g, "") : css)
.replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => { .replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => {
const cp = parseInt(hex, 16); const cp = parseInt(hex, 16);
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd"; return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd";
@@ -94,7 +95,7 @@ const FORBIDDEN_CSS = [
/@import/, /@import/,
/@font-face/, /@font-face/,
/@namespace/, /@namespace/,
/(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/, /(?:^|[^a-z])(?:-[a-z]+-)?(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
/-moz-binding/, /-moz-binding/,
/behavior\s*:/, /behavior\s*:/,
/javascript:/, /javascript:/,
@@ -102,7 +103,10 @@ const FORBIDDEN_CSS = [
]; ];
export function isSafeThemeCss(css: string): boolean { export function isSafeThemeCss(css: string): boolean {
const normalized = normalizeCss(css); return isSafeNormalized(normalizeCss(css, true)) && isSafeNormalized(normalizeCss(css, false));
}
function isSafeNormalized(normalized: string): boolean {
if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false; if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false;
for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) { for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) {
if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false; if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false;
@@ -130,9 +134,7 @@ async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
storeCache = themes; storeCache = themes;
// Write-then-rename: a crash mid-write must not leave a truncated file, // Write-then-rename: a crash mid-write must not leave a truncated file,
// which loadStoreThemes() would read as "no themes" and then overwrite. // which loadStoreThemes() would read as "no themes" and then overwrite.
const tmp = `${STORE_DATA_FILE}.tmp`; await writeFileAtomic(STORE_DATA_FILE, JSON.stringify(themes));
await writeFile(tmp, JSON.stringify(themes), "utf-8");
await rename(tmp, STORE_DATA_FILE);
} }
export function isAdminRequest(req: IncomingMessage): boolean { export function isAdminRequest(req: IncomingMessage): boolean {
@@ -372,8 +374,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
const themes = await loadStoreThemes(); const themes = await loadStoreThemes();
// Re-uploading an installed store theme unchanged would just duplicate it. // Re-uploading an installed store theme unchanged would just duplicate it.
const cssKey = normalizeCss(css).replace(/\s+/g, ""); const cssKey = normalizeCss(css, true).replace(/\s+/g, "");
if (themes.some((t) => normalizeCss(t.css).replace(/\s+/g, "") === cssKey)) { if (themes.some((t) => normalizeCss(t.css, true).replace(/\s+/g, "") === cssKey)) {
res.writeHead(409, { "Content-Type": "application/json" }); res.writeHead(409, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "duplicate" })); res.end(JSON.stringify({ error: "duplicate" }));
return; return;
+3 -5
View File
@@ -8,9 +8,9 @@
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts. // One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { mkdir, readdir, readFile, rm } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js"; import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR; const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*"; const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
@@ -76,9 +76,7 @@ async function load(id: string): Promise<Account | null> {
} }
async function save(id: string, account: Account) { async function save(id: string, account: Account) {
const tmp = `${file(id)}.tmp`; await writeFileAtomic(file(id), JSON.stringify(account));
await writeFile(tmp, JSON.stringify(account), "utf-8");
await rename(tmp, file(id));
} }
// Writes to one account run one after another, so the version check can't race. // Writes to one account run one after another, so the version check can't race.
+20
View File
@@ -0,0 +1,20 @@
// Concurrent saves to one file used to share a .tmp path: all but one rename
// failed with ENOENT (seen live from a parallel /api/ping probe).
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { writeFileAtomic } from "../dist/net.js";
test("parallel writes to one file all succeed, last one wins", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-atomic-"));
try {
const file = path.join(dir, "data.json");
await Promise.all(Array.from({ length: 50 }, (_, i) => writeFileAtomic(file, JSON.stringify({ i, pad: "x".repeat(i * 500) }))));
assert.equal(JSON.parse(readFileSync(file, "utf-8")).i, 49);
assert.deepEqual(readdirSync(dir), ["data.json"]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+21
View File
@@ -0,0 +1,21 @@
// Theme CSS from the Design Store must never load anything external.
import { test } from "node:test";
import assert from "node:assert/strict";
import { isSafeThemeCss } from "../dist/store.js";
test("theme CSS filter", () => {
const evil = "url(https://attacker.example/t.png)";
for (const css of [
`body{background:${evil}}`,
`body{background:\\75rl(https://attacker.example/t.png)}`,
`body{background:image-set("https://attacker.example/t.png" 1x)}`,
`a{content:"/*"}body{background:${evil}}b{content:"*/"}`,
`a{--x:\\/*}body{background:${evil}}b{--y:*/}`,
`body{background:-webkit-image-set("https://attacker.example/t.png" 1x)}`,
]) assert.equal(isSafeThemeCss(css), false, css);
for (const css of [
":root{--bg:#123}body{color:red}a:hover{opacity:.5}",
"body{background:url(data:image/png;base64,AAAA)}",
"/* a comment */ body{color:red}",
]) assert.equal(isSafeThemeCss(css), true, css);
});
+96
View File
@@ -0,0 +1,96 @@
// Connect/close races on one WebSocket must not leave connector processes
// behind. Uses a fake connector that records its PID and lives until its
// stdin closes (like the real one), against the built gateway.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
const INDEX = path.resolve(import.meta.dirname, "../dist/index.js");
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
const freePort = () => new Promise((ok) => {
const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); });
});
test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-orphans-"));
const pids = path.join(dir, "pids");
const fake = path.join(dir, "fake-connector.sh");
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\nsleep 1\n`);
chmodSync(fake, 0o755);
const port = await freePort();
const gw = spawn(process.execPath, [INDEX], {
cwd: dir,
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake },
stdio: "ignore",
});
const recorded = () => (existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).map(Number) : []);
try {
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
const connect = JSON.stringify({ type: "connect", host: "example.invalid", nickname: "dummy" });
const open = async () => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
return ws;
};
// connect, connect while the first connector shuts down, close
let ws = await open();
ws.send(connect); await wait(300);
ws.send(connect); await wait(100);
ws.close();
// connect, then two connects back to back, close later
ws = await open();
ws.send(connect); await wait(300);
ws.send(connect); ws.send(connect);
await wait(4000);
ws.close();
await wait(4000);
assert.ok(recorded().length >= 2, "fake connector was spawned");
assert.deepEqual(recorded().filter(alive), [], "connector processes left behind");
} finally {
for (const pid of recorded()) if (alive(pid)) process.kill(pid, "SIGKILL");
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
rmSync(dir, { recursive: true, force: true });
}
});
test("ALLOWED_SERVERS can't be bypassed with a bracketed prefix", { timeout: 30_000 }, async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-allow-"));
const pids = path.join(dir, "pids");
const fake = path.join(dir, "fake-connector.sh");
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\n`);
chmodSync(fake, 0o755);
const port = await freePort();
const gw = spawn(process.execPath, [INDEX], {
cwd: dir,
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake, ALLOWED_SERVERS: "ts.example.com" },
stdio: "ignore",
});
try {
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
const reply = async (host) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
const msgs = [];
ws.onmessage = (e) => msgs.push(JSON.parse(e.data));
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
ws.send(JSON.stringify({ type: "connect", host, nickname: "dummy" }));
await wait(500);
ws.close();
return msgs.find((m) => m.type === "error")?.message ?? "";
};
for (const host of ["[ts.example.com]evil.tld", "[ts.example.com]evil.tld:9987", "evil.tld"]) {
assert.match(await reply(host), /not allowed/, host);
}
assert.doesNotMatch(await reply("ts.example.com:9987"), /not allowed/);
assert.equal(existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).length : 0, 1, "only the allowed host spawned a connector");
} finally {
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
rmSync(dir, { recursive: true, force: true });
}
});
+65 -34
View File
@@ -26,7 +26,6 @@
--log-bg: #f7f8f9; --log-bg: #f7f8f9;
--log-text: #333; --log-text: #333;
--log-error: #b3261e; --log-error: #b3261e;
--alpha-badge: #a15c07;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -72,7 +71,6 @@
--log-bg: #202124; --log-bg: #202124;
--log-text: #c7c9cc; --log-text: #c7c9cc;
--log-error: #f2867a; --log-error: #f2867a;
--alpha-badge: #e0a23c;
color-scheme: dark; color-scheme: dark;
} }
@@ -116,7 +114,6 @@
--log-bg: oklch(0.17 0.014 258); --log-bg: oklch(0.17 0.014 258);
--log-text: oklch(0.62 0.014 258); --log-text: oklch(0.62 0.014 258);
--log-error: oklch(0.68 0.16 25); --log-error: oklch(0.68 0.16 25);
--alpha-badge: oklch(0.75 0.14 70);
color-scheme: dark; color-scheme: dark;
font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
} }
@@ -865,7 +862,6 @@
--log-bg: oklch(0.155 0.018 290); --log-bg: oklch(0.155 0.018 290);
--log-text: oklch(0.64 0.014 290); --log-text: oklch(0.64 0.014 290);
--log-error: oklch(0.68 0.16 25); --log-error: oklch(0.68 0.16 25);
--alpha-badge: oklch(0.75 0.14 70);
color-scheme: dark; color-scheme: dark;
font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
} }
@@ -1480,7 +1476,7 @@
.ts-stream-panel { .ts-stream-panel {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: min(480px, calc(100vw - 2rem)); min-width: 0;
background: var(--bg-toolbar-1); background: var(--bg-toolbar-1);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 6px; border-radius: 6px;
@@ -1511,30 +1507,6 @@
/* Deliberately loud: the feature speaks an undocumented TS6 protocol, so the /* Deliberately loud: the feature speaks an undocumented TS6 protocol, so the
user should never be in doubt that it is experimental. */ user should never be in doubt that it is experimental. */
.ts-alpha-badge {
display: inline-block;
padding: 0 0.35em;
border: 1px solid var(--alpha-badge);
border-radius: 3px;
color: var(--alpha-badge);
font-size: 0.7em;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
vertical-align: middle;
white-space: nowrap;
}
.ts-alpha-note {
margin: 0 0 0.75rem;
padding: 0.5rem 0.6rem;
border-left: 3px solid var(--alpha-badge);
background: var(--log-bg);
color: var(--text-muted);
font-size: 0.85em;
line-height: 1.4;
}
.ts-stream-panel-close { .ts-stream-panel-close {
padding: 0 0.35rem; padding: 0 0.35rem;
background: none; background: none;
@@ -1551,6 +1523,34 @@
object-fit: contain; object-fit: contain;
} }
/* A stream in our channel nobody opened yet: same 16:9 area, one click to watch. */
.ts-stream-panel-watch {
aspect-ratio: 16 / 9;
width: 100%;
background: #000;
border: none;
color: #fff;
font-size: 1.1em;
cursor: pointer;
opacity: 0.8;
}
.ts-stream-panel-watch:hover {
opacity: 1;
}
/* Stream icons in the tree sit on the right with the group icons and are clickable. */
.ts-stream-icon {
padding: 0;
font-size: 11px;
line-height: 1;
cursor: pointer;
}
span.ts-stream-icon {
cursor: default;
}
.ts-stream-panel-error { .ts-stream-panel-error {
padding: 0.35rem 0.5rem; padding: 0.35rem 0.5rem;
color: var(--danger, #e05a5a); color: var(--danger, #e05a5a);
@@ -1661,21 +1661,52 @@
border-color: var(--accent); border-color: var(--accent);
} }
/* Watching and broadcasting can run at the same time, so the two panels stack /* Every watched stream (and our own broadcast) is a tile in one grid, like
instead of each anchoring itself to the same corner. */ Discord: up to two columns in the corner, as many as fit when popped out. */
.ts-stream-panels { .ts-stream-panels {
position: fixed; position: fixed;
right: 1rem; right: 1rem;
bottom: 1rem; bottom: 1rem;
z-index: 29; z-index: 29;
display: flex; display: grid;
flex-direction: column; grid-template-columns: repeat(var(--stream-cols, 1), minmax(0, 1fr));
align-content: safe end;
gap: 0.5rem; gap: 0.5rem;
align-items: flex-end; width: min(calc(var(--stream-cols, 1) * 480px), calc(100vw - 2rem));
max-height: calc(100vh - 2rem); max-height: calc(100vh - 2rem);
overflow-y: auto; overflow-y: auto;
} }
.ts-stream-panel-focused {
grid-column: 1 / -1;
}
/* Inside the separate window the grid owns the whole viewport. */
.ts-stream-panels-popout {
position: static;
width: auto;
max-height: none;
padding: 0.5rem;
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
align-content: start;
}
/* Discord-style focus: the enlarged stream on top, the rest below it. */
.ts-stream-panels-popout .ts-stream-panel-focused {
order: -1;
}
.ts-stream-panels-popout .ts-stream-panel-focused video {
max-height: calc(100vh - 6rem);
}
/* Wraps the grid in the popped-out window; carries the theme variables. */
.ts-stream-popout-root {
min-height: 100vh;
background: var(--bg);
color: var(--text);
}
.ts-context-menu { .ts-context-menu {
position: fixed; position: fixed;
z-index: 30; z-index: 30;
+470 -134
View File
@@ -9,6 +9,7 @@ import {
useSyncExternalStore, useSyncExternalStore,
type ReactNode, type ReactNode,
} from "react"; } from "react";
import { createPortal } from "react-dom";
import { identityUid } from "./identityUid"; import { identityUid } from "./identityUid";
import qrcode from "qrcode-generator"; import qrcode from "qrcode-generator";
import { useRegisterSW } from "virtual:pwa-register/react"; import { useRegisterSW } from "virtual:pwa-register/react";
@@ -135,6 +136,22 @@ import {
type StreamPublishOptions, type StreamPublishOptions,
} from "./publish"; } from "./publish";
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
type PublishSource = StreamPublishOptions["source"];
interface PublishTile {
state: PublishState;
viewers: number[];
pending: [number, string][];
error: string | null;
}
interface WatchedStream {
info: StreamInfo;
media: MediaStream | null;
state: RTCPeerConnectionState;
error: string | null;
}
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
import { import {
DEFAULT_SYNC_SERVER, DEFAULT_SYNC_SERVER,
@@ -1472,6 +1489,50 @@ function TalkLamp({
); );
} }
/** Streams per publishing client, and how to open one - read by the channel tree. */
const StreamsContext = createContext<{
byClient: Record<number, StreamInfo[]>;
watch: (streamId: string) => void;
}>({ byClient: {}, watch: () => {} });
const streamIcon = (info: StreamInfo) => (info.camera ? "📷" : "🖥️");
/** Right-hand stream icons on a client row; a click opens that stream. */
function ClientStreamIcons({ client, isSelf }: { client: ClientInfo; isSelf: boolean }) {
const t = useT();
const { byClient, watch } = useContext(StreamsContext);
const streams = byClient[client.id] ?? [];
if (streams.length === 0) {
// Streaming, but the stream info has not arrived yet.
return client.isStreaming ? <span className="ts-stream-icon" title={t("tree.streaming")}>📺</span> : null;
}
return (
<>
{streams.map((info) => {
const label = `${t(info.camera ? "tree.streamingCamera" : "tree.streaming")}${info.name ? `: ${info.name}` : ""}`;
return isSelf ? (
<span key={info.id} className="ts-stream-icon" title={label}>{streamIcon(info)}</span>
) : (
<button
key={info.id}
type="button"
className="ts-stream-icon ts-plain-button"
title={label}
aria-label={label}
onClick={(e) => {
e.stopPropagation();
watch(info.id);
}}
onDoubleClick={(e) => e.stopPropagation()}
>
{streamIcon(info)}
</button>
);
})}
</>
);
}
function ClientStatusIcons({ client }: { client: ClientInfo }) { function ClientStatusIcons({ client }: { client: ClientInfo }) {
const t = useT(); const t = useT();
const { tree } = useContext(DisplayPrefsContext); const { tree } = useContext(DisplayPrefsContext);
@@ -1482,7 +1543,6 @@ function ClientStatusIcons({ client }: { client: ClientInfo }) {
{!client.inputMuted && client.inputHardwareEnabled && !client.hasTalkPower && ( {!client.inputMuted && client.inputHardwareEnabled && !client.hasTalkPower && (
<span title={t("tree.noTalkPower")}>🔒</span> <span title={t("tree.noTalkPower")}>🔒</span>
)} )}
{client.isStreaming && <span title={t("tree.streaming")}>📺</span>}
</span> </span>
); );
} }
@@ -1872,6 +1932,7 @@ function ChannelTree({
<span className="ts-client-away-message">({c.awayMessage})</span> <span className="ts-client-away-message">({c.awayMessage})</span>
)} )}
<span className="ts-client-icons"> <span className="ts-client-icons">
<ClientStreamIcons client={c} isSelf={c.id === ownClientId} />
{clientGroupBadges(c).map((g) => ( {clientGroupBadges(c).map((g) => (
<GroupIcon key={g.id} group={g} images={groupIconImages} /> <GroupIcon key={g.id} group={g} images={groupIconImages} />
))} ))}
@@ -2555,6 +2616,32 @@ function AboutDialog({ onClose }: { onClose: () => void }) {
); );
} }
/** Seconds the "Are you still there?" dialog waits before disconnecting. */
const IDLE_CHECK_SECONDS = 60;
function IdleCheckDialog({ secondsLeft, onStay }: { secondsLeft: number; onStay: () => void }) {
const t = useT();
return (
<div className="ts-dialog-backdrop">
<div className="ts-dialog ts-restart-notice-dialog" role="alertdialog" onClick={(e) => e.stopPropagation()}>
<div className="ts-dialog-titlebar">
<span>{t("idleCheck.title")}</span>
</div>
<div className="ts-dialog-body">
<p>{t("idleCheck.body", { seconds: String(secondsLeft) })}</p>
</div>
<div className="ts-dialog-buttons">
<div className="ts-dialog-buttons-right">
<button type="button" autoFocus onClick={onStay}>
{t("idleCheck.stay")}
</button>
</div>
</div>
</div>
</div>
);
}
function RestartNoticeDialog({ message, onAck }: { message: string; onAck: () => void }) { function RestartNoticeDialog({ message, onAck }: { message: string; onAck: () => void }) {
const t = useT(); const t = useT();
return ( return (
@@ -2705,18 +2792,6 @@ const RESOLUTION_CHOICES = [360, 480, 720, 1080, 1440, 0];
const FPS_CHOICES = [5, 30, 60]; const FPS_CHOICES = [5, 30, 60];
const AUDIO_BITRATE_CHOICES = [64, 96, 128, 192, 256, 320]; const AUDIO_BITRATE_CHOICES = [64, 96, 128, 192, 256, 320];
// Streaming talks to TS6 over a protocol nobody published, so it is marked
// alpha everywhere the user can reach it: the settings dialog, both stream
// panels, and the toolbar button's tooltip.
function AlphaBadge() {
const t = useT();
return (
<span className="ts-alpha-badge" title={t("publish.alphaTitle")}>
{t("publish.alpha")}
</span>
);
}
function SegmentedChoice<T extends string | number>({ function SegmentedChoice<T extends string | number>({
value, value,
options, options,
@@ -2748,17 +2823,19 @@ function SegmentedChoice<T extends string | number>({
function StreamSettingsDialog({ function StreamSettingsDialog({
ownName, ownName,
initialSource,
onStart, onStart,
onCancel, onCancel,
}: { }: {
ownName: string; ownName: string;
initialSource: "display" | "camera";
onStart: (options: StreamPublishOptions) => void; onStart: (options: StreamPublishOptions) => void;
onCancel: () => void; onCancel: () => void;
}) { }) {
const t = useT(); const t = useT();
const backdrop = useBackdropDismiss(onCancel); const backdrop = useBackdropDismiss(onCancel);
const [preset, setPreset] = useState<string | null>("720"); const [preset, setPreset] = useState<string | null>("720");
const [source, setSource] = useState<"display" | "camera">("display"); const [source, setSource] = useState<"display" | "camera">(initialSource);
const [audio, setAudio] = useState(true); const [audio, setAudio] = useState(true);
const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC); const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
const [advanced, setAdvanced] = useState(false); const [advanced, setAdvanced] = useState(false);
@@ -2794,14 +2871,13 @@ function StreamSettingsDialog({
<div className="ts-dialog ts-stream-settings" onClick={(e) => e.stopPropagation()}> <div className="ts-dialog ts-stream-settings" onClick={(e) => e.stopPropagation()}>
<div className="ts-dialog-titlebar"> <div className="ts-dialog-titlebar">
<span> <span>
{t("publish.dialog.title")} <AlphaBadge /> {t("publish.dialog.title")}
</span> </span>
<button onClick={onCancel} title={t("dialog.close")} aria-label={t("dialog.close")}> <button onClick={onCancel} title={t("dialog.close")} aria-label={t("dialog.close")}>
✕ ✕
</button> </button>
</div> </div>
<div className="ts-dialog-body"> <div className="ts-dialog-body">
<p className="ts-alpha-note">{t("publish.alphaNote")}</p>
<h4 className="ts-stream-settings-section">{t("publish.dialog.basic")}</h4> <h4 className="ts-stream-settings-section">{t("publish.dialog.basic")}</h4>
<div className="ts-stream-settings-row"> <div className="ts-stream-settings-row">
@@ -8984,6 +9060,12 @@ function AppInner() {
const [gatewayFeatures, setGatewayFeatures] = useState<ReadonlySet<string>>(new Set()); const [gatewayFeatures, setGatewayFeatures] = useState<ReadonlySet<string>>(new Set());
// TURN relay the gateway offers for screen streams (TURN_URLS), if any. // TURN relay the gateway offers for screen streams (TURN_URLS), if any.
const [turnServers, setTurnServers] = useState<RTCIceServer[]>([]); const [turnServers, setTurnServers] = useState<RTCIceServer[]>([]);
// IDLE_TIMEOUT_MINUTES from the hello; 0 = the gateway never asks.
const [idleTimeoutMin, setIdleTimeoutMin] = useState(0);
const lastActivityRef = useRef(Date.now());
// Countdown of the "Are you still there?" dialog, null while it is closed.
const [idleCheckLeft, setIdleCheckLeft] = useState<number | null>(null);
const [idleDisconnected, setIdleDisconnected] = useState(false);
// Terms of use, own-hosted instance only (see IS_OWN_HOSTED_INSTANCE): shown // Terms of use, own-hosted instance only (see IS_OWN_HOSTED_INSTANCE): shown
// mandatorily on first visit, reopenable any time from the menu afterwards. // mandatorily on first visit, reopenable any time from the menu afterwards.
const [tosOpen, setTosOpen] = useState(false); const [tosOpen, setTosOpen] = useState(false);
@@ -9006,20 +9088,22 @@ function AppInner() {
const [treeFilter, setTreeFilter] = useState(""); const [treeFilter, setTreeFilter] = useState("");
const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes); const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes);
/** Stream metadata per publishing client id, keyed by clid. */ /** Stream metadata per publishing client id, keyed by clid. */
const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({}); const [streamInfos, setStreamInfos] = useState<Record<string, StreamInfo>>({});
const [watchedStream, setWatchedStream] = useState<StreamInfo | null>(null); /** Streams being watched, keyed by the publisher's clid - several at once, like Discord. */
const [streamMedia, setStreamMedia] = useState<MediaStream | null>(null); /** Keyed by stream id: one client can send screen and camera at once. */
const [streamState, setStreamState] = useState<RTCPeerConnectionState>("new"); const [watchedStreams, setWatchedStreams] = useState<Record<string, WatchedStream>>({});
const [streamError, setStreamError] = useState<string | null>(null); const streamViewersRef = useRef<Map<string, StreamViewer>>(new Map());
const streamViewerRef = useRef<StreamViewer | null>(null); /** Streams the pop-out already opened by itself; closed or refused ones are not retried. */
const [publishState, setPublishState] = useState<PublishState>("idle"); const autoWatchedRef = useRef<Set<string>>(new Set());
const [publishViewers, setPublishViewers] = useState<number[]>([]); /** Tile shown across the whole grid, Discord's "focus" (clid, or -1 for our own broadcast). */
const [publishPending, setPublishPending] = useState<[number, string][]>([]); const [focusedStream, setFocusedStream] = useState<string | null>(null);
const [publishError, setPublishError] = useState<string | null>(null); /** Separate browser window the stream grid is portalled into, if popped out. */
const publisherRef = useRef<StreamPublisher | null>(null); const [streamPopout, setStreamPopout] = useState<Window | null>(null);
const publishPreviewRef = useRef<HTMLVideoElement | null>(null); const [popoutSize, setPopoutSize] = useState({ width: 0, height: 0 });
/** Our own broadcasts, at most one per source, so screen and camera can run together. */
const [publishes, setPublishes] = useState<Partial<Record<PublishSource, PublishTile>>>({});
const publishersRef = useRef<Map<PublishSource, StreamPublisher>>(new Map());
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false); const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
const streamVideoRef = useRef<HTMLVideoElement | null>(null);
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */ /** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
const requestedStreamInfoRef = useRef<Set<number>>(new Set()); const requestedStreamInfoRef = useRef<Set<number>>(new Set());
/** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */ /** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */
@@ -10115,6 +10199,14 @@ function AppInner() {
if (data.type === "hello") { if (data.type === "hello") {
setGatewayFeatures(new Set(Array.isArray(data.features) ? data.features : [])); setGatewayFeatures(new Set(Array.isArray(data.features) ? data.features : []));
setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []); setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []);
setIdleTimeoutMin(Math.max(0, Number(data.idleTimeoutMinutes) || 0));
return;
}
if (data.type === "idleTimeout") {
// The gateway dropped us for inactivity: deliberate, no auto-reconnect.
setIdleCheckLeft(null);
handleDisconnectAll();
setIdleDisconnected(true);
return; return;
} }
if (data.type === "turnstileRequired") { if (data.type === "turnstileRequired") {
@@ -10381,21 +10473,26 @@ function AppInner() {
const streamEvent = data as StreamEvent; const streamEvent = data as StreamEvent;
if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") { if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") {
const info = parseStreamInfo(streamEvent.args); const info = parseStreamInfo(streamEvent.args);
if (info) setStreamInfos((prev) => ({ ...prev, [info.clientId]: info })); // notifystreaminfo may leave `type` out; keep what notifystreamstarted said.
if (info)
setStreamInfos((prev) => ({
...prev,
[info.id]: { ...info, camera: info.camera ?? prev[info.id]?.camera },
}));
} }
if (streamEvent.name === "notifystreamstopped") { if (streamEvent.name === "notifystreamstopped") {
const clid = Number(streamEvent.args.clid); const { id } = streamEvent.args;
if (Number.isFinite(clid)) { if (id) {
setStreamInfos((prev) => { setStreamInfos((prev) => {
if (!(clid in prev)) return prev; if (!(id in prev)) return prev;
const next = { ...prev }; const next = { ...prev };
delete next[clid]; delete next[id];
return next; return next;
}); });
} }
} }
streamViewerRef.current?.handleEvent(streamEvent); for (const viewer of streamViewersRef.current.values()) viewer.handleEvent(streamEvent);
publisherRef.current?.handleEvent(streamEvent); for (const publisher of publishersRef.current.values()) publisher.handleEvent(streamEvent);
break; break;
} }
case "poke": { case "poke": {
@@ -10471,17 +10568,10 @@ function AppInner() {
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" }); appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
logClient("info", "Connection", `Disconnected: ${data.reason}`); logClient("info", "Connection", `Disconnected: ${data.reason}`);
if (wasConnected) void notify("CONNECTION_DISCONNECTED"); if (wasConnected) void notify("CONNECTION_DISCONNECTED");
streamViewerRef.current?.close(); handleStopWatchingStream();
streamViewerRef.current = null;
setWatchedStream(null);
setStreamMedia(null);
setStreamInfos({}); setStreamInfos({});
requestedStreamInfoRef.current.clear(); requestedStreamInfoRef.current.clear();
publisherRef.current?.stop(); handleStopPublishing();
publisherRef.current = null;
setPublishState("idle");
setPublishViewers([]);
setPublishPending([]);
removeSession(sessionId, { skipSocketClose: true }); removeSession(sessionId, { skipSocketClose: true });
break; break;
} }
@@ -12135,70 +12225,141 @@ function AppInner() {
if (!streaming.has(id)) requestedStreamInfoRef.current.delete(id); if (!streaming.has(id)) requestedStreamInfoRef.current.delete(id);
} }
setStreamInfos((prev) => { setStreamInfos((prev) => {
const stale = Object.keys(prev).filter((id) => !streaming.has(Number(id))); const stale = Object.values(prev).filter((info) => !streaming.has(info.clientId));
if (stale.length === 0) return prev; if (stale.length === 0) return prev;
const next = { ...prev }; const next = { ...prev };
for (const id of stale) delete next[Number(id)]; for (const info of stale) delete next[info.id];
return next; return next;
}); });
}, [clients]); }, [clients]);
useEffect(() => { const activePublishes = (Object.entries(publishes) as [PublishSource, PublishTile][]).filter(
const video = streamVideoRef.current; ([, tile]) => tile.state !== "idle" && tile.state !== "stopped",
if (video && video.srcObject !== streamMedia) video.srcObject = streamMedia; );
}, [streamMedia, watchedStream]); const streamsByClient: Record<number, StreamInfo[]> = {};
for (const info of Object.values(streamInfos)) (streamsByClient[info.clientId] ??= []).push(info);
// Like Discord: streams in our channel show up as tiles before anyone clicks "watch".
const ownChannel = clients.find((c) => c.id === ownClientId)?.channel;
const availableStreams = Object.values(streamInfos).filter(
(info) =>
info.clientId !== ownClientId &&
!watchedStreams[info.id] &&
ownChannel !== undefined &&
clients.find((c) => c.id === info.clientId)?.channel === ownChannel,
);
const streamTileCount = Object.keys(watchedStreams).length + activePublishes.length + availableStreams.length;
useEffect(() => { const openStreamPopout = () => {
// The publisher owns the capture; the preview only mirrors it, so it is const win = window.open("", "webspeak3-streams", "popup,width=1280,height=760");
// read off the peer connection's senders rather than kept in state. if (!win) return;
const video = publishPreviewRef.current; win.document.title = "WebSpeak3 – Streams";
if (!video) return; win.document.head.replaceChildren(
const media = publisherRef.current?.previewStream ?? null; ...[...document.querySelectorAll('link[rel="stylesheet"], style')].map((node) => node.cloneNode(true)),
if (video.srcObject !== media) video.srcObject = media; );
}, [publishState, publishViewers]); win.document.body.style.margin = "0";
const measure = () => setPopoutSize({ width: win.innerWidth, height: win.innerHeight });
const handleStopWatchingStream = () => { measure();
// close() sends leaveStream and fires onClosed, which clears the rest. win.addEventListener("resize", measure);
streamViewerRef.current?.close(); // Fires when the user closes the window; the grid then moves back in here.
streamViewerRef.current = null; win.addEventListener("pagehide", () => setStreamPopout(null));
setWatchedStream(null); setStreamPopout(win);
setStreamMedia(null);
setStreamState("new");
}; };
const handleWatchStream = (clientId: number) => { const closeStreamPopout = () => {
const info = streamInfos[clientId]; streamPopout?.close();
if (!info) return; setStreamPopout(null);
handleStopWatchingStream(); };
setStreamError(null);
useEffect(() => {
// Nothing left to show (or the tab goes away): don't leave an empty window behind.
if (!streamPopout) return;
if (streamTileCount === 0) {
streamPopout.close();
setStreamPopout(null);
return;
}
const close = () => streamPopout.close();
window.addEventListener("pagehide", close);
return () => window.removeEventListener("pagehide", close);
}, [streamPopout, streamTileCount]);
/** Stops one watched stream, or all of them without an id. */
const handleStopWatchingStream = (streamId?: string) => {
const viewers = streamViewersRef.current;
const ids = streamId === undefined ? [...viewers.keys()] : [streamId];
for (const id of ids) {
// close() sends leaveStream; delete first so its onClosed is a no-op.
const viewer = viewers.get(id);
viewers.delete(id);
viewer?.close();
}
setWatchedStreams((prev) => {
if (streamId === undefined) return {};
const next = { ...prev };
delete next[streamId];
return next;
});
};
const handleWatchStream = (streamId: string) => {
const info = streamInfos[streamId];
if (!info || streamViewersRef.current.has(streamId)) return;
const patch = (change: Partial<WatchedStream>) =>
setWatchedStreams((prev) => (prev[streamId] ? { ...prev, [streamId]: { ...prev[streamId], ...change } } : prev));
const viewer = new StreamViewer(info.id, info.clientId, { const viewer = new StreamViewer(info.id, info.clientId, {
send: (message) => socketRef.current?.send(JSON.stringify(message)), send: (message) => socketRef.current?.send(JSON.stringify(message)),
onTrack: setStreamMedia, onTrack: (media) => patch({ media }),
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers], iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
onStateChange: setStreamState, onStateChange: (state) => patch({ state }),
onError: setStreamError, onError: (error) => patch({ error }),
onClosed: () => { onClosed: () => {
// Also reached when the publisher stops, not just via the close button. // Also reached when the publisher stops, not just via the close button.
streamViewerRef.current = null; if (streamViewersRef.current.get(streamId) !== viewer) return;
setWatchedStream(null); handleStopWatchingStream(streamId);
setStreamMedia(null);
}, },
}); });
streamViewerRef.current = viewer; streamViewersRef.current.set(streamId, viewer);
setWatchedStream(info); setWatchedStreams((prev) => ({ ...prev, [streamId]: { info, media: null, state: "new", error: null } }));
viewer.join(); viewer.join();
}; };
const handleStopPublishing = () => { // Popped out, the window is meant for watching: open channel streams right
publisherRef.current?.stop(); // away. Only once per stream, so closing one (or a refused join request)
publisherRef.current = null; // leaves a tile to click instead of reopening it in a loop.
setPublishState("idle"); const availableStreamIds = availableStreams.map((info) => info.id).join(",");
setPublishViewers([]); useEffect(() => {
setPublishPending([]); if (!streamPopout) return;
for (const info of availableStreams) {
if (autoWatchedRef.current.has(info.id)) continue;
autoWatchedRef.current.add(info.id);
handleWatchStream(info.id);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [streamPopout, availableStreamIds]);
/** Stops one broadcast, or all of them without a source. */
const handleStopPublishing = (source?: PublishSource) => {
const publishers = publishersRef.current;
for (const key of source ? [source] : [...publishers.keys()]) {
const publisher = publishers.get(key);
publishers.delete(key);
publisher?.stop();
}
setPublishes((prev) => {
if (!source) return {};
const next = { ...prev };
delete next[source];
return next;
});
}; };
const publishingAll = publishersRef.current.size >= 2;
// Two publishers waiting for notifystreamstarted at once could not tell
// whose id it is, so a second one waits until the first is live.
const publishStarting = activePublishes.some(([, tile]) => tile.state === "starting");
const handleStreamButton = () => { const handleStreamButton = () => {
if (publisherRef.current) { if (publishingAll) {
handleStopPublishing(); handleStopPublishing();
return; return;
} }
@@ -12209,28 +12370,32 @@ function AppInner() {
clients.find((c) => c.id === clid)?.name ?? `#${clid}`; clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
const handleStartPublishing = (options: StreamPublishOptions) => { const handleStartPublishing = (options: StreamPublishOptions) => {
if (ownClientId === null) return; if (ownClientId === null || publishStarting) return;
setStreamSettingsOpen(false); setStreamSettingsOpen(false);
setPublishError(null); const source = options.source;
// Same source again replaces the running one.
if (publishersRef.current.has(source)) handleStopPublishing(source);
const patch = (change: Partial<PublishTile>) =>
setPublishes((prev) => (prev[source] ? { ...prev, [source]: { ...prev[source], ...change } } : prev));
const publisher = new StreamPublisher({ const publisher = new StreamPublisher({
send: (message) => socketRef.current?.send(JSON.stringify(message)), send: (message) => socketRef.current?.send(JSON.stringify(message)),
ownClientId, ownClientId,
onStateChange: (state) => { onStateChange: (state) => {
setPublishState(state);
// "stopped" is also how the browser's own stop-sharing bar reports in, // "stopped" is also how the browser's own stop-sharing bar reports in,
// so the ref has to be dropped here and not only in the click handler. // so the publisher has to be dropped here and not only on the ✕.
if (state === "stopped" || state === "idle") { if (state === "stopped" || state === "idle") {
publisherRef.current = null; if (publishersRef.current.get(source) === publisher) handleStopPublishing(source);
setPublishViewers([]); return;
setPublishPending([]);
} }
patch({ state });
}, },
onViewersChange: setPublishViewers, onViewersChange: (viewers) => patch({ viewers }),
onPendingChange: setPublishPending, onPendingChange: (pending) => patch({ pending }),
onError: setPublishError, onError: (error) => patch({ error }),
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers], iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
}); });
publisherRef.current = publisher; publishersRef.current.set(source, publisher);
setPublishes((prev) => ({ ...prev, [source]: { state: "idle", viewers: [], pending: [], error: null } }));
void publisher.start(options); void publisher.start(options);
}; };
@@ -12773,6 +12938,62 @@ function AppInner() {
} }
if (ownMicClicks && !outputMuted) void notify(selfTalking ? "SPECIAL_MIC_CLICK_SELF_ON" : "SPECIAL_MIC_CLICK_SELF_OFF"); if (ownMicClicks && !outputMuted) void notify(selfTalking ? "SPECIAL_MIC_CLICK_SELF_ON" : "SPECIAL_MIC_CLICK_SELF_OFF");
}, [selfTalking]); // eslint-disable-line react-hooks/exhaustive-deps }, [selfTalking]); // eslint-disable-line react-hooks/exhaustive-deps
// "Are you still there?": input in the main window or the stream pop-out,
// talking and broadcasting all count as activity. After IDLE_TIMEOUT_MINUTES
// without any, ask; no answer within IDLE_CHECK_SECONDS disconnects all tabs.
// ponytail: enforced by the client only, a modified client can skip it.
useEffect(() => {
const bump = () => {
lastActivityRef.current = Date.now();
};
const targets: Window[] = streamPopout ? [window, streamPopout] : [window];
const events = ["pointerdown", "keydown", "wheel", "touchstart"];
for (const w of targets) for (const e of events) w.addEventListener(e, bump, { passive: true });
return () => {
for (const w of targets) for (const e of events) w.removeEventListener(e, bump);
};
}, [streamPopout]);
const keepAwakeRef = useRef(false);
useEffect(() => {
keepAwakeRef.current = selfTalking || publishersRef.current.size > 0;
});
const connectedTabs = sessionTabs.length;
// Tells the gateway, at most once a minute, that someone is here - it
// enforces the timeout too, for pages that don't ask.
const activeSentRef = useRef(0);
const sendActive = () => {
activeSentRef.current = Date.now();
for (const rec of sessionsRef.current.values())
if (rec.socket?.readyState === WebSocket.OPEN) rec.socket.send('{"type":"active"}');
};
useEffect(() => {
if (!idleTimeoutMin || connectedTabs === 0) return;
lastActivityRef.current = Math.max(lastActivityRef.current, Date.now() - 1000);
const timer = window.setInterval(() => {
if (keepAwakeRef.current) lastActivityRef.current = Date.now();
if (lastActivityRef.current > activeSentRef.current && Date.now() - activeSentRef.current > 60_000) sendActive();
if (Date.now() - lastActivityRef.current > idleTimeoutMin * 60_000)
setIdleCheckLeft((left) => left ?? IDLE_CHECK_SECONDS);
}, 10_000);
return () => window.clearInterval(timer);
}, [idleTimeoutMin, connectedTabs]);
useEffect(() => {
if (idleCheckLeft === null) return;
if (connectedTabs === 0) {
setIdleCheckLeft(null);
return;
}
if (idleCheckLeft <= 0) {
setIdleCheckLeft(null);
handleDisconnectAll();
setIdleDisconnected(true);
return;
}
const timer = window.setTimeout(() => setIdleCheckLeft((left) => (left === null ? null : left - 1)), 1000);
return () => window.clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [idleCheckLeft, connectedTabs]);
const showServerQueryClients = const showServerQueryClients =
activeFavoriteId != null && activeFavoriteId != null &&
favorites.some((f) => f.id === activeFavoriteId && f.showServerQueryClients); favorites.some((f) => f.id === activeFavoriteId && f.showServerQueryClients);
@@ -12818,14 +13039,62 @@ function AppInner() {
const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute"); const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute");
const streamLabel = DEMO_MODE const streamLabel = DEMO_MODE
? t("publish.demoUnavailable") ? t("publish.demoUnavailable")
: `${publishState === "live" ? t("publish.stop") : t("publish.start")} (${t("publish.alpha")})`; : `${publishingAll ? t("publish.stop") : t("publish.start")}`;
const themeClassName = `ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${
activeCustomTheme ? " ts-design-custom" : ""
}`;
/**
* Popped out and nothing focused: pick the column count that makes the 16:9
* tiles largest for this window, like Discord's grid.
*/
const popoutGridStyle = ((): React.CSSProperties => {
if (!streamPopout || focusedStream !== null) return {};
const pad = 16, gap = 8, header = 30; // px: grid padding, gap, tile header
const width = popoutSize.width - pad;
const height = popoutSize.height - pad;
let best = { cols: 1, tile: 0 };
for (let cols = 1; cols <= streamTileCount; cols++) {
const rows = Math.ceil(streamTileCount / cols);
const tile = Math.min(
(width - gap * (cols - 1)) / cols,
((height - gap * (rows - 1)) / rows - header) * (16 / 9),
);
if (tile > best.tile) best = { cols, tile };
}
return {
gridTemplateColumns: `repeat(${best.cols}, ${Math.max(160, Math.floor(best.tile))}px)`,
justifyContent: "center",
alignContent: "center",
minHeight: "100vh",
boxSizing: "border-box",
};
})();
const streamToggle = (id: string) => (
<>
<button
className="ts-stream-panel-close"
onClick={streamPopout ? closeStreamPopout : openStreamPopout}
title={t(streamPopout ? "stream.popin" : "stream.popout")}
>
{streamPopout ? "⇲" : "⧉"}
</button>
<button
className="ts-stream-panel-close"
onClick={() => setFocusedStream((cur) => (cur === id ? null : id))}
title={t(focusedStream === id ? "stream.unfocus" : "stream.focus")}
>
{focusedStream === id ? "⤡" : "⤢"}
</button>
</>
);
return ( return (
<DisplayPrefsContext.Provider value={displayPrefs}> <DisplayPrefsContext.Provider value={displayPrefs}>
<div <div
className={`ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${ className={`${themeClassName}${demoForceMobile ? " ts-force-mobile" : ""}${mobile ? ` ts-mobile ts-mobile-tab-${mobileTab}` : ""}${novaSplash ? " ts-nova-splash" : ""}${
activeCustomTheme ? " ts-design-custom" : ""
}${demoForceMobile ? " ts-force-mobile" : ""}${mobile ? ` ts-mobile ts-mobile-tab-${mobileTab}` : ""}${novaSplash ? " ts-nova-splash" : ""}${
designTheme === "ide" && !idePixelFont ? " ts-ide-plain-font" : "" designTheme === "ide" && !idePixelFont ? " ts-ide-plain-font" : ""
}`} }`}
data-custom-theme={activeCustomTheme?.id} data-custom-theme={activeCustomTheme?.id}
@@ -13594,16 +13863,16 @@ function AppInner() {
</label> </label>
)} )}
<button <button
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`} className={`ts-icon-button${activePublishes.length > 0 ? " ts-mic-on" : ""}`}
onClick={handleStreamButton} onClick={handleStreamButton}
// DemoSocket has no answer for setupstream, so in demo mode the // DemoSocket has no answer for setupstream, so in demo mode the
// panel would sit at "starting" forever - after the browser has // panel would sit at "starting" forever - after the browser has
// already asked the visitor to pick a screen. Don't offer it. // already asked the visitor to pick a screen. Don't offer it.
disabled={!connected || ownClientId === null || DEMO_MODE} disabled={!connected || ownClientId === null || DEMO_MODE || publishStarting}
title={streamLabel} title={streamLabel}
aria-label={streamLabel} aria-label={streamLabel}
> >
{publishState === "live" ? "🛑" : "🖥️"} {publishingAll ? "🛑" : "🖥️"}
</button> </button>
{TAB_AUDIO_SUPPORTED && ( {TAB_AUDIO_SUPPORTED && (
<button <button
@@ -13757,6 +14026,19 @@ function AppInner() {
</div> </div>
)} )}
{restartNotice && <RestartNoticeDialog message={restartNotice} onAck={() => setRestartNotice(null)} />} {restartNotice && <RestartNoticeDialog message={restartNotice} onAck={() => setRestartNotice(null)} />}
{idleCheckLeft !== null && (
<IdleCheckDialog
secondsLeft={idleCheckLeft}
onStay={() => {
lastActivityRef.current = Date.now();
sendActive();
setIdleCheckLeft(null);
}}
/>
)}
{idleDisconnected && (
<RestartNoticeDialog message={t("idleCheck.disconnected")} onAck={() => setIdleDisconnected(false)} />
)}
{aboutOpen && ( {aboutOpen && (
<AboutDialog <AboutDialog
@@ -14266,34 +14548,55 @@ function AppInner() {
{streamSettingsOpen && ( {streamSettingsOpen && (
<StreamSettingsDialog <StreamSettingsDialog
ownName={ownClient?.name ?? "WebSpeak3"} ownName={ownClient?.name ?? "WebSpeak3"}
// Offer the source that is not running yet, so the second start is camera after screen.
initialSource={publishersRef.current.has("display") ? "camera" : "display"}
onStart={handleStartPublishing} onStart={handleStartPublishing}
onCancel={() => setStreamSettingsOpen(false)} onCancel={() => setStreamSettingsOpen(false)}
/> />
)} )}
{(watchedStream || (publishState !== "idle" && publishState !== "stopped")) && ( {streamTileCount > 0 && (() => {
<div className="ts-stream-panels"> const grid = (
{publishState !== "idle" && publishState !== "stopped" && ( <div
<div className="ts-stream-panel ts-stream-panel-publish"> className={`ts-stream-panels${streamPopout ? " ts-stream-panels-popout" : ""}`}
style={{ "--stream-cols": Math.min(streamTileCount, 2), ...popoutGridStyle } as React.CSSProperties}
>
{activePublishes.map(([source, tile]) => {
const focusId = `publish-${source}`;
const publisher = publishersRef.current.get(source);
return (
<div
key={source}
className={`ts-stream-panel ts-stream-panel-publish${focusedStream === focusId ? " ts-stream-panel-focused" : ""}`}
>
<div className="ts-stream-panel-header"> <div className="ts-stream-panel-header">
<span className="ts-stream-panel-title"> <span className="ts-stream-panel-title">
🖥️ {t("publish.title")} <AlphaBadge /> {source === "camera" ? "📷" : "🖥️"} {t("publish.title")}
</span> </span>
<span className="ts-stream-panel-state"> <span className="ts-stream-panel-state">
{publishState === "live" {tile.state === "live"
? t("publish.viewers", { count: String(publishViewers.length) }) ? t("publish.viewers", { count: String(tile.viewers.length) })
: t("publish.starting")} : t("publish.starting")}
</span> </span>
{streamToggle(focusId)}
<button <button
className="ts-stream-panel-close" className="ts-stream-panel-close"
onClick={handleStopPublishing} onClick={() => handleStopPublishing(source)}
title={t("publish.stop")} title={t("publish.stop")}
> >
✕ ✕
</button> </button>
</div> </div>
{/* muted: this is our own capture playing back locally */} {/* muted: this is our own capture playing back locally */}
<video ref={publishPreviewRef} autoPlay playsInline muted /> <video
{publishPending.map(([clid, message]) => ( ref={(video) => {
const media = publisher?.previewStream ?? null;
if (video && video.srcObject !== media) video.srcObject = media;
}}
autoPlay
playsInline
muted
/>
{tile.pending.map(([clid, message]) => (
<div className="ts-stream-request" key={clid}> <div className="ts-stream-request" key={clid}>
<span className="ts-stream-request-who"> <span className="ts-stream-request-who">
{publishClientName(clid)} {publishClientName(clid)}
@@ -14301,49 +14604,76 @@ function AppInner() {
</span> </span>
<button <button
className="ts-stream-request-allow" className="ts-stream-request-allow"
onClick={() => void publisherRef.current?.approve(clid)} onClick={() => void publisher?.approve(clid)}
> >
{t("publish.request.allow")} {t("publish.request.allow")}
</button> </button>
<button onClick={() => publisherRef.current?.deny(clid)}> <button onClick={() => publisher?.deny(clid)}>
{t("publish.request.deny")} {t("publish.request.deny")}
</button> </button>
<button <button
className="ts-stream-request-block" className="ts-stream-request-block"
onClick={() => publisherRef.current?.deny(clid, true)} onClick={() => publisher?.deny(clid, true)}
title={t("publish.request.blockHint")} title={t("publish.request.blockHint")}
> >
{t("publish.request.block")} {t("publish.request.block")}
</button> </button>
</div> </div>
))} ))}
{publishError && <div className="ts-stream-panel-error">{publishError}</div>} {tile.error && <div className="ts-stream-panel-error">{tile.error}</div>}
</div> </div>
)} );
{watchedStream && ( })}
<div className="ts-stream-panel"> {Object.entries(watchedStreams).map(([streamId, watched]) => (
<div className={`ts-stream-panel${focusedStream === streamId ? " ts-stream-panel-focused" : ""}`} key={streamId}>
<div className="ts-stream-panel-header"> <div className="ts-stream-panel-header">
<span className="ts-stream-panel-title"> <span className="ts-stream-panel-title">
📺 {watchedStream.name || t("stream.untitled")} <AlphaBadge /> {streamIcon(watched.info)} {watched.info.name || t("stream.untitled")}
</span> </span>
<span className="ts-stream-panel-state"> <span className="ts-stream-panel-state">
{streamState === "connected" ? t("stream.live") : t(`stream.state.${streamState}`)} {watched.state === "connected" ? t("stream.live") : t(`stream.state.${watched.state}`)}
</span> </span>
{streamToggle(streamId)}
<button <button
className="ts-stream-panel-close" className="ts-stream-panel-close"
onClick={handleStopWatchingStream} onClick={() => handleStopWatchingStream(streamId)}
title={t("stream.stop")} title={t("stream.stop")}
> >
✕ ✕
</button> </button>
</div> </div>
{/* muted so autoplay is never blocked; the user unmutes via the controls */} {/* muted so autoplay is never blocked; the user unmutes via the controls */}
<video ref={streamVideoRef} autoPlay playsInline muted controls /> <video
{streamError && <div className="ts-stream-panel-error">{streamError}</div>} ref={(video) => {
if (video && video.srcObject !== watched.media) video.srcObject = watched.media;
}}
autoPlay
playsInline
muted
controls
/>
{watched.error && <div className="ts-stream-panel-error">{watched.error}</div>}
</div> </div>
)} ))}
{availableStreams.map((info) => (
<div className="ts-stream-panel" key={info.id}>
<div className="ts-stream-panel-header">
<span className="ts-stream-panel-title">
{streamIcon(info)} {info.name || t("stream.untitled")}
</span>
<span className="ts-stream-panel-state">{publishClientName(info.clientId)}</span>
</div> </div>
)} <button className="ts-stream-panel-watch" onClick={() => handleWatchStream(info.id)}>
▶ {t("stream.watch")}
</button>
</div>
))}
</div>
);
return streamPopout
? createPortal(<div className={`${themeClassName} ts-stream-popout-root`}>{grid}</div>, streamPopout.document.body)
: grid;
})()}
{clientContextMenu && ( {clientContextMenu && (
<div <div
ref={clientContextMenuRef} ref={clientContextMenuRef}
@@ -14410,18 +14740,22 @@ function AppInner() {
</label> </label>
); );
})()} })()}
{!clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && ( {!clientContextMenu.isSelf &&
(streamsByClient[clientContextMenu.clientId] ?? []).map((info) => (
<button <button
key={info.id}
className="ts-menu-item" className="ts-menu-item"
onClick={() => { onClick={() => {
handleWatchStream(clientContextMenu.clientId); handleWatchStream(info.id);
setClientContextMenu(null); setClientContextMenu(null);
}} }}
> >
<span className="ts-menu-item-icon">📺</span> <span className="ts-menu-item-icon">{streamIcon(info)}</span>
<span className="ts-menu-item-label">{t("clientContext.watchStream")}</span> <span className="ts-menu-item-label">
{t(info.camera ? "clientContext.watchCamera" : "clientContext.watchStream")}
</span>
</button> </button>
)} ))}
{!clientContextMenu.isSelf && ( {!clientContextMenu.isSelf && (
<button <button
className="ts-menu-item" className="ts-menu-item"
@@ -14713,6 +15047,7 @@ function AppInner() {
{treeSearch && treeSearch.channels.length === 0 && ( {treeSearch && treeSearch.channels.length === 0 && (
<div className="ts-tree-empty">{t("tree.noMatches")}</div> <div className="ts-tree-empty">{t("tree.noMatches")}</div>
)} )}
<StreamsContext.Provider value={{ byClient: streamsByClient, watch: handleWatchStream }}>
<ChannelTree <ChannelTree
channels={treeSearch?.channels ?? channels} channels={treeSearch?.channels ?? channels}
clients={treeSearch?.clients ?? treeClients} clients={treeSearch?.clients ?? treeClients}
@@ -14732,6 +15067,7 @@ function AppInner() {
onClientContextMenu={handleClientContextMenu} onClientContextMenu={handleClientContextMenu}
onChannelContextMenu={handleChannelContextMenu} onChannelContextMenu={handleChannelContextMenu}
/> />
</StreamsContext.Provider>
</> </>
) : ( ) : (
<div className="ts-tree-empty"> <div className="ts-tree-empty">
-3
View File
@@ -492,10 +492,7 @@
"tree.noTalkPower": "V tomto kanálu nemáte právo mluvit", "tree.noTalkPower": "V tomto kanálu nemáte právo mluvit",
"tree.soundMuted": "Zvuk ztlumen (ohluchnutí)", "tree.soundMuted": "Zvuk ztlumen (ohluchnutí)",
"tree.streaming": "Vysílá stream", "tree.streaming": "Vysílá stream",
"publish.alpha": "Alfa",
"publish.alphaTitle": "Alfa – nestabilní, může se kdykoli změnit nebo přestat fungovat",
"publish.demoUnavailable": "Streamování není v demu dostupné – vyžaduje skutečný server TeamSpeak 6.", "publish.demoUnavailable": "Streamování není v demu dostupné – vyžaduje skutečný server TeamSpeak 6.",
"publish.alphaNote": "Streamování je ve fázi alfa. Používá nezdokumentovaný protokol Stream/Call služby TeamSpeak 6, takže připojení, kvalita obrazu i práce s diváky mohou selhat nebo se bez upozornění změnit. Není určeno pro produkční použití.",
"publish.start": "Sdílet obrazovku nebo kameru", "publish.start": "Sdílet obrazovku nebo kameru",
"publish.stop": "Zastavit sdílení", "publish.stop": "Zastavit sdílení",
"publish.title": "Vaše vysílání", "publish.title": "Vaše vysílání",
+12 -4
View File
@@ -492,10 +492,7 @@
"tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel", "tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel",
"tree.soundMuted": "Ton stummgeschaltet (deafened)", "tree.soundMuted": "Ton stummgeschaltet (deafened)",
"tree.streaming": "Überträgt einen Stream", "tree.streaming": "Überträgt einen Stream",
"publish.alpha": "Alpha",
"publish.alphaTitle": "Alpha – instabil, kann sich jederzeit ändern oder brechen",
"publish.demoUnavailable": "Übertragen ist in der Demo nicht verfügbar – dafür braucht es einen echten TeamSpeak-6-Server.", "publish.demoUnavailable": "Übertragen ist in der Demo nicht verfügbar – dafür braucht es einen echten TeamSpeak-6-Server.",
"publish.alphaNote": "Streaming ist Alpha. Es spricht TeamSpeak 6s Stream/Call-Protokoll, das nicht dokumentiert ist – Verbindungsaufbau, Bildqualität und Zuschauerverwaltung können fehlschlagen oder sich ohne Vorankündigung ändern. Nicht für produktive Nutzung gedacht.",
"publish.start": "Bildschirm oder Kamera übertragen", "publish.start": "Bildschirm oder Kamera übertragen",
"publish.stop": "Übertragung beenden", "publish.stop": "Übertragung beenden",
"publish.title": "Deine Übertragung", "publish.title": "Deine Übertragung",
@@ -533,6 +530,13 @@
"publish.mode.server": "Server", "publish.mode.server": "Server",
"publish.mode.serverUnavailable": "Der Server-Modus läuft über TS6s SFU und ist noch nicht implementiert.", "publish.mode.serverUnavailable": "Der Server-Modus läuft über TS6s SFU und ist noch nicht implementiert.",
"stream.untitled": "Stream", "stream.untitled": "Stream",
"tree.streamingCamera": "Kamera",
"clientContext.watchCamera": "Kamera ansehen",
"stream.watch": "Ansehen",
"stream.popout": "In eigenem Fenster",
"stream.popin": "Zurück ins Hauptfenster",
"stream.focus": "Vergrößern",
"stream.unfocus": "Zurück zum Raster",
"stream.stop": "Stream schließen", "stream.stop": "Stream schließen",
"stream.live": "Live", "stream.live": "Live",
"stream.state.new": "Warte auf Angebot…", "stream.state.new": "Warte auf Angebot…",
@@ -1013,5 +1017,9 @@
"mobile.mic": "Mikro", "mobile.mic": "Mikro",
"mobile.sound": "Ton", "mobile.sound": "Ton",
"mobile.leave": "Trennen", "mobile.leave": "Trennen",
"mobile.talk": "Sprechen" "mobile.talk": "Sprechen",
"idleCheck.title": "Bist du noch da?",
"idleCheck.body": "Du hast eine Weile nichts im Client gemacht. Ohne Antwort wirst du in {seconds} s getrennt.",
"idleCheck.stay": "Ich bin noch da",
"idleCheck.disconnected": "Du wurdest getrennt, weil du auf „Bist du noch da?“ nicht geantwortet hast."
} }
+12 -4
View File
@@ -492,10 +492,7 @@
"tree.noTalkPower": "No talk power in this channel", "tree.noTalkPower": "No talk power in this channel",
"tree.soundMuted": "Sound muted (deafened)", "tree.soundMuted": "Sound muted (deafened)",
"tree.streaming": "Broadcasting a stream", "tree.streaming": "Broadcasting a stream",
"publish.alpha": "Alpha",
"publish.alphaTitle": "Alpha - unstable, may change or break at any time",
"publish.demoUnavailable": "Streaming is not available in the demo - it needs a real TeamSpeak 6 server.", "publish.demoUnavailable": "Streaming is not available in the demo - it needs a real TeamSpeak 6 server.",
"publish.alphaNote": "Streaming is alpha. It speaks TeamSpeak 6's undocumented Stream/Call protocol, so connecting, picture quality and viewer handling can fail or change without notice. Not meant for production use.",
"publish.start": "Share your screen or camera", "publish.start": "Share your screen or camera",
"publish.stop": "Stop sharing", "publish.stop": "Stop sharing",
"publish.title": "Your broadcast", "publish.title": "Your broadcast",
@@ -533,6 +530,13 @@
"publish.mode.server": "Server", "publish.mode.server": "Server",
"publish.mode.serverUnavailable": "Server mode goes through TS6's SFU and is not implemented yet.", "publish.mode.serverUnavailable": "Server mode goes through TS6's SFU and is not implemented yet.",
"stream.untitled": "Stream", "stream.untitled": "Stream",
"tree.streamingCamera": "Camera",
"clientContext.watchCamera": "Watch camera",
"stream.watch": "Watch",
"stream.popout": "Open in own window",
"stream.popin": "Back to main window",
"stream.focus": "Enlarge",
"stream.unfocus": "Back to grid",
"stream.stop": "Close stream", "stream.stop": "Close stream",
"stream.live": "Live", "stream.live": "Live",
"stream.state.new": "Waiting for offer…", "stream.state.new": "Waiting for offer…",
@@ -1013,5 +1017,9 @@
"mobile.mic": "Mic", "mobile.mic": "Mic",
"mobile.sound": "Sound", "mobile.sound": "Sound",
"mobile.leave": "Leave", "mobile.leave": "Leave",
"mobile.talk": "Talk" "mobile.talk": "Talk",
"idleCheck.title": "Are you still there?",
"idleCheck.body": "You haven't done anything in the client for a while. Without an answer you will be disconnected in {seconds} s.",
"idleCheck.stay": "I'm still here",
"idleCheck.disconnected": "You were disconnected because you didn't answer \"Are you still there?\"."
} }
-3
View File
@@ -491,10 +491,7 @@
"tree.noTalkPower": "در این کانال حق صحبت ندارد", "tree.noTalkPower": "در این کانال حق صحبت ندارد",
"tree.soundMuted": "صدا بی‌صدا (کر)", "tree.soundMuted": "صدا بی‌صدا (کر)",
"tree.streaming": "در حال پخش زنده", "tree.streaming": "در حال پخش زنده",
"publish.alpha": "آلفا",
"publish.alphaTitle": "آلفا - ناپایدار، ممکن است هر زمان تغییر کند یا از کار بیفتد",
"publish.demoUnavailable": "پخش زنده در حالت دمو در دسترس نیست - به یک سرور واقعی TeamSpeak 6 نیاز دارد.", "publish.demoUnavailable": "پخش زنده در حالت دمو در دسترس نیست - به یک سرور واقعی TeamSpeak 6 نیاز دارد.",
"publish.alphaNote": "پخش زنده در مرحله آلفا است. این ویژگی از پروتکل مستندنشده Stream/Call در TeamSpeak 6 استفاده می‌کند، بنابراین اتصال، کیفیت تصویر و مدیریت بینندگان ممکن است بدون اطلاع قبلی دچار خطا شوند یا تغییر کنند. برای استفاده تولیدی مناسب نیست.",
"publish.start": "اشتراک‌گذاری صفحه یا دوربین", "publish.start": "اشتراک‌گذاری صفحه یا دوربین",
"publish.stop": "توقف اشتراک‌گذاری", "publish.stop": "توقف اشتراک‌گذاری",
"publish.title": "پخش زنده تو", "publish.title": "پخش زنده تو",
-3
View File
@@ -492,10 +492,7 @@
"tree.noTalkPower": "Нет права голоса в этом канале", "tree.noTalkPower": "Нет права голоса в этом канале",
"tree.soundMuted": "Звук выключен", "tree.soundMuted": "Звук выключен",
"tree.streaming": "Ведёт трансляцию", "tree.streaming": "Ведёт трансляцию",
"publish.alpha": "Альфа",
"publish.alphaTitle": "Альфа - нестабильно, может измениться или сломаться в любой момент",
"publish.demoUnavailable": "Трансляция недоступна в демо - нужен настоящий сервер TeamSpeak 6.", "publish.demoUnavailable": "Трансляция недоступна в демо - нужен настоящий сервер TeamSpeak 6.",
"publish.alphaNote": "Трансляция находится в альфе. Она использует недокументированный протокол Stream/Call TeamSpeak 6, поэтому подключение, качество изображения и работа со зрителями могут сбоить или меняться без предупреждения. Не для рабочего использования.",
"publish.start": "Показать экран или камеру", "publish.start": "Показать экран или камеру",
"publish.stop": "Остановить показ", "publish.stop": "Остановить показ",
"publish.title": "Ваша трансляция", "publish.title": "Ваша трансляция",
-3
View File
@@ -705,10 +705,7 @@
"design.store.publish.error": "发布失败。", "design.store.publish.error": "发布失败。",
"recording.autoGainControl": "自动增益控制", "recording.autoGainControl": "自动增益控制",
"tree.streaming": "正在直播", "tree.streaming": "正在直播",
"publish.alpha": "内测",
"publish.alphaTitle": "内测阶段 —— 不稳定,可能随时变更或失效",
"publish.demoUnavailable": "演示模式下无法使用直播功能 —— 需要真实的 TeamSpeak 6 服务器。", "publish.demoUnavailable": "演示模式下无法使用直播功能 —— 需要真实的 TeamSpeak 6 服务器。",
"publish.alphaNote": "直播功能处于内测阶段,使用的是 TeamSpeak 6 未公开文档的 Stream/Call 协议,因此连接、画质和观众处理可能会出错或在无预警的情况下发生变化,不建议用于正式场合。",
"publish.start": "共享屏幕或摄像头", "publish.start": "共享屏幕或摄像头",
"publish.stop": "停止共享", "publish.stop": "停止共享",
"publish.title": "你的直播", "publish.title": "你的直播",
+30 -1
View File
@@ -22,8 +22,37 @@ const root = createRoot(document.getElementById('root')!)
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open // App reads its stored identities/favorites while loading, so it's imported only after the vault is open
// and the sync account (Options -> Konto) had its chance to bring in newer data. // and the sync account (Options -> Konto) had its chance to bring in newer data.
// After a deploy, a page (or the service worker cache) can still point at
// chunk files that no longer exist, which used to leave a black screen. One
// fresh load fixes that; the flag stops a reload loop if the server is broken.
const RELOAD_FLAG = 'ws3-chunk-reload'
function reloadOnceForStaleChunks(): boolean {
try {
if (sessionStorage.getItem(RELOAD_FLAG)) return false
sessionStorage.setItem(RELOAD_FLAG, '1')
} catch {
return false
}
location.reload()
return true
}
window.addEventListener('vite:preloadError', (event) => {
if (reloadOnceForStaleChunks()) event.preventDefault()
})
async function start() { async function start() {
const { default: App } = await import('./App.tsx') let App: typeof import('./App.tsx').default
try {
;({ default: App } = await import('./App.tsx'))
} catch (error) {
if (reloadOnceForStaleChunks()) return
throw error
}
try {
sessionStorage.removeItem(RELOAD_FLAG)
} catch {
// storage blocked - nothing to clear
}
startAutoSync() startAutoSync()
root.render( root.render(
<StrictMode> <StrictMode>
+9 -1
View File
@@ -176,7 +176,15 @@ export class StreamPublisher {
case "notifystreamstarted": case "notifystreamstarted":
// Everyone in the channel sees this, so the clid decides whether it // Everyone in the channel sees this, so the clid decides whether it
// is the answer to our own setupstream. // is the answer to our own setupstream.
if (Number(event.args.clid) === this.opts.ownClientId && event.args.id) { // Several publishers can run at once (screen + camera), so only one
// still waiting for its own id takes it; the app starts them one at
// a time so this is never ambiguous.
if (
this.state === "starting" &&
this.streamId === null &&
Number(event.args.clid) === this.opts.ownClientId &&
event.args.id
) {
this.streamId = event.args.id; this.streamId = event.args.id;
this.setState("live"); this.setState("live");
} }
+3
View File
@@ -43,6 +43,8 @@ export interface StreamInfo {
viewers: number; viewers: number;
hasAudio: boolean; hasAudio: boolean;
bitrate: number; bitrate: number;
/** `type` 1 (CAMERA) vs. screen/window; undefined when the notify left it out. */
camera?: boolean;
} }
export interface StreamViewerOptions { export interface StreamViewerOptions {
@@ -86,6 +88,7 @@ export function parseStreamInfo(args: Record<string, string>): StreamInfo | null
viewers: Number(args.viewer ?? 0) || 0, viewers: Number(args.viewer ?? 0) || 0,
hasAudio: args.audio === "1", hasAudio: args.audio === "1",
bitrate: Number(args.bitrate ?? 0) || 0, bitrate: Number(args.bitrate ?? 0) || 0,
camera: args.type === undefined ? undefined : args.type === "1",
}; };
} }