Compare commits

..
20 Commits
Author SHA1 Message Date
MoepchiandClaude Opus 5.5 70423d0114 docs: README/roadmap catch up with streaming, languages, sync and idle check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-12-02 08:26:33 +00:00
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
MoepchiandClaude Opus 5.5 ab588f5ca2 Gateway: test admin login, 2FA and password changes
npm test builds the gateway and runs it on a free port in a temp dir.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:17:53 +00:00
MoepchiandClaude Opus 5.5 1a13c54b72 Admin panel: clearer 2FA setup steps and success notice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:11:00 +00:00
MoepchiandClaude Opus 5.5 3f69692d79 Add admin panel for live gateway settings
/admin (enabled by ADMIN_USER + ADMIN_PASSWORD) lets self-hosters change
most .env settings at runtime. Overrides live in ADMIN_CONFIG_FILE and are
written onto process.env, so the modules now read their settings at use
time instead of at load time.

- Sidebar navigation with search, DE/EN, light/dark, phone layout
- "Restart required" group (PORT, TLS, paths, WEB_STATIC) plus a restart
  button that goes through the graceful SIGTERM path
- Status line: version, uptime, connected users
- Optional TOTP 2FA: QR setup, code check, switch on/off in the panel
- Password change in the panel (scrypt hash in ADMIN_AUTH_FILE); every
  credential change re-asks the current password; deleting the file
  falls back to .env
- Login rate limits, CSRF header, HttpOnly/SameSite session cookie, CSP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 11:40:33 +00:00
32 changed files with 2009 additions and 335 deletions

No files matched your search

+10 -3
View File
@@ -95,14 +95,16 @@ not need to be installed on the same machine, modified, or operated by you.
| 👉 **Poke & away status** | Poke clients with an optional message; set yourself away with presets or a custom status | | 👉 **Poke & away status** | Poke clients with an optional message; set yourself away with presets or a custom status |
| ⭐ **Favorites & reconnect** | Remembers your last server/nickname; switch servers without leaving your tab | | ⭐ **Favorites & reconnect** | Remembers your last server/nickname; switch servers without leaving your tab |
| 📱 **Mobile-friendly layout** | Responsive single-column layout for narrow screens, not just a shrunk desktop UI | | 📱 **Mobile-friendly layout** | Responsive single-column layout for narrow screens, not just a shrunk desktop UI |
| 🌍 **Localized UI** | Interface available in German, English, Simplified Chinese, and Persian (Beta), detected automatically or switchable in Options | | 🌍 **Localized UI** | Interface available in German, English, Czech, Simplified Chinese, Persian (Beta), and Russian (Beta), detected automatically or switchable in Options |
| 🌗 **Dark / light theme** | Clean, modern UI that adapts to your preference | | 🌗 **Themes & Design Store** | Dark and light mode, plus community designs you can browse, install, or upload from the built-in Design Store |
| ☁️ **Account sync** | Carry identities, favorites, settings and designs to your other devices. No email, no name, end-to-end encrypted in the browser |
| 💤 **"Are you still there?"** | Optional idle check: after a gateway-set time without input the client asks, and disconnects if nobody answers (`IDLE_TIMEOUT_MINUTES`) |
| 🔁 **Multi-join (server tabs)** | Several connections in parallel — one tab per server, like VoySpeak. Audio stays on the active tab | | 🔁 **Multi-join (server tabs)** | Several connections in parallel — one tab per server, like VoySpeak. Audio stays on the active tab |
| 🔁 **Seamless reconnect** | Switch or add connections mid-session without tearing down unrelated tabs; dropped connections come back on their own, with the channel tree intact | | 🔁 **Seamless reconnect** | Switch or add connections mid-session without tearing down unrelated tabs; dropped connections come back on their own, with the channel tree intact |
| ⌨️ **Keyboard & screen readers** | Arrow keys through the channel tree (exposed as an ARIA tree) and through menus, Enter joins, context-menu key opens the menu; focus-trapped dialogs, labelled toolbar buttons | | ⌨️ **Keyboard & screen readers** | Arrow keys through the channel tree (exposed as an ARIA tree) and through menus, Enter joins, context-menu key opens the menu; focus-trapped dialogs, labelled toolbar buttons |
| 🍵 **VoySpeak support** | Connects to real VoySpeak servers (formerly GreenTeaSpeak), not just TS3/TS6/TeaSpeak | | 🍵 **VoySpeak support** | Connects to real VoySpeak servers (formerly GreenTeaSpeak), not just TS3/TS6/TeaSpeak |
| 📟 **TeamSpeak 2** | <sub>**EXPERIMENTAL**</sub> Voice, channels, private messages and server messages on old TS2 servers. Registered accounts work too, and the server type "Auto" detects TS2 on its own. Off by default, the gateway enables it with `ENABLE_TS2=1` | | 📟 **TeamSpeak 2** | <sub>**EXPERIMENTAL**</sub> Voice, channels, private messages and server messages on old TS2 servers. Registered accounts work too, and the server type "Auto" detects TS2 on its own. Off by default, the gateway enables it with `ENABLE_TS2=1` |
| 🖥️ **Screen streaming to/from TS6** | <sub>**ALPHA · UNSTABLE**</sub> Share your screen to native TeamSpeak 6 clients and watch theirs. Built on TS6's undocumented Stream/Call protocol — expect it to break; see [Roadmap](ROADMAP.md) | | 🖥️ **Screen & camera streaming with TS6** | Share your screen and camera (also both at once) with native TeamSpeak 6 clients and watch theirs. Watch several streams in a grid, focus one, or pop them out into their own window. Streams show up as tiles and as clickable icons in the channel tree. Built on TS6's undocumented Stream/Call protocol, so a TS6 update can still break it; see [Roadmap](ROADMAP.md) |
## 🧱 Tech Stack ## 🧱 Tech Stack
@@ -232,6 +234,10 @@ All optional; add them under `environment:` in your compose override next to `PO
| `WEB_DIST` | `web/dist` next to the gateway | Overrides the directory served when `WEB_STATIC` is on. Only needed for non-standard layouts. | | `WEB_DIST` | `web/dist` next to the gateway | Overrides the directory served when `WEB_STATIC` is on. Only needed for non-standard layouts. |
| `DEFAULT_SERVER` / `DEFAULT_CHANNEL` | unset | Server (and optionally channel) every visitor auto-connects to — see [Bake in a default server](#2-bake-in-a-default-server). | | `DEFAULT_SERVER` / `DEFAULT_CHANNEL` | unset | Server (and optionally channel) every visitor auto-connects to — see [Bake in a default server](#2-bake-in-a-default-server). |
| `BROADCAST_TOKEN` | unset | Bearer token required to call `/api/broadcast` (send an in-app notice to all connected clients before a maintenance restart). Endpoint 404s while unset. | | `BROADCAST_TOKEN` | unset | Bearer token required to call `/api/broadcast` (send an in-app notice to all connected clients before a maintenance restart). Endpoint 404s while unset. |
| `ADMIN_USER` / `ADMIN_PASSWORD` | unset | Enables the admin panel at `/admin` (works with `WEB_STATIC=0` too). Most settings in this table can be changed there without a restart (limits, access lists, connect dialog, features, feedback, store, news ticker, Turnstile, TURN, tokens); the ones read at startup (`PORT`, TLS, file paths, `WEB_STATIC`) are saved and applied by the panel's restart button, which relies on your restart policy (`restart: unless-stopped`) to bring the gateway back. Secrets are write-only. The panel also shows version, uptime and connected users, and can change the password (stored as an scrypt hash in `ADMIN_AUTH_FILE`; `ADMIN_PASSWORD` is then ignored). 5 login attempts per IP per 15 minutes. Without both variables `/admin` 404s. Not settable from the panel on purpose: `CONNECTOR_BIN`, `ALLOW_PRIVATE_TARGETS` and `ADMIN_USER`. |
| `ADMIN_TOTP_SECRET` | unset | Optional base32 secret: the admin login then also asks for a 6-digit authenticator code (Google Authenticator, Aegis, 2FAS, ...). Easier: switch 2FA on in the panel, which shows a QR code, checks a code from your app and asks for your password before activating. Switching it off there needs a current code. |
| `ADMIN_CONFIG_FILE` | `./admin-config.json` | Where panel changes are stored; they override `.env`. Put it on a volume (e.g. `/data/admin-config.json`) so it survives container recreation. |
| `ADMIN_AUTH_FILE` | `admin-auth.json` next to `ADMIN_CONFIG_FILE` | Password hash and 2FA secret set in the panel; they override `.env`. **Locked out?** Delete this file (and remove a bad `PORT` from `admin-config.json` if the panel is unreachable), then restart: `ADMIN_PASSWORD`/`ADMIN_TOTP_SECRET` from `.env` apply again. |
| `TLS_CERT` / `TLS_KEY` | unset | Paths to serve the gateway over HTTPS/WSS directly instead of behind a reverse proxy/tunnel. Both must be set together. | | `TLS_CERT` / `TLS_KEY` | unset | Paths to serve the gateway over HTTPS/WSS directly instead of behind a reverse proxy/tunnel. Both must be set together. |
| `STORE_ENABLED` | off | Set to `1` to turn this gateway's own `/api/store/themes` endpoint on. Only needed if you want to run your own Design Store instead of using the maintainer's shared one (see `STORE_URL` build arg above) — the endpoint 404s while unset. The store can also run as its own process (`node dist/store-server.js`, same image) so redeploying it never drops voice connections; route `/api/store/*` to it in your reverse proxy. | | `STORE_ENABLED` | off | Set to `1` to turn this gateway's own `/api/store/themes` endpoint on. Only needed if you want to run your own Design Store instead of using the maintainer's shared one (see `STORE_URL` build arg above) — the endpoint 404s while unset. The store can also run as its own process (`node dist/store-server.js`, same image) so redeploying it never drops voice connections; route `/api/store/*` to it in your reverse proxy. |
| `STORE_DATA_FILE` | `store-themes.json` in the container's working dir | Where submitted themes (including screenshots) are stored. Mount a volume over this path if they should survive a container recreate. | | `STORE_DATA_FILE` | `store-themes.json` in the container's working dir | Where submitted themes (including screenshots) are stored. Mount a volume over this path if they should survive a container recreate. |
@@ -244,6 +250,7 @@ All optional; add them under `environment:` in your compose override next to `PO
| `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. | | `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. |
| `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `60` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. | | `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `60` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. |
| `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | *(unset)* | Optional [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/) bot check before connecting. With both set, a browser solves the (usually invisible) check once and gets a pass bound to its IP for 12 h. Keeps scripts from opening TeamSpeak connections through your gateway. | | `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | *(unset)* | Optional [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/) bot check before connecting. With both set, a browser solves the (usually invisible) check once and gets a pass bound to its IP for 12 h. Keeps scripts from opening TeamSpeak connections through your gateway. |
| `IDLE_TIMEOUT_MINUTES` | `0` (off) | Minutes without input after which the client asks "Are you still there?". No answer within 60 s disconnects; the gateway also closes connections that stop reporting activity. Changeable live in the admin panel (applies to new connections). |
| `CONNECT_RATE_LIMIT` | `30` | Server connects per client IP per minute. Each one starts a new TeamSpeak session, so this stops anyone from flooding a server through your gateway. `0` disables it. | | `CONNECT_RATE_LIMIT` | `30` | Server connects per client IP per minute. Each one starts a new TeamSpeak session, so this stops anyone from flooding a server through your gateway. `0` disables it. |
| `TRUST_PROXY` | off | Only when the gateway is reachable **solely** through a proxy/tunnel, so per-IP limits see the real client instead of the proxy: `cloudflare` (Cloudflare Tunnel or proxy) uses `CF-Connecting-IP`; `1` (your own nginx/Caddy/Traefik) uses the last `X-Forwarded-For` entry, the one your proxy appended. Don't set it on a directly exposed gateway - clients could then fake their IP. | | `TRUST_PROXY` | off | Only when the gateway is reachable **solely** through a proxy/tunnel, so per-IP limits see the real client instead of the proxy: `cloudflare` (Cloudflare Tunnel or proxy) uses `CF-Connecting-IP`; `1` (your own nginx/Caddy/Traefik) uses the last `X-Forwarded-For` entry, the one your proxy appended. Don't set it on a directly exposed gateway - clients could then fake their IP. |
| `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). | | `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). |
+6 -6
View File
@@ -17,17 +17,17 @@ This roadmap is intentionally outcome-focused. It does not promise fixed dates.
- File transfers, local session recording, sound packs, and administration tools - File transfers, local session recording, sound packs, and administration tools
- Design Store: browse, upload, rate, and download community-made themes - Design Store: browse, upload, rate, and download community-made themes
- Opt-in WASM AEC3 echo cancellation for speaker+mic setups - Opt-in WASM AEC3 echo cancellation for speaker+mic setups
- Responsive desktop and mobile interfaces in German, English, Simplified Chinese, and Persian (Beta) - Responsive desktop and mobile interfaces in German, English, Czech, Simplified Chinese, Persian (Beta), and Russian (Beta)
- Docker image and Compose-based self-hosting - Docker image and Compose-based self-hosting
## Experimental or still being validated ## Experimental or still being validated
- **Screen streaming to and from TeamSpeak 6 (alpha, unstable).** WebSpeak3 can - **Screen and camera streaming with TeamSpeak 6.** WebSpeak3 can publish a
publish a screen share that a native TS6 client can watch, and watch a stream screen share and a camera (also both at once) that native TS6 clients can
a TS6 client publishes. It speaks TS6's Stream/Call protocol, which TeamSpeak watch, and watch several TS6 streams at once in a grid or a pop-out window. It speaks TS6's Stream/Call protocol, which TeamSpeak
does not document, so the wire format was derived from observed behavior and does not document, so the wire format was derived from observed behavior and
may break with any TS6 update. Connection setup, picture quality, and viewer may break with any TS6 update. Connection setup and picture quality can still
admission are not yet dependable. The "Server" connection mode (TS6's SFU) is vary with network conditions. The "Server" connection mode (TS6's SFU) is
not implemented; only direct P2P works. Streaming needs a gateway from v0.11.0-beta.1 not implemented; only direct P2P works. Streaming needs a gateway from v0.11.0-beta.1
on; since v0.15 the gateway announces its features when the browser connects, on; since v0.15 the gateway announces its features when the browser connects,
so newer features stay hidden behind an older gateway instead of hanging. so newer features stay hidden behind an older gateway instead of hanging.
+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);
+7
View File
@@ -8,6 +8,7 @@
"name": "webspeak3-gateway", "name": "webspeak3-gateway",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"qrcode-generator": "^1.4.4",
"ws": "^8.18.0" "ws": "^8.18.0"
}, },
"devDependencies": { "devDependencies": {
@@ -536,6 +537,12 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0" "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
} }
}, },
"node_modules/qrcode-generator": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.4.4.tgz",
"integrity": "sha512-HM7yY8O2ilqhmULxGMpcHSF1EhJJ9yBj8gvDEuZ6M+KGJ0YY2hKpnXvRD+hZPLrDVck3ExIGhmPtSdcjC+guuw==",
"license": "MIT"
},
"node_modules/tsx": { "node_modules/tsx": {
"version": "4.23.1", "version": "4.23.1",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",
+3 -1
View File
@@ -7,9 +7,11 @@
"scripts": { "scripts": {
"dev": "tsx watch src/index.ts", "dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json", "build": "tsc -p tsconfig.json",
"start": "node dist/index.js" "start": "node dist/index.js",
"test": "tsc -p tsconfig.json && node --test \"test/*.test.mjs\""
}, },
"dependencies": { "dependencies": {
"qrcode-generator": "^1.4.4",
"ws": "^8.18.0" "ws": "^8.18.0"
}, },
"devDependencies": { "devDependencies": {
+1 -2
View File
@@ -51,7 +51,6 @@ export async function logFeedback(entry: FeedbackEntry): Promise<void> {
// and other instances shouldn't get connection logging just because it's in // and other instances shouldn't get connection logging just because it's in
// the codebase. Set LOG_CONNECTIONS=1 in the .env of the instance you want it // the codebase. Set LOG_CONNECTIONS=1 in the .env of the instance you want it
// on. Logs only host/server-name/timestamp — no nickname, no IP. // on. Logs only host/server-name/timestamp — no nickname, no IP.
export const LOG_CONNECTIONS = process.env.LOG_CONNECTIONS === "1";
export interface ConnectionEvent { export interface ConnectionEvent {
type: "connected" | "disconnected"; type: "connected" | "disconnected";
@@ -60,7 +59,7 @@ export interface ConnectionEvent {
} }
export function logConnectionEvent(event: ConnectionEvent): void { export function logConnectionEvent(event: ConnectionEvent): void {
if (!LOG_CONNECTIONS) return; if (process.env.LOG_CONNECTIONS !== "1") return;
if (event.type === "connected") { if (event.type === "connected") {
console.log(`[connections] connected host=${event.host} server=${event.server} at=${new Date().toISOString()}`); console.log(`[connections] connected host=${event.host} server=${event.server} at=${new Date().toISOString()}`);
} else { } else {
+688
View File
@@ -0,0 +1,688 @@
// Admin panel at /admin: change the live settings from config.ts in the
// browser. Off unless both ADMIN_USER and ADMIN_PASSWORD are set (404
// otherwise). Optional ADMIN_TOTP_SECRET (base32) adds a 6-digit
// authenticator code to the login.
//
// The panel can also change the password and switch 2FA on or off. Those
// land in ADMIN_AUTH_FILE (next to the settings file) and override .env;
// every such change asks for the current password again, so a stolen session
// alone can't lock the operator out. Deleting that file goes back to .env.
import type { IncomingMessage, ServerResponse } from "node:http";
import type { TLSSocket } from "node:tls";
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { readFileSync } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import qrcode from "qrcode-generator";
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
import { describeSettings, updateSettings, validate } from "./config.js";
const ADMIN_USER = process.env.ADMIN_USER ?? "";
const ENV_PASSWORD = process.env.ADMIN_PASSWORD ?? "";
const ENV_TOTP = (process.env.ADMIN_TOTP_SECRET ?? "").replace(/[\s=]/g, "").toUpperCase();
export const ADMIN_ENABLED = ADMIN_USER !== "" && ENV_PASSWORD !== "";
const AUTH_FILE = process.env.ADMIN_AUTH_FILE
?? path.join(path.dirname(process.env.ADMIN_CONFIG_FILE ?? path.resolve(process.cwd(), "admin-config.json")), "admin-auth.json");
// Set from the panel. totpSecret "" = 2FA switched off there (wins over .env).
let auth: { passwordHash?: string; totpSecret?: string } = {};
try {
const raw = JSON.parse(readFileSync(AUTH_FILE, "utf8"));
if (typeof raw?.passwordHash === "string") auth.passwordHash = raw.passwordHash;
if (typeof raw?.totpSecret === "string") auth.totpSecret = raw.totpSecret;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`[admin] Ignoring unreadable ${AUTH_FILE}:`, err);
}
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
async function saveAuth(next: typeof auth) {
await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
auth = next;
}
const scryptAsync = promisify(scrypt) as (pw: string, salt: Buffer, len: number) => Promise<Buffer>;
async function hashPassword(pw: string): Promise<string> {
const salt = randomBytes(16);
return `scrypt$${salt.toString("base64url")}$${(await scryptAsync(pw, salt, 32)).toString("base64url")}`;
}
async function passwordOk(pw: string): Promise<boolean> {
if (!auth.passwordHash) return sameString(pw, ENV_PASSWORD);
const [, salt = "", hash = ""] = auth.passwordHash.split("$");
const want = Buffer.from(hash, "base64url");
const got = await scryptAsync(pw, Buffer.from(salt, "base64url"), 32);
return want.length === got.length && timingSafeEqual(want, got);
}
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
const COOKIE = "webspeak3_admin";
const sessions = new Map<string, number>(); // token -> expiry
// Every attempt counts, so a right guess can't be hidden between wrong ones.
const tooManyFromIp = createRateLimiter(5, 15 * 60_000);
const tooManyOverall = createRateLimiter(30, 15 * 60_000);
const tooManyReauth = createRateLimiter(10, 15 * 60_000);
let lastTotpCounter = -1; // a code works once, even within its window
const sha256 = (s: string) => createHash("sha256").update(s).digest();
const sameString = (a: string, b: string) => timingSafeEqual(sha256(a), sha256(b));
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
function base32Decode(s: string): Buffer {
let bits = 0, value = 0;
const out: number[] = [];
for (const c of s) {
const i = B32.indexOf(c);
if (i === -1) throw new Error("invalid base32");
value = (value << 5) | i;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 0xff);
bits -= 8;
}
}
return Buffer.from(out);
}
function base32Encode(buf: Buffer): string {
let bits = 0, value = 0, out = "";
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += B32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
return bits > 0 ? out + B32[(value << (5 - bits)) & 31] : out;
}
/** RFC 6238 code (SHA-1, 6 digits, 30 s) for a given time step. */
export function totp(secret: Buffer, counter: number): string {
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(counter));
const h = createHmac("sha1", secret).update(msg).digest();
const o = h[h.length - 1] & 0xf;
return String((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).padStart(6, "0");
}
/** Accepts the current code and one step either side (clock drift). */
/** Time step the code matches (±1 step of clock drift, only steps after `after`), or -1. */
function matchTotp(secretB32: string, code: unknown, after = -1): number {
if (typeof code !== "string" || !/^\d{6}$/.test(code)) return -1;
const secret = base32Decode(secretB32);
const now = Math.floor(Date.now() / 30_000);
for (const c of [now - 1, now, now + 1]) {
if (c > after && sameString(totp(secret, c), code)) return c;
}
return -1;
}
function checkTotp(code: unknown): boolean {
const c = matchTotp(totpSecret(), code, lastTotpCounter);
if (c < 0) return false;
lastTotpCounter = c;
return true;
}
if (ADMIN_ENABLED && totpSecret()) {
try {
if (base32Decode(totpSecret()).length < 10) throw new Error("too short");
} catch (err) {
// Fail closed: a typo here must not silently drop the second factor.
console.error(`[admin] ADMIN_TOTP_SECRET is not valid base32 (${(err as Error).message}); login disabled`);
}
}
function json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}) {
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers });
res.end(JSON.stringify(body));
}
async function readJson(req: IncomingMessage): Promise<Record<string, unknown> | undefined> {
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return undefined;
let size = 0;
const chunks: Buffer[] = [];
for await (const chunk of req) {
size += (chunk as Buffer).length;
if (size > 64 * 1024) return undefined;
chunks.push(chunk as Buffer);
}
try {
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
return v && typeof v === "object" && !Array.isArray(v) ? v : undefined;
} catch {
return undefined;
}
}
function sessionOf(req: IncomingMessage): string | undefined {
const m = new RegExp(`(?:^|;\\s*)${COOKIE}=([A-Za-z0-9_-]+)`).exec(req.headers.cookie ?? "");
if (!m) return undefined;
const expires = sessions.get(m[1]);
if (!expires || expires < Date.now()) {
sessions.delete(m[1]);
return undefined;
}
return m[1];
}
function cookie(req: IncomingMessage, value: string, maxAgeS: number): string {
// Secure only where the browser actually talks HTTPS, else a plain-HTTP
// LAN setup could never log in.
const https = (req.socket as TLSSocket).encrypted || req.headers["x-forwarded-proto"] === "https";
return `${COOKIE}=${value}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeS}${https ? "; Secure" : ""}`;
}
async function handleLogin(req: IncomingMessage, res: ServerResponse) {
const ip = clientIp(req);
if (tooManyFromIp(ip) || tooManyOverall("all")) {
console.warn("[admin] login rate-limited");
return json(res, 429, { error: "rate_limited" });
}
const body = await readJson(req);
const userOk = sameString(String(body?.user ?? ""), ADMIN_USER);
const passOk = await passwordOk(String(body?.password ?? ""));
// The code is only used up by a fully successful login, so a password typo
// doesn't burn it.
let step = -1;
if (totpSecret()) {
try {
step = matchTotp(totpSecret(), body?.code, lastTotpCounter);
} catch {
step = -1;
}
}
if (!(userOk && passOk && (step >= 0 || !totpSecret()))) {
console.warn("[admin] failed login");
return json(res, 401, { error: "invalid_login" });
}
if (step >= 0) lastTotpCounter = step;
const token = randomBytes(32).toString("base64url");
sessions.set(token, Date.now() + SESSION_TTL_MS);
for (const [t, exp] of sessions) if (exp < Date.now()) sessions.delete(t);
console.log("[admin] login");
json(res, 200, { ok: true }, { "Set-Cookie": cookie(req, token, SESSION_TTL_MS / 1000) });
}
let countConnections = () => 0;
/** index.ts hands in its WebSocket server's client count (shown before a restart). */
export function setConnectionCounter(fn: () => number) {
countConnections = fn;
}
const state = () => ({
settings: describeSettings(),
totp: totpSecret() ? (auth.totpSecret ? "panel" : "env") : "",
passwordFromPanel: Boolean(auth.passwordHash),
connections: countConnections(),
version: process.env.WEBSPEAK3_VERSION || "",
uptime: Math.round(process.uptime()),
});
// Credential changes re-check the current password (own limiter, so a few
// panel actions don't eat the login budget).
async function reauth(req: IncomingMessage, res: ServerResponse, body: Record<string, unknown> | undefined): Promise<boolean> {
if (tooManyReauth(clientIp(req))) return json(res, 429, { error: "rate_limited" }), false;
if (!(await passwordOk(String(body?.password ?? "")))) {
console.warn("[admin] wrong password on credential change");
return json(res, 403, { error: "wrong_password" }), false;
}
return true;
}
export async function handleAdmin(req: IncomingMessage, res: ServerResponse, pathname: string) {
if (!ADMIN_ENABLED) return json(res, 404, { error: "not_found" });
if (pathname === "/admin" || pathname === "/admin/") {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
"X-Frame-Options": "DENY",
});
return res.end(PAGE);
}
if (pathname === "/admin/admin.js") {
res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store" });
return res.end(SCRIPT);
}
if (req.method !== "GET" && req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
// Cross-site requests can't set this header without a CORS preflight,
// which this endpoint never grants: CSRF protection on top of SameSite.
if (req.method === "POST" && req.headers["x-webspeak3-admin"] !== "1") return json(res, 403, { error: "forbidden" });
if (pathname === "/admin/api/login" && req.method === "POST") return handleLogin(req, res);
const session = sessionOf(req);
if (!session) return json(res, 401, { error: "unauthorized" });
if (pathname === "/admin/api/logout" && req.method === "POST") {
sessions.delete(session);
return json(res, 200, { ok: true }, { "Set-Cookie": cookie(req, "", 0) });
}
if (pathname === "/admin/api/config" && req.method === "GET") return json(res, 200, state());
if (pathname === "/admin/api/restart" && req.method === "POST") {
console.log(`[admin] restart requested (${countConnections()} connected)`);
json(res, 200, { ok: true });
// Same graceful path as `docker stop`: users get the restart notice, TS
// sessions are closed. Coming back up is the supervisor's job (Docker's
// restart policy, systemd Restart=always).
setTimeout(() => process.kill(process.pid, "SIGTERM"), 300);
return;
}
if (pathname === "/admin/api/config" && req.method === "POST") {
const body = await readJson(req);
const changes = body?.changes;
if (!changes || typeof changes !== "object" || Array.isArray(changes)) return json(res, 400, { error: "bad_request" });
const clean: Record<string, string | null> = {};
for (const [key, value] of Object.entries(changes)) {
if (value !== null && typeof value !== "string") return json(res, 400, { error: "bad_request", key });
// null = reset to .env; then only the key itself has to be known.
const err = value === null ? (validate(key, "") === "unknown setting" ? "unknown setting" : undefined) : validate(key, value.trim());
if (err) return json(res, 400, { error: err, key });
clean[key] = value === null ? null : value.trim();
}
await updateSettings(clean);
console.log(`[admin] settings changed: ${Object.keys(clean).join(", ")}`);
return json(res, 200, state());
}
if (pathname === "/admin/api/totp-secret" && req.method === "GET") {
const secret = base32Encode(randomBytes(20));
const label = encodeURIComponent(`WebSpeak3:${ADMIN_USER}`);
const uri = `otpauth://totp/${label}?secret=${secret}&issuer=WebSpeak3`;
const qr = qrcode(0, "M");
qr.addData(uri);
qr.make();
return json(res, 200, { secret, uri, qr: qr.createDataURL(5, 4) });
}
// Setup check: does the authenticator app produce codes for the secret
// just generated? Only then the panel shows the .env line.
if (pathname === "/admin/api/totp-verify" && req.method === "POST") {
const body = await readJson(req);
const secret = String(body?.secret ?? "");
if (!/^[A-Z2-7]{16,64}$/.test(secret)) return json(res, 400, { error: "bad_request" });
return json(res, 200, { ok: matchTotp(secret, String(body?.code ?? "").trim()) >= 0 });
}
if (pathname === "/admin/api/totp-enable" && req.method === "POST") {
const body = await readJson(req);
const secret = String(body?.secret ?? "");
if (!/^[A-Z2-7]{16,64}$/.test(secret)) return json(res, 400, { error: "bad_request" });
if (!(await reauth(req, res, body))) return;
const c = matchTotp(secret, String(body?.code ?? "").trim());
if (c < 0) return json(res, 400, { error: "code_wrong" });
await saveAuth({ ...auth, totpSecret: secret });
lastTotpCounter = c; // the code just typed can't be replayed at login
console.log("[admin] 2FA switched on in the panel");
return json(res, 200, state());
}
if (pathname === "/admin/api/totp-disable" && req.method === "POST") {
const body = await readJson(req);
if (!(await reauth(req, res, body))) return;
if (!checkTotp(String(body?.code ?? "").trim())) return json(res, 400, { error: "code_wrong" });
await saveAuth({ ...auth, totpSecret: "" });
console.log("[admin] 2FA switched off in the panel");
return json(res, 200, state());
}
if (pathname === "/admin/api/password" && req.method === "POST") {
const body = await readJson(req);
const next = String(body?.newPassword ?? "");
if (next.length < 10 || next.length > 200) return json(res, 400, { error: "weak_password" });
if (!(await reauth(req, res, body))) return;
await saveAuth({ ...auth, passwordHash: await hashPassword(next) });
for (const t of sessions.keys()) if (t !== session) sessions.delete(t); // other logins end
console.log("[admin] password changed in the panel");
return json(res, 200, state());
}
json(res, 404, { error: "not_found" });
}
const PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
<title>WebSpeak3 Admin</title><style>
:root{color-scheme:light;--bg:#f4f6f8;--card:#fff;--fg:#1b1f24;--muted:#5f6b7a;--line:#dde2e8;--field:#f7f9fb;--accent:#2f6fde;--on-accent:#fff;--bad:#c0392b;--warn:#a86200;--ok:#1e7f43}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){color-scheme:dark;--bg:#131619;--card:#1c2025;--fg:#e6e9ed;--muted:#97a1ad;--line:#2f363e;--field:#15191d;--accent:#6a9cff;--on-accent:#0b1426;--bad:#ff6b5b;--warn:#f0b35a;--ok:#5cc98a}}
:root[data-theme="dark"]{color-scheme:dark;--bg:#131619;--card:#1c2025;--fg:#e6e9ed;--muted:#97a1ad;--line:#2f363e;--field:#15191d;--accent:#6a9cff;--on-accent:#0b1426;--bad:#ff6b5b;--warn:#f0b35a;--ok:#5cc98a}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.45 system-ui,sans-serif}
main{max-width:1320px;margin:0 auto;padding:20px 16px 0}
header{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;margin-bottom:18px}
h1{font-size:22px;margin:0}#stat{margin:2px 0 0}.tools{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--card)}
.seg button{background:transparent;color:var(--fg);border:0;border-radius:0;padding:6px 10px;font-size:13px}
.seg button[aria-pressed="true"]{background:var(--accent);color:var(--on-accent)}
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px}
.layout{display:grid;grid-template-columns:230px minmax(0,1fr);gap:20px;align-items:start}
.side{position:sticky;top:12px;display:flex;flex-direction:column;gap:10px}
#nav{display:flex;flex-direction:column;gap:2px}
#nav button{display:flex;justify-content:space-between;align-items:center;gap:8px;background:transparent;color:var(--fg);text-align:left;padding:8px 10px;border:1px solid transparent;border-radius:8px}
#nav button:hover{background:var(--card)}
#nav button[aria-current="true"]{background:var(--card);border-color:var(--line);font-weight:600;box-shadow:inset 3px 0 0 var(--accent)}
#nav button.muted{color:var(--muted)}#nav hr{width:100%;border:0;border-top:1px solid var(--line);margin:6px 0}
.cnt{font-size:12px;line-height:18px;min-width:18px;text-align:center;border-radius:9px;padding:0 6px;background:var(--accent);color:var(--on-accent);font-weight:600}.cnt.warnc{background:var(--warn)}
#content>#groups>.card,#extras>.card{margin-bottom:16px}
.rows{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,340px),1fr));column-gap:32px}
.rows .row{border-top:0;border-bottom:1px solid var(--line)}
.lab{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:6px}.lab label{margin:0}
.badge{font-size:11px;padding:1px 8px;border-radius:9px;border:1px solid var(--line);color:var(--muted)}.badge.panel{border-color:var(--accent);color:var(--accent)}
.lab .reset{margin-left:auto;font-size:13px}.help{margin-top:4px}
@media (max-width:760px){.layout{grid-template-columns:minmax(0,1fr)}.side{position:static}#nav{flex-direction:row;overflow-x:auto;padding-bottom:4px}#nav button{flex:none;white-space:nowrap}#nav hr{display:none}}
h2{font-size:15px;margin:0 0 4px;padding-bottom:8px;border-bottom:2px solid var(--accent)}
label{display:block;font-weight:600;font-size:13px;margin-bottom:4px;font-family:ui-monospace,monospace}
input,select{width:100%;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--field);color:var(--fg);font:inherit}
input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}
button{padding:8px 14px;border:0;border-radius:6px;background:var(--accent);color:var(--on-accent);font:inherit;cursor:pointer}
button.plain{background:transparent;color:var(--accent);padding:2px 0}
.row{padding:12px 0;border-top:1px solid var(--line)}h2+.row{border-top:0}
.help,.meta{color:var(--muted);font-size:13px}.err{color:var(--bad);min-height:1.4em;margin:0}
.changed input,.changed select{border-color:var(--accent)}
.inactive input,.inactive select{opacity:.5}button.second{background:transparent;color:var(--accent);border:1px solid var(--accent)}button.second.due{background:var(--warn);border-color:var(--warn);color:var(--on-accent)}.warn{color:var(--warn);font-size:13px}
.foot{display:flex;justify-content:space-between;align-items:center;gap:8px}
.savebar{position:sticky;bottom:0;margin:16px -16px 0;padding:12px 16px;background:var(--bg);border-top:1px solid var(--line);display:flex;gap:12px;align-items:center;flex-wrap:wrap}
#pwCard input{max-width:420px}.step{font-weight:600;font-size:14px;margin:16px 0 8px}.okbox{display:flex;width:fit-content;align-items:center;gap:8px;color:var(--ok);font-weight:600;margin:4px 0 0;padding:8px 12px;border-radius:8px;background:color-mix(in srgb,var(--ok) 12%,transparent)}#login{max-width:380px;margin:40px auto}#login p{margin:0 0 12px}
code{word-break:break-all}[hidden]{display:none!important}
</style></head><body><main>
<header><div><h1>WebSpeak3 Admin</h1><p class="meta" id="stat" hidden></p></div><div class="tools">
<span class="seg" id="langSeg"><button type="button" data-lang="de">DE</button><button type="button" data-lang="en">EN</button></span>
<span class="seg" id="themeSeg"><button type="button" data-theme-btn="auto" data-i18n="auto"></button><button type="button" data-theme-btn="light" data-i18n="light"></button><button type="button" data-theme-btn="dark" data-i18n="dark"></button></span>
<button id="logout" class="plain" type="button" data-i18n="logout" hidden></button></div></header>
<form id="login" class="card" hidden>
<p><label for="u" data-i18n="user"></label><input id="u" autocomplete="username" required></p>
<p><label for="p" data-i18n="pass"></label><input id="p" type="password" autocomplete="current-password" required></p>
<p><label for="c"><span data-i18n="code"></span> <span class="meta" data-i18n="codeHint"></span></label><input id="c" inputmode="numeric" autocomplete="one-time-code" maxlength="6"></p>
<p class="err" id="loginErr"></p><button data-i18n="login"></button></form>
<form id="panel" hidden><div class="layout"><div class="side"><input id="search" type="search" autocomplete="off"><nav id="nav"></nav></div>
<div id="content"><div id="groups"></div><p class="meta" id="noHits" hidden></p>
<div id="extras"><div class="card" id="totpCard"><h2 data-i18n="totpTitle"></h2><p class="help" id="totpState"></p>
<div id="totpOffBox" hidden><p class="help" data-i18n="offHint"></p>
<p style="display:flex;gap:8px;flex-wrap:wrap"><input id="offCode" inputmode="numeric" autocomplete="off" maxlength="6" style="max-width:9em"><input id="offPw" type="password" autocomplete="current-password" style="max-width:16em"><button type="button" id="offBtn" class="second" data-i18n="turnOff"></button></p>
<p class="err" id="offErr"></p></div>
<button class="plain" id="genTotp" type="button" data-i18n="gen"></button><div id="totpOut" hidden>
<p class="step" data-i18n="step1"></p>
<p><img id="totpQr" alt="QR" style="image-rendering:pixelated;background:#fff;padding:4px;border-radius:6px;max-width:100%"></p>
<p class="help"><span data-i18n="cantScan"></span> <code id="totpSecret"></code></p>
<p class="step" data-i18n="step2"></p>
<p style="display:flex;gap:8px"><input id="totpCheck" inputmode="numeric" autocomplete="off" maxlength="6" style="max-width:9em"><button type="button" id="totpCheckBtn" class="second" data-i18n="check"></button></p>
<p class="err" id="totpCheckErr"></p>
<div id="totpDone" hidden><p class="okbox" data-i18n="codeOk"></p><p class="step" data-i18n="step3"></p>
<p style="display:flex;gap:8px;flex-wrap:wrap"><input id="onPw" type="password" autocomplete="current-password" style="max-width:16em"><button type="button" id="onBtn" data-i18n="turnOn"></button></p>
<p class="err" id="onErr"></p>
<p class="help"><span data-i18n="envAlt"></span> <code id="totpEnv"></code></p></div></div></div>
<div class="card" id="pwCard"><h2 data-i18n="pwTitle"></h2><p class="help" id="pwState"></p>
<p><label for="pwOld" data-i18n="pwOld"></label><input id="pwOld" type="password" autocomplete="current-password"></p>
<p><label for="pwNew" data-i18n="pwNew"></label><input id="pwNew" type="password" autocomplete="new-password" minlength="10"></p>
<p><label for="pwNew2" data-i18n="pwNew2"></label><input id="pwNew2" type="password" autocomplete="new-password"></p>
<p class="err" id="pwErr"></p><button type="button" id="pwBtn" data-i18n="pwBtn"></button></div>
<div class="card" id="aboutCard"><h2 data-i18n="aboutTitle"></h2><p class="help" data-i18n="about"></p></div></div>
</div></div>
<div class="savebar"><button id="save" data-i18n="save"></button><button id="restart" type="button" class="second"></button><span class="meta" id="status"></span><p class="err" id="saveErr"></p></div>
</form></main><script src="/admin/admin.js"></script></body></html>`;
const SCRIPT = `"use strict";
const T = {
en: {
user: "Username", pass: "Password", code: "Authenticator code", codeHint: "(if 2FA is on)", login: "Log in", logout: "Log out",
auto: "Auto", light: "Light", dark: "Dark", save: "Save", saved: "Saved, active now.", unsaved: (n) => n + " unsaved change" + (n === 1 ? "" : "s"),
fromPanel: "set in panel", fromEnv: "from .env", notSet: "not set (built-in default)", reset: "Reset", on: "On", off: "Off", def: "default: ",
secretSet: "set - type to replace", secretUnset: "not set", tooMany: "Too many attempts, try again in 15 minutes.", loginFailed: "Login failed.", saveFailed: "Save failed",
inactive: "No effect here: WEB_STATIC=0, the web UI is hosted separately (set it in that build instead).",
totpTitle: "Two-factor login", totpOn: "On (set in .env).", totpOnPanel: "On (switched on here).", totpOff: "Off. Generate a secret below to require a code at login.",
offHint: "Switch off: current code from the app and your password.", turnOff: "Switch 2FA off", turnOn: "Switch 2FA on",
envAlt: "Or put this line in .env instead:", codePh: "Code", pwPh: "Password",
pwTitle: "Password", pwEnv: "Currently the password from .env (ADMIN_PASSWORD).", pwPanel: "Changed here; ADMIN_PASSWORD in .env is no longer used.",
pwOld: "Current password", pwNew: "New password (at least 10 characters)", pwNew2: "Repeat new password", pwBtn: "Change password",
pwMismatch: "The new passwords differ.", pwDone: "Password changed. Other logins were signed out.", totpDoneOn: "2FA is on now. Next login asks for the code.",
statConn: (n) => n + " connected", statUp: "up ", statVer: "version ",
gen: "Generate a new secret", step1: "1. Scan this code with your authenticator app (Google Authenticator, Aegis, 2FAS, ...):", cantScan: "Can't scan? Enter the secret manually:",
step2: "2. Enter the 6-digit code the app now shows for WebSpeak3:", check: "Check", codeWrong: "Code doesn\\u2019t match. Wait for the next code, check the phone\\u2019s clock, or scan again.",
codeOk: "\\u2713 Code is correct", step3: "3. Confirm with your password to switch 2FA on:",
credErr: { wrong_password: "Wrong password.", code_wrong: "Wrong code.", weak_password: "At least 10 characters.", rate_limited: "Too many attempts, try again in 15 minutes." },
aboutTitle: "How this works", about: "Changes apply immediately, except in \\u201cRestart required\\u201d. They override .env and are stored in admin-config.json (ADMIN_CONFIG_FILE). \\u201cReset\\u201d returns a setting to its .env value. Password and 2FA changes go to admin-auth.json; deleting that file goes back to .env (e.g. if you are locked out).",
search: "Search settings\\u2026", noHits: "No matching settings.", std: "default",
restartBtn: "Restart gateway", restartDue: (n) => "Restart gateway (" + n + " pending)", pendingRestart: "Saved \\u2013 applies after the next restart.",
restartConfirm: (n) => (n ? n + " connection(s) are open right now; they get a restart notice and are dropped. " : "Nobody is connected. ") + "Restart now? This only works if Docker's restart policy or systemd brings the gateway back up.",
restarting: "Restarting\\u2026 the page reloads when the gateway is back.", restartFailed: "Restart failed",
errors: {}, groups: {}, help: {},
},
de: {
user: "Benutzername", pass: "Passwort", code: "Authenticator-Code", codeHint: "(falls 2FA an ist)", login: "Anmelden", logout: "Abmelden",
auto: "Auto", light: "Hell", dark: "Dunkel", save: "Speichern", saved: "Gespeichert, sofort aktiv.", unsaved: (n) => n + " ungespeicherte \\u00c4nderung" + (n === 1 ? "" : "en"),
fromPanel: "im Panel gesetzt", fromEnv: "aus .env", notSet: "nicht gesetzt (Standardwert)", reset: "Zur\\u00fccksetzen", on: "An", off: "Aus", def: "Standard: ",
secretSet: "gesetzt \\u2013 zum Ersetzen tippen", secretUnset: "nicht gesetzt", tooMany: "Zu viele Versuche, bitte in 15 Minuten erneut versuchen.", loginFailed: "Anmeldung fehlgeschlagen.", saveFailed: "Speichern fehlgeschlagen",
inactive: "Hier ohne Wirkung: WEB_STATIC=0, die Web-Oberfl\\u00e4che wird separat gehostet (dort beim Build setzen).",
totpTitle: "Zwei-Faktor-Anmeldung", totpOn: "Aktiv (in der .env gesetzt).", totpOnPanel: "Aktiv (hier eingeschaltet).", totpOff: "Aus. Unten ein Secret erzeugen, um beim Login einen Code zu verlangen.",
offHint: "Abschalten: aktueller Code aus der App und dein Passwort.", turnOff: "2FA abschalten", turnOn: "2FA einschalten",
envAlt: "Oder stattdessen diese Zeile in die .env:", codePh: "Code", pwPh: "Passwort",
pwTitle: "Passwort", pwEnv: "Aktuell gilt das Passwort aus der .env (ADMIN_PASSWORD).", pwPanel: "Hier ge\\u00e4ndert; ADMIN_PASSWORD in der .env wird nicht mehr verwendet.",
pwOld: "Aktuelles Passwort", pwNew: "Neues Passwort (mindestens 10 Zeichen)", pwNew2: "Neues Passwort wiederholen", pwBtn: "Passwort \\u00e4ndern",
pwMismatch: "Die neuen Passw\\u00f6rter stimmen nicht \\u00fcberein.", pwDone: "Passwort ge\\u00e4ndert. Andere Anmeldungen wurden abgemeldet.", totpDoneOn: "2FA ist jetzt aktiv. Der n\\u00e4chste Login fragt nach dem Code.",
statConn: (n) => n + " verbunden", statUp: "l\\u00e4uft seit ", statVer: "Version ",
gen: "Neues Secret erzeugen", step1: "1. Diesen Code mit der Authenticator-App scannen (Google Authenticator, Aegis, 2FAS, ...):", cantScan: "Scannen klappt nicht? Secret von Hand eingeben:",
step2: "2. Den 6-stelligen Code eingeben, den die App jetzt f\\u00fcr WebSpeak3 anzeigt:", check: "Pr\\u00fcfen", codeWrong: "Code passt nicht. Auf den n\\u00e4chsten Code warten, die Uhrzeit am Handy pr\\u00fcfen oder neu scannen.",
codeOk: "\\u2713 Code stimmt", step3: "3. Mit deinem Passwort best\\u00e4tigen, um 2FA einzuschalten:",
credErr: { wrong_password: "Falsches Passwort.", code_wrong: "Falscher Code.", weak_password: "Mindestens 10 Zeichen.", rate_limited: "Zu viele Versuche, in 15 Minuten erneut probieren." },
aboutTitle: "So funktioniert's", about: "\\u00c4nderungen gelten sofort, au\\u00dfer unter \\u201eNeustart n\\u00f6tig\\u201c. Sie \\u00fcberschreiben die .env und liegen in admin-config.json (ADMIN_CONFIG_FILE). \\u201eZur\\u00fccksetzen\\u201c stellt den Wert aus der .env wieder her. Passwort und 2FA aus dem Panel liegen in admin-auth.json; wer die Datei l\\u00f6scht, ist wieder bei der .env (z. B. wenn man sich ausgesperrt hat).",
search: "Einstellungen suchen\\u2026", noHits: "Keine passende Einstellung.", std: "Standardwert",
restartBtn: "Gateway neu starten", restartDue: (n) => "Gateway neu starten (" + n + " ausstehend)", pendingRestart: "Gespeichert \\u2013 gilt ab dem n\\u00e4chsten Neustart.",
restartConfirm: (n) => (n ? "Gerade sind " + n + " Verbindung(en) offen; sie bekommen einen Neustart-Hinweis und werden getrennt. " : "Niemand ist verbunden. ") + "Jetzt neu starten? Das klappt nur, wenn Dockers Restart-Policy oder systemd das Gateway wieder hochf\\u00e4hrt.",
restarting: "Startet neu\\u2026 die Seite l\\u00e4dt neu, sobald das Gateway wieder da ist.", restartFailed: "Neustart fehlgeschlagen",
errors: { "must be a port (1-65535)": "muss ein Port sein (1\\u201365535)", "must be a whole number": "muss eine ganze Zahl sein", "must be 0 or 1": "muss 0 oder 1 sein", "invalid characters or too long": "ung\\u00fcltige Zeichen oder zu lang", "unknown setting": "unbekannte Einstellung" },
groups: { "Connections & limits": "Verbindungen & Limits", "Access": "Zugriff", "Connect dialog": "Verbindungsdialog", "Features": "Funktionen", "News ticker": "News-Ticker", "Bot check (Cloudflare Turnstile)": "Bot-Check (Cloudflare Turnstile)", "Screen sharing & webcam (TURN)": "Bildschirmfreigabe & Webcam (TURN)", "Feedback & GitHub": "Feedback & GitHub", "Design Store": "Design Store", "Restart required": "Neustart n\\u00f6tig" },
help: {
MAX_CONNECTIONS: "Offene WebSocket-Verbindungen insgesamt (0 = unbegrenzt).", MAX_CONNECTIONS_PER_IP: "Offene Verbindungen pro Client-IP (0 = unbegrenzt).",
CONNECT_RATE_LIMIT: "Verbindungsversuche pro IP und Minute (0 = unbegrenzt).",
ALLOWED_SERVERS: "Kommagetrennte TeamSpeak-Server, mit denen sich dieses Gateway verbinden darf (*.example.com erlaubt). Leer = alle.",
ALLOWED_ORIGINS: "Kommagetrennte Web-Origins, die dieses Gateway nutzen d\\u00fcrfen (https://client.example.com). Leer = alle.",
SERVER_PICKER: "ALLOWED_SERVERS im Verbindungsdialog als Auswahlliste anbieten.", DEFAULT_SERVER: "Im Verbindungsdialog vorausgef\\u00fcllte Serveradresse.", DEFAULT_CHANNEL: "Im Verbindungsdialog vorausgef\\u00fcllter Kanal.",
FEEDBACK_ENABLED: "Feedback aus der App annehmen (/api/feedback).", STORE_ENABLED: "Design Store betreiben (Theme-Einreichungen und Downloads).", LOG_CONNECTIONS: "Verbindungen protokollieren (gehashte Client-Kennungen, keine Klartext-IPs).",
NEWS_TICKER: "News-Ticker anzeigen.", NEWS_TICKER_CENTRAL: "Offizielle WebSpeak3-News im Ticker mit anzeigen.", NEWS_TICKER_MESSAGES: "Eigene Ticker-Meldungen, getrennt durch |.",
TURNSTILE_SITE_KEY: "Cloudflare-Turnstile-Site-Key (Bot-Check, braucht auch das Secret).", TURNSTILE_SECRET: "Cloudflare-Turnstile-Secret-Key.",
TURN_URLS: "Kommagetrennte TURN-Server-URLs f\\u00fcr Bildschirmfreigabe/Webcam.", TURN_SECRET: "coturn use-auth-secret (Zugangsdaten pro Nutzer).",
TURN_USERNAME: "Fester TURN-Benutzername (ohne TURN_SECRET).", TURN_CREDENTIAL: "Festes TURN-Passwort (ohne TURN_SECRET).",
ENABLE_TS2: "TeamSpeak-2-Server erlauben (experimentell).", TELEMETRY: "Anonymer t\\u00e4glicher Nutzungs-Ping (nur zuf\\u00e4llige Instanz-ID + Version).",
FEEDBACK_ALLOWED_ORIGIN: "Web-Origin, die Feedback senden darf (CORS). * = alle.", GITHUB_TOKEN: "GitHub-Token (Issues: write), um aus Feedback Issues zu machen.",
GITHUB_REPO: "Repository f\\u00fcr Feedback-Issues und die Release-News.", STORE_ALLOWED_ORIGIN: "Web-Origin, die den Store nutzen darf (CORS). * = alle.",
STORE_RESERVED_AUTHORS: "Kommagetrennte Autorennamen, unter denen nur der Store-Admin ver\\u00f6ffentlichen darf.", STORE_ADMIN_TOKEN: "Token zum Freigeben von Store-Einreichungen.",
TRUST_PROXY: "Hinter einem Proxy: \\"cloudflare\\" (CF-Connecting-IP) oder \\"1\\" (letzter X-Forwarded-For). Nur wenn das Gateway ausschlie\\u00dflich dar\\u00fcber erreichbar ist. Leer = aus.",
SYNC_URL: "Eigener Konto-Sync-Server (sync-server.js). Leer = der offizielle.",
PORT: "Port, auf dem das Gateway lauscht. Vorsicht: Bei Docker muss das Port-Mapping passen, sonst ist dieses Panel nicht mehr erreichbar (Abhilfe: PORT aus admin-config.json entfernen).",
TLS_CERT: "Pfad zum TLS-Zertifikat (mit TLS_KEY: HTTPS direkt ausliefern). Ein falscher Pfad verhindert den Start.", TLS_KEY: "Pfad zum privaten TLS-Schl\\u00fcssel.",
WEB_STATIC: "Web-Oberfl\\u00e4che von diesem Gateway ausliefern. Aus, wenn sie woanders gehostet wird.", WEB_DIST: "Ordner mit der gebauten Web-Oberfl\\u00e4che (web/dist).",
STORE_DATA_FILE: "Datendatei des Design Stores.", NEWS_DATA_FILE: "Datei f\\u00fcr News aus dem Stats-Panel.",
FEEDBACK_LOG_FILE: "Privates Feedback-Log (enth\\u00e4lt Kontakt-E-Mails).", TELEMETRY_ID_FILE: "Datei mit der zuf\\u00e4lligen Instanz-ID des Nutzungs-Pings.",
BROADCAST_TOKEN: "Bearer-Token f\\u00fcr /api/broadcast (Hinweise an alle Nutzer). Leer = Endpunkt aus.",
},
},
};
const $ = (id) => document.getElementById(id);
const store = { get(k) { try { return localStorage.getItem(k); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch {} } };
let lang = store.get("wsAdminLang") || (navigator.language.toLowerCase().startsWith("de") ? "de" : "en");
let theme = store.get("wsAdminTheme") || "auto";
let data = null, pending = {};
let current = store.get("wsAdminTab") || "";
// Non-setting pages in the sidebar: [tab key, card id, title string].
const EXTRA = [["__totp", "totpCard", "totpTitle"], ["__pw", "pwCard", "pwTitle"], ["__about", "aboutCard", "aboutTitle"]];
const gname = (g) => t("groups")[g] || g;
const t = (k) => T[lang][k];
const api = (path, body) => fetch("/admin/api/" + path, body === undefined ? {} : {
method: "POST", headers: { "Content-Type": "application/json", "X-WebSpeak3-Admin": "1" }, body: JSON.stringify(body),
}).then(async (r) => ({ status: r.status, data: await r.json().catch(() => ({})) }));
function el(tag, props, ...kids) { const e = Object.assign(document.createElement(tag), props); e.append(...kids); return e; }
function applyChrome() {
document.documentElement.lang = lang;
if (theme === "auto") document.documentElement.removeAttribute("data-theme"); else document.documentElement.dataset.theme = theme;
for (const b of document.querySelectorAll("[data-lang]")) b.setAttribute("aria-pressed", String(b.dataset.lang === lang));
for (const b of document.querySelectorAll("[data-theme-btn]")) b.setAttribute("aria-pressed", String(b.dataset.themeBtn === theme));
for (const e of document.querySelectorAll("[data-i18n]")) e.textContent = t(e.dataset.i18n);
$("search").placeholder = t("search"); $("noHits").textContent = t("noHits");
$("offCode").placeholder = $("totpCheck").placeholder = t("codePh"); $("offPw").placeholder = $("onPw").placeholder = t("pwPh");
}
function updateStatus() {
const n = Object.keys(pending).length;
$("status").textContent = n ? t("unsaved")(n) : "";
}
function render() {
applyChrome();
if (!data) return;
$("login").hidden = true; $("panel").hidden = false; $("logout").hidden = false;
$("totpState").textContent = data.totp === "panel" ? t("totpOnPanel") : data.totp ? t("totpOn") : t("totpOff");
$("totpOffBox").hidden = !data.totp;
$("pwState").textContent = data.passwordFromPanel ? t("pwPanel") : t("pwEnv");
renderStat();
const groups = $("groups"); groups.replaceChildren();
const cards = {};
for (const s of data.settings) {
let card = cards[s.group];
if (!card) {
card = cards[s.group] = el("section", { className: "card" }, el("h2", { textContent: gname(s.group) }), el("div", { className: "rows" }));
card.dataset.group = s.group; groups.append(card);
}
const id = "s_" + s.key;
const help = t("help")[s.key] || s.help;
let input;
if (s.kind === "bool") {
input = el("select", { id }, el("option", { value: "1", textContent: t("on") }), el("option", { value: "0", textContent: t("off") }));
input.value = s.value || s.fallback || "0";
} else {
input = el("input", { id, type: s.kind === "secret" ? "password" : s.kind === "number" ? "number" : "text", autocomplete: "off" });
if (s.kind === "number") input.min = "0";
if (s.kind === "secret") input.placeholder = s.isSet ? t("secretSet") : t("secretUnset");
else { input.value = s.value; if (s.fallback) input.placeholder = t("def") + s.fallback; }
}
if (s.key in pending) input.value = pending[s.key];
const reset = el("button", { type: "button", className: "plain reset", textContent: t("reset"), hidden: !s.overridden });
reset.addEventListener("click", () => save({ [s.key]: null }));
const badge = el("span", { className: "badge" + (s.overridden ? " panel" : ""), textContent: s.overridden ? t("fromPanel") : s.fromEnv ? t("fromEnv") : t("std") });
const row = el("div", { className: "row" + (s.inactive ? " inactive" : "") + (s.key in pending ? " changed" : "") },
el("div", { className: "lab" }, el("label", { htmlFor: id, textContent: s.key }), badge, reset), input, el("div", { className: "help", textContent: help }));
row.dataset.find = (s.key + " " + help + " " + gname(s.group)).toLowerCase();
const mark = () => { pending[s.key] = input.value; row.classList.add("changed"); updateStatus(); renderNav(); };
input.addEventListener("input", mark); input.addEventListener("change", mark);
if (s.inactive) row.append(el("div", { className: "warn", textContent: t("inactive") }));
if (s.pendingRestart) row.append(el("div", { className: "warn", textContent: t("pendingRestart") }));
card.lastChild.append(row);
}
if (!cards[current] && !EXTRA.some(([k]) => k === current)) current = data.settings[0].group;
const due = data.settings.filter((s) => s.pendingRestart).length;
$("restart").textContent = due ? t("restartDue")(due) : t("restartBtn");
$("restart").classList.toggle("due", due > 0);
updateStatus(); renderNav(); applyView();
}
function renderNav() {
const nav = $("nav"); nav.replaceChildren();
const item = (key, label, badge) => {
const b = el("button", { type: "button" }, el("span", { textContent: label }), ...(badge ? [badge] : []));
b.dataset.tab = key;
b.addEventListener("click", () => { current = key; store.set("wsAdminTab", key); $("search").value = ""; applyView(); });
nav.append(b); return b;
};
for (const g of [...new Set(data.settings.map((s) => s.group))]) {
const ss = data.settings.filter((s) => s.group === g);
const unsaved = ss.filter((s) => s.key in pending).length;
const badge = unsaved ? el("span", { className: "cnt", textContent: String(unsaved), title: t("unsaved")(unsaved) })
: ss.some((s) => s.pendingRestart) ? el("span", { className: "cnt warnc", textContent: "!", title: t("pendingRestart") }) : null;
const b = item(g, gname(g), badge);
if (ss.every((s) => s.inactive)) { b.classList.add("muted"); b.title = t("inactive"); }
}
nav.append(el("hr"));
for (const [k, , label] of EXTRA) item(k, t(label));
markCurrent();
}
function markCurrent() {
const q = $("search").value.trim();
for (const b of $("nav").children) if (b.dataset.tab) b.setAttribute("aria-current", String(!q && b.dataset.tab === current));
}
// One page at a time; a search shows matches from every category instead.
function applyView() {
const q = $("search").value.trim().toLowerCase();
let hits = 0;
for (const card of $("groups").children) {
let any = false;
for (const row of card.lastChild.children) { const m = !q || row.dataset.find.includes(q); row.hidden = !m; if (m) { any = true; hits++; } }
card.hidden = q ? !any : card.dataset.group !== current;
}
for (const [k, id] of EXTRA) $(id).hidden = Boolean(q) || current !== k;
$("noHits").hidden = !q || hits > 0;
markCurrent();
}
function renderStat() {
const up = data.uptime, d = Math.floor(up / 86400), h = Math.floor(up / 3600) % 24, m = Math.floor(up / 60) % 60;
const parts = [t("statConn")(data.connections), t("statUp") + (d ? d + " d " : "") + (d || h ? h + " h " : "") + m + " min"];
if (data.version) parts.unshift(t("statVer") + data.version);
$("stat").textContent = parts.join(" \\u00b7 "); $("stat").hidden = false;
}
// Keeps the status line fresh without re-rendering half-typed fields.
setInterval(async () => {
if (!data || document.hidden) return;
const r = await api("config");
if (r.status === 200) { data.connections = r.data.connections; data.uptime = r.data.uptime; renderStat(); }
}, 30000);
// Credential actions: show the server's error next to the form, else take the new state.
async function cred(path, body, errId) {
$(errId).textContent = "";
const r = await api(path, body);
if (r.status === 401) { load(); return false; }
if (r.status !== 200) { $(errId).textContent = t("credErr")[r.data.error] || r.data.error || t("saveFailed"); return false; }
data = r.data; render(); return true;
}
async function load() {
const r = await api("config");
if (r.status === 200) { data = r.data; pending = {}; return render(); }
data = null; applyChrome();
$("panel").hidden = true; $("logout").hidden = true; $("stat").hidden = true; $("login").hidden = false;
}
async function save(changes) {
$("saveErr").textContent = "";
const r = await api("config", { changes });
if (r.status === 401) return load();
if (r.status !== 200) { $("saveErr").textContent = (r.data.key ? r.data.key + ": " : "") + (t("errors")[r.data.error] || r.data.error || t("saveFailed")); return; }
data = r.data; for (const k of Object.keys(changes)) delete pending[k];
render(); $("status").textContent = t("saved");
}
document.querySelectorAll("[data-lang]").forEach((b) => b.addEventListener("click", () => { lang = b.dataset.lang; store.set("wsAdminLang", lang); render(); }));
document.querySelectorAll("[data-theme-btn]").forEach((b) => b.addEventListener("click", () => { theme = b.dataset.themeBtn; store.set("wsAdminTheme", theme); applyChrome(); }));
$("login").addEventListener("submit", async (e) => {
e.preventDefault(); $("loginErr").textContent = "";
const r = await api("login", { user: $("u").value, password: $("p").value, code: $("c").value });
if (r.status === 200) { $("p").value = ""; $("c").value = ""; return load(); }
$("loginErr").textContent = r.status === 429 ? t("tooMany") : t("loginFailed");
});
$("panel").addEventListener("submit", (e) => { e.preventDefault(); if (Object.keys(pending).length) save({ ...pending }); });
$("search").addEventListener("input", applyView);
$("restart").addEventListener("click", async () => {
const fresh = await api("config"); if (fresh.status !== 200) return load();
if (!confirm(t("restartConfirm")(fresh.data.connections))) return;
const r = await api("restart", {});
if (r.status !== 200) { $("saveErr").textContent = t("restartFailed"); return; }
$("restart").disabled = $("save").disabled = true; $("status").textContent = t("restarting");
// Wait for the old process to go away, then until /admin answers again.
await new Promise((ok) => setTimeout(ok, 2000));
for (let i = 0; i < 90; i++) {
try { if ((await fetch("/admin/admin.js", { cache: "no-store" })).ok) return location.reload(); } catch {}
await new Promise((ok) => setTimeout(ok, 2000));
}
$("saveErr").textContent = t("restartFailed");
});
$("logout").addEventListener("click", async () => { await api("logout", {}); load(); });
$("genTotp").addEventListener("click", async () => {
const r = await api("totp-secret"); if (r.status !== 200) return load();
$("totpQr").src = r.data.qr; $("totpSecret").textContent = r.data.secret; $("totpEnv").textContent = "ADMIN_TOTP_SECRET=" + r.data.secret; $("totpOut").hidden = false; $("totpDone").hidden = true; $("totpCheck").value = ""; $("totpCheckErr").textContent = "";
});
$("totpCheckBtn").addEventListener("click", async () => {
$("totpCheckErr").textContent = "";
const r = await api("totp-verify", { secret: $("totpSecret").textContent, code: $("totpCheck").value });
if (r.status === 401) return load();
if (r.status === 200 && r.data.ok) { $("totpDone").hidden = false; return; }
$("totpDone").hidden = true; $("totpCheckErr").textContent = t("codeWrong");
});
$("onBtn").addEventListener("click", async () => {
if (await cred("totp-enable", { secret: $("totpSecret").textContent, code: $("totpCheck").value, password: $("onPw").value }, "onErr")) {
$("onPw").value = ""; $("totpOut").hidden = true; $("totpState").textContent = t("totpDoneOn");
}
});
$("offBtn").addEventListener("click", async () => {
if (await cred("totp-disable", { code: $("offCode").value, password: $("offPw").value }, "offErr")) { $("offCode").value = $("offPw").value = ""; }
});
$("pwBtn").addEventListener("click", async () => {
$("pwErr").textContent = "";
if ($("pwNew").value !== $("pwNew2").value) { $("pwErr").textContent = t("pwMismatch"); return; }
if (await cred("password", { password: $("pwOld").value, newPassword: $("pwNew").value }, "pwErr")) {
$("pwOld").value = $("pwNew").value = $("pwNew2").value = ""; $("pwState").textContent = t("pwDone");
}
});
applyChrome();
load();
`;
+141
View File
@@ -0,0 +1,141 @@
// Settings the admin panel (admin.ts) may change at runtime. Values saved
// there live in ADMIN_CONFIG_FILE and are written onto process.env, both at
// startup and on every save, so code that reads process.env at use time picks
// them up without a restart. Must be imported before any module that reads
// these variables at load time (first import in index.ts).
//
// Settings marked `restart` are only written onto process.env at startup:
// they are read once at load time, so the panel saves them and asks for a
// restart instead of pretending they are live.
//
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
// operator's LAN), and the admin credentials themselves.
import { readFileSync } from "node:fs";
import { writeFileAtomic } from "./net.js";
import path from "node:path";
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
export interface Setting {
key: string;
kind: SettingKind;
/** Value used when neither .env nor the panel sets one (shown as hint). */
fallback?: string;
help: string;
group: string;
/** Only ends up in the UI this gateway serves itself (meta tags). */
staticOnly?: boolean;
/** Read once at startup; changes take effect after a restart. */
restart?: boolean;
}
export const SETTINGS: Setting[] = [
{ group: "Connections & limits", key: "MAX_CONNECTIONS", kind: "number", fallback: "60", help: "Open WebSocket connections in total (0 = unlimited)." },
{ group: "Connections & limits", key: "MAX_CONNECTIONS_PER_IP", kind: "number", fallback: "10", help: "Open connections per client IP (0 = unlimited)." },
{ group: "Connections & limits", key: "CONNECT_RATE_LIMIT", kind: "number", fallback: "30", help: "Connect attempts per IP per minute (0 = unlimited)." },
{ group: "Access", key: "ALLOWED_SERVERS", kind: "list", help: "Comma-separated TeamSpeak servers this gateway may connect to (*.example.com allowed). Empty = any." },
{ group: "Access", key: "ALLOWED_ORIGINS", kind: "list", help: "Comma-separated web origins allowed to use this gateway (https://client.example.com). Empty = any." },
{ group: "Access", key: "TRUST_PROXY", kind: "text", help: "Behind a proxy: \"cloudflare\" (CF-Connecting-IP) or \"1\" (last X-Forwarded-For). Only if the gateway is reachable solely through it. Empty = off." },
{ group: "Connect dialog", staticOnly: true, key: "SERVER_PICKER", kind: "bool", fallback: "1", help: "Offer ALLOWED_SERVERS as a dropdown 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: "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: "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: "ENABLE_TS2", kind: "bool", fallback: "0", help: "Allow TeamSpeak 2 servers (experimental)." },
{ group: "Features", key: "TELEMETRY", kind: "bool", fallback: "1", help: "Anonymous daily usage ping (random instance id + version only)." },
{ group: "Feedback & GitHub", key: "FEEDBACK_ALLOWED_ORIGIN", kind: "text", fallback: "*", help: "Web origin allowed to send feedback (CORS). * = any." },
{ group: "Feedback & GitHub", key: "GITHUB_TOKEN", kind: "secret", help: "GitHub token (Issues: write) to turn feedback into issues." },
{ group: "Feedback & GitHub", key: "GITHUB_REPO", kind: "text", fallback: "WebSpeak3/webspeak3", help: "Repository for feedback issues and the release news." },
{ group: "Design Store", key: "STORE_ALLOWED_ORIGIN", kind: "text", fallback: "*", help: "Web origin allowed to use the store (CORS). * = any." },
{ group: "Design Store", key: "STORE_RESERVED_AUTHORS", kind: "list", fallback: "Möpchi,Moepchi", help: "Comma-separated author names only the store admin may publish under." },
{ group: "Design Store", key: "STORE_ADMIN_TOKEN", kind: "secret", help: "Token for approving store submissions." },
{ group: "Access", key: "BROADCAST_TOKEN", kind: "secret", help: "Bearer token for /api/broadcast (notices to all users). Empty = endpoint off." },
{ group: "News ticker", key: "NEWS_TICKER", kind: "bool", fallback: "1", help: "Show the news ticker." },
{ group: "News ticker", key: "NEWS_TICKER_CENTRAL", kind: "bool", fallback: "1", help: "Include the official WebSpeak3 news in the ticker." },
{ group: "News ticker", key: "NEWS_TICKER_MESSAGES", kind: "text", help: "Own ticker messages, separated by |." },
{ group: "Bot check (Cloudflare Turnstile)", key: "TURNSTILE_SITE_KEY", kind: "text", help: "Cloudflare Turnstile site key (bot check, needs the secret too)." },
{ group: "Bot check (Cloudflare Turnstile)", key: "TURNSTILE_SECRET", kind: "secret", help: "Cloudflare Turnstile secret key." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_URLS", kind: "list", help: "Comma-separated TURN server URLs for screen sharing/webcam." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_SECRET", kind: "secret", help: "coturn use-auth-secret (per-user credentials)." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_USERNAME", kind: "text", help: "Static TURN username (if no TURN_SECRET)." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_CREDENTIAL", kind: "secret", help: "Static TURN password (if no TURN_SECRET)." },
{ group: "Restart required", restart: true, key: "PORT", kind: "number", fallback: "8080", help: "Port the gateway listens on. Careful: with Docker the port mapping must match, or this panel becomes unreachable (fix: remove PORT from admin-config.json)." },
{ group: "Restart required", restart: true, key: "TLS_CERT", kind: "text", help: "Path to the TLS certificate (with TLS_KEY: serve HTTPS directly). A wrong path stops the gateway from starting." },
{ group: "Restart required", restart: true, key: "TLS_KEY", kind: "text", help: "Path to the TLS private key." },
{ group: "Restart required", restart: true, key: "WEB_STATIC", kind: "bool", fallback: "1", help: "Serve the web UI from this gateway. Off when the UI is hosted elsewhere." },
{ group: "Restart required", restart: true, key: "WEB_DIST", kind: "text", help: "Folder with the built web UI (web/dist)." },
{ group: "Restart required", restart: true, key: "STORE_DATA_FILE", kind: "text", fallback: "./store-themes.json", help: "Design Store data file." },
{ group: "Restart required", restart: true, key: "NEWS_DATA_FILE", kind: "text", help: "File for news managed in the stats panel." },
{ group: "Restart required", restart: true, key: "FEEDBACK_LOG_FILE", kind: "text", fallback: "./feedback.log", help: "Private feedback log (includes contact e-mails)." },
{ group: "Restart required", restart: true, key: "TELEMETRY_ID_FILE", kind: "text", fallback: "./instance-id", help: "File holding the random instance id of the usage ping." },
];
const BY_KEY = new Map(SETTINGS.map((s) => [s.key, s]));
const CONFIG_FILE = process.env.ADMIN_CONFIG_FILE ?? path.resolve(process.cwd(), "admin-config.json");
// What .env said before any override, so "reset" can go back to it.
const ENV_DEFAULTS = new Map(SETTINGS.map((s) => [s.key, process.env[s.key]]));
let overrides: Record<string, string> = {};
const configured = (key: string) => (key in overrides ? overrides[key] : ENV_DEFAULTS.get(key));
function apply(startup = false): void {
for (const { key, restart } of SETTINGS) {
if (restart && !startup) continue;
const value = configured(key);
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
try {
const raw = JSON.parse(readFileSync(CONFIG_FILE, "utf8")) as Record<string, unknown>;
for (const [key, value] of Object.entries(raw)) {
if (BY_KEY.has(key) && typeof value === "string") overrides[key] = value;
}
apply(true);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`[admin] Ignoring unreadable ${CONFIG_FILE}:`, err);
}
/** Returns an error message, or undefined when the value is acceptable. */
export function validate(key: string, value: string): string | undefined {
const setting = BY_KEY.get(key);
if (!setting) return "unknown setting";
if (value.length > 4000 || /[\p{Cc}]/u.test(value)) return "invalid characters or too long";
if (setting.kind === "number" && !/^\d{1,6}$/.test(value)) return "must be a whole number";
if (setting.kind === "bool" && value !== "0" && value !== "1") return "must be 0 or 1";
if (key === "PORT" && value !== "" && (Number(value) < 1 || Number(value) > 65535)) return "must be a port (1-65535)";
return undefined;
}
/** Applies and persists changes. `null` removes the override (back to .env). */
export async function updateSettings(changes: Record<string, string | null>): Promise<void> {
const next = { ...overrides };
for (const [key, value] of Object.entries(changes)) {
if (value === null) delete next[key];
else next[key] = value;
}
await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
overrides = next;
apply();
}
/** Panel view: secrets only say whether they are set. */
export function describeSettings() {
return SETTINGS.map((s) => {
// Restart settings show what is saved, not what the process still runs with.
const value = s.restart ? configured(s.key) : process.env[s.key];
return {
...s,
overridden: s.key in overrides,
fromEnv: ENV_DEFAULTS.get(s.key) !== undefined,
value: s.kind === "secret" ? undefined : (value ?? ""),
isSet: Boolean(value),
// With WEB_STATIC=0 the UI comes from elsewhere and never sees these.
inactive: Boolean(s.staticOnly && process.env.WEB_STATIC === "0"),
pendingRestart: Boolean(s.restart && (value ?? "") !== (process.env[s.key] ?? "")),
};
});
}
+128 -60
View File
@@ -1,3 +1,4 @@
import "./config.js"; // first: applies admin-panel overrides to process.env
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createServer as createSecureServer } from "node:https"; import { createServer as createSecureServer } from "node:https";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
@@ -9,17 +10,18 @@ import { WebSocketServer, type WebSocket } from "ws";
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js"; import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
import { handleStore } from "./store.js"; import { handleStore } from "./store.js";
import { handleNewsConfig } from "./news.js"; import { handleNewsConfig } from "./news.js";
import { handleAdmin, setConnectionCounter } from "./admin.js";
import { logFeedback, logConnectionEvent } from "./activity-log.js"; import { logFeedback, logConnectionEvent } from "./activity-log.js";
import { clientIp, createRateLimiter } from "./net.js"; import { clientIp, createRateLimiter } from "./net.js";
import { TURNSTILE_ENABLED, TURNSTILE_SITE_KEY, isValidPass, issuePass, verifyToken } from "./turnstile.js"; import { turnstileEnabled, turnstileSiteKey, isValidPass, issuePass, verifyToken } from "./turnstile.js";
import "./telemetry.js"; import "./telemetry.js";
// TeamSpeak 2 support is experimental and opt-in (ENABLE_TS2=1). // TeamSpeak 2 support is experimental and opt-in (ENABLE_TS2=1).
const TS2_ENABLED = process.env.ENABLE_TS2 === "1"; const ts2Enabled = () => process.env.ENABLE_TS2 === "1";
const SERVER_TYPES = new Set<ServerType>(["teamspeak", "teaspeak", "auto", ...(TS2_ENABLED ? (["ts2"] as const) : [])]); const serverTypes = () => new Set<ServerType>(["teamspeak", "teaspeak", "auto", ...(ts2Enabled() ? (["ts2"] as const) : [])]);
function parseServerType(value: unknown): ServerType | undefined { function parseServerType(value: unknown): ServerType | undefined {
return typeof value === "string" && SERVER_TYPES.has(value as ServerType) return typeof value === "string" && serverTypes().has(value as ServerType)
? (value as ServerType) ? (value as ServerType)
: undefined; : undefined;
} }
@@ -34,10 +36,13 @@ function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): st
// Self-hosting admins may want to lock their instance to specific server(s) // Self-hosting admins may want to lock their instance to specific server(s)
// instead of leaving it as a general-purpose "connect anywhere" client. // instead of leaving it as a general-purpose "connect anywhere" client.
// Unset (the default) means unrestricted, unchanged from before this existed. // Unset (the default) means unrestricted, unchanged from before this existed.
const ALLOWED_SERVERS = (process.env.ALLOWED_SERVERS ?? "") // Live settings below are functions, not constants: the admin panel
.split(",") // (config.ts/admin.ts) can change process.env while the gateway runs.
.map((s) => s.trim().toLowerCase()) const allowedServers = () =>
.filter(Boolean); (process.env.ALLOWED_SERVERS ?? "")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
// Strips a trailing ":port" so "ts.example.com:9987" and "ts.example.com" // Strips a trailing ":port" so "ts.example.com:9987" and "ts.example.com"
// both match a plain "ts.example.com" allowlist entry. IPv6 literals come // both match a plain "ts.example.com" allowlist entry. IPv6 literals come
@@ -45,14 +50,17 @@ const ALLOWED_SERVERS = (process.env.ALLOWED_SERVERS ?? "")
// 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;
} }
function isServerAllowed(host: unknown): boolean { function isServerAllowed(host: unknown): boolean {
const ALLOWED_SERVERS = allowedServers();
if (ALLOWED_SERVERS.length === 0) return true; if (ALLOWED_SERVERS.length === 0) return true;
if (typeof host !== "string") return false; if (typeof host !== "string") return false;
const target = stripPort(host).trim().toLowerCase(); const target = stripPort(host).trim().toLowerCase();
@@ -88,24 +96,25 @@ function isValidNickname(nickname: unknown): nickname is string {
// Unset keeps the old "any origin" behavior for self-hosters; entries are // Unset keeps the old "any origin" behavior for self-hosters; entries are
// full origins ("https://client.example.com"). Non-browser clients send no // full origins ("https://client.example.com"). Non-browser clients send no
// Origin header at all - they could fake one anyway, so they aren't blocked. // Origin header at all - they could fake one anyway, so they aren't blocked.
const ALLOWED_ORIGINS = (process.env.ALLOWED_ORIGINS ?? "") const allowedOrigins = () =>
.split(",") (process.env.ALLOWED_ORIGINS ?? "")
.map((s) => s.trim().replace(/\/+$/, "").toLowerCase()) .split(",")
.filter(Boolean); .map((s) => s.trim().replace(/\/+$/, "").toLowerCase())
.filter(Boolean);
// Each /ws socket can spawn a connector process holding a live TeamSpeak // Each /ws socket can spawn a connector process holding a live TeamSpeak
// session, so both need a ceiling. 0 disables the respective limit. // session, so both need a ceiling. 0 disables the respective limit.
const MAX_CONNECTIONS_PER_IP = Number(process.env.MAX_CONNECTIONS_PER_IP ?? 10); const maxConnectionsPerIp = () => Number(process.env.MAX_CONNECTIONS_PER_IP ?? 10);
// Measured 2026-10-25: ~8-9 % of a core per client listening to constant audio // Measured 2026-10-25: ~8-9 % of a core per client listening to constant audio
// (connector + node + cloudflared), ~10-15 MB RAM. 60 suits a 2-core VPS. // (connector + node + cloudflared), ~10-15 MB RAM. 60 suits a 2-core VPS.
const MAX_CONNECTIONS = Number(process.env.MAX_CONNECTIONS ?? 60); const maxConnections = () => Number(process.env.MAX_CONNECTIONS ?? 60);
const connectionsPerIp = new Map<string, number>(); const connectionsPerIp = new Map<string, number>();
// Every "connect" spawns a fresh connector, and a socket can send any number // Every "connect" spawns a fresh connector, and a socket can send any number
// of them - without this, 10 sockets were enough to join-flood a TS server // of them - without this, 10 sockets were enough to join-flood a TS server
// through this gateway at several joins per second. Real clients (reconnect // through this gateway at several joins per second. Real clients (reconnect
// backoff, restoring a handful of tabs) stay far below it. // backoff, restoring a handful of tabs) stay far below it.
const CONNECT_RATE_LIMIT = Number(process.env.CONNECT_RATE_LIMIT ?? 30); const connectRateLimit = () => Number(process.env.CONNECT_RATE_LIMIT ?? 30);
const isConnectRateLimited = createRateLimiter(CONNECT_RATE_LIMIT, 60_000); const isConnectRateLimited = createRateLimiter(connectRateLimit, 60_000);
// Largest single WS message. Uploads now arrive in small "uploadFileChunk" // Largest single WS message. Uploads now arrive in small "uploadFileChunk"
// pieces; this size only stays for browsers still running a client from // pieces; this size only stays for browsers still running a client from
@@ -127,15 +136,16 @@ const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist
const SERVE_STATIC = process.env.WEB_STATIC !== "0"; const SERVE_STATIC = process.env.WEB_STATIC !== "0";
// Sent to every browser in the "hello" message on socket open; see there. // Sent to every browser in the "hello" message on socket open; see there.
const GATEWAY_FEATURES = ["clientVolume", "keepalive", "chunkedUpload", "whisperPolicy", "transferLimit", ...(TS2_ENABLED ? ["ts2"] : [])]; const gatewayFeatures = () => ["clientVolume", "keepalive", "chunkedUpload", "whisperPolicy", "transferLimit", ...(ts2Enabled() ? ["ts2"] : [])];
// Optional TURN relay for screen streams, also handed out in "hello". With // Optional TURN relay for screen streams, also handed out in "hello". With
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential, // TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
// valid for a day; TURN_USERNAME/TURN_CREDENTIAL are static and so readable by // valid for a day; TURN_USERNAME/TURN_CREDENTIAL are static and so readable by
// every visitor. ponytail: a socket open longer than a day hands an expired // every visitor. ponytail: a socket open longer than a day hands an expired
// credential to a stream started after that; reconnecting fixes it. // credential to a stream started after that; reconnecting fixes it.
const TURN_URLS = (process.env.TURN_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean);
function turnServers() { function turnServers() {
const TURN_URLS = (process.env.TURN_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean);
if (!TURN_URLS.length) return undefined; if (!TURN_URLS.length) return undefined;
const secret = process.env.TURN_SECRET; const secret = process.env.TURN_SECRET;
if (!secret) { if (!secret) {
@@ -152,11 +162,14 @@ function turnServers() {
// The allowlist goes along so the client can offer it as a dropdown (or a // The allowlist goes along so the client can offer it as a dropdown (or a
// locked field for a single entry) instead of a free-text address; not with // locked field for a single entry) instead of a free-text address; not with
// wildcards, which can't be listed, nor with SERVER_PICKER=0. // wildcards, which can't be listed, nor with SERVER_PICKER=0.
const SERVER_PICKER = // Built per request, since the admin panel can change these at runtime.
process.env.SERVER_PICKER !== "0" && !ALLOWED_SERVERS.some((e) => e.startsWith("*.")) const runtimeConfigMeta = () => {
? ALLOWED_SERVERS.join(",") const ALLOWED_SERVERS = allowedServers();
: undefined; const SERVER_PICKER =
const RUNTIME_CONFIG_META = Object.entries({ process.env.SERVER_PICKER !== "0" && !ALLOWED_SERVERS.some((e) => e.startsWith("*."))
? ALLOWED_SERVERS.join(",")
: undefined;
return Object.entries({
"webspeak3-default-server": process.env.DEFAULT_SERVER, "webspeak3-default-server": process.env.DEFAULT_SERVER,
"webspeak3-default-channel": process.env.DEFAULT_CHANNEL, "webspeak3-default-channel": process.env.DEFAULT_CHANNEL,
"webspeak3-allowed-servers": SERVER_PICKER, "webspeak3-allowed-servers": SERVER_PICKER,
@@ -167,6 +180,7 @@ const RUNTIME_CONFIG_META = Object.entries({
value ? [`<meta name="${name}" content="${value.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}">`] : [], value ? [`<meta name="${name}" content="${value.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}">`] : [],
) )
.join(""); .join("");
};
const MIME_TYPES: Record<string, string> = { const MIME_TYPES: Record<string, string> = {
".html": "text/html", ".html": "text/html",
@@ -190,16 +204,15 @@ const MIME_TYPES: Record<string, string> = {
// (see IS_OWN_HOSTED_INSTANCE in web/src/App.tsx), but this endpoint // (see IS_OWN_HOSTED_INSTANCE in web/src/App.tsx), but this endpoint
// enforces its own opt-in independently since it's reachable directly over // enforces its own opt-in independently since it's reachable directly over
// HTTP by anyone who finds the gateway's address, not just from that UI. // HTTP by anyone who finds the gateway's address, not just from that UI.
const FEEDBACK_ENABLED = process.env.FEEDBACK_ENABLED === "1";
// The web app is commonly hosted on a different origin than the gateway // The web app is commonly hosted on a different origin than the gateway
// (see mem:deployment / GATEWAY_URL in web/), so this needs its own CORS // (see mem:deployment / GATEWAY_URL in web/), so this needs its own CORS
// allowance; default "*" since the endpoint is opt-in, rate-limited, and // allowance; default "*" since the endpoint is opt-in, rate-limited, and
// only ever accepts a feedback submission, nothing that reads data back. // only ever accepts a feedback submission, nothing that reads data back.
const FEEDBACK_ALLOWED_ORIGIN = process.env.FEEDBACK_ALLOWED_ORIGIN ?? "*"; const feedbackAllowedOrigin = () => process.env.FEEDBACK_ALLOWED_ORIGIN || "*";
// A token with "Issues: write" access on the target repo. Without it, // A token with "Issues: write" access on the target repo. Without it,
// feedback is still accepted and logged, just never turned into an issue. // feedback is still accepted and logged, just never turned into an issue.
const GITHUB_TOKEN = process.env.GITHUB_TOKEN; const githubRepo = () => process.env.GITHUB_REPO || "WebSpeak3/webspeak3";
const GITHUB_REPO = process.env.GITHUB_REPO ?? "WebSpeak3/webspeak3";
const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]); const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]);
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000; const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
@@ -210,18 +223,18 @@ const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
// tab (reuses the same {type:"notice"} message the SIGTERM handler already // tab (reuses the same {type:"notice"} message the SIGTERM handler already
// sends, which the frontend renders even without a messageKey). Unset // sends, which the frontend renders even without a messageKey). Unset
// BROADCAST_TOKEN and the endpoint 404s, same as feedback when disabled. // BROADCAST_TOKEN and the endpoint 404s, same as feedback when disabled.
const BROADCAST_TOKEN = process.env.BROADCAST_TOKEN;
const BROADCAST_MESSAGE_MAX_LENGTH = 500; const BROADCAST_MESSAGE_MAX_LENGTH = 500;
function isValidBroadcastToken(provided: string): boolean { function isValidBroadcastToken(provided: string): boolean {
if (!BROADCAST_TOKEN) return false; const token = process.env.BROADCAST_TOKEN;
if (!token) return false;
const a = Buffer.from(provided); const a = Buffer.from(provided);
const b = Buffer.from(BROADCAST_TOKEN); const b = Buffer.from(token);
return a.length === b.length && timingSafeEqual(a, b); return a.length === b.length && timingSafeEqual(a, b);
} }
async function handleBroadcast(req: IncomingMessage, res: ServerResponse) { async function handleBroadcast(req: IncomingMessage, res: ServerResponse) {
if (!BROADCAST_TOKEN) { if (!process.env.BROADCAST_TOKEN) {
res.writeHead(404, { "Content-Type": "application/json" }); res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" })); res.end(JSON.stringify({ error: "not_found" }));
return; return;
@@ -300,7 +313,8 @@ function neutralizeMentions(text: string): string {
// The contact e-mail is deliberately *not* part of this: it's only kept in // The contact e-mail is deliberately *not* part of this: it's only kept in
// the private feedback log (logFeedback), never in the public issue. // the private feedback log (logFeedback), never in the public issue.
async function createGithubIssue(payload: { category: string; message: string }): Promise<string | undefined> { async function createGithubIssue(payload: { category: string; message: string }): Promise<string | undefined> {
if (!GITHUB_TOKEN) return undefined; const githubToken = process.env.GITHUB_TOKEN;
if (!githubToken) return undefined;
const title = neutralizeMentions( const title = neutralizeMentions(
`[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`, `[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`,
); );
@@ -316,10 +330,10 @@ async function createGithubIssue(payload: { category: string; message: string })
"_Submitted via the in-client feedback form._", "_Submitted via the in-client feedback form._",
].join("\n"); ].join("\n");
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/issues`, { const res = await fetch(`https://api.github.com/repos/${githubRepo()}/issues`, {
method: "POST", method: "POST",
headers: { headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`, Authorization: `Bearer ${githubToken}`,
Accept: "application/vnd.github+json", Accept: "application/vnd.github+json",
"Content-Type": "application/json", "Content-Type": "application/json",
"User-Agent": "webspeak3-gateway", "User-Agent": "webspeak3-gateway",
@@ -337,7 +351,7 @@ async function createGithubIssue(payload: { category: string; message: string })
} }
async function handleFeedback(req: IncomingMessage, res: ServerResponse) { async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", FEEDBACK_ALLOWED_ORIGIN); res.setHeader("Access-Control-Allow-Origin", feedbackAllowedOrigin());
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS"); res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.setHeader("Access-Control-Allow-Headers", "Content-Type");
@@ -346,7 +360,7 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.end(); res.end();
return; return;
} }
if (!FEEDBACK_ENABLED) { if (process.env.FEEDBACK_ENABLED !== "1") {
res.writeHead(404, { "Content-Type": "application/json" }); res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" })); res.end(JSON.stringify({ error: "not_found" }));
return; return;
@@ -491,13 +505,17 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
// Same list as the "hello" message, readable before any connect // Same list as the "hello" message, readable before any connect
// (the connect dialog offers TeamSpeak 2 only when it is enabled). // (the connect dialog offers TeamSpeak 2 only when it is enabled).
res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=300" }); res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=300" });
res.end(JSON.stringify({ features: GATEWAY_FEATURES, ...(TURNSTILE_ENABLED ? { turnstileSiteKey: TURNSTILE_SITE_KEY } : {}) })); res.end(JSON.stringify({ features: gatewayFeatures(), ...(turnstileEnabled() ? { turnstileSiteKey: turnstileSiteKey() } : {}) }));
return; return;
} }
if (requestUrl.pathname === "/api/news") { if (requestUrl.pathname === "/api/news") {
handleNewsConfig(res); handleNewsConfig(res);
return; return;
} }
if (requestUrl.pathname === "/admin" || requestUrl.pathname.startsWith("/admin/")) {
await handleAdmin(req, res, requestUrl.pathname);
return;
}
if (requestUrl.pathname === "/api/broadcast") { if (requestUrl.pathname === "/api/broadcast") {
await handleBroadcast(req, res); await handleBroadcast(req, res);
return; return;
@@ -551,9 +569,10 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
filePath = path.join(WEB_DIST, "index.html"); filePath = path.join(WEB_DIST, "index.html");
body = await readFile(filePath); body = await readFile(filePath);
} }
if (RUNTIME_CONFIG_META && filePath === path.join(WEB_DIST, "index.html")) { const meta = filePath === path.join(WEB_DIST, "index.html") ? runtimeConfigMeta() : "";
if (meta) {
// Function replacer: a string one would expand "$&" etc. in the values. // Function replacer: a string one would expand "$&" etc. in the values.
body = Buffer.from(body.toString("utf8").replace("</head>", () => `${RUNTIME_CONFIG_META}</head>`)); body = Buffer.from(body.toString("utf8").replace("</head>", () => `${meta}</head>`));
} }
const ext = path.extname(filePath); const ext = path.extname(filePath);
res.writeHead(200, { res.writeHead(200, {
@@ -579,10 +598,12 @@ const wss = new WebSocketServer({
path: "/ws", path: "/ws",
maxPayload: WS_MAX_PAYLOAD, maxPayload: WS_MAX_PAYLOAD,
verifyClient: ({ origin, req }, done) => { verifyClient: ({ origin, req }, done) => {
const ALLOWED_ORIGINS = allowedOrigins();
if (ALLOWED_ORIGINS.length > 0 && origin && !ALLOWED_ORIGINS.includes(origin.toLowerCase())) { if (ALLOWED_ORIGINS.length > 0 && origin && !ALLOWED_ORIGINS.includes(origin.toLowerCase())) {
return done(false, 403, "Origin not allowed"); return done(false, 403, "Origin not allowed");
} }
const ip = clientIp(req); const ip = clientIp(req);
const MAX_CONNECTIONS_PER_IP = maxConnectionsPerIp();
if (MAX_CONNECTIONS_PER_IP > 0 && (connectionsPerIp.get(ip) ?? 0) >= MAX_CONNECTIONS_PER_IP) { if (MAX_CONNECTIONS_PER_IP > 0 && (connectionsPerIp.get(ip) ?? 0) >= MAX_CONNECTIONS_PER_IP) {
console.warn(`[ratelimit] too many open connections from one IP (limit ${MAX_CONNECTIONS_PER_IP})`); console.warn(`[ratelimit] too many open connections from one IP (limit ${MAX_CONNECTIONS_PER_IP})`);
return done(false, 429, "Too many connections"); return done(false, 429, "Too many connections");
@@ -590,6 +611,7 @@ const wss = new WebSocketServer({
done(true); done(true);
}, },
}); });
setConnectionCounter(() => wss.clients.size);
// Heartbeat: a browser tab that loses its network mid-session (mobile // Heartbeat: a browser tab that loses its network mid-session (mobile
// handover, Wi-Fi drop, backgrounded/frozen tab) often never sends a proper // handover, Wi-Fi drop, backgrounded/frozen tab) often never sends a proper
@@ -602,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
@@ -625,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
@@ -688,9 +731,14 @@ 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 (MAX_CONNECTIONS > 0 && wss.clients.size > MAX_CONNECTIONS) { if (maxConnections() > 0 && wss.clients.size > maxConnections()) {
socket.send(JSON.stringify({ type: "error", code: "gateway_full", message: "This gateway is full right now. Please try again in a few minutes." })); socket.send(JSON.stringify({ type: "error", code: "gateway_full", message: "This gateway is full right now. Please try again in a few minutes." }));
socket.close(1013, "Gateway is full"); socket.close(1013, "Gateway is full");
return; return;
@@ -703,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: GATEWAY_FEATURES, 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;
@@ -737,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)) {
@@ -749,14 +810,14 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
); );
break; break;
} }
if (CONNECT_RATE_LIMIT > 0 && isConnectRateLimited(ip)) { if (connectRateLimit() > 0 && isConnectRateLimited(ip)) {
console.warn(`[ratelimit] too many connects from one IP, target host=${msg.host}`); console.warn(`[ratelimit] too many connects from one IP, target host=${msg.host}`);
socket.send( socket.send(
JSON.stringify({ type: "error", message: "Too many connection attempts. Please wait a minute." }), JSON.stringify({ type: "error", message: "Too many connection attempts. Please wait a minute." }),
); );
break; break;
} }
if (TURNSTILE_ENABLED && !isValidPass(msg.turnstilePass, ip)) { if (turnstileEnabled() && !isValidPass(msg.turnstilePass, ip)) {
// No (valid) pass yet: ask the browser to solve the check, it // No (valid) pass yet: ask the browser to solve the check, it
// resends this connect with the token. // resends this connect with the token.
if (msg.turnstileToken === undefined) { if (msg.turnstileToken === undefined) {
@@ -771,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(); connection = undefined;
} catch { if (prev) {
/* ignore */ liveConnections.delete(prev);
} await prev.disconnect().catch(() => {});
liveConnections.delete(connection);
connection = undefined;
} }
if (closed || gen !== connectGen) break;
const options: Ts3ConnectOptions = { const options: Ts3ConnectOptions = {
host: msg.host, host: msg.host,
nickname: msg.nickname, nickname: msg.nickname,
@@ -1075,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:
@@ -1093,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;
}
}); });
}); });
+23 -4
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
@@ -6,9 +7,9 @@ import type { IncomingMessage } from "node:http";
// - "cloudflare": CF-Connecting-IP, which Cloudflare always sets itself. // - "cloudflare": CF-Connecting-IP, which Cloudflare always sets itself.
// - "1": the last X-Forwarded-For entry, the one our own proxy appended; // - "1": the last X-Forwarded-For entry, the one our own proxy appended;
// anything before it came from the client and can be made up. // anything before it came from the client and can be made up.
const TRUST_PROXY = process.env.TRUST_PROXY;
export function clientIp(req: IncomingMessage): string { export function clientIp(req: IncomingMessage): string {
// Read per request: the admin panel can change it live.
const TRUST_PROXY = process.env.TRUST_PROXY;
if (TRUST_PROXY === "cloudflare") { if (TRUST_PROXY === "cloudflare") {
const cf = req.headers["cf-connecting-ip"]; const cf = req.headers["cf-connecting-ip"];
if (typeof cf === "string" && cf.trim()) return cf.trim(); if (typeof cf === "string" && cf.trim()) return cf.trim();
@@ -22,7 +23,7 @@ export function clientIp(req: IncomingMessage): string {
/** Sliding-window "N per window per key" limiter. Expired keys are swept /** Sliding-window "N per window per key" limiter. Expired keys are swept
* periodically so the map can't grow without bound under a stream of * periodically so the map can't grow without bound under a stream of
* one-shot IPs. */ * one-shot IPs. */
export function createRateLimiter(limit: number, windowMs: number): (key: string) => boolean { export function createRateLimiter(limit: number | (() => number), windowMs: number): (key: string) => boolean {
const hits = new Map<string, number[]>(); const hits = new Map<string, number[]>();
setInterval(() => { setInterval(() => {
const now = Date.now(); const now = Date.now();
@@ -35,6 +36,24 @@ export function createRateLimiter(limit: number, windowMs: number): (key: string
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs); const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
recent.push(now); recent.push(now);
hits.set(key, recent); hits.set(key, recent);
return recent.length > 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;
}
+18 -14
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";
@@ -24,7 +25,6 @@ type NewsItem =
type TextItem = Extract<NewsItem, { kind: "text" }>; type TextItem = Extract<NewsItem, { kind: "text" }>;
const NEWS_DATA_FILE = process.env.NEWS_DATA_FILE; const NEWS_DATA_FILE = process.env.NEWS_DATA_FILE;
const GITHUB_REPO = process.env.GITHUB_REPO ?? "WebSpeak3/webspeak3";
const MAX_ITEMS = 20; const MAX_ITEMS = 20;
const MAX_TEXT = 300; const MAX_TEXT = 300;
const AUTO_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; const AUTO_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
@@ -44,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;
} }
@@ -57,7 +55,7 @@ async function latestRelease(): Promise<NewsItem | null> {
if (Date.now() - release.fetchedAt < 60 * 60 * 1000) return release.item; if (Date.now() - release.fetchedAt < 60 * 60 * 1000) return release.item;
release.fetchedAt = Date.now(); release.fetchedAt = Date.now();
try { try {
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=1`, { const res = await fetch(`https://api.github.com/repos/${process.env.GITHUB_REPO || "WebSpeak3/webspeak3"}/releases?per_page=1`, {
headers: { Accept: "application/vnd.github+json", "User-Agent": "webspeak3-store" }, headers: { Accept: "application/vnd.github+json", "User-Agent": "webspeak3-store" },
}); });
if (!res.ok) return release.item; if (!res.ok) return release.item;
@@ -135,16 +133,22 @@ export async function handleNewsFeed(req: IncomingMessage, res: ServerResponse,
json(res, 400, { error: "bad_request" }); json(res, 400, { error: "bad_request" });
} }
const NEWS_TICKER = process.env.NEWS_TICKER !== "0"; // Read per request: the admin panel (config.ts) can change these at runtime.
const NEWS_TICKER_CENTRAL = process.env.NEWS_TICKER_CENTRAL !== "0"; const localItems = (): NewsItem[] =>
const LOCAL_ITEMS: NewsItem[] = (process.env.NEWS_TICKER_MESSAGES ?? "") (process.env.NEWS_TICKER_MESSAGES ?? "")
.split("|") .split("|")
.map((text) => text.trim().slice(0, MAX_TEXT)) .map((text) => text.trim().slice(0, MAX_TEXT))
.filter(Boolean) .filter(Boolean)
.map((text, i) => ({ id: `local-${i}-${text}`, kind: "text", text, at: "" })); .map((text, i) => ({ id: `local-${i}-${text}`, kind: "text", text, at: "" }));
export function handleNewsConfig(res: ServerResponse) { export function handleNewsConfig(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "public, max-age=300"); res.setHeader("Cache-Control", "public, max-age=300");
json(res, 200, NEWS_TICKER ? { enabled: true, central: NEWS_TICKER_CENTRAL, items: LOCAL_ITEMS } : { enabled: false }); json(
res,
200,
process.env.NEWS_TICKER !== "0"
? { enabled: true, central: process.env.NEWS_TICKER_CENTRAL !== "0", items: localItems() }
: { enabled: false },
);
} }
+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) {
+22 -21
View File
@@ -11,13 +11,12 @@
// 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 STORE_ENABLED = process.env.STORE_ENABLED === "1"; const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
const STORE_ALLOWED_ORIGIN = 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
// feedback.log in index.ts): the store needs to list and look up by id, and // feedback.log in index.ts): the store needs to list and look up by id, and
// the expected volume (community theme submissions) is small enough that // the expected volume (community theme submissions) is small enough that
@@ -42,18 +41,18 @@ const STORE_BASE_THEMES = new Set(["standard", "nova", "pulse", "ide"]);
// STORE_ADMIN_TOKEN may publish under - stops anyone else from impersonating // STORE_ADMIN_TOKEN may publish under - stops anyone else from impersonating
// the maintainer in the author field. Everyone else's name is first-come, // the maintainer in the author field. Everyone else's name is first-come,
// unenforced, same as any other free-text field here. // unenforced, same as any other free-text field here.
const STORE_RESERVED_AUTHORS = new Set( const storeReservedAuthors = () => new Set(
(process.env.STORE_RESERVED_AUTHORS ?? "Möpchi,Moepchi") (process.env.STORE_RESERVED_AUTHORS ?? "Möpchi,Moepchi")
.split(",") .split(",")
.map((s) => s.trim().toLowerCase()) .map((s) => s.trim().toLowerCase())
.filter(Boolean) .filter(Boolean)
); );
const STORE_ADMIN_TOKEN = process.env.STORE_ADMIN_TOKEN;
function isValidStoreAdminToken(provided: string): boolean { function isValidStoreAdminToken(provided: string): boolean {
if (!STORE_ADMIN_TOKEN) return false; const token = process.env.STORE_ADMIN_TOKEN;
if (!token) return false;
const a = Buffer.from(provided); const a = Buffer.from(provided);
const b = Buffer.from(STORE_ADMIN_TOKEN); const b = Buffer.from(token);
return a.length === b.length && timingSafeEqual(a, b); return a.length === b.length && timingSafeEqual(a, b);
} }
@@ -76,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";
@@ -95,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:/,
@@ -103,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;
@@ -131,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 {
@@ -165,7 +166,7 @@ const isStoreRateLimited = createRateLimiter(STORE_RATE_LIMIT, STORE_RATE_WINDOW
const storeRatingsSeen = new Set<string>(); const storeRatingsSeen = new Set<string>();
function setStoreCors(res: ServerResponse) { function setStoreCors(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", STORE_ALLOWED_ORIGIN); res.setHeader("Access-Control-Allow-Origin", storeAllowedOrigin());
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
} }
@@ -346,7 +347,7 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
} }
const isAdmin = isAdminRequest(req); const isAdmin = isAdminRequest(req);
if (STORE_RESERVED_AUTHORS.has(author.toLowerCase())) { if (storeReservedAuthors().has(author.toLowerCase())) {
if (!isAdmin) { if (!isAdmin) {
res.writeHead(403, { "Content-Type": "application/json" }); res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "author_reserved" })); res.end(JSON.stringify({ error: "author_reserved" }));
@@ -373,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;
@@ -506,7 +507,7 @@ export async function handleStore(req: IncomingMessage, res: ServerResponse, pat
res.end(); res.end();
return; return;
} }
if (!STORE_ENABLED) { if (process.env.STORE_ENABLED !== "1") {
res.writeHead(404, { "Content-Type": "application/json" }); res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" })); res.end(JSON.stringify({ error: "not_found" }));
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.
+9 -6
View File
@@ -33,12 +33,17 @@ async function instanceId(): Promise<string> {
return id; return id;
} }
async function ping(id: string) { let id: Promise<string> | undefined;
async function ping() {
// Checked on every ping: the admin panel can switch it on/off live.
if (process.env.TELEMETRY === "0") return;
id ??= instanceId();
try { try {
await fetch(TELEMETRY_URL, { await fetch(TELEMETRY_URL, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, version: VERSION }), body: JSON.stringify({ id: await id, version: VERSION }),
signal: AbortSignal.timeout(10_000), signal: AbortSignal.timeout(10_000),
}); });
} catch { } catch {
@@ -50,8 +55,6 @@ if (process.env.TELEMETRY !== "0") {
console.log( console.log(
`Sending an anonymous usage ping (random instance id + version ${VERSION}) to ${new URL(TELEMETRY_URL).host} at startup and once a day. Disable with TELEMETRY=0.` `Sending an anonymous usage ping (random instance id + version ${VERSION}) to ${new URL(TELEMETRY_URL).host} at startup and once a day. Disable with TELEMETRY=0.`
); );
void instanceId().then((id) => {
void ping(id);
setInterval(() => void ping(id), DAY_MS).unref();
});
} }
void ping();
setInterval(() => void ping(), DAY_MS).unref();
+7 -6
View File
@@ -5,16 +5,17 @@
// most once in that window. // most once in that window.
import { createHmac, timingSafeEqual } from "node:crypto"; import { createHmac, timingSafeEqual } from "node:crypto";
export const TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY ?? ""; // Read at use time: the admin panel (config.ts) can change both at runtime.
const SECRET = process.env.TURNSTILE_SECRET ?? ""; export const turnstileSiteKey = () => process.env.TURNSTILE_SITE_KEY ?? "";
export const TURNSTILE_ENABLED = TURNSTILE_SITE_KEY !== "" && SECRET !== ""; const secret = () => process.env.TURNSTILE_SECRET ?? "";
export const turnstileEnabled = () => turnstileSiteKey() !== "" && secret() !== "";
const PASS_TTL_MS = 12 * 60 * 60 * 1000; const PASS_TTL_MS = 12 * 60 * 60 * 1000;
// Derived from the secret, so passes survive a gateway restart. // Derived from the secret, so passes survive a gateway restart.
const PASS_KEY = createHmac("sha256", SECRET).update("webspeak3-turnstile-pass").digest(); const passKey = () => createHmac("sha256", secret()).update("webspeak3-turnstile-pass").digest();
const sign = (ip: string, expires: number) => const sign = (ip: string, expires: number) =>
createHmac("sha256", PASS_KEY).update(`${ip}|${expires}`).digest("base64url"); createHmac("sha256", passKey()).update(`${ip}|${expires}`).digest("base64url");
export function issuePass(ip: string): string { export function issuePass(ip: string): string {
const expires = Date.now() + PASS_TTL_MS; const expires = Date.now() + PASS_TTL_MS;
@@ -36,7 +37,7 @@ export async function verifyToken(token: unknown, ip: string): Promise<boolean>
try { try {
const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST", method: "POST",
body: new URLSearchParams({ secret: SECRET, response: token, remoteip: ip }), body: new URLSearchParams({ secret: secret(), response: token, remoteip: ip }),
signal: AbortSignal.timeout(10_000), signal: AbortSignal.timeout(10_000),
}); });
const data = (await res.json()) as { success?: boolean; "error-codes"?: string[] }; const data = (await res.json()) as { success?: boolean; "error-codes"?: string[] };
+98
View File
@@ -0,0 +1,98 @@
// Admin panel login and credential changes, against the built gateway
// (npm test builds first). Runs a real process on a free port in a temp dir.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createHmac } from "node:crypto";
import { mkdtempSync, rmSync } 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");
function totp(secretB32, step) {
let bits = "";
for (const c of secretB32) bits += "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(c).toString(2).padStart(5, "0");
const key = Buffer.from(bits.match(/.{8}/g).map((b) => parseInt(b, 2)));
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(step));
const h = createHmac("sha1", key).update(msg).digest();
return String((h.readUInt32BE(h[19] & 15) & 0x7fffffff) % 1e6).padStart(6, "0");
}
const freePort = () => new Promise((ok) => {
const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); });
});
async function startGateway(dir, port) {
const child = spawn(process.execPath, [INDEX], {
cwd: dir,
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", ADMIN_USER: "admin", ADMIN_PASSWORD: "env-password" },
stdio: "ignore",
});
for (let i = 0; i < 50; i++) {
try { await fetch(`http://127.0.0.1:${port}/admin/admin.js`); return child; } catch { await new Promise((r) => setTimeout(r, 100)); }
}
child.kill();
throw new Error("gateway did not start");
}
const stop = (child) => new Promise((ok) => { child.once("exit", ok); child.kill("SIGTERM"); });
function client(port) {
let cookie = "";
return async (p, body) => {
const r = await fetch(`http://127.0.0.1:${port}/admin/api/${p}`, {
method: body === undefined ? "GET" : "POST",
headers: { "Content-Type": "application/json", "X-WebSpeak3-Admin": "1", Cookie: cookie },
body: body === undefined ? undefined : JSON.stringify(body),
});
const set = r.headers.get("set-cookie");
if (set) cookie = set.split(";")[0];
return { status: r.status, data: await r.json().catch(() => ({})) };
};
}
test("password and 2FA set in the panel", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-admin-"));
const port = await freePort();
let gw = await startGateway(dir, port);
try {
const now = Math.floor(Date.now() / 30000);
const a = client(port);
// Mind the limit of 5 login attempts per IP per process start.
assert.equal((await a("login", { user: "admin", password: "env-password" })).status, 200);
const { secret } = (await a("totp-secret")).data;
assert.equal((await a("totp-enable", { secret, code: totp(secret, now), password: "wrong" })).status, 403);
assert.equal((await a("totp-enable", { secret, code: "000000", password: "env-password" })).data.error, "code_wrong");
assert.equal((await a("totp-enable", { secret, code: totp(secret, now), password: "env-password" })).data.totp, "panel");
const b = client(port);
assert.equal((await b("login", { user: "admin", password: "env-password" })).status, 401, "code required now");
assert.equal((await b("login", { user: "admin", password: "env-password", code: totp(secret, now) })).status, 401, "enable code can't be replayed");
const next = totp(secret, now + 1);
assert.equal((await b("login", { user: "admin", password: "typo", code: next })).status, 401);
assert.equal((await b("login", { user: "admin", password: "env-password", code: next })).status, 200, "password typo must not burn the code");
assert.equal((await b("password", { password: "env-password", newPassword: "short" })).data.error, "weak_password");
assert.equal((await b("password", { password: "wrong", newPassword: "new-password-42" })).status, 403);
assert.equal((await b("password", { password: "env-password", newPassword: "new-password-42" })).data.passwordFromPanel, true);
assert.equal((await a("config")).status, 401, "other sessions end on password change");
assert.equal((await b("config")).status, 200);
// Both survive a restart and win over .env.
await stop(gw);
gw = await startGateway(dir, port);
const c = client(port);
assert.equal((await c("login", { user: "admin", password: "env-password", code: totp(secret, now) })).status, 401);
assert.equal((await c("login", { user: "admin", password: "new-password-42", code: totp(secret, now) })).status, 200);
assert.equal((await client(port)("login", { user: "admin", password: "new-password-42", code: totp(secret, now) })).status, 401, "login code can't be replayed");
assert.equal((await c("totp-disable", { password: "new-password-42", code: "000000" })).data.error, "code_wrong");
assert.equal((await c("totp-disable", { password: "new-password-42", code: totp(secret, now + 1) })).data.totp, "");
assert.equal((await client(port)("login", { user: "admin", password: "new-password-42" })).status, 200);
} finally {
await stop(gw);
rmSync(dir, { recursive: true, force: true });
}
});
+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;
+477 -141
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>
<button className="ts-stream-panel-watch" onClick={() => handleWatchStream(info.id)}>
▶ {t("stream.watch")}
</button>
</div>
))}
</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 &&
<button (streamsByClient[clientContextMenu.clientId] ?? []).map((info) => (
className="ts-menu-item" <button
onClick={() => { key={info.id}
handleWatchStream(clientContextMenu.clientId); className="ts-menu-item"
setClientContextMenu(null); onClick={() => {
}} handleWatchStream(info.id);
> setClientContextMenu(null);
<span className="ts-menu-item-icon">📺</span> }}
<span className="ts-menu-item-label">{t("clientContext.watchStream")}</span> >
</button> <span className="ts-menu-item-icon">{streamIcon(info)}</span>
)} <span className="ts-menu-item-label">
{t(info.camera ? "clientContext.watchCamera" : "clientContext.watchStream")}
</span>
</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",
}; };
} }