Compare commits

...
Author SHA1 Message Date
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
Möpchi b856094b48 Merge pull request #19 from VoySpeak/fix/channel-order-and-bans
Fix channel list order and ban feedback, per-identity HWID
2026-11-24 23:21:39 +01:00
Nico B.andClaude Opus 5.5 f67d171001 Fix channel list order and ban feedback, per-identity HWID
- Move-client dialog, permission editor and whisper menu list channels in
  channel-tree order (parent, then its subchannels) instead of a flat sort
  by the per-parent order index or no sort at all.
- A refused banclient now shows an error naming the usual causes; the UI
  logs "Ban requested" instead of claiming the ban succeeded.
- The connector sends a stable HWID derived from the identity's UID instead
  of tsclientlib's built-in one shared by every web user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:57:20 +01:00
MoepchiandClaude Opus 5.5 762554b39d web: center the disconnected/connecting state in the channel tree
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-20 10:34:43 +00:00
MoepchiandClaude Opus 5.5 e96eb62d90 web: friendlier first screen for people without a server
- Connect dialog no longer prefills "localhost" (always rejected on the
  public gateway); empty field with an example placeholder instead.
- Empty channel tree on desktop gets a Connect button and, outside the demo,
  a "No server? Try the demo" link.
- While a connection is being set up the tree shows a spinner,
  "Connecting to <host>…" and a Cancel button instead of "Not connected".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-20 03:39:51 +00:00
MoepchiandClaude Opus 5.5 4afab66d6b Bump tsclientlib: 60 ms minimum audio pre-buffer against jitter wobble
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 17:09:38 +00:00
MoepchiandClaude Opus 5.5 e19ced1bd1 Optional Cloudflare Turnstile bot check before connecting
With TURNSTILE_SITE_KEY and TURNSTILE_SECRET set, the gateway answers a
connect without a valid pass with "turnstileRequired". The browser solves
the (usually invisible) check and resends the connect with the token; the
gateway verifies it and hands out a pass bound to the client IP for 12 h,
so reconnects and new tabs skip the check. Off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 16:50:10 +00:00
MoepchiandClaude Opus 5.5 4e04ddb526 Gateway: log rejected connections over the per-IP limit
Rejections at the WebSocket upgrade (429) were silent, so a client
hammering MAX_CONNECTIONS_PER_IP left no trace. Now logged as a
[ratelimit] line like the connect rate limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 11:31:54 +00:00
MoepchiandClaude Opus 5.5 169d32a292 Client tree: own icons for TeamSpeak's built-in group icons
Built-in group icons (Server Admin, Channel Admin, ...) were plain coloured
letter circles. Now a small person with the group's initial in a coloured
badge, in the style of the mute icons. Own artwork, not a copy of the
native client's icons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 21:01:16 +00:00
MoepchiandClaude Opus 5.5 de94859a16 Client tree: channel group icon after the server group icons
Like the native client: server group icons, channel group icon, then the
flag on the far right. The channel group list is now fetched on connect
like the server group list, and its custom icons are downloaded too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 20:28:16 +00:00
MoepchiandClaude Opus 5.5 810d922b09 Client tree: flags on the far right, work in Chromium on Windows, zzz for away
- Country flag is the rightmost icon, after the group icons.
- Flags render through the Twemoji Country Flags font (CC-BY 4.0), since
  Chromium on Windows has no flag emoji and shows the two letters.
  unicode-range keeps it to flag characters and loads it only on demand.
- Away is the 💤 again, still in place of the talk dot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 20:22:34 +00:00
MoepchiandClaude Opus 5.5 5e76bd3bdf Client tree: away and sound mute replace the talk dot, like the native client
Sound mute is a crossed-out speaker instead of a bell, away a moon.
Order as in TeamSpeak: away, sound muted, mic muted, talking/idle.
Icon pack ids stay the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 20:18:53 +00:00
MoepchiandClaude Opus 5.5 bfe05a8b02 TS2: registered login and Auto fallback
- Connector: --login-name/--login-password (TS_LOGIN_NAME/TS_LOGIN_PASSWORD)
  send a registered login (flag 2 + account name + password).
- Server type "auto" retries as TeamSpeak 2 when the TS3 handshake gets no
  answer, only with ENABLE_TS2=1. Default port 9987 is swapped for 8767.
- Gateway and connect dialog pass account name/password for TS2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 18:38:37 +00:00
MoepchiandClaude Opus 5.5 83877aaa76 TS2: parse channel delete id as u16, surface server refusals (0xff9a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 18:22:30 +00:00
MoepchiandClaude Opus 5.5 6cce28aa9d TS2: fix voice header order and ghost players after logout
- Voice packets: packet counter before conversation id (native client order);
  swapped, the native client stuttered on WebSpeak3 voice.
- Logout: wait for and ack the server's own 'player left'; leaving earlier
  kept us half-present and listed as a ghost to clients joining meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-12 17:20:54 +00:00
MoepchiandClaude Opus 5.5 0d8421692a Mobile menu: pin Feedback to the bottom of the ☰ drawer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-11 08:21:25 +00:00
MoepchiandClaude Opus 5.5 3e84e18535 Mobile menu: hide Feedback while a submenu is open, keep it last in the ☰ panel
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-11 08:17:50 +00:00
MoepchiandClaude Opus 5.5 d3b0d8ccdd Experimental TeamSpeak 2 support behind ENABLE_TS2
New connector module (connector/src/ts2.rs) speaks the TS2 UDP protocol:
login, channel and player lists, Speex voice both ways, status flags,
channel switching, private messages and server messages. Channel/server
chat goes through too but the server only delivers it when the user has
the text permission; a refusal shows up as an error.

Off by default. ENABLE_TS2=1 on the gateway adds "ts2" as a server type
and feature; the connect dialog offers it only then, read from the new
GET /api/features. Documented in the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-10 10:11:25 +00:00
MoepchiandClaude Opus 5.5 9878b1caf3 Master password: say it's asked again every session when turning it on
The README now points to the master password instead of only saying
everything is stored unencrypted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:55:04 +00:00
MoepchiandClaude Opus 5.5 36f510b28e README: new desktop screenshot in a narrower aspect ratio
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:45:36 +00:00
MoepchiandClaude Opus 5.5 faef5c7d19 README: rename phone screenshot so GitHub's image cache picks up the new one
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:35:59 +00:00
MoepchiandClaude Opus 5.5 ecf0285f1c README: new phone screenshot showing the mobile layout
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:33:01 +00:00
MoepchiandClaude Opus 5.5 b11a7a73b8 Mobile: keep the mobile layout under Nova, Pulse and IDE themes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:12:04 +00:00
MoepchiandClaude Opus 5.5 b5e2ce3f7e Mobile: hamburger menu opens as a left drawer sized to its entries
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 10:01:51 +00:00
MoepchiandClaude Opus 5.5 e5cda8301d Mobile: back chevron vertically centred with its label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:57:50 +00:00
MoepchiandClaude Opus 5.5 708ad72e59 Mobile: dialogs as bottom sheets / full-screen pages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:51:22 +00:00
MoepchiandClaude Opus 5.5 85fa73c7d6 Hamburger menu: picking an entry closes the whole panel
It stayed open on top of the dialog the entry had just opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:44:16 +00:00
MoepchiandClaude Opus 5.5 8a3e1c230e Mobile: open submenu fills the screen with a sticky back row
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:38:09 +00:00
MoepchiandClaude Opus 5.5 b50dc338df Mobile: hamburger menu drills into one submenu with a back row
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:34:56 +00:00
MoepchiandClaude Opus 5.5 b40ada8cff Mobile options: no outline on the last-picked section
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:30:38 +00:00
MoepchiandClaude Opus 5.5 fa2c68b622 Mobile: options as full-screen list -> page with back button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:30:30 +00:00
MoepchiandClaude Opus 5.5 54046d51fe Mobile: active tab highlight wraps icon and label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:23:51 +00:00
MoepchiandClaude Opus 5.5 9364a7d48a Mobile: readable accent buttons, calmer disconnected state, no demo toggle on phones
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:21:33 +00:00
MoepchiandClaude Opus 5.5 dab1a7637e Demo mobile preview: keep floating buttons inside the phone frame
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-09 09:19:15 +00:00
MoepchiandClaude Opus 5.5 a4da3409bc Mobile: own touch layout with bottom voice bar and tabs
Below 700px (or with the demo's mobile toggle) the client switches to its own
shell instead of squeezing the desktop layout: header with the menu behind a
hamburger, one full-height panel at a time (channels / chat / info), big
mic / sound / leave buttons and a tab bar at the bottom. Touch targets are at
least 44px, the chat input is 16px so iOS doesn't zoom. Desktop is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-08 21:14:33 +00:00
MoepchiandClaude Opus 5.5 da985ef7d1 README: add table of contents
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-08 21:00:52 +00:00
MoepchiandClaude Opus 5.5 806de52382 i18n: drop Weblate, take translations via pull request
Weblate stayed pinned to the pre-transfer repo URL and stopped syncing.
The in-app links now point to a new README section explaining how to
fix or add a language with a PR or by sending the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-08 20:50:03 +00:00
MoepchiandClaude Opus 5.5 d299343835 stream: add webcam as a stream source
The stream dialog gets a source choice: screen/window via the browser
picker, or the camera via getUserMedia, announced to TS6 as type=1
(CAMERA). Camera streams send no audio track, since that would be the
microphone a second time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-05 11:28:51 +00:00
MoepchiandClaude Opus 5.5 10ae24a99f i18n: add Russian translation (beta)
Russia is the third-largest country in the connection stats and had no
translation yet. Machine-assisted, so marked (Beta) until a native
speaker has reviewed it, like Persian.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-26 22:00:36 +00:00
MoepchiandClaude Opus 5.5 ffb542d9bd Connector: say VoySpeak instead of GreenTeaSpeak
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-25 21:03:17 +00:00
MoepchiandClaude Opus 5.5 e02a41d855 Tell clients when the gateway is full; default limit 60
A browser can't see why a WebSocket upgrade was refused, so a full gateway
now accepts, sends a gateway_full error and closes. The client shows a
translated hint that includes self-hosting. Default MAX_CONNECTIONS drops
from 300 to 60 after measuring ~8-9 % of a core per listening client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-25 20:45:15 +00:00
MoepchiandClaude Opus 5.5 999262b6df Remove the GreenTeaSpeak theme; it is VoySpeak now
GreenTeaSpeak was renamed to VoySpeak with new colours, so the theme no
longer matches anything. The server tab strip that lived in the theme
module moves to ConnectionTabs. A saved GreenTeaSpeak pick or custom-theme
base falls back to Standard. Server-compat wording says VoySpeak.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-25 20:45:15 +00:00
MoepchiandClaude Opus 5.5 9e61f21316 Open #about / #options links from the ticker in the same window
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-25 08:06:55 +00:00
MoepchiandClaude Opus 5.5 a720f72943 Open Options on a section from an #options/<id> link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-25 08:02:04 +00:00
MoepchiandClaude Opus 5.5 9a4639f76c Identities: wide enough unique ID field
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-24 19:46:27 +00:00
MoepchiandClaude Opus 5.5 bf6ab112ed Identities: compute the unique ID from the stored key instead of showing Unbekannt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-24 19:14:21 +00:00
MoepchiandClaude Opus 5.5 9e4ff35e8e Invite a friend: WebSpeak3 join link, whisper history cleanup as spin box, German typing attenuation label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-24 08:12:23 +00:00
MoepchiandClaude Opus 5.5 5b61def4b2 Konto: hide the default sync server address, empty field = default
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-24 07:51:37 +00:00
MoepchiandClaude Opus 5.5 0a9dd545b1 Account sync: Mullvad-style, end-to-end encrypted
Options -> Konto: random 16-digit account number, optional random password,
no personal data. The browser derives account id, AES key and auth secret,
so the new standalone sync server (node dist/sync-server.js, SYNC_DATA_DIR)
only stores padded encrypted blobs. Proof-of-work on account creation,
1 year expiry, no IP logging. Pulled at startup, pushed when synced keys
change, conflict prompt when both sides changed. QR link, recovery file,
per-category selection; device-specific keys stay local. Self-hosters can
run their own and set SYNC_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-24 07:40:00 +00:00
MoepchiandClaude Opus 5.5 a82c99972e Options: drop advanced permission system toggle
The web permission editor is the advanced one only; the switch had nothing to switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:58:57 +00:00
MoepchiandClaude Opus 5.5 8ce9848493 Options: Anwendung tab laid out like native
Server/Verschiedenes/Channel-Abo groups with working toggles (mic on server
switch, reconnect after sleep, middle-click quick access, nickname to
favorite, auto-open channel chat, muted-talking hint, no poke dialog).
Browser-impossible options (always on top, autostart, update channel,
statistics, reset confirmations) left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:52:19 +00:00
MoepchiandClaude Opus 5.5 440e7b7ae8 Options -> Sicherheit: real master password
Identities, favorites (with their passwords), saved channel passwords and the
store admin token are kept AES-GCM encrypted (PBKDF2, 310k rounds) in one
localStorage entry and only decrypted in memory. The app asks for the password
on load before App is imported; "forgot password" wipes the encrypted data.
Enable, change and disable (the latter two re-ask the current password).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:43:40 +00:00
MoepchiandClaude Opus 5.5 14aa44c1c9 Options -> Meldungen: multiple-choice text position (Server/Channel/Client), 'only important sounds' when muted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:38:13 +00:00
MoepchiandClaude Opus 5.5 b808e2ec99 Options -> Meldungen: checkmark applies the sound pack to all favorites
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:30:42 +00:00
MoepchiandClaude Opus 5.5 b4bd62c1b5 Options: Meldungen tab (TS3 notification tree, sound packs, text position)
All 93 TS3 notification keys in the native tree layout (Aktion / Sound Skript /
Text Position), per-row and per-group checkboxes, editable scripts (play/say),
customized rows in bold. Sound packs: WebSpeak3 default, no sounds, or an
imported .ts3_soundpack (settings.ini parsed 1:1). "Wenn Ausgabe stumm", and a
per-favorite sound pack override in the favorites dialog. Existing sound
triggers now go through the keys; server log lines follow Text Position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:26:40 +00:00
MoepchiandClaude Opus 5.5 7f8fada880 Options: Sicherheit tab (saved channel passwords, cleanup, identities)
Opt-in saved channel passwords per server (dropped when rejected), delete
button, clear cache / collected URLs on exit, "Cache löschen" (service
worker caches + icon/avatar/GIF caches, refetched right away) and a shortcut
to the identities dialog. Master password greyed out for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 20:07:30 +00:00
MoepchiandClaude Opus 5.5 977f5d2c3b Options -> Chat: line counts as spin boxes like the native client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 19:57:41 +00:00
MoepchiandClaude Opus 5.5 e76278c5b8 Options: Chat tab (line limit, font, chat logs, unread hints)
Max lines per chat tab, chat font family/size, per-server local chat logs
(channel/private/server, last 1000 lines each, also for background tabs),
reloading the last N logged lines into channel/private chats (shown dimmed),
and unread highlighting for server/channel/private tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 19:54:13 +00:00
MoepchiandClaude Opus 5.5 bc2d1f65a0 Tag file transfer errors with channel + path; feature-gate new gateway messages
Connector transfer errors stay type "error" (old clients unchanged) but now
carry cid/path, so the transfer window marks the right transfer as failed.
setWhisperPolicy/setTransferLimit are only sent to gateways that announce
whisperPolicy/transferLimit, so older gateways don't log "Unknown message type".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 19:47:15 +00:00
MoepchiandClaude Opus 5.5 d0fc97d921 Options: Download tab with transfer window, queue and bandwidth limits
Download folder via the File System Access API (Chromium; browser default
elsewhere), "ask every time" save dialog, file transfer window with progress,
completion pop-up, concurrent upload/download caps and connector-side
bandwidth limits (new "ftlimit" stdin command / setTransferLimit message).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 19:32:25 +00:00
MoepchiandClaude Opus 5.5 7b98cb2d7c Whisper settings: incoming whisper rights, sound, history auto-open/cleanup
Options -> Whispern like TS3: allow/block by default with per-contact
overrides (new Whisper field in contacts) or block all. The connector drops
blocked whispers before decoding (whisperpolicy stdin command) and reports
accepted ones as whisperReceived, which logs them in the whisper history,
plays the new whisper sound and can open the history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 19:01:53 +00:00
MoepchiandClaude Opus 5.5 2e6b295185 Design tab: one theme dropdown for built-in and custom designs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:50:11 +00:00
MoepchiandClaude Opus 5.5 6e2278498c Design tab: real group icons in group menus, client info tooltips
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:37:09 +00:00
MoepchiandClaude Opus 5.5 ae7c24bd37 Design tab: native TS3 layout, icon packs, channel tree and GIF options
Style/theme/icon pack dropdowns, a manage view for designs and icon packs
(.ts3_iconpack import), channel tree options (expand depth/own channel,
clients below, flags, commander lamp, away message, tooltips, group icons
in menus) and GIF animation toggles. Overwolf, badges and inaccessible
groups are greyed out until the connector forwards that data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:27:23 +00:00
MoepchiandClaude Opus 5.5 ced63fdb2a Make continuous transmission and typing attenuation work
Continuous transmission is a third activation mode next to push-to-talk
and voice activation (the toolbar hides the VAD slider then). Typing
attenuation damps the mic to 10% for 0.2 s after each keystroke, so typing
in the client doesn't trigger voice activation. Both off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:10:01 +00:00
MoepchiandClaude Opus 5.5 d860aa61e5 Softer test tone
Half the volume, with a fade in and decay instead of hard edges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:06:23 +00:00
MoepchiandClaude Opus 5.5 341a1644a6 Mic clicks as regular sounds, own clicks off by default
The two clicks now live in the sound settings (toggle, test, custom file,
soundpack import via mic_click_on/off) instead of being fixed tones in the
voice player. Own mic clicks start off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 18:03:04 +00:00
MoepchiandClaude Opus 5.5 97421ff2de Make the three playback options work
Automatic volume leveling runs incoming voice through a compressor,
own mic clicks tick when you start/stop transmitting, and other clients'
mic clicks tick when someone else does. Defaults match TS3 (on, on, off)
and are stored like the other audio settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-23 17:59:12 +00:00
MoepchiandClaude Opus 5.5 d64b25f22f Play straight to the AudioContext where devices can't be switched
On Android (Chrome and Firefox) the hidden <audio> element fed from a
MediaStreamAudioDestinationNode stays silent even after play(). It only
exists for HTMLMediaElement.setSinkId, which those browsers don't have,
so connect playback directly to context.destination there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 20:53:18 +00:00
MoepchiandClaude Opus 5.5 be7247f3f6 Fix silent playback on phones
Playback runs through a hidden <audio> element that only had autoplay
set, which mobile browsers ignore for audible media, so it never started.
Call play() on it from a user gesture (any tap/key, and the test tone
button). Also listen for pointerup: on touch screens pointerdown is not a
user activation, so resuming the AudioContext from it alone failed too.

Reported via feedback (Chrome on Android, no voice or test tone) and
reproduced with Firefox on Android.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 20:48:34 +00:00
MoepchiandClaude Opus 5.5 bcdbabe201 News ticker: scroll a bit slower
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 20:02:30 +00:00
MoepchiandClaude Opus 5.5 3c24ddc7d3 News ticker: constant scroll speed
Derive the animation duration from the distance travelled instead of
the item count, so wide screens no longer scroll faster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 19:54:33 +00:00
MoepchiandClaude Opus 5.5 94b290fa06 News ticker: show each message once per pass
The duplicated content for a seamless loop put two copies on screen when
there are only a few messages. Run a single copy from the right edge
until it has left on the left instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 19:51:21 +00:00
MoepchiandClaude Opus 5.5 bf6008f857 Open the About dialog from a #about link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 19:45:07 +00:00
MoepchiandClaude Opus 5.5 632e77ccc8 Add news ticker at the bottom of the client
Central feed (/api/store/news on the store server: manual items via
STORE_ADMIN_TOKEN, plus the latest release and newest store design for
30 days) and a per-gateway /api/news with NEWS_TICKER, NEWS_TICKER_CENTRAL
and NEWS_TICKER_MESSAGES so self-hosters can turn it off or add their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 18:38:00 +00:00
MoepchiandClaude Opus 5.5 aa324274a4 Feedback: keep the bug report's server out of the public issue
The server is sent as its own field and only appended to the private
feedback log, like the contact e-mail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 18:28:13 +00:00
MoepchiandClaude Opus 5.5 00c8cfac06 Feedback: ask bug reports for browser/OS, server and steps
Bug reports now prefill a detected browser/OS (editable), offer optional
server and steps fields, and append a visible block of technical details
(page, user agent, language, audio context state, setSinkId support).
Everything is folded into the message, so gateway and storage are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-22 12:04:25 +00:00
MoepchiandClaude Opus 5.5 ff570d9131 README: add memorial section for Akimo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-21 13:17:24 +00:00
MoepchiandClaude Opus 5.5 b5a5ec5236 Add About dialog with a permanent memorial for Akimo
Help → About now opens a small dialog instead of linking out. It
carries a dedication to Akimo, the project owner's dog, who crossed
the rainbow bridge on 2026-10-21. This part stays in for good.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-21 12:40:01 +00:00
MoepchiandClaude Opus 5.5 5a639628a9 Trigger Pages build after the move to the WebSpeak3 org
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-19 15:49:13 +00:00
MoepchiandClaude Opus 5.5 7a0a64b518 Point links at the new WebSpeak3 organization
The repo moved from Moepchi/webspeak3 to WebSpeak3/webspeak3. GitHub
redirects the old URLs, but the feedback-to-issue default (GITHUB_REPO)
POSTs to the API, and a 301 there turns the POST into a GET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-19 15:26:08 +00:00
Möpchi 935b867c76 Update README.md 2026-10-19 16:14:29 +02:00
MoepchiandClaude Opus 5.5 cc70bc4736 Anonymous usage ping from self-hosted gateways
On startup and once a day the gateway sends a random instance id and its
version to gateway.webspeak3.de (TELEMETRY=0 turns it off, the startup log
says so). The standalone store server receives it with PING_DATA_FILE set,
keeps id/version/first/last seen without IPs, and serves admin-only counts.
The release tag is baked into the image as WEBSPEAK3_VERSION.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-19 09:01:59 +00:00
MoepchiandClaude Opus 5.5 603cedd907 Push-to-talk with custom key/mouse button, Hotkeys options, standalone store
- Push-to-talk: configurable key or middle/side mouse button (tab must be
  focused), hold button in the toolbar, settings under Capture and the new
  Options -> Hotkeys page, which also lists the fixed shortcuts.
- Design Store rejects uploads whose CSS is already in the store.
- gateway/src/store-server.ts runs the store as its own process from the
  same image, so store deploys don't drop voice connections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-19 08:40:03 +00:00
MoepchiandClaude Opus 5.5 803cefd653 Give Command Center its own sounds and a pixel terminal font
Command Center now plays short synthesized blips instead of the default
chimes, and every layout gets a mute toggle sound. The layout uses the
self-hosted VT323 pixel font throughout; a design option switches back
to the previous sans/mono mix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-18 17:46:29 +00:00
MoepchiandClaude Opus 5.5 01faa6593c Self-host Manrope instead of loading it from Google Fonts
Loading from fonts.googleapis.com sends every visitor's IP to Google.
The OFL-licensed files now ship with the client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-18 17:46:29 +00:00
MoepchiandClaude Opus 5.5 e28e89bc60 Simulate a busy server in the demo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-18 12:34:11 +00:00
MoepchiandClaude Opus 5.5 8d8d942038 Keep double-clicks on controls from selecting text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-18 12:34:11 +00:00
MoepchiandClaude Opus 5.5 e28e18c88c Add the Command Center (IDE) layout
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-18 12:34:11 +00:00
MoepchiandClaude Opus 5.5 2615904b1e Send server-log field names in camelCase
rename_all on the enum only renamed the kind tags, so the channel switch
entry arrived as from_channel/to_channel and the Server tab showed the raw
{fromChannel}/{toChannel} placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-16 08:41:58 +00:00
MoepchiandClaude Opus 5.5 5e7add6dc8 Drain queued packets before audio ticks in the connector
After a stall (CPU steal on the host), the missed 20 ms ticks fire in a
burst. With an unbiased select a tick could run before the already
received voice packets were processed, find an empty queue and play Opus
loss concealment, which sounds like a slowed-down tape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-16 08:18:20 +00:00
MoepchiandClaude Opus 5.5 983ce1e105 Rejoin the last channel after an automatic reconnect
A dropped gateway connection reconnected with the original connect
parameters, so everyone landed in the server's default channel again.
The reconnect now aims at the channel the user was in ("/<id>"), with
its cached password if one was entered.

The client log also records why a gateway connection ended: the
WebSocket close code, or the keepalive watchdog firing. Until now a drop
left no trace on the client side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-15 12:14:12 +00:00
MoepchiandClaude Opus 5.5 7d14c3409e Wait longer for the release preview image before giving up
GitHub's image service answered 429 for the whole 20 seconds after the
v0.16.0-beta.5 release, so the Bluesky post went out without a card. Back
off 15/30/45/60 s and honor Retry-After (capped at 60 s), which fits in
the job's 5-minute timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-11 15:24:01 +00:00
MoepchiandClaude Opus 5.5 882265beae Send file transfers in 192 KiB pieces instead of one message
A whole file used to cross the gateway as a single base64 line, which
readline, JSON.parse and JSON.stringify each copied: over 100 MB of heap
for one 25 MB download. Two parallel downloads ran the gateway out of
memory on 2026-10-11.

Downloads now arrive as fileDownloadChunk events that the web client
joins back together. Uploads go out as uploadFileChunk pieces when the
gateway announces "chunkedUpload"; older gateways still get the single
uploadFile message, and the gateway keeps accepting it from cached
clients.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-11 14:59:07 +00:00
MoepchiandClaude Opus 5.5 0aefd4198b ci: add a link preview card to Bluesky release posts
The Bluesky app builds the card itself when a link is pasted, the API
doesn't. Uses GitHub's social preview image for the release page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-07 18:46:00 +00:00
MoepchiandClaude Opus 5.5 3a91a8db07 ci: announce releases on Bluesky
Posts the first paragraph of the release notes plus the link. Notes with
<!-- no-social --> are skipped; a manual run defaults to a dry run that only
logs in and prints the post.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-07 18:05:55 +00:00
rex2630andClaude Opus 5.5 51d7e107e5 i18n: add Czech translation (#14)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-07 19:25:04 +02:00
MoepchiandClaude Opus 5.5 1e71e43bd7 fix(web): only reset the reconnect backoff after a stable connection
On a flaky network every successful reconnect reset the backoff to 1 s,
so a connection that kept dropping after a few seconds made each tab
reconnect every few seconds. The backoff now starts over only once a
connection held for 30 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-07 17:04:06 +00:00
MoepchiandClaude Opus 5.5 c2b52b323d fix(gateway): rate-limit server connects per IP
Each "connect" spawns a new connector and a socket could send any number
of them, so a handful of sockets could join-flood a TeamSpeak server
through the gateway. New CONNECT_RATE_LIMIT (default 30/min per IP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-07 11:47:05 +00:00
MoepchiandClaude Opus 5.5 bbb44b3eaa fix(gateway): don't let clients pick their IP behind TRUST_PROXY
TRUST_PROXY=1 trusted CF-Connecting-IP and the first X-Forwarded-For
entry, both of which a client can send itself when the proxy in front
isn't Cloudflare (nginx's $proxy_add_x_forwarded_for only appends), so
per-IP limits could be sidestepped. Now TRUST_PROXY=1 takes the last
X-Forwarded-For entry (the one the proxy appended), and the new
TRUST_PROXY=cloudflare takes only CF-Connecting-IP. The bundled compose
file (cloudflared) switches to cloudflare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-05 18:31:13 +00:00
MoepchiandClaude Opus 5.5 bda908029b docs: link the wiki's full environment variable list from the README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-05 18:14:27 +00:00
MoepchiandClaude Opus 5.5 45e4af026f feat: offer ALLOWED_SERVERS as a dropdown or locked address field
With ALLOWED_SERVERS set, the gateway now passes the list to the web client
it serves, and the connect dialog shows a dropdown of those servers instead
of a free-text address, or a locked field when only one is allowed.
SERVER_PICKER=0 keeps the plain text field; lists with *. wildcards can't be
enumerated and keep it too. Entries may now carry a port, which is the
address offered in the dialog (the allowlist still ignores ports).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-05 15:06:45 +00:00
MoepchiandClaude Opus 5.5 ef0e3fad7d feat: more BBCode tags, basic Markdown and an opt-in for chat images
Chat now renders [size], [left]/[center]/[right], [list]/[*], [hr] and
[noparse] plus the Markdown TS6 sends (emphasis, code, links, images,
quotes, lists, headings, rules, escapes). [img] stays a link unless
"Load images in chat" is enabled in Options -> Application (off by
default, since loading reveals the reader's IP to the image host).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-04 11:09:05 +00:00
MoepchiandClaude Opus 5.5 839e26e4a3 feat: send links as [URL]...[/URL] like the native clients
Native TeamSpeak clients wrap links in [URL] tags when sending and only
link tagged ones, so a bare URL typed in the web client stayed plain
text for them. Chat and offline messages now wrap bare http(s) URLs;
links that are already tagged are left alone.

Also stops the collected-URLs list from picking up "[/URL]" as part of
a link, by sharing the renderer's URL pattern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-04 10:32:10 +00:00
MoepchiandClaude Opus 5.5 e37e090ab2 feat: render BBCode in chat messages
Server, channel and private chat now render [b] [i] [u] [s] [color]
[url] (and [img] as a plain link), and bare http(s) URLs become links -
the welcome message's [URL]...[/URL] showed up as raw text before.
Built as React elements, so message text can't inject markup; only
http(s) links are allowed and [color] only takes a name or hex value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-04 10:29:05 +00:00
MoepchiandClaude Opus 5.5 9b836d5830 Fix server-edited log spam and chat panel growing with its lines
The 20s servergetvariables poll is answered with notifyserverupdated,
which tsclientlib applies as a PropertyChanged per field even when
nothing changed - so every poll logged "server settings changed".
Only log for notifyserveredited, the one that carries an invoker.

In the classic design .ts-chat-panel lacked min-height: 0, so the
message list grew with every line instead of scrolling, pushing the
chat input off-screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-04 09:33:33 +00:00
MoepchiandClaude Opus 5.5 d36b94a496 feat: arrow-key tree and menus, real buttons, contrast fixes
Accessibility stage 2.

- The channel tree is an ARIA tree with one Tab stop. Up/Down/Home/End walk
  the visible rows, Left/Right collapse, expand, or jump to parent and first
  child, and selection follows focus. The server row is focusable too.
- Menu bar entries are buttons with aria-expanded. Dropdown and context
  menus focus their first item on open, move with the arrow keys (except
  inside the volume slider), and Escape returns focus to the opener.
- Bookmark and contact list items, chat tabs and server tabs work from the
  keyboard (Delete closes a tab, since its × can't be a nested button).
- <main> landmark and a level-1 heading for screen-reader navigation.

An axe-core scan of the connected UI in every built-in design turned up
contrast failures, three of them real bugs: the active server tab, the
update toast and the feedback bubble sit on a fixed dark background but used
the theme's text colour, so the light theme showed dark-on-dark text. Also
darkens the light theme's muted text, the donate button, and lifts
GreenTeaSpeak's muted grey to 4.5:1 (its selection colour stays native).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-04 09:19:24 +00:00
MoepchiandClaude Opus 5.5 b84dc0faac chore: hide the tab audio button for now
It clicks in the mix and Edge delivers Windows system audio as silence;
parked until there's time to move capture to an AudioWorklet. The code
stays in place behind TAB_AUDIO_SUPPORTED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:42:54 +00:00
MoepchiandClaude Opus 5.5 4752971f31 fix: shared audio clicked and clipped in the voice mix
The shared source is mixed in at -6 dB so music near full scale doesn't
clip with the voice on top. With AEC3 its blocks made the extra queue run
short now and then, which was padded with silence (clicks); it now skips
once and stays a frame ahead, capped to bound latency.

Drops the temporary diagnostics: Edge delivered silence for Windows system
audio even without the mic open, so the hint now points to sharing a tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:40:02 +00:00
MoepchiandClaude Opus 5.5 93b809ff9a fix: shared tab/system audio arrived silent in Edge
Edge ran its echo canceller on the display-capture track (getSettings showed
echoCancellation: true on deviceId "loopback"), which subtracts exactly
what the speakers play - the whole signal. Voice processing is now off for
that track; noise suppression would mangle music anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:27:39 +00:00
MoepchiandClaude Opus 5.5 fa3fa2e4ad chore: temporary diagnostics when shared audio stays silent
Measures the captured track directly, next to the mixer's view, to tell a
silent capture apart from a mixing bug (Edge + Windows system audio report).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:24:28 +00:00
MoepchiandClaude Opus 5.5 16e3cd8dd7 fix: keep the capture's video track alive while sharing tab audio
Stopping it right away may end or silence the capture session the audio
track belongs to (suspected with Windows system audio in Edge). It runs at
1 fps and stops together with the audio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:19:19 +00:00
MoepchiandClaude Opus 5.5 9d736dbfdd feat: warn when shared tab/system audio stays silent
Windows system audio only covers the default playback device, so music on
another device is mixed in as pure silence with no hint why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:13:23 +00:00
MoepchiandClaude Opus 5.5 5268c8f57a fix: offer tab audio only in Chromium-based browsers
Firefox and Safari give getDisplayMedia video without audio, so the button
could only ever answer "no audio" there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 09:02:30 +00:00
MoepchiandClaude Opus 5.5 deabfbff3c feat: server banner can be turned off; document what the browser stores
Review S12: the banner loads from a host the server admin picks, which sees
the viewer's IP. It's now a switch under Options -> Application and is
requested without a referrer. Proxying it through the gateway would make the
gateway fetch arbitrary URLs, so that's left out.

Review S10: identities and favorite passwords stay in localStorage (the
native client keeps them in plain settings files too; favorite passwords
are already optional). The README now says so.

Also labels the dialogs' close buttons for screen readers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 01:54:31 +00:00
MoepchiandClaude Opus 5.5 81107c659e feat: keyboard and screen-reader basics for dialogs, toolbar, and tree
Dialogs move focus in on open, trap Tab, close on Escape, and return focus.
Toolbar icon buttons get aria-labels; away/whisper carets expose their menu
state. Channel and client rows are focusable: Enter joins/opens chat, Space
selects, arrows collapse/expand, the context-menu key opens the menu with
focus on its first item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 01:50:29 +00:00
MoepchiandClaude Opus 5.5 bf4507ae9d feat: share a tab's or window's audio into the voice channel
The new toolbar button asks the browser for a tab or window with audio and
mixes it into what the mic sends. It joins after AEC3, per 20 ms frame, so the
canceller only ever sees the mic, and while sharing the voice activation stays
open so music pauses don't cut out. Hidden where getDisplayMedia is missing
(mobile); a restarted mic picks the shared audio up again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 01:42:13 +00:00
MoepchiandClaude Opus 5.5 12e482b223 fix: recover from silent network drops on both sides of the gateway
Measured with relays that blackhole traffic:

- Gateway to TS server: tsclientlib reconnects on its own after a timeout or
  server restart, but the connector ignored that, so the browser got no notice
  and the new session stayed unsubscribed - everyone but us vanished from the
  tree. The connector now emits "reconnecting"/"reconnected", resubscribes,
  and pauses the server-variable poll meanwhile; the page logs both.
- Browser to gateway: a network that dies silently never closed the socket on
  the page, which kept showing "connected" indefinitely. The gateway now sends
  an app-level keepalive every 20 s (announced as "keepalive" in hello), and
  a socket quiet for 50 s is handled as dropped and reconnected.
- Coming back online skips any remaining reconnect backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 01:37:13 +00:00
MoepchiandClaude Opus 5.5 23e61c86b3 feat: optional TURN relay for screen streams
TURN_URLS on the gateway is handed to the browser in "hello" and added to the
STUN defaults for both watching and publishing. With TURN_SECRET (coturn's
use-auth-secret) each socket gets its own credential valid for 24 h; static
TURN_USERNAME/TURN_CREDENTIAL work too but are public to every visitor.

Also moves GATEWAY_FEATURES above the runtime-config comment it had split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 00:58:22 +00:00
MoepchiandClaude Opus 5.5 d67053f2dd docs: list Persian (Beta) and the new tree, avatar, and volume features
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 00:54:44 +00:00
MoepchiandClaude Opus 5.5 728c900bb2 feat: search channels and users in the tree
A search field above the channel tree filters it live: a channel whose name
matches keeps all of its clients, a client whose name matches keeps its
channel, and the parent chain of every match stays so it is shown in place.
Collapsed channels open while searching; Escape clears the field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 00:53:06 +00:00
MoepchiandClaude Opus 5.5 4b245d69d3 feat: show real TeamSpeak avatars
The connector now reports client_flag_avatar (the avatar's MD5) per client.
The browser derives /avatar_<uid> from the UID and fetches it through the
existing channel-0 file cache used for group icons, again whenever the hash
changes. Only the own channel and the selected client are fetched, so a big
server does not push every avatar through the gateway; avatars are capped at
512 KiB like icons. They replace the initials tile in the tree (Nova/Pulse),
the speaking-now bar, and appear in the client info panel.

Also fixes the Nova connect dialog staying open over an auto-connect: its
"forced open while disconnected" effect ran after the auto-connect had closed
it, and nothing closed it again once connected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 00:50:54 +00:00
MoepchiandClaude Opus 5.5 7b3cb5ef09 feat: per-speaker volume and a gateway feature handshake
The gateway now greets every browser with {type:"hello", features:[...]} so
the hosted client, which updates on every push, can hide what an older
gateway cannot do instead of hanging on it. A gateway without "hello" is
treated as the v0.14 feature set, which replaces the hand-flipped
STREAM_UI_ENABLED switch.

First feature behind it: "clientVolume". The client context menu gets a
0-200% slider, stored per client UID in localStorage. The connector applies
it to tsclientlib's per-speaker AudioQueue.volume while mixing, and keeps the
value across talk pauses, when that queue is torn down and recreated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-03 00:34:12 +00:00
Stephan SeifermannandClaude Opus 5.5 c0778c8adb Docker: provide images for amd64 and arm64 (#13)
The connector is cross-compiled with tonistiigi/xx on the build platform
(pinned by digest); web-builder and gateway-builder also run natively there
since their output is platform-independent JS. Only the runtime stage runs
per target platform. README mentions the arm64 image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-02 11:49:32 +02:00
MoepchiandClaude Opus 5.5 8e934c6646 Default server/channel as runtime config for the Docker image (#12)
DEFAULT_SERVER/DEFAULT_CHANNEL used to be build args only, so pointing a
self-hosted instance at its server meant cloning the repo and rebuilding
the image. The gateway now reads them from its own environment and puts
them into the index.html it serves as <meta> tags (HTML-escaped; an
inline script would be blocked by the page's CSP). The client prefers
those over the build-time VITE_ values, which keep working as before.

Closes #12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-10-02 07:26:05 +00:00
MoepchiandClaude Opus 5.5 a9f0586b88 web: keep the PWA's SPA fallback away from the gateway's /api/ pages
With UI and gateway on one origin, the service worker answered a
navigation to /api/store/admin with index.html, so the moderation page
opened the client instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 20:12:02 +00:00
MoepchiandClaude Opus 5.5 ddc7ce5dec Compose: trust the tunnel's client IP by default
The bundled setup is only reachable through cloudflared, so without
TRUST_PROXY every user shares one IP and the per-IP connection limit (10)
would cap the whole instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:45:16 +00:00
MoepchiandClaude Opus 5.5 a79f2aa4a7 CI: pin actions to commit SHAs, pass release tag via env (S14)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:20:47 +00:00
MoepchiandClaude Opus 5.5 2b668a7f73 Gateway: unreadable store file fails loudly instead of reading as empty (S13)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:20:47 +00:00
MoepchiandClaude Opus 5.5 eba1e1af92 Web: smaller review fixes (A10-A19, S10, S11, lint)
- A10: drop labels of unimplemented shortcuts, localize "Ctrl", never
  fire shortcuts (Ctrl+D!) while typing in a field
- A11: in-memory localStorage stand-in when storage is blocked instead
  of a blank page
- A12: invite link falls back to selecting the text without clipboard API
- A13: AEC3 script honors BASE_URL, failed loads are retried
- A14: shared downloadBlob helper, object URLs revoked with a delay
- A15: remaining hardcoded German/English strings moved to the locales
- A16: broken soundpack files show an error instead of failing silently
- A17: connect buttons no longer pass the click event as overrides
- A18: design base persisted from the resolved theme
- A19: no audio send() while the socket is still connecting
- S10: privilege keys are no longer persisted in localStorage
- S11: share links can carry the token in the fragment (#token=)
- oxlint: 0 warnings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:20:47 +00:00
MoepchiandClaude Opus 5.5 034be9cc77 Docker: run as unprivileged user, drop capabilities (S8)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:08:19 +00:00
MoepchiandClaude Opus 5.5 92479d8a38 Web: end streams when their server tab is parked (A9)
Viewer, publisher and streamInfos are global, so after a tab switch a
running stream's signaling went to the new server's socket and stream
infos showed up in the other tab under clids that name other people.
Parking a tab now stops watching/publishing (still via the old socket)
and clears the stream infos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:07:41 +00:00
MoepchiandClaude Opus 5.5 37a84e4cee Web: permissions editor no longer edits the previous tab's target (A5)
Server and channel group ids overlap, and the editor kept both groupId
and the loaded entries across tab switches - so after switching from
server group 6 to the channel group tab, delete/add hit channel group 6
while the table still showed server group 6. The group selection now
resets between the group tabs, the new tab reloads, and entries are only
shown while they belong to the target on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:06:45 +00:00
MoepchiandClaude Opus 5.5 e89d83c4bb Web: socket handlers always see current state (A6)
wireSocket's handlers were created once per socket, so they kept the
state from connect time: "ignore contact" never applied, the file list
didn't refresh after uploads, the channel-password dialog lacked the
name, log texts stayed in the old language and reconnect restarted the
mic with old settings. The handlers are now rebuilt every render and
the socket calls the latest version through a ref.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:05:26 +00:00
MoepchiandClaude Opus 5.5 57447fdd11 Design Store: moderation queue and stricter CSS check (S4, S13)
New submissions are "pending" until approved by the STORE_ADMIN_TOKEN
holder via the new /api/store/admin review page (CSS shown as text only).
Theme CSS is normalized (comments, escapes, case) before checking and may
no longer load anything: no @import/@font-face, no image-set()/src()/etc.,
url() only for inline data: images. Already-approved themes failing the
new check are hidden. Store file is written atomically.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 19:01:53 +00:00
MoepchiandClaude Opus 5.5 b87eb0f4b7 Fix audio/session lifecycle bugs (review A1-A4, A7, A8)
- A1: resume a suspended AudioContext on any click/keypress, so playback
  works even with the mic denied or absent
- A2: own mute state and message sounds follow ownClientId, not the
  nickname, so they keep working after a rename
- A3: startMic/stopMic generation counter - a stop during getUserMedia no
  longer gets overridden by the late mic; failed starts clean up
- A4: a failed reconnect of a previously connected session keeps its tab
  and retries instead of removing it
- A7: new AudioPlayer instances get the current volume and output device
- A8: AEC3 is (re)created with its AudioContext instead of only on toggle

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 18:56:54 +00:00
MoepchiandClaude Opus 5.5 4124071371 Harden the gateway against abuse (review S1-S3, S5-S7, S9)
- /ws: optional ALLOWED_ORIGINS allowlist, connection limits per IP and
  in total, 34 MiB maxPayload (uploads capped at 24 MiB client-side)
- connect: reject malformed host/nickname before spawning a connector;
  args passed as --flag=value, secrets via env instead of argv
- connector: 25 MiB download cap, 512 KiB for auto-fetched icons, friendly
  error for blocked private targets (tsclientlib: ALLOW_PRIVATE_TARGETS)
- feedback: contact e-mail never goes into the public GitHub issue;
  mentions/links in the issue body are neutralized; form says so
- rate limits: TRUST_PROXY-aware client IP, expiring limiter maps
- security headers (nosniff, frame options, CSP on served HTML)
- web: icon downloads requested once per path instead of on every update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 18:52:35 +00:00
MoepchiandClaude Sonnet 5 295af1781e Fix nickname-connect failures and add ALLOWED_SERVERS gateway allowlist
- Dockerfile: install ca-certificates in the runtime stage. Its absence
  broke the Rust connector's native-tls HTTPS call to the TeamSpeak
  nickname-lookup API for every nickname-based connection (GitHub
  issue #11, "mgonline" report) - Node's own bundled certs masked this
  everywhere else in the gateway, so only that one HTTPS call failed.
- tsclientlib bump: resolver.rs now surfaces the real per-step errors
  instead of an empty list when every resolution method fails (see
  that submodule's own commit for detail).
- gateway: new ALLOWED_SERVERS env var lets self-hosting admins lock
  their instance down to specific server(s) (with *.example.com
  wildcard support) instead of accepting connections to any address.
  Documented in the README env var table.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-27 11:18:17 +00:00
MoepchiandClaude Sonnet 5 914afd19bd gateway: guard child-process spawn errors and skip a pointless disconnect() stall
Two more unhandled-EventEmitter crash/latency bugs in the same spot as the
last one:

spawn() itself can fail asynchronously (bad CONNECTOR_BIN path, no exec
permission, or EMFILE/ENFILE under load) and emits an unhandled 'error' on
the child process object - just as fatal to the whole gateway as the stdin
EPIPE case, and more likely to hit exactly when the most connections are
already open. Now caught and turned into a normal error event.

disconnect() attached its exit listener with child.once("exit", ...), which
never fires if the connector already exited before disconnect() was called -
'exit' fires exactly once, and by then it's already happened. That always
fell through to the 3s hard-kill timeout for a process that was already
gone, needlessly stalling explicit disconnects and same-socket reconnects
after the connector died on its own. A childGone flag, set by both the new
error handler and the existing exit handler, lets disconnect() skip that
wait entirely when there's nothing left to wait for.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-23 11:36:50 +00:00
MoepchiandClaude Sonnet 5 032969d16a gateway: don't crash the whole process on a dead connector stdin pipe
writeLine()'s killed check only reflects Node-side .kill() calls, so it
can't catch the connector exiting on its own (e.g. the TS3 server drops
it) and closing its stdin first. Writing to that closed pipe threw an
unhandled EPIPE 'error' event, which Node treats as fatal - crashing the
gateway and every other client's live session along with it. Listening
for the error on child.stdin turns it into an isolated write failure.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-23 10:36:39 +00:00
MoepchiandClaude Sonnet 5 0428f80af8 ROADMAP: add Design Store and AEC3 to available-today list
Both shipped since the roadmap was last touched and were missing from
the "Available today" section.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 11:36:02 +00:00
MoepchiandClaude Sonnet 5 3c58650c1c Document and wire up STORE_URL for self-hosters
The Design Store defaults to the maintainer's shared catalog for
every build, but a self-hoster running their own gateway store
(STORE_ENABLED=1) had no way to actually point their Docker build at
it - VITE_STORE_URL existed in App.tsx but wasn't wired as a build
arg, and neither it nor the gateway-side STORE_* vars were documented
anywhere. Add the --build-arg STORE_URL passthrough (same unset-means-
no-override convention as DEFAULT_SERVER) and document both it and
the STORE_ENABLED/STORE_DATA_FILE/STORE_ALLOWED_ORIGIN/STORE_ADMIN_TOKEN
gateway env vars in the README.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 11:30:02 +00:00
MoepchiandClaude Sonnet 5 395aa3e6b6 Centralize design store URL to the maintainer's VPS
The store was previously derived per-instance from VITE_GATEWAY_URL,
so every self-hosted Docker image silently got its own empty,
isolated catalog instead of sharing the curated one. The store is a
single curated catalog (gateway/src/store.ts), unrelated to which
TS3/TeaSpeak gateway a build otherwise talks to, so all builds now
default to the same central endpoint. VITE_STORE_URL still lets a
self-hoster point at their own store instead. DEMO_MODE keeps the old
same-origin derivation, which 404s on the static demo host, so the
public demo can never write to the real production store.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 11:22:40 +00:00
MoepchiandClaude Sonnet 5 da4f416e32 Extract feedback/connection logging into a swappable module
Same pattern as the recent store.ts extraction: feedback-log writes and
connection-event logging move from inline file/console I/O in index.ts
into activity-log.ts, called via logFeedback()/logConnectionEvent(). The
public default behavior is unchanged (JSON-lines file with rotation,
console logging gated by LOG_CONNECTIONS).

This is the piece of the private SQLite overlay's persistence swap that's
a clean drop-in replacement - the private VPS gateway now imports the same
two function names from its own activity-log.ts (SQLite-backed) instead of
patching these call sites into a forked index.ts.

Note: the private overlay's live host-ban enforcement (blocked_hosts
table, heartbeat-driven disconnect) is NOT extracted here - it has no
public equivalent and touches the WS connection/heartbeat control flow
directly, not just a persistence call. Left as-is for now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 11:09:37 +00:00
MoepchiandClaude Sonnet 5 d54c4d0dc2 Extract design store into its own module
Moved all store code (constants, cache, handlers) from index.ts into
store.ts verbatim, no behavior change. It has zero private-VPS
modifications (unlike feedback/connection persistence, which the private
overlay patches to use SQLite), so this file can be copied unmodified into
the private overlay - future store changes there no longer need a manual
diff/patch against a hand-patched index.ts.

A full separate microservice was considered but rejected: this repo builds
one Docker image (connector + web + gateway) and self-hosters run one
container via docker-compose.yml; splitting the store into its own service
would force a second mandatory container for what's an opt-in, currently
tiny feature. A module boundary gets the actual pain point (patch-merge
friction) without that cost.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 11:00:11 +00:00
MoepchiandClaude Sonnet 5 c0e7f7412e Lower design store cap to bound worst-case RAM usage
STORE_MAX_THEMES was 2000, meaning the in-memory store cache could
theoretically grow to ~900MB (2000 * up to 450KB CSS+screenshot each) with
no eviction. 300 bounds that to ~135MB, which is proportionate for what is
currently a niche community design store.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:47:35 +00:00
MoepchiandClaude Sonnet 5 cfd9503313 Design store: make the delete button red in every design
Explicit red instead of the theme's accent color, so it stays visually
distinct as a destructive action regardless of the active design. The
confirm() prompt before deletion was already there.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:32:59 +00:00
MoepchiandClaude Sonnet 5 ed9fb80a9b Design store: fix root cause - icon row never actually spanned full width
.ts-design-theme-card has align-items:flex-start, so its flex children
shrink to content width unless given width:100% explicitly (like
.ts-design-theme-card-select already does). The actions row was
missing that, so flex:1 on its buttons had no extra width to grow
into - they stayed small and left-aligned no matter how the buttons
themselves were styled. That's why nothing helped until now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:28:59 +00:00
MoepchiandClaude Sonnet 5 9285e50412 Design store: revert icon row to 4-across, they already spanned full width
The 2x2 layout looked worse. flex:1 on a 4-in-a-row already makes the
four buttons together fill the card's full width - that was right the
first time, just needed the mismatched-glyph fix, not a layout change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:25:41 +00:00
MoepchiandClaude Sonnet 5 f113dbbecb Design store: lay out icon action row as 2x2 instead of 4 across
Taller wasn't what was asked for - wider was. A 2x2 grid gives each
button the full card-half width instead of a cramped quarter.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:22:42 +00:00
MoepchiandClaude Sonnet 5 d319d989da Design store: enlarge icon action buttons further
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:19:37 +00:00
MoepchiandClaude Sonnet 5 f29a1da7d4 Design store: replace mismatched icon glyphs with consistent SVG icons
The edit/duplicate/export/delete row mixed three text glyphs with a
color emoji (🗑), which render at different sizes and weights across
platforms - that was the actual cause of the row looking uneven, not
just sizing. Swapped all four for matching stroke-style SVG icons.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 10:16:18 +00:00
MoepchiandClaude Sonnet 5 587c0048e3 Design store: fix button sizing/theming, move back button to header
The store's install button had accidentally inherited the icon-row's
big-icon sizing (shared class) and rendered huge. Gave it and the
publish/new-design/import/store buttons proper themed gradient styling
instead of the browser default, and moved "back" to a top-left header
button instead of stacking it under publish.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 06:58:07 +00:00
MoepchiandClaude Sonnet 5 a98cf59111 Design store: fix hasScreenshot/rating defaults for pre-existing themes
Themes published before this schema existed have no screenshot/rating
fields at all, so `t.screenshot !== null` (undefined) and the rating
counters (undefined += n) were both wrong for them.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 06:46:38 +00:00
MoepchiandClaude Sonnet 5 eb7cb78042 Design store: reserved author names, screenshots, ratings, descriptions
Möpchi/Moepchi can only be used as an author name with a matching
STORE_ADMIN_TOKEN bearer token. Submissions can now include an optional
description and a manually uploaded screenshot (data URL, capped size),
shown on browse cards, plus a simple 1-5 star rating (one vote per IP
per theme).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 06:38:25 +00:00
MoepchiandClaude Sonnet 5 dd8528d3cb Make custom-theme card action icons noticeably bigger
15px/0.4rem padding still read as tiny per user feedback. Bump to 20px with
a fixed 2.4rem min-height so the icons are unmistakably buttons, not text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 06:28:46 +00:00
MoepchiandClaude Sonnet 5 dcb57aedbe Enlarge and improve contrast of custom-theme card action icons
The edit/duplicate/export/delete row used 12px muted-color icons with no
horizontal padding - hard to hit and easy to lose against darker custom
themes. Bump size/padding and switch to the full-contrast text color.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-18 06:24:36 +00:00
MoepchiandClaude Sonnet 5 bd33b962fe Add client-only Design Store MVP
Opt-in gateway endpoints (STORE_ENABLED=1, off by default like every other
optional feature here) to browse and publish community themes, reusing the
existing {name, baseTheme, css} export/import shape so no new packaging
format is needed. CSS is sanitized against @import and remote url() before
being accepted, since it's rendered on other users' pages. Client side adds
a "Store" button to the design picker with a browse/install and a publish
view built on the same DesignPanel patterns as import/export.

No website-side store yet - deliberately client-only for the MVP.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 21:22:57 +00:00
MoepchiandClaude Sonnet 5 7b52c0baa4 Route mic self-test monitoring through the (possibly AEC3-cancelled) signal
setMonitoring() connected the raw pre-AEC3 mic source straight to playback,
so the self-test howled regardless of AEC3 - it was bypassing the whole
cancellation path entirely, not failing to cancel. Mirror the processed
signal into the ScriptProcessorNode's own output and monitor that instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 18:41:31 +00:00
MoepchiandClaude Sonnet 5 effabafa23 Fix AEC3 pitch drift by using the AudioContext's actual sample rate
The requested AudioContext sampleRate is only a hint - some backends
(notably Linux/PulseAudio) silently run at their own native rate anyway.
AEC3 was told the requested rate (48000) regardless, so its internal
frame timing drifted from the actual sample rate its buffers came in at,
audibly heard as the echo's pitch descending with each repeat instead of
being cancelled.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 18:33:33 +00:00
MoepchiandClaude Sonnet 5 258d108f59 Add opt-in WASM AEC3 echo canceller for speaker+mic setups
Off-by-default toggle in the recording options (Aufnahmeoptionen), using
@ennuicastr/webrtcaec3.js (Google WebRTC's AEC3, compiled to WASM) as a
stronger supplement to native browser echo cancellation - addresses the
speaker+studio-mic (no headset) case from issue #2. Native echoCancellation
is turned off while this is enabled since running both fights the same
signal. Assets are synced from node_modules into public/vendor/ at
dev/build time rather than committed, since the module's glue code needs
its .wasm co-located under an exact, unhashed filename.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 18:12:52 +00:00
MoepchiandClaude Sonnet 5 390a2b5749 Remove implicit database/analytics contrast from feedback log comment
Wording implied a fancier database-backed variant exists elsewhere;
just describe what this file actually is.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 17:48:09 +00:00
MoepchiandClaude Sonnet 5 41e415d98b Trim env var docs to exclude the feedback/connection-logging pipeline
LOG_CONNECTIONS and the FEEDBACK_*/GITHUB_* vars are the same toggles
that data collection for the private stats panel is built on; leaving
those undocumented here on purpose.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 17:42:47 +00:00
MoepchiandClaude Sonnet 5 934c41fefd Document gateway environment variables in README
WEB_STATIC/WEB_DIST were mentioned once in passing for local dev; the
rest (feedback, broadcast, TLS, connection logging) weren't documented
at all, so self-hosters had to read gateway/src/index.ts to discover
them.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 17:41:03 +00:00
MoepchiandClaude Sonnet 5 83afe6c2cd Fix path-traversal-adjacent bypass in static file containment check
The WEB_STATIC file server checked containment with a plain string
prefix (filePath.startsWith(WEB_DIST)), which a sibling directory
sharing that prefix passes without actually being inside WEB_DIST -
e.g. WEB_DIST "/app/web/dist" also accepts "/app/web/dist-backup/...".
Now requires an exact match or a path-separator boundary.

WEB_STATIC defaults to on, so this affects any self-hoster serving the
UI from the gateway with the stock config, not just this deployment.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 17:35:54 +00:00
MoepchiandClaude Sonnet 5 667012d710 Fix WS message handler crash and stdin command injection in gateway
socket.on("message") parsed JSON and ran the whole handler switch with no
try/catch. Since the callback is async, any throw - malformed JSON from
any connected browser tab, or a handler throwing on unexpected input -
became an unhandled rejection and crashed the entire gateway process,
dropping every other connected user's live session. Now wrapped so one bad
message only errors back to that socket.

connection.ts wrote several fields (permission scope/ids, whisper targets)
straight into the connector's line-based stdin protocol without stripping
embedded CR/LF, unlike the sanitization already applied to every other
free-text field in the file - a newline in one of them could smuggle in a
second, attacker-chosen connector command. All stdin writes now go through
one writeLine() helper that strips embedded CR/LF, closing this for every
call site at once instead of patching each one individually.

Bumps the tsclientlib submodule for the matching SSRF/panic fixes there.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 11:06:16 +00:00
MoepchiandClaude Sonnet 5 3ffd7e5ce5 Fix unstyled "In new tab" button in Nova connect dialog
The Nova connect dialog styles its buttons per-class rather than via
the shared wrapper selector Standard/Pulse use. The Cancel and Connect
buttons had their Nova classes, but "In new tab" had none, so it fell
back to unstyled browser-default chrome instead of matching Cancel's
outline style.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 07:22:05 +00:00
MoepchiandClaude Sonnet 5 ae8f1f764b Fix dialog backdrop rendering below floating donate/feedback buttons
.ts-dialog-backdrop was z-index:15 while the donate/feedback FABs are
z-index:500, so any modal (connect dialog, settings, etc.) opened while
those buttons are visible left them floating undimmed in front of the
backdrop instead of behind it. Bumped the backdrop above the FABs but
below the update-available toast (600).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 06:58:37 +00:00
MoepchiandClaude Sonnet 5 42ac4e9aaa Fix Nova design: floating FABs overlapping chat composer, textarea stuck collapsed
Nova relocates the self/voice toolbar below the chat panel, adding ~6.7rem
of footprint the fixed-position donate/feedback buttons didn't account for,
so they landed on top of the composer's send button. Also the chat
textarea's auto-resize effect only ran on chatInput/theme change, so on
first mount (while the chat panel was hidden pre-connect, scrollHeight 0)
it locked in a near-zero height that never got recalculated after
connecting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-17 06:40:34 +00:00
MoepchiandClaude Sonnet 5 961084e9a0 README: expand auto-connect blurb into a full tutorial section
Own top-level section with a share-link table and the build-time
default walkthrough, instead of a two-line paragraph buried in the
Docker install steps.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-16 13:52:44 +00:00
MoepchiandClaude Sonnet 5 faeb269fdd Add URL-based and build-time auto-connect (closes #10)
Landing pages can now send visitors straight into a TeamSpeak server:
a ?connect=host&nickname=&channel=&token= share link auto-connects on
any deployment, or a self-hoster can bake in a default server at build
time (VITE_DEFAULT_SERVER/VITE_DEFAULT_CHANNEL, mirroring the existing
DONATE_URL Docker ARG pattern) so every visitor auto-joins with zero
params. A share link always overrides the build-time default. Waits
for the mandatory first-visit ToS gate where applicable, falls back to
a prefilled reopened connect dialog on failure, and generates a
Guest-XXXX nickname when none is available.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-16 12:34:14 +00:00
MoepchiandClaude Sonnet 5 f44327aabc ROADMAP: add concrete accessibility milestone for the web client
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-15 18:03:32 +00:00
MoepchiandClaude Sonnet 5 7357dfa85d Bump tsclientlib: fix live stream start/stop not seen by connected clients
An already-connected client only learned about another client's TS6
stream via the initial snapshot; a live start/stop toggle mid-session
went out via notifyclientupdated, whose attribute list didn't include
client_is_streaming, so tsclientlib silently dropped it. Fixed upstream
in tsdeclarations/Messages.toml; only a reconnect used to pick it up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-15 17:37:00 +00:00
MoepchiandClaude Sonnet 5 ceeba24f86 ROADMAP: fix stale note about streaming UI flag being off
client.webspeak3.de's gateway has answered setupStream/joinStream/
sendStreamSignal since v0.11.0-beta.1 (2026-09-11); STREAM_UI_ENABLED
was flipped back on then but this doc never caught up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-15 17:16:13 +00:00
MoepchiandClaude Sonnet 5 817aa0f5f6 Gracefully disconnect live sessions on SIGTERM before exiting
Previously the container was killed with connector child processes still
mid-session, so the target TS3/TeaSpeak server only noticed the drop via
its own timeout. A client's automatic reconnect (see App.tsx's
scheduleReconnect) landing before that timeout got rejected as a
duplicate identity (e.g. ClientTooManyClonesConnected).

Now SIGTERM disconnects every live connection first (bounded to 5s) so
the target server frees the slot immediately. The connector's own
resulting "disconnected" event is suppressed from reaching the browser
during shutdown (shuttingDown flag) so the browser sees a raw socket
close, which it treats as an unexpected drop and retries, rather than an
explicit disconnect, which it treats as deliberate and gives up on.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-15 06:56:19 +00:00
MoepchiandClaude Sonnet 5 bc6022b45f Add optional token-authenticated /api/broadcast endpoint
Lets the operator send a free-text maintenance notice to every connected
browser tab via POST /api/broadcast (Bearer BROADCAST_TOKEN). Reuses the
existing {type:"notice"} WebSocket message the frontend already renders
for the SIGTERM restart notice, so no frontend changes are needed. Off
(404) unless BROADCAST_TOKEN is set, same opt-in convention as
FEEDBACK_ENABLED/LOG_CONNECTIONS.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-15 05:25:33 +00:00
MoepchiandClaude Sonnet 5 8d17514774 Add Weblate translation link to language settings and Help menu
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 20:01:58 +00:00
MoepchiandClaude Sonnet 5 d62e47ca63 Move translations to plain JSON files (de/en/zh-CN/fa)
Translation strings were split across inline TS objects in i18n.tsx
(de/en) and separate .ts modules (zh-CN, fa). Consolidated into one
JSON file per language under web/src/locales/ - translation tools
(e.g. Weblate) can read/write these directly, and i18n.tsx is now
just the loader/lookup logic. No string content changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 19:08:03 +00:00
MoepchiandClaude Sonnet 5 45af66f84b Tag Persian as beta in the language selector
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 19:02:57 +00:00
MoepchiandClaude Sonnet 5 be946c2a5e Add Persian (fa) translation, incl. RTL toggle
- New locales/fa.ts, 618 keys, full parity with de/en/zh-CN
- document.documentElement.dir flips to rtl/ltr with the active language
- Language selector + system-locale auto-detect (fa-*) updated

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 19:01:16 +00:00
MoepchiandClaude Sonnet 5 732a905f32 zh-CN: catch up 116 missing keys, drop 2 stale ones
Feedback dialog (incl. new report category), ToS modal, restart
notice, Hilfe menu, channel password dialog, custom design manager,
and the whole screen-share/publish feature were falling back to
English. Also removed connect.sendMyTeamSpeakId and
favorites.enableMyTeamSpeak, which no longer exist in de/en.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 18:53:19 +00:00
MoepchiandClaude Sonnet 5 77e147cc27 Add Hilfe dropdown menu (About, GitHub, Changelog, ToS)
Replaces the inert "Hilfe" label with a real dropdown, folding the
standalone ToS menubar item into it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 18:42:57 +00:00
MoepchiandClaude Sonnet 5 b0495367cb Link ToS modal to legal pages, add report feedback category
- ToS modal: Datenschutzerklärung/Impressum words are now real links
- Feedback form: new "report" category (abuse/violation), hidden
  GitHub-issue option since reports must stay private
- Gateways: accept "report" in FEEDBACK_CATEGORIES

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 18:33:27 +00:00
MoepchiandClaude Sonnet 5 73303e1229 Add SIGTERM restart-warning broadcast and first-visit ToS modal
- Gateway: on SIGTERM, broadcast a "notice" event to every connected
  socket before shutting down, so an active call/stream doesn't just
  silently drop during a redeploy.
- Web client: new "notice" event handling shows a non-dismissable
  restart-warning dialog; new ToS modal shown on first visit to the
  own-hosted instance (client.webspeak3.de only), versioned via
  localStorage, reopenable from the menu.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 18:15:15 +00:00
MoepchiandClaude Opus 4.8 741528220e Bump tsclientlib: SRV on exact host only, no apex fallback (#9)
Pulls in the resolver fix so a subdomain with its own A record (e.g.
ts6.rush-zone.com) is no longer hijacked onto a different server's apex
SRV. Fixes #9.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-14 15:02:42 +00:00
MoepchiandClaude Opus 5 0b34e7ecfb web: put the donation pill below the feedback button
The two floating buttons swap places: the Ko-fi pill now sits in the
corner at bottom: 5.5rem and the feedback button stacks above it at
8.5rem, which keeps the same 12px gap the previous arrangement had.

The offset still follows the instance rather than the dialog, it just
moved to the other element: the feedback button only shifts up where the
donation pill is actually rendered, and takes the corner spot where the
build dropped it via VITE_DONATE_URL=.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 16:28:18 +00:00
MoepchiandClaude Opus 5 6ebc3e22e0 web: add a Ko-fi donation button
A small pill in the bottom right corner, in Ko-fi's own red rather than
the theme colors so it reads as what it is. It sits above the feedback
button where that one exists and takes its place where it does not; the
offset follows the instance rather than the dialog, so opening feedback
does not make it jump.

Unlike the feedback button this is not limited to the maintainer's own
instance - it ships in every build, the Docker image included. Since
that means self-hosters carry someone else's donation link, there is a
way out: VITE_DONATE_URL= (empty) drops the button, any other value
retargets it, and the Dockerfile passes it through as --build-arg
DONATE_URL. The "keep" sentinel there is not decoration - an unset and
an empty build arg are indistinguishable inside RUN, so without it
"not passed" would silently mean "remove".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 16:12:58 +00:00
MoepchiandClaude Opus 5 fa4daf7831 gateway: serve nothing to browsers when WEB_STATIC=0
The notice page at "/" was the last thing a browser could get from a
host that only exists to answer /ws and /api/feedback. It is gone; every
path now 404s, so the gateway hostname has no web presence at all.

That broke the container healthcheck, which probed "/" and required a
200 - a correctly configured gateway would have reported itself
unhealthy. The probe now has its own route, /healthz, served before the
WEB_STATIC branch so it answers in either mode.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 15:34:16 +00:00
MoepchiandClaude Opus 5 f48c1cc91a Say what WEB_STATIC=0 actually does in the startup log
The line pointed at the Vite dev server, which is only ever right on a
developer's machine - on a deployed gateway it reads like a bug report
waiting to happen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 12:45:02 +00:00
MoepchiandClaude Opus 5 cc715e24b2 Fix the feedback URL and stop serving a UI when WEB_STATIC=0
VITE_GATEWAY_URL names a WebSocket origin, and FEEDBACK_URL was derived
from it verbatim - so with VITE_GATEWAY_URL=wss://gateway.example the
form posted to wss://gateway.example/api/feedback, which fetch() refuses
outright ("TypeError: unknown scheme"). Every submission from a
separately hosted frontend failed before it left the browser. Map the
scheme back to http(s); an already-http VITE_GATEWAY_URL is untouched.

While there: WEB_STATIC=0 answered every path with the dev hint page,
which talks about localhost:5173 and npm run dev. That page is wrong for
a gateway that is reachable publicly, and an SPA-shaped answer on every
path makes the host look like a second, stale copy of the app. Serve a
short deployment-neutral notice at "/" and 404 everywhere else; the dev
hint stays for the case it is actually about, a missing web/dist.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 12:39:50 +00:00
MoepchiandClaude Opus 5 2ee6d1f0b5 Stop the service worker from stranding clients
Between 48f5e35 (07.09., registerType: 'autoUpdate') and 5b5f4ca (10.09.,
switched to 'prompt') every client that cached the app froze: the new
worker sits in `waiting` and the only code that could release it - the
update toast - lives in the build behind that worker. Their next update
never arrives, and Pages deletes the hashed assets they still run from,
so the bundle they serve does not exist on the server any more. That is
how the feedback form went missing on client.webspeak3.de.

- Back to 'autoUpdate', with skipWaiting/clientsClaim spelled out: the
  plugin only sets them when it also injects registerSW.js, so with
  injectRegister: false the generated worker was byte-identical to the
  'prompt' one. Verified in dist/sw.js.
- onNeedReload instead of onNeedRefresh: the worker takes over on its
  own, the toast only decides *when* to reload, so nobody is thrown out
  of a running connection.
- version.json plus a __BUILD_ID__ baked into the bundle, checked every
  30 min and on tab focus, deliberately routed around the worker (not in
  globPatterns, so never precached). If the server is on another build
  and no new worker turns up, the worker is wedged and the button clears
  registrations and caches instead of reloading into the same cache.
- Dismissing the toast snoozes for 30 min rather than for good.

Verified in headless Chromium against simulated deploys: a client stuck
on the old worker lands on the new bundle at the first plain F5.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 12:20:53 +00:00
MoepchiandClaude Opus 5 06f38b4582 Switch the streaming UI back on
The gateway on the VPS was rebuilt on the v0.11.0-beta.1 image and now
answers setupStream/joinStream/sendStreamSignal, so the condition the kill
switch was waiting for is met. Verified against the live gateway rather
than assumed: a WebSocket connect through gateway.webspeak3.de reached a
real TS6 server, and all five stream commands are present in the running
dist.

The switch itself stays - it is the lever for the next time the frontend
ships a stream feature before the gateway has it. The durable fix is still
a capability handshake; see ROADMAP.md.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 11:23:54 +00:00
MoepchiandClaude Opus 5 5024bf9856 Switch the streaming UI off until the gateway catches up
client.webspeak3.de is rebuilt by Cloudflare Pages on every push to main, but
the gateway and connector are a Docker image that has to be pulled onto the
host by hand. v0.11.0-beta.1 therefore put a browser that knows setupStream in
front of a gateway that does not - and an unsupported setupStream is not an
error, it is silence: the publish panel waits at "starting" forever, after the
browser has already asked the user to share a screen. That reads as a broken
feature, which is worse than an absent one.

Both entry points are gated on one flag: the toolbar button and the "watch
stream" context-menu item. The publisher is tree-shaken out of the bundle as a
result, so nothing can reach the gateway by accident. Flip it back once the
deployed gateway is on v0.11.0-beta.1 or newer.

The durable fix is a capability handshake so the client can tell what its
gateway supports instead of assuming; noted in the roadmap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 06:39:13 +00:00
MoepchiandClaude Opus 5 478e5c0384 Merge: TS6 screen streaming (alpha)
Adds screen streaming to and from TeamSpeak 6, marked alpha and unstable in
the UI and the docs because it speaks a protocol TeamSpeak does not publish.
Also repoints both submodules at Moepchi forks, so a fresh clone resolves
every pinned commit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 06:27:35 +00:00
MoepchiandClaude Opus 5 550a8896a5 Point the tsclientlib submodule at Moepchi/tsclientlib
Streaming needs a commit in tsclientlib, and the branch was hosted in an
organization this project cannot publish to, so a fresh clone would pin a
commit that never appears. Moepchi/tsclientlib is the older fork in the same
network - GreenTeaSpeak/tsclientlib was itself forked from it - and both share
ReSpeak/tsclientlib as upstream, so no history is rewritten or lost; the
branch keeps every GreenTeaSpeak commit it already had.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 06:09:15 +00:00
MoepchiandClaude Opus 5 e7d5b3be0a Don't offer streaming in demo mode
DemoSocket answers a fixed set of gateway messages and silently drops the
rest, setupstream among them. Clicking the button on the public demo would
therefore prompt the visitor to pick a screen, start the capture, and then
leave the panel at "starting" forever with no error - which reads as a broken
feature rather than an absent one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:37:19 +00:00
MoepchiandClaude Opus 5 9652a3efe5 Mark TS6 streaming as alpha in the UI and the docs
Streaming interoperates with TeamSpeak 6 over a protocol TeamSpeak does not
document; the wire format here was derived from observed behavior. It can fail
to connect, deliver a poor picture, mishandle viewer admission, or break with
any TS6 update - which is a different stability expectation than the rest of
WebSpeak3, and users should not have to infer that from a release note they
read once.

So the badge sits everywhere the feature is reachable: the stream settings
dialog (with a sentence explaining what "alpha" means here), both stream
panels, and the toolbar button's tooltip. README and ROADMAP say the same,
including the two gaps that are most likely to be mistaken for bugs - no SFU
("Server" mode), no camera source.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:35:04 +00:00
MoepchiandClaude Opus 5 4d549887d5 Bump tsclientlib for TS6 stream signaling
The connector reads TS6's stream commands off StreamItem::UnknownCommand,
which tsclientlib only started emitting in this commit; before it, every
notifystream* packet was logged as an unknown command and dropped, so the
signaling never reached the gateway. Also carries the client_is_streaming
client property.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:34:54 +00:00
MoepchiandClaude Opus 5 686458807a publish: stop the encoder from shrinking the picture
Every resolution above 360p was effectively a lie. The capture ran at the
requested size, the bitrate cap was applied, and the encoder then scaled
the picture down by 3x anyway and never recovered.

The cause is degradationPreference, which we never set. Its default for a
track hinted "motion" - which is every preset except Presentation - is to
protect the frame rate and sacrifice resolution. For a screen share that
is backwards: the user picked 1080p, so 1080p is what to keep.

Measured on a 1440x1080 capture with a 6000 kbps cap, 12 s each:

    default             480x270  @20  limit=bandwidth  ~214 kbps
    maintain-framerate  480x270  @20  limit=bandwidth  ~212 kbps
    balanced            480x270  @15  limit=bandwidth  ~169 kbps
    maintain-resolution 1440x810 @19  limit=none       ~717 kbps

Note the bitrate column: the shrunken variants were not short of budget,
they had 6000 kbps and used 214. Setting contentHint "detail" fixes it
too, which is why Presentation was the one preset that looked right.

Audio senders are left alone; degradationPreference is video-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 b505d68f56 publish: drop a queued request when the client leaves
notifystreamclientleft only removed connected viewers, so a request that
was still waiting for a decision outlived the person who made it - the
row stayed in the panel and approving it would have opened a connection
to a client that is gone. Leaving while pending is not exotic: it is what
closing TS6, or giving up on "waiting for access", looks like from here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 13d3f56c89 publish: mirror TS6's pending-join model instead of refusing
Live testing against a real TS6 client settled how both settings actually
behave, and neither is what the previous commit assumed.

The server enforces nothing. It stores accessibility and viewer_limit,
echoes them back in notifystreamstarted, and then forwards every join
request anyway - a PRIVATE stream at viewer_limit=1 still had both
viewers announced to us. Enforcement is entirely the publisher's job.

And a refusal is the wrong tool for it. TS6's own rule, from main.js:

    !autoAccept || full ? pendingJoinRequests.push(...)
                        : joinStreamResponse(...)

A request it will not take automatically is left *pending*, not denied.
That matters because a denial does not stick - TS6 pairs its own deny
with a ban (blockAndDenyJoinRequest) precisely because of this - so a
refused client just asks again. Measured: 7 retries in 40 s, with nothing
shown to the person waiting. Left pending, the same client asks once and
displays "waiting for access" until answered, then connects normally.

So: PUBLIC with room to spare admits; anything else queues for the user,
including a full stream. Deny is now an explicit choice, and block is the
sticky variant. CONTACTS_ONLY behaves as PRIVATE because the contact list
is a TS6 account feature we cannot read.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 4d0954054c publish: actually enforce the viewer limit
viewer_limit went out with setupstream and was then never looked at
again - admit() handed a peer connection to every join request that
arrived. Nothing establishes that the server turns anyone away, so the
setting was advisory at best.

The publisher is the only side that can enforce it: it is the one
handing out peer connections, and in P2P mode each one is another
encode. respondJoinStream(accept: false) was already plumbed end to end
down to decision=0 in the connector; it just had no caller.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 115cd7150e web: TS6's stream-start options in the publish dialog
TS6 shows a settings dialog before going live; this builds the same set
into webspeak3, split into Basic (preset, capture audio, privacy) and an
Advanced section (resolution, FPS, bitrate, audio bitrate, viewer limit,
connection mode).

The three numeric setupstream fields are enums lifted out of TS6's own
main.js rather than guessed (findings §10): source NONE/CAMERA/SCREEN/
WINDOW/EXISTING_SESSION, accessibility NONE/PUBLIC/CONTACTS_ONLY/PRIVATE,
mode NONE/P2P/SFU. We had been sending type=3 (WINDOW) unconditionally;
detectSourceType() now picks SCREEN for displaySurface === "monitor".

Resolution, FPS and the two bitrates are not protocol fields. They are
applied locally: capture constraints, track.contentHint, and
sender.setParameters() with encoding.maxBitrate. bitrate= on the wire is
advisory - the server echoes back its own number either way.

Connection mode "Server" (SFU) is rendered disabled with a tooltip. That
path is a separate transport (requeststreamsfuaccessinfo -> mediasoup)
that we have not built, and announcing mode=2 without it would publish a
stream nobody could watch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 7083e8e29f gateway: serve HTTPS when TLS_CERT and TLS_KEY are set
Not a nicety. getDisplayMedia, getUserMedia and crypto.randomUUID are
secure-context-only, so a LAN instance reached over plain http could
neither share a screen nor use the microphone. Chrome additionally hides
host ICE candidates behind mDNS names until a media permission is
granted, which keeps a peer-to-peer stream from connecting at all - so
the publishing direction was effectively unreachable from anywhere but
localhost.

The frontend already derives ws:// or wss:// from the page's own scheme,
so nothing else needs configuring. Verified from the LAN address with a
self-signed cert: isSecureContext true, both media APIs present.

gateway/certs/ is gitignored - a private key never belongs in the repo.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 15e215d892 stream: publish a stream TS6 can watch
The other direction, live-verified against TS6 6.0.0-beta12.1: a real
client rendered our video. Connector gains setupstream, stopstream and
respondjoinstreamrequest; the browser gains publish.ts and a toolbar
button.

The publisher offers. TS6 puts the first SDP in respondjoinstreamrequest,
so the side that owns the stream is the side that makes the offer - the
mirror of how it answered us when we were watching. Its reply confirmed
the key rule found in 7a8a1ea from the other side: TS6 sends us
args.answer, exactly as it expects args.answer from us. The key is always
named after the cmd.

The notify filter had to be fixed first. It matched
starts_with("notifyrespondjoinstream"), which drops the inbound
notifyjoinstreamrequest - so every viewer asking to watch *us* was
silently discarded, and the whole publishing direction was mute. Match
ends_with("joinstreamrequest") instead.

P2P mode is a mesh with no SFU in the path, so each viewer gets its own
peer connection and its own encode. Watching and broadcasting can run at
once, so the two panels stack in a shared container rather than both
anchoring to the same corner.

Note for later: we send bitrate=1500000 and the server reports 58208
back. It does not take our value - a real TS6 client showed 50880. Looks
server-side, and it does not stop the connection.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 b57d32bc18 stream: the answer args key is "answer", and it plays
Live-verified against TS6 6.0.0-beta12.1: the working payload is
{"cmd":"answer","args":{"answer":"<sdp>"}}. Audio and video RTP now
arrive from a real TS6 publisher into the browser.

53f6856 sent the bare SDP string instead, inferred statically from an
`answer` branch in the inbound dispatcher that references no key
literal. The inference was wrong - that branch delegates the object
read to a shared JSON helper, and the key lives there. A branch with no
key literal in it means the read is elsewhere, not that there is no key.

The wrong shape is completely silent: the server accepts and routes the
command, and the client discards it. Only getStats() shows it, as TS6
answering our connectivity checks while never sending one of its own
(requestsReceived=0) - it replies from the credentials in its own offer
without ever having applied a remote description. So drop the 5 s
retry-in-the-other-shape fallback, and keep send_with_result on
streamsignaling so a refused command at least surfaces as an error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 c2e4760e37 Don't crash on a plain-http origin
crypto.randomUUID() exists only in a secure context, so opening a self-hosted
instance over http on a LAN IP threw at module load - before React rendered
anything - and left a blank page with no visible cause.

Falls back to a v4 id built from crypto.getRandomValues(). These ids are local
identifiers (identities, sessions, whisper lists), not secrets.

navigator.mediaDevices was already guarded, so the mic just reports "requires
HTTPS (or localhost)" as intended.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 087b8a90c5 stream: answer args are the bare SDP, not {sdp}
TeamSpeak.dll's inbound signaling dispatcher LEAs a key literal in every
branch that reads an object out of `args` (decision/offer for joinResponse,
sdp/mid/mLine for iceCandidate) and none in the answer and offer branches,
whose handler ends in StreamP2P::SetAnswerString(const std::string&).

That is static evidence only - TS6 has never had an answer from us to react
to, and it drops an unreadable payload silently - so the viewer re-sends the
object form after 5s if nothing connected. The first live test settles it.

Inbound offer/reconnectOffer now accept both shapes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 6107501445 Browser: watch a TS6 stream
Adds web/src/stream.ts, the receive-only RTCPeerConnection that takes TS6's
SDP offer out of notifyrespondjoinstreamrequest, trickles ICE both ways over
notifystreamsignaling and hands the remote MediaStream back.

App.tsx only wires it up: a client with client_is_streaming gets a requeststreaminfo
(that property is the *only* way a late joiner learns a stream is running), a
badge in the tree, a context-menu entry and a floating video panel.

Also adds the missing requestStreamInfo path in the gateway - the connector
already had `streaminfo <clid>` on stdin, nothing could reach it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 11a413d2b6 Add requeststreaminfo so late joiners can find a running stream
Verified end to end against a live TS6 client: the passthrough delivers
notifyrespondjoinstreamrequest with the full SDP offer plus 18 iceCandidate
notifies, all correctly unescaped.

Getting there turned up a gap. A client entering a channel where a stream is
already running receives no stream command at all - 35 s in the channel
produced zero undeclared commands. Discovery runs over the ordinary
client_is_streaming property instead, and the stream id has to be pulled per
client with requeststreaminfo. Without that, only a viewer who happened to be
present when the stream started could ever join.

The unknown-command names now go to stderr, which is what made the difference
between "the server sent nothing" and "we filtered it out" visible at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Opus 5 9f1a63c9d3 Pass TS6 stream signaling through connector and gateway
tsclientlib dropped every command missing from the message declarations,
which silently swallowed TS6's whole Stream/Call signaling exchange: none of
the stream commands are declared, so notifystreamsignaling never reached a
consumer. That is why the protocol could only be captured with a standalone
raw-tsproto tool.

handle_command now splits the parse failure - ParseError::UnknownCommand hands
the raw line up as StreamItem::UnknownCommand instead of warning and returning,
everything else keeps the old behaviour.

The connector unescapes the TS wire format and forwards the stream commands as
a streamEvent, filtered to notifystream*/notifyrespondjoinstream* so unrelated
undeclared commands stay dropped. The JSON payload stays opaque the whole way -
SDP and ICE belong to the browser's RTCPeerConnection, not to the connector.
Outbound, streamjoin/streamleave/streamsignal join the existing raw OutCommand
handlers; parameter names and order are as recovered from TeamSpeak.dll and
confirmed against a live TS6 client.

The gateway serializes the payload itself so no literal newline can reach the
line-based stdin protocol.

Nothing renders video yet - the browser side is still missing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-09-11 05:26:33 +00:00
MoepchiandClaude Sonnet 5 7776a71e84 Harden and polish the feedback endpoint
- Honeypot field ("website", hidden via CSS + tabIndex -1): any
  non-empty value silently short-circuits to a fake success response
  without logging or filing anything, at near-zero cost to real users.
- Tag created GitHub issues with the feedback category (bug/idea/
  other) alongside the existing "feedback" label, for easier triage -
  GitHub auto-creates labels that don't exist yet.
- Rotate feedback.log once it crosses 5MB (move to feedback.log.1) so
  a busy instance doesn't grow the file unbounded.
- Push the nudge bubble's cooldown out from the moment someone
  actually submits feedback, so it doesn't ask again shortly after
  they just did.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 09:15:05 +02:00
MoepchiandClaude Sonnet 5 5b5f4caf79 Add PWA update prompt instead of silent stale caching
Previously the service worker used registerType: 'autoUpdate' with
the default injected register script - a new deploy would install
and activate a new SW in the background, but an already-open tab
kept running the old JS/CSS from memory with no indication a newer
version existed, short of a manual hard reload (or clearing SW/
caches by hand, which we had to do repeatedly while verifying
deploys this session).

Switch to registerType: 'prompt' and register the SW ourselves via
virtual:pwa-register/react (useRegisterSW), showing a small "new
version available" toast with a reload button when an update is
waiting. Also poll registration.update() hourly so long-lived tabs
notice updates without needing a fresh navigation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 09:13:15 +02:00
MoepchiandClaude Sonnet 5 dc35526727 Fix mobile dropdown menus overflowing off-screen
Each menubar dropdown (Extras, Rechte, ...) opened flush with the
left edge of the specific menu item that triggered it. On a narrow
screen, any item not near the left edge (e.g. Extras) opened a
260px-wide panel that ran off the right side of the viewport.

On mobile, anchor the dropdown to the whole menubar instead of the
individual item, and let it span (almost) the full width with a
max-height + scroll for long lists (Extras has a lot of entries).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 08:44:16 +02:00
MoepchiandClaude Sonnet 5 20a861caff Fix mobile menu bar clipping new items off-screen
.ts-menubar had flex-wrap set for mobile, but the actual row of
menu items lives in the nested .ts-menubar-items flex container,
which never wrapped - so on narrow screens items past a certain
width (like the new Feedback entry) were clipped off the right
edge instead of wrapping to a second line.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 08:33:43 +02:00
MoepchiandClaude Sonnet 5 6c764578a7 Raise feedback FAB and add occasional nudge bubble
- Move the floating feedback button up above the message compose bar
  so it no longer overlaps the input/send controls.
- Add a small dismissible speech bubble inviting feedback, shown once
  ~45s after load and at most every 3 days (tracked via localStorage),
  auto-hiding after 14s if not interacted with.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 08:23:50 +02:00
MoepchiandClaude Sonnet 5 d48172f4d1 Make feedback access more visible
Move the feedback entry out of the Extras submenu into its own
top-level menubar item, and add a floating action button (bottom
right) as a second, always-visible entry point. Both stay gated
behind IS_OWN_HOSTED_INSTANCE like before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 08:15:45 +02:00
MoepchiandClaude Sonnet 5 e2a09fbb43 Add in-client feedback form (own-hosted instance only)
- gateway: opt-in POST /api/feedback endpoint (FEEDBACK_ENABLED=1),
  logs submissions to feedback.log and optionally files a GitHub issue
  on Moepchi/webspeak3 when GITHUB_TOKEN is set and the user opts in.
  Rate-limited per IP, CORS-aware for split-hosted deployments.
- web: new "Feedback" menu entry under Extras, gated to
  client.webspeak3.de at runtime (IS_OWN_HOSTED_INSTANCE) so other
  self-hosted/forked deployments and the public demo never see it.
  New FeedbackDialog with category/message/email fields and an
  opt-in "publish as GitHub issue" checkbox. New i18n strings (DE/EN).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 07:29:48 +02:00
MoepchiandClaude Sonnet 5 1d20eb15de connector: silence noisy ts_bookkeeping::messages::s2c warnings by default
ts_bookkeeping::messages::s2c logs a WARN for every server/property
field it doesn't have a parser for. Harmless (the field is simply
dropped) but extremely noisy on TeaSpeak/GreenTeaSpeak servers, where
it fires on nearly every ServerUpdated/ClientEnterView and drowns out
warnings that actually matter.

Also makes RUST_LOG actually functional for the first time - the
filter was previously a hardcoded EnvFilter::new("warn") literal that
ignored the env var entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 14:28:52 +02:00
Moepchi 42f33840a5 Add opt-in connection logging (LOG_CONNECTIONS env var)
Off by default — this is an open-source, self-hostable image, so other
instances shouldn't get connection logging just because it's in the
codebase. Set LOG_CONNECTIONS=1 in an instance's .env to log a single
line per TS3/TeaSpeak connect and disconnect (host, server name,
timestamp — no nickname, no IP).
2026-09-09 07:20:24 +02:00
Moepchi 48f5e35a38 Add PWA installability (manifest + service worker)
- Wire up vite-plugin-pwa: generates a web app manifest and a
  precache-only service worker for the built app shell (JS/CSS/HTML/
  icons). WebSocket (/ws) and file-transfer traffic are never
  intercepted or cached. Disabled in dev so it doesn't interfere with
  Vite's own HMR websocket.
- Add 512px + maskable 512px icons generated from the existing logo.
- Add iOS "Add to Home Screen" meta tags (manifest support there is
  partial).
- Gateway: serve .webmanifest with the correct MIME type.
2026-09-07 16:16:44 +02:00
Moepchi 20d1944dc9 Reconnect resilience: gateway heartbeat + session auto-reconnect
Two related bugs: a browser tab that lost network (or got backgrounded/
suspended on Android) could leave the connector alive on the TS3/TeaSpeak
server for minutes after the frontend showed disconnected, and multi-join
background tabs simply vanished on any drop instead of staying connected.

- gateway: WebSocket ping/pong heartbeat (20s) so a dead browser socket is
  detected and its connector torn down promptly instead of waiting on an
  OS-level TCP timeout.
- web: every session (active tab or parked multi-join background tab) now
  remembers its connect params and can reopen its own socket after an
  unexpected drop, with exponential backoff (1s-30s) so a persistently
  unreachable gateway isn't hammered. Wake Lock keeps the screen (and the
  tab's throttling) at bay while any session is live; a visibilitychange
  sweep reconnects every dropped session once the page is visible again.
  Mic stays off for background sessions throughout, same as before.
2026-09-07 16:01:05 +02:00
Möpchi fd5a4cd6e0 Merge pull request #6 from Moepchi/pr-5-review-fixes
Client move/DnD, ServerQuery toggle, TeaSpeak poke handling + review fixes
2026-09-06 12:03:53 +02:00
MoepchiandClaude Sonnet 5 701bd867fc fix: self-move channel password prompt, spacer targets, client-list memoization
- handleMoveClient: route self-drags through handleSwitchChannel so
  moving your own client still prompts for a channel password when
  required, while admin moves of other clients keep bypassing the
  target channel's password (matches native TS3/GTS behavior - only
  the mover needs permission, not the password).
- MoveClientDialog: disable channel spacers as move targets, they are
  display-only rows with no backing channel.
- connector moveclient handler: carry the already-decoded password
  through the fallback branch (client not found in local state)
  instead of hardcoding an empty password, so self-moves via that
  path still authenticate correctly.
- App.tsx: memoize treeClients/queryClientCount so they are not
  recomputed on every render (e.g. on unrelated "talkers" updates),
  and simplify the duplicated displayClientCount ternary.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 11:57:30 +02:00
Nico B.andCursor b6448e65e8 Add client move/DnD, ServerQuery favorite toggle, and TeaSpeak poke handling.
Lets users move clients via context menu or drag-and-drop (including spacers), show ServerQuery clients per favorite without reconnecting, and surface TeaSpeak/GTS notifyclientpoke reliably via connector fallback plus tsclientlib parse fallthrough.

EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 02:09:52 +02:00
Moepchi bf85173a54 docs: clarify GreenTeaSpeak feature covers server connectivity, not just theme 2026-09-06 02:00:45 +02:00
Moepchi cf5ecb1455 docs: mention TeaSpeak/GreenTeaSpeak support in README
PR #4 added TeaSpeak/GreenTeaSpeak protocol support alongside existing
TS3/TS6, plus an optional GTS-styled theme - update the tagline, quick
start text, features table, architecture section, and trademark
disclaimer to reflect that.
2026-09-06 01:54:52 +02:00
Möpchi 9206b12e25 Merge pull request #4 from GreenTeaSpeak/main
Add TeaSpeak/GTS support and multi-join functionality
2026-09-06 01:39:07 +02:00
Nico B.andCursor 5d2b02feb0 Point tsclientlib at GreenTeaSpeak tsdeclarations fork.
Track the org-owned declarations remote via the updated tsclientlib submodule.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 01:32:53 +02:00
Nico B.andCursor 77165af5e4 Exclude ServerQuery from online total so it matches the filtered client list.
The PR #4 review fix still preferred virtualserver_clientsonline which usually includes Query; subtract bookkeeping Query count before applying the stale-data max.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 01:28:19 +02:00
Nico B. a118c0f58e Merge pull request #1 from Moepchi/fix/pr-4-review-bugs
Fix 8 correctness bugs found in review of TeaSpeak/GTS + multi-join PR
2026-09-06 01:20:59 +02:00
Nico B.andCursor 3db5d90d89 Merge upstream/main into GreenTeaSpeak main to resolve PR #4 conflicts.
Keep TeaSpeak/GTS multi-tab work while integrating channel-password prompts and the Pulse theme.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 00:54:04 +02:00
Nico B.andCursor ecdd69bceb Point tsclientlib submodule at GreenTeaSpeak fork.
The TeaSpeak commit was only local; clones and CI failed. Host it on the org fork and track that remote.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 00:48:00 +02:00
Moepchi 9702c671e8 Fix 8 correctness bugs found in code review of PR #4
- Connection log only ever rendered the single latest entry
  (log.slice(-1) -> log.slice(-50)), and appendLog grew log[] unbounded
- Mic stayed off after switching back to a parked multi-join tab
  (added ParkedSessionState.micWasOn, restore mic on switch-back)
- Packet-loss heuristic guessed fraction-vs-percent by magnitude, which
  can't disambiguate; now branches on actual server type (GTS vs TS3)
- serverGroups/channelGroups/permissionCatalog/banList/fileBrowser were
  page-global caches never invalidated on multi-join tab switch, so a
  newly active tab could show another server's stale data
- ServerQuery clients were filtered from the client list but still
  counted in the online-total fallback; total now matches the list
- gateway disconnect() resolved before the connector child process
  actually exited, allowing two connector processes to run briefly on
  a fast reconnect; now waits for exit (with a hard-kill fallback)
- switching a parked multi-join tab back in replayed a spurious
  whisper-target log entry and resent setWhisperTargets even when
  nothing changed, because the diff was against the wrong tab's ref
- double-click-to-join channel detection used module-level state,
  so a click in one multi-join tab could pair with a click in another
  tab's tree as a false double-click; now keyed per session

Note: could not verify with a full cargo build - the PR's own
'Update tsclientlib' commit (cd6928b) points at a tsclientlib submodule
commit that isn't pushed to any reachable branch (not even the PR
author's own fork), so nobody can currently build this PR end-to-end.
That is unrelated to these fixes.
2026-09-06 00:20:33 +02:00
Moepchi 27ac828641 Add channel password prompt on mid-session join (fixes #3)
Joining a password-protected channel after connecting silently failed
with only a generic error in the log - there was no way to enter a
password except the initial-connect "default channel" field.

- connector: "switch" now accepts an optional base64-encoded password
  and wires it through tsclientlib's existing set_password() API; a
  ChannelInvalidPassword failure is reported as a distinct
  channelPasswordRequired event instead of a generic error.
- gateway: forwards channelPassword through switchChannel and remaps
  the connector's snake_case event to the frontend's camelCase shape.
- web: new ChannelPasswordDialog prompts for the password (and flags
  a wrong retry); the password is cached in memory for the session so
  re-entering an already-unlocked channel doesn't prompt again, and
  the cache is cleared on disconnect.

Also includes two earlier Pulse-theme CSS fixes (bottom-toolbar
dropdowns opening off-screen; caret button height mismatch) and the
Speaking Now bar / Pulse Phase D wiring from this session.
2026-09-05 23:49:43 +02:00
Nico B. cd6928b407 Update tsclientlib 2026-09-05 22:48:31 +02:00
Nico B. e9ee12c7b5 Add TeaSpeak/GTS support, multi-join & GTS theme
Adds TeaSpeak/GreenTeaSpeak protocol support and multi-join session tabs plus a GreenteaSpeak UI theme. Key changes: connector (Rust) supports --server-type, privilege key, server variables, license formatting, Query-client filtering and extra metrics; gateway accepts serverType/privilegeKey, optional static serving (WEB_STATIC), and per-tab /ws sessions; web frontend: multi-session parking (connectionSessions), channel spacer parsing, talk-lamp UI, extended server connection info, connect dialog serverType/privilegeKey, GreenteaSpeak CSS & chrome, i18n updates, and demo updates. Also adds docs/teaspeak.md and dependency num-traits.
2026-09-05 22:45:21 +02:00
MoepchiandClaude Sonnet 5 804fa44ab6 fix: update stale moepchi.de OG/Twitter meta tags to webspeak3.de
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 20:35:49 +02:00
MoepchiandClaude Sonnet 5 563bca2a4b feat: add Simplified Chinese (zh-CN) locale, harden runtime image
zh-CN i18n adapted from MIKU-N's fork (github.com/MIKU-N/webspeak3):
new web/src/locales/zh-CN.ts, wired into i18n.tsx's Lang type, system
language detection, language preference persistence, the app.language
option list, and a new document.documentElement.lang sync effect.
App.tsx's language dropdown and the README feature table updated to
match. Missing keys naturally fall back to English via the existing
translations[lang][key] ?? translations.en[key] ?? key chain.

Also adapted from the same fork: the runtime stage's Dockerfile now
strips npm/npx (and npm's cache/package tree) after installing the
gateway's production deps, since nothing in the running container
invokes either afterwards - shrinks the image and drops npm's own CVEs
from the final attack surface. Adds a HEALTHCHECK that curls the
gateway's own port via Node's fetch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 18:50:01 +02:00
MoepchiandClaude Sonnet 5 b14292a95d ci: build and push Docker image on release
Adds a GitHub Actions workflow (docker-publish.yml) that builds the
webspeak3 image and pushes it to Docker Hub as moepchi/webspeak3:latest
plus a matching version tag whenever a GitHub Release is published (or
manually via workflow_dispatch). Uses GHA layer caching so the Rust
connector build doesn't redo work on every release.

Also hardens the Dockerfile's web-builder stage against a long-standing
npm bug (npm/cli#4828) where `npm ci` intermittently fails to install
Vite 8's platform-specific Rolldown binding without a non-zero exit
code, surfacing later as a confusing vite build MODULE_NOT_FOUND. Now
verified and self-healed (rm + npm install) before the real build runs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 16:55:22 +02:00
MoepchiandClaude Sonnet 5 a6e2130d29 docs: fix broken README preview images
The desktop/mobile screenshots linked to raw.githubusercontent.com on
the private webspeak3-landing repo, which 404s for anyone without
access. Copy both images into docs/screenshots/ in this repo and
reference them with relative paths instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 04:46:19 +02:00
Moepchi f490ca5776 Add auto gain control toggle for echo cancellation tuning (#2)
Exposes autoGainControl as its own Options -> Aufnahme toggle (was
implicitly left to the browser default) and requests the pipeline's own
48kHz sample rate explicitly, so the mic doesn't need an extra internal
resample before the browser's own AEC runs. Both are standard
getUserMedia constraints, honored the same way by Chromium and Firefox
(unlike vendor-prefixed googEchoCancellation-style flags, which only
affect Chromium).

Helps speaker+mic (no headset) setups where AGC re-amplifying the mic
signal after AEC can bring back audible echo residue - see #2.
2026-08-29 04:29:04 +02:00
Moepchi 24f070ce67 Untrack .serena/
Local Serena project config/memory files, not part of the repo's source.
2026-08-29 04:06:42 +02:00
Moepchi 8c954f9540 Add user-created custom design themes
Lets users build their own theme packages from Options > Design: pick a
structural base (Standard or Nova), write free-form CSS, and save/select
it locally. Supports duplicate, export/import (JSON), and delete.

Custom CSS is injected via a dedicated <style> tag while the theme is
active. Fixes the built-in theme variable rules (.ts-app,
.ts-app.ts-theme-dark, .ts-app.ts-design-nova) so a plain .ts-app { ... }
override in custom CSS always wins, by wrapping them in :where() to
strip their specificity - previously the compound selectors always beat
a same-specificity custom rule regardless of injection order.

Standard/Nova behavior is unchanged when no custom theme is selected.
2026-08-29 04:05:18 +02:00
Moepchi 3ad086aedd Add Nova design theme: redesigned menu bar, connect splash screen
- Restyle classic top menu bar into pill-chip items merged into the
  same row as the WebSpeak3 logo/server/status cluster, collapsed
  behind a hamburger button with an outside-click/Escape-aware
  dropdown panel (nested submenus flip to open leftward to avoid
  clipping at the viewport edge).
- Make the Connect dialog the sole visible surface while
  disconnected in Nova: it auto-opens on load and after every
  disconnect, and the app chrome (menu/toolbar/body/log) is hidden
  behind it until a connection succeeds.
- Rebuild the Connect dialog for Nova to match the TS6 Redesign
  mockup's dedicated Connect screen: centered hero (logo/title/
  subtitle) above an elevated card, a chevron-toggle "Erweiterte
  Optionen" moved under the nickname field, reordered ghost/primary
  footer buttons, and a fixed settings-gear shortcut into Options.
  The 11 existing form fields/handlers are shared with the Standard
  dialog via one JSX tree, decorated only through small nova ternaries.
- Nova starts with an empty server-address field instead of the
  Standard theme's "localhost" default.
- All changes scoped under .ts-app.ts-design-nova (or nested
  classes); Standard theme verified pixel- and behavior-identical
  throughout via repeated live comparisons.
2026-08-29 03:15:06 +02:00
MoepchiandClaude Sonnet 5 8e78ae98c9 Remove non-functional myTeamSpeak ID feature
Both checkboxes were disabled stubs; the underlying protocol field is
hardcoded to None in tsclientlib and not exposed as a settable option,
so the feature can't be implemented. Removed from Connect and
Favorites dialogs plus the now-orphaned i18n keys (DE+EN).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 22:28:51 +02:00
Moepchi e2c67ef23c Remove landing page from client repository 2026-08-23 10:09:28 +02:00
Moepchi 34fdd04c1c Improve project documentation and beta roadmap 2026-08-23 00:35:16 +02:00
Moepchi b0eda9a22c Add mobile navigation and release updates 2026-08-22 23:35:59 +02:00
Moepchi bdfc0bcc10 Expand landing navigation sections 2026-08-22 23:25:20 +02:00
Moepchi 6bdd0fa171 Stabilize landing navigation scroll state 2026-08-22 23:19:17 +02:00
Moepchi ccceacba07 Polish landing navigation and section motion 2026-08-22 23:17:31 +02:00
Moepchi f56990f033 Add landing community feedback section 2026-08-22 23:10:56 +02:00
Moepchi a58a649818 Clarify Safari client workflow labels 2026-08-22 22:59:56 +02:00
Moepchi a26b7e02ec Test WebSpeak3 client capabilities in Safari 2026-08-22 22:58:54 +02:00
Moepchi 386c6ad49b Fix Safari language switch selector 2026-08-22 22:52:39 +02:00
Moepchi a8cf46f2da Use isolated Python environment for Safari check 2026-08-22 22:51:09 +02:00
Moepchi c5635102f0 Add free Safari landing page checks 2026-08-22 22:50:12 +02:00
Moepchi 27fbd3cd10 Fix connection status indicator spacing 2026-08-22 22:41:29 +02:00
Moepchi dfae1b53d2 Expand landing onboarding and project details 2026-08-22 22:37:51 +02:00
Moepchi e221c9d73d Overlay Android camera and gesture bar 2026-08-22 22:23:07 +02:00
Moepchi 8ff35abdf1 Refine iPhone preview frame 2026-08-22 22:19:58 +02:00
Moepchi bb152a9bda Add device-aware phone frames 2026-08-22 22:14:09 +02:00
Moepchi 0b76f2e354 Show real mobile client preview 2026-08-22 22:09:50 +02:00
Moepchi 0ad64fd4f8 Update interactive client preview 2026-08-22 22:04:07 +02:00
Moepchi c6fbc04236 Clarify connection to any TeamSpeak server 2026-08-22 21:37:58 +02:00
Moepchi 7deee1a8c3 Expand landing page with product details 2026-08-22 21:31:02 +02:00
Moepchi 69efb64db6 Add bilingual WebSpeak3 landing page 2026-08-22 12:47:09 +02:00
MoepchiandClaude Sonnet 5 e917e8e906 Remove GitHub Pages demo workflow
Cloudflare Pages (demo.webspeak3.de) already covers this for free,
no need for a second free hosting fallback.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-12 21:39:49 +02:00
MoepchiandClaude Sonnet 5 5e2b2860ae Drop GitHub Pages fallback mention from README demo blurb
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-12 21:38:23 +02:00
MoepchiandClaude Sonnet 5 80e36539f3 Link webspeak3.de, client.webspeak3.de and demo.webspeak3.de in README
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-12 21:37:39 +02:00
MoepchiandClaude Sonnet 5 b70b4d1fc9 Fix: VITE_GATEWAY_URL override was missing the /ws path
The gateway's WebSocketServer only listens on /ws (gateway/src/index.ts),
but the VITE_GATEWAY_URL build-time override connected to the bare host
instead - causing 'Could not reach the gateway' on split-hosted deploys
(e.g. client.webspeak3.de -> gateway.webspeak3.de). Now /ws is always
appended, whether the URL comes from the same-origin fallback or the
override.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 02:17:53 +02:00
MoepchiandClaude Sonnet 5 fd24ae740e Add cloudflared tunnel service to docker-compose
Enables exposing the gateway via Cloudflare Tunnel without a public
DNS record pointing at the home server's real IP. Token is supplied
via CLOUDFLARE_TUNNEL_TOKEN in a gitignored .env file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 01:22:48 +02:00
Moepchi c10572feda Support VITE_GATEWAY_URL to point the built frontend at a gateway on another host 2026-08-10 21:46:39 +02:00
Moepchi c305fc4e1e Remove redundant poke hover-button from client tree rows (already in context menu) 2026-08-10 21:31:13 +02:00
Moepchi ec3a693292 Fix icon right-alignment: remove duplicate margin-left:auto from poke button 2026-08-10 21:28:16 +02:00
Moepchi 6bc3dca567 Add colored-letter badges for TS3 built-in default group icons; only fetch real custom icon files 2026-08-10 21:23:54 +02:00
Moepchi 0a1163d4f9 Widen tree row to fill panel width; add ftdownload debug logging 2026-08-10 20:47:13 +02:00
Moepchi fee0169463 Right-align client row icons flush to the edge; add debug logging for group icon ids
Status icons and group badges previously sat right after the name with no
push-right, so they clustered close to it instead of at the row's right
edge like the poke button already does. Wrapped them in a flex span with
margin-left: auto to match.

Also added temporary eprintln logging of each channel/server group's
resolved icon_id, to check whether this server's groups actually have
custom icons assigned (native TS3 doesn't show a badge for groups without
one either) before assuming the icon feature itself is broken.
2026-08-10 20:09:10 +02:00
Moepchi b7ef6f78e7 Add server group icon badges and a 'no talk power' status icon
Group icons were entirely missing from the data model - GroupEntry only
carried id/name. Added icon_id (from ServerGroup/ChannelGroup's Icon field)
through connector -> gateway -> frontend, matching the same channel-0
icon_<id> file convention already used for server icons (#77), reusing
that dialog's fetch/cache/render plumbing (serverIconImages, iconDataUrl).

Client rows now render a small badge per server group with a non-zero
icon, positioned after the name/status icons (i.e. on the right), instead
of not existing at all. Also added a 🔒 status icon for clients who aren't
muted but still can't talk due to insufficient talk power in a moderated
channel (previously no icon indicated this state at all).
2026-08-10 19:11:03 +02:00
Moepchi 6e343c4d4c Fix talking indicator: also respect missing talk power in moderated channels
The previous fix only accounted for the local mute toggle. In a moderated
channel (one with a talk power requirement) a client without sufficient
talk power still has selfActive/VAD firing locally and no local concept of
whether they're actually allowed to transmit, so the indicator stayed on
regardless.

The connector now computes has_talk_power per client from the book state
(talk_power_granted || talk_power >= channel.needed_talk_power), mirroring
tsclientlib's own internal intern_can_send_audio moderated-channel check,
and threads it through gateway and frontend. The talking indicator (both
the own-client injection into displayTalkers and the general per-client
render in ChannelTree) now requires hasTalkPower too.
2026-08-10 18:47:37 +02:00
Moepchi 4847972c80 Fix: don't show local talking indicator while mic is muted
selfActive is driven by MicCapture's local VAD (raw input level), which has
no notion of the input-muted state - only the actual audio send (onFrame)
checked inputMutedRef. So muting the mic still lit up the green talking
indicator on your own row locally, even though nothing was being
transmitted.
2026-08-10 18:30:37 +02:00
Moepchi 44450ab35f Fix permission catalog names: server never sends explicit permission_id, only implicit stream position
Live debug logging confirmed notifypermissionlist entries always had
permission_id=None - only permission_name/description were populated, plus
an unrelated group_id_end marker. The old code silently discarded every
entry because it only inserted into the name cache when permission_id was
Some. Real numeric IDs (as seen e.g. in notifyservergrouppermlist) only
match a catalog entry's ordinal position in the arrival stream, so names
are now assigned from a running counter instead.

Also fixed a related race: three call sites (permoverview, permissionlist,
permlist) each independently checked permission_names.is_empty() before
firing their own 'permissionlist' catalog fetch, so two could race and
fire duplicate concurrent fetches whose interleaved chunks would have
corrupted the new ordinal counter. They now check pending_permission_list
too and piggyback on an in-flight fetch instead of duplicating it.
2026-08-10 18:14:26 +02:00
Moepchi 9d6dcebfa9 Temporary debug logging for the missing permission-names bug investigation 2026-08-10 17:48:28 +02:00
Moepchi e26b02c449 Remove local .claude config from the repo and ignore it going forward 2026-08-06 03:22:54 +02:00
Moepchi f629666bc2 Fix missing permission names: don't finalize the catalog after the first reply chunk
A full permissionlist reply on a real account (hundreds of real
permissions) arrives as several separate notifypermissionlist events,
not one - only a permission-limited guest's tiny marker-only reply
fits in a single message, which is all that had been tested before.
The connector finalized permission_names right after the first chunk,
so anything past roughly the first packet's worth of entries never got
a name and fell back to '#<id>' in the UI.

Now it just accumulates names as chunks arrive and only finalizes -
resolving buffered PermissionOverview/PermList/PermissionCatalog
requests - once the command's MessageResult confirms completion.
2026-08-06 03:01:25 +02:00
Moepchi 684e597529 Fix Server/Channel Gruppen lists: read from book state instead of waiting for a reply that never arrives
notifyservergrouplist/notifychannelgrouplist never surface as an
InMessage the connector can match on - the server delivers them as
book-state PropertyAdded events (populating con.server_groups /
con.channel_groups), while the command's MessageResult itself comes
back Ok(()) with no payload. The connector was waiting on the wrong
stream item, so the group lists silently never resolved for any
account, not just permission-limited ones - confirmed via live debug
logging against the real server with a full Server Admin identity.

Fix: once the servergrouplist/channelgrouplist command result comes
back Ok, read the groups straight out of the already-synced book
state instead of trying to match a reply that never comes.
2026-08-06 02:33:55 +02:00
Moepchi 79df26c3bc Temporary debug logging for the blank group-list bug investigation 2026-08-06 02:08:04 +02:00
Moepchi b4ec2a26b6 Fix blank Server/Channel Gruppen tabs when the group list can't load
servergrouplist/channelgrouplist decline silently on the server when the
account lacks permission to see them (no reply at all - same behavior as
banlist/complainlist elsewhere in this app). The permissions editor's
group list only rendered when it had data, so a permission-limited
account just saw a permanently blank left panel with no explanation
(reported by a screenshot from the real server).

Added the same loading/6s-timeout/"nicht verfügbar" fallback every other
list dialog in this app already uses (GroupAssignDialog, banlist, etc.) -
now shows a loading indicator, then a clear "unavailable" message
instead of nothing.

Verified in demo mode: both Server Gruppen and Channel Gruppen tabs still
list their (demo) groups correctly - no regression from the loading-state
change.
2026-08-06 01:50:53 +02:00
Moepchi ecc07308f6 Fix mojibake in imported .ini identity names/nicknames
The previous \xHH unescaper treated every escape as exactly 2 hex digits
representing one raw byte. The native client's .ini format (Qt's
QSettings escaping) actually uses \x followed by 1-4 hex digits for one
UTF-16 code unit - astral characters (emoji) become two consecutive
escapes forming a surrogate pair, e.g. "\xd83d\xde43" for 🙃. The old
code only consumed the first 2 digits of each escape, leaving the rest as
stray literal text - exactly the mojibake ("Ø3dÞ43" etc.) a user hit
when importing an identity with emoji/Greek/Turkish letters in the name.

Root-caused directly from the user's screenshot (reverse-engineered the
old buggy output back to the real escape sequence) and confirmed against
their actual .ini file content. New parser correctly reconstructs
"[🙃 ] λşşαşşỉŋş88 / Möpchi" and a real connect using that identity's
exact key + nickname succeeds against the live server.
2026-08-06 01:20:51 +02:00
Moepchi 53ccb22189 Support importing native TeamSpeak .ini identity files
The connector now parses --identity either as our own JSON blob or as a
raw TS3 identity string ("<counter>V<base64-key>", the format inside a
native client's exported .ini and in teamspeak:// URLs) via tsproto's
Identity::new_from_str, which already handles both.

The web client's "Identitäten" > Importieren now recognizes a native
.ini file (looks for a [Identity] section), unescapes its \xHH-escaped
name field, and pulls out id/identity/nickname/phonetic_nickname directly
- no conversion needed, the raw identity string is stored as-is and self-
migrates to our JSON format after the first successful connect (same as
any other imported/created identity).

Verified with a real exported .ini file: parsing extracts the right
name/nickname/blob, and connecting the connector directly against the
real server with that exact identity string succeeds and is recognized
as the already-known account (its own channel/server group, not the
default guest group) - not just a fresh/anonymous identity.
2026-08-06 00:48:42 +02:00
Moepchi 17899ae137 Rework Identitäten dialog to match the native client's layout
The old dialog was a flat list with an inline rename field and a radio
button per row - visually and structurally nothing like the native
myTeamSpeak-style Identitäten window. Reworked to the same list + detail
panel layout: pick an identity on the left, edit its Name/Nickname/
Phonetischer Nickname on the right, see its Eindeutige ID (once known)
and creation status, Standard/Löschen/Exportieren buttons per identity.

Also added what was actually missing functionally, not just visually:
- Import/Export: an identity's opaque tsclientlib blob can be downloaded
  as a JSON file and re-imported later (backup/transfer between browsers).
- Per-identity nickname: each identity now remembers its own nickname
  (like native TS3), applied when switching identities in the connect
  dialog and saved back after a successful connect - previously there was
  only one global nickname shared by every identity.

Deliberately left out of scope (documented inline in the component):
myTeamSpeak cloud-synced identities (a whole separate account system this
self-hosted client has no equivalent of) and the manual "Sicherheitsstufe
erhöhen" button (tsclientlib already runs that proof-of-work step
automatically during connect whenever a server demands a higher level,
so a manual trigger wouldn't add functionality, only let you pre-compute
it before connecting).

Verified interactively in demo mode: dialog renders in the new layout,
fields are all editable, Standard/Löschen/Export honor their expected
enabled/disabled states.
2026-08-06 00:39:26 +02:00
Moepchi ea7b97b161 Add full permissions editor window (#71)
The "Rechte" top menu's four previously-disabled items now open a tabbed
editor matching the real TS3 client's window: Server Gruppen, Client
Rechte, Channel Rechte, Channel Gruppen, Channel Client Rechte. For each
tab you pick a group/channel/client (or combination), see its currently
assigned permissions in a filterable table, add new ones from a searchable
catalog, and remove existing ones.

Connector: new servergrouppermlist/channelgrouppermlist/channelpermlist/
clientpermlist/channelclientpermlist request handling (unified behind one
"permlist <scope> ..." stdin command and a single-target pending-list
mechanism, mirroring the existing permoverview pattern's name-resolution
cache) plus servergroupaddperm/-delperm, channelgroupaddperm/-delperm,
channeladdperm/-delperm, clientaddperm/-delperm, channelclientaddperm/
-delperm for mutating them, and a "permissionlist" command to expose the
full permission catalog (needed for the "add permission" picker).

Verified against the real server: permission list/catalog requests reach
the server correctly. The test guest account turns out to lack rights to
see permission names/IDs at all (server replies with only the hierarchy's
group-boundary markers, no populated permid/permname) - same class of
account-permission ceiling as banlist/file uploads/etc. earlier in this
project, not a bug in this feature. Add/remove wire commands support both
numeric permid and permsid addressing per the protocol, so this should
work fully for an account with actual view rights (e.g. the real server
admin), even though it couldn't be exercised end-to-end with this guest
account. Full interactive verification (list, add, remove) done in demo
mode instead.

"Rechteübersicht" (viewing another client's computed effective
permissions with grant provenance) stays disabled - a materially
different feature the connector doesn't support.
2026-08-06 00:16:30 +02:00
Moepchi 6d6803d9b3 Add server icons window (#77)
Right-click on the server row -> "Server-Icons..." opens a grid of the
server's icon repository (TS3's special "channel 0" filebase). Reuses the
file-transfer plumbing from #83 (ftgetfilelist/download/upload/delete)
rather than adding new connector commands - icon_<id> files under channel
0 *are* the server icon repository, so no new protocol handling was
needed. Lets you view existing icons as real thumbnails (sniffed from the
downloaded bytes - PNG/GIF/JPEG/BMP), upload a new one under a chosen
numeric ID, and delete icons.

Out of scope for this pass: actually assigning an icon to the server/a
channel/a group (there's no icon-picker wired into the server/channel
edit dialogs yet) - this delivers the icon repository browser only.

Demo mode gets a small fake icon repository (two placeholder icons) so
the window is interactive in the GitHub Pages demo too.
2026-08-05 23:36:45 +02:00
Moepchi 7901aafbb1 Add file transfer support (#83)
Channel-scoped file browser reachable via right-click on a channel:
navigate directories, create folders, rename/delete, and upload/download
files. Backed by tsclientlib's built-in download_file/upload_file (which
already handles the ftinitdownload/ftinitupload -> TCP data-port dance),
plus raw ftgetfilelist/ftcreatedir/ftdeletefile/ftrenamefile commands for
everything else. Downloads/uploads are buffered whole in memory and
base64-relayed over the existing stdin/WebSocket text protocol - fine for
a channel filebase's typical file sizes, not meant for huge transfers.

Verified against the real server: upload/list/download round-trip reaches
the server correctly (list succeeds, upload correctly surfaces the
guest account's missing permission via the new FiletransferFailed
handling instead of hanging or crashing).

Demo mode gets a small in-memory per-channel filesystem so the file
browser is fully interactive in the GitHub Pages demo too.
2026-08-05 22:39:35 +02:00
MoepchiandClaude Sonnet 5 41ac845fbc Add read-only permission overview ("Eigene Rechte anzeigen")
Partial progress on #71 (full permissions editor). A genuine full
editor - server/channel/group permission grids across 5 permission
scopes with add/remove/modify for hundreds of possible permissions -
is a much bigger undertaking than fits in one pass, so this lands a
real, useful slice of it first: a read-only view of the caller's own
effective permissions in their current channel.

- Connector: "permoverview" (raw command, no typed builder exists)
  requests the caller's effective permission set for cid+cldbid.
  Permission IDs are opaque numeric values server-side, so results are
  name-resolved via a "permissionlist" id->name/description lookup
  that's fetched once and cached for the connection's lifetime. The two
  requests are chained (list first, overview second) with buffering in
  case the overview reply somehow arrives first.
- Gateway: typed passthrough for the merged, name-resolved entries.
- Frontend: new dialog wired to "Eigene Rechte anzeigen" in the Rechte
  menu (previously disabled) - a filterable table of permission
  name/value/negated/skip.

Verified against the real server: initially got a clean
"ParameterNotFound" error revealing that permoverview needs an
explicit permid=0 ("all permissions") even though tsclientlib's
generated type treats it as optional; after adding that argument the
command reaches the server correctly and returns the expected
permission-denied response for the guest test account (same pattern
as every other admin-gated feature this session).

The remaining scope of #71 - editable server-group/channel-group/
channel/client permission grids - is unchanged and left for later.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 21:35:09 +02:00
MoepchiandClaude Sonnet 5 0f8576ac6c Add ServerQuery Login dialog
Wires up the previously-disabled "ServerQuery Login" Extras menu item
with a username/password form. Sends the raw TS3 "login" command
(client_login_name/client_login_password) over the existing
connection - no typed builder exists for it upstream, same situation
as the other raw-command features this session. Credentials are
base64-encoded over the connector's stdin protocol (rather than naive
space-splitting) so passwords with spaces or special characters
survive the trip intact.

Fire-and-forget like kick/ban: the dialog closes on submit and relies
on the existing generic error/permission-error event path for
feedback. Verified against the real server end-to-end - bogus
credentials round-tripped through connector -> gateway -> frontend
and surfaced as a clean error event (this particular server responds
"NotImplemented" to post-connect query login, which is itself proof
the command reached the server and got a real protocol-level reply).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 21:02:16 +02:00
MoepchiandClaude Sonnet 5 db8b5ea958 Complete client context menu: channel/server group assignment
Fills out the last two disabled entries in the client right-click menu
(#72): "Channel-Gruppe zuweisen" and "Server-Gruppe zuweisen".

- Connector: exposes each client's database_id, channel_group, and
  server_groups (already present in tsclientlib's bookkeeping Client
  struct, just not threaded through before) on the "channels" snapshot.
  Adds raw commands for channelgrouplist/servergrouplist (list requests,
  same InMessage pattern as banlist/complainlist) and
  setclientchannelgroup/servergroupaddclient/servergroupdelclient
  (assignment, fire-and-forget like kick/ban).
- Gateway: typed passthrough for the new client fields and five new
  message types (getChannelGroupList, getServerGroupList,
  setChannelGroup, addServerGroup, removeServerGroup).
- Frontend: new GroupAssignDialog reused for both channel groups
  (single-select, closes after assigning) and server groups
  (multi-select, checkmarked entries toggle add/remove and the dialog
  stays open). Demo mode simulates real group membership changes,
  including live re-render after assignment.

Verified against the real server: the client's own database_id/
channel_group/server_groups now flow correctly end-to-end (confirmed
via a throwaway gateway test script). The list-request commands are
permission-gated for the guest test account and decline silently, same
as serverlog/serverconninfo before them - the dialog's existing 6s
"unavailable" timeout already covers this.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 20:40:52 +02:00
MoepchiandClaude Sonnet 5 203e8fba51 Add "Rechte" top menu
Turns the previously-static "Rechte" label into a real dropdown menu,
matching the layout of TeamSpeak's native permissions menu: server
groups, channel groups, server/channel permission editors, a
permission overview, and "eigene Rechte anzeigen".

All entries are disabled with the standard "not yet supported in the
web client" tooltip - actual permission querying/editing needs new
protocol plumbing (permlist/permidgetbyname etc., same class of work
as the full permissions editor tracked separately) that doesn't exist
yet. This gives the menu real content and correct TS3-parity structure
without faking functionality that isn't there.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 20:22:58 +02:00
MoepchiandClaude Sonnet 5 b9d4bd533d Complete server right-click context menu
Right-clicking the server row in the tree previously did nothing.
Adds a context menu (same styling/dismiss pattern as the client
context menu) offering: server connection info, edit virtual server,
copy server address, add to favorites, server protocol log, ban list,
complaint list, and disconnect - all wired to handlers that already
existed for the menu bar / info panel equivalents.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 20:17:55 +02:00
MoepchiandClaude Sonnet 5 dbe9a3c2df Add offline messages (Offline Nachrichten) dialog
Wires up raw TS3 protocol commands for offline messages, since
tsclientlib's generated code has no typed builder for them (same
situation as banlist/complainlist in the previous feature):

- Connector: messagelist, messageget, messageadd, messagedel,
  messageupdateflag as raw OutCommand invocations. Replies parsed via
  the existing StreamItem::MessageEvent pending-flag pattern, reusing
  InMessage::OfflineMessageList (list, no body) and InMessage::OfflineMessage
  (single message with full body, response to messageget).
- Gateway: typed events/methods threading the new commands from
  WebSocket clients through to the connector's stdin protocol.
- Frontend: new "Offline Nachrichten" dialog in the Extras menu with a
  message list (subject/from/timestamp, unread dot), a detail view
  (full body + mark-as-read), delete, and a compose form to send a new
  message to a target client UID. Demo mode gets one scripted message.

Verified against the real test server (192.168.178.108): messagelist
returns a clean DatabaseEmptyResult error for an account with no
messages (falls back to the dialog's existing 6s "unavailable" timeout,
same as banlist/complainlist), and messageadd correctly surfaces a
permissionError for a guest account lacking send rights - both proving
the raw command round-trip works end to end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 19:57:05 +02:00
MoepchiandClaude Sonnet 5 bd0122812d Add Bannliste and Beschwerdeliste management dialogs
Implements #91 (ban list) and #92 (complaint list), reusing the
StreamItem::MessageEvent handling infrastructure added for #94.

Connector:
- New raw commands: banlist, bandel, bandelall, complainlist,
  complaindel, complaindelall (no typed builders exist for these).
- New pending_ban_list/pending_complain_list flags + MessageEvent
  match arms parsing InMessage::BanList/ComplainList replies into
  BanListEntry/ComplainListEntry structs, emitted as banList/
  complainList events.
- Unlike serverlog/serverconninfo, the test server actually replies
  with an error return code for these (surfaced as a "permission
  error" Server-tab log line) rather than staying silent - the
  connector already handles that path via the existing pending
  message result matching.

Gateway: getBanList/deleteBan/deleteAllBans/getComplainList/
deleteComplaint/deleteAllComplaintsFor methods and message cases,
plus camelCase remapping for the two new event types.

Frontend: BanListDialog and ComplainListDialog components (table
view, per-row delete + delete-all for bans, optimistic local removal
on delete), wired into the Extras menu (previously disabled
placeholders), with the same 6s timeout-to-"unavailable" fallback
pattern used by the other async-reply dialogs. Demo mode gets fake
ban/complaint entries.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 13:08:01 +02:00
MoepchiandClaude Sonnet 5 4318ce359f Add Server Protokoll dialog
Adds the first StreamItem::MessageEvent handler in the connector's
event loop (previously dropped by a catch-all) - needed because log
lines aren't part of the bookkeeping data model, unlike client/server
connection info, so they only ever arrive as a raw notifyserverlog
reply rather than a book-state update. This unblocks the same pattern
for Bannliste/Beschwerdeliste next.

Sends "logview" via tsclientlib's typed Server::log_view() builder,
requesting the last 200 lines. Verified end-to-end against the real
server (though a permission-gated account got no reply at all there -
the frontend dialog now falls back to a "no response" message after a
timeout instead of loading forever, matching the connection-info
dialogs' existing behavior).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 12:45:59 +02:00
MoepchiandClaude Sonnet 5 181b0fc43b Add "Virtuellen Server editieren" dialog
Wires up tsclientlib's typed Server::edit() builder (name, welcome
message, password, host message/banner/button settings, nickname,
phonetic name, codec encryption mode) through a new "serveredit"
stdin command. Frontend dialog has Host and Verschiedenes tabs fully
implemented, with Übertragung/Anti-Flood/Sicherheit/Protokoll shown as
not-yet-implemented placeholders (their fields have no typed setter in
tsclientlib's generated bindings, would need hand-built raw commands).

Entry point is a new link in the server info panel, next to the
connection-info one added earlier. Every field is optional in the
payload - blank means "leave unchanged" - except the password field,
which has an explicit "remove password" checkbox for the clear case.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 12:08:43 +02:00
MoepchiandClaude Sonnet 5 330ecccadb Add kick and ban to the client context menu
Wires up "Aus dem Channel kicken", "Vom Server kicken", and "Bannen"
(previously disabled placeholders). Kick uses tsclientlib's typed
Client::kick() builder; ban has no typed wrapper so it's built as a
raw "banclient" command (same OutCommand::write_arg approach used for
the connection-info requests). Both use send_with_result() so a
missing-permission rejection surfaces as a visible error.

"Channel-Gruppe zuweisen"/"Server-Gruppe zuweisen" remain disabled -
they need the server's group list threaded through first, left for a
follow-up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 11:21:52 +02:00
MoepchiandClaude Sonnet 5 74f688aba8 Add client and server connection-info windows
Sends raw getconnectioninfo/serverrequestconnectioninfo commands and
reads the reply out of tsclientlib's bookkeeping state (it already
tracks ping, packet loss, bytes/packets sent+received internally -
just needed to be requested and surfaced). Wired into the client
context menu (any client), the Selbst menu (self), and a new link in
the server info panel.

Uses send_with_result() so a permission-denied rejection surfaces as
a visible error instead of silently doing nothing; the dialogs also
fall back to a "no response" message after 6s in case the server
declines without any reply at all (observed against a real server
where a guest lacked b_virtualserver_connectioninfo_view).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 22:42:23 +02:00
MoepchiandClaude Sonnet 5 a300daedeb Add Identitäten (identity) management dialog
Replaces the single flat identity key with a list of named identities
you can add, rename, delete, and switch between (each keeps its own
tsclientlib identity blob, generated lazily on first connect). The
Connect dialog's identity dropdown, previously a disabled "Standard"
placeholder, now reflects and can switch the active one too. Existing
users' single stored identity migrates automatically into the new list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 19:47:20 +02:00
MoepchiandClaude Sonnet 5 46ae5b120e Add Whisperlisten (saved whisper target lists)
Lets you save the current whisper channel/client selection as a named
list and reactivate it later. Lists are matched by name rather than id
on activation, since ids only stay stable for the current connection.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 19:37:14 +02:00
MoepchiandClaude Sonnet 5 284645f18d Save local recordings as WAV instead of webm
Swaps the MediaRecorder-based capture for a raw PCM tap (ScriptProcessorNode)
and a hand-rolled WAV encoder, since MediaRecorder's output format/codec is
browser-dependent (webm/opus) and the user wants a plain, universally
compatible file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 19:28:46 +02:00
MoepchiandClaude Sonnet 5 67c4bc1072 Add local session recording (Aufnahme)
Wires up the Extras menu's Aufnahme starten/beenden items: mixes the
incoming voice playback and outgoing mic signal into a MediaRecorder
and downloads the result as webm on stop. Multitrack recording stays
disabled (needs a plugin-equivalent per-client split not modeled here).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 19:21:29 +02:00
Moepchi 7bcced06fd Add Kontakte (contacts) feature
Threads the client's persistent unique identifier through the
connector/gateway/frontend pipeline (previously only the ephemeral
session client id was exposed) so contacts can be keyed by the same
person across reconnects, not by name. The Kontakte dialog supports
adding currently-online clients, per-contact category/phonetic name,
ignoring (filters their chat messages), and quick-whisper/show actions
that reuse existing whisper and channel-selection logic.
2026-08-04 18:37:49 +02:00
Moepchi f5cb4dd160 Add Whisper Verlauf dialog and complete the Selbst menu
Whisper Verlauf logs outgoing whisper-target changes with timestamps
(incoming-whisper detection isn't observable yet, so it's outgoing-only
for now). The Selbst menu now wires Abwesend/Mikrofon/Lautsprecher to
the existing toolbar actions and adds a real nickname-change flow,
backed by a new "nickname" connector command using tsclientlib's
existing client_update().set_name().
2026-08-04 18:14:04 +02:00
Moepchi a0ede4a12a Add Gesammelte URLs, Freund einladen, and Client Protokoll dialogs
Three of the Extras menu's placeholder items are now functional:
collected chat URLs with counts/timestamps, a ts3server:// invite
link generator, and a local client-side event log with level
filtering and search.
2026-08-04 17:53:12 +02:00
Moepchi 6c1fec8dcc Remove Overwolf, File Transfers, and Offline Messages menu items
These pointed at features that don't exist in this project and were
never going to be built - Overwolf integration is out of scope
entirely, and the other two are covered by planned real features
instead.
2026-08-04 16:52:00 +02:00
Moepchi 6c4ace585d Update README feature list
The table hadn't been touched since the early prototype and was
missing everything shipped since: whisper, persistent identity,
country flags, soundpack import, mobile layout, context menu, server
log, sound notifications, and i18n.
2026-08-02 17:51:48 +02:00
Moepchi 5858631e6d Add whisper (targeted voice to channels/clients)
Connector: a new "whisper <channelIds>;<clientIds>" stdin command sets
persistent whisper targets; outgoing audio then goes out as
AudioData::C2SWhisper instead of the normal C2S broadcast until
"unwhisper" clears it. Gateway relays a setWhisperTargets message the
same way.

Frontend: a toolbar toggle lists channels as checkboxes, and the
client context menu gets an "add/remove as whisper target" entry;
selecting any target switches all subsequent outgoing voice to
whisper mode.

Verified against the real test server: setting a channel target and
sending a frame produced no connector error, and clearing targets
resumed normal voice cleanly.
2026-08-02 14:41:54 +02:00
Moepchi 7217bc146a Persist client identity across sessions
Previously every connect generated a fresh tsclientlib identity, so
the server saw a new client UID each session. The connector now
accepts a saved identity via --identity and always reports the one
actually used (freshly generated or reused) back in the "connected"
event; the frontend round-trips it through localStorage so
reconnecting keeps the same UID.

Verified end-to-end against the real test server: two separate
connects with the identity carried over produced byte-identical
identity blobs.
2026-08-02 14:29:00 +02:00
Moepchi 249687d98a Support importing .ts3soundpack files
Real TS3 soundpacks have no documented, stable manifest format across
client versions, so instead of parsing a manifest this unzips the
pack (via fflate) and matches each audio file to one of our sound
events by keyword against its filename. Unmatched files are reported
rather than silently dropped, since match confidence varies by pack.
2026-08-02 14:21:55 +02:00
Moepchi 3644ae7c41 Show country flags next to client nicknames
Threads TeamSpeak's per-client country_code field through the
connector snapshot and gateway relay, then renders it as a flag
emoji (regional indicator symbols, no image assets needed) next to
the nickname. Renders nothing when the server has no geo-IP data for
a client (most common on non-official/self-hosted servers).
2026-08-02 14:15:39 +02:00
Moepchi 0529ab72f1 Add right-click context menu on channel tree clients
Works for both other clients (private chat, poke, copy name, plus
disabled placeholders for group assignment/kick/ban) and the own
client (copy name and group placeholders only, since you can't poke
or private-message yourself).
2026-08-02 14:03:01 +02:00
Moepchi af3a7c97cf Support Shift+Enter for newlines in chat input
The chat field was a single-line <input>, unable to hold a line
break. Switch it to an auto-growing <textarea>: plain Enter still
sends, Shift+Enter inserts a newline.
2026-08-02 13:55:23 +02:00
Moepchi 69b256eb42 Add demo-only mobile view toggle
Simulates a narrow viewport by capping .ts-app's own width and using
a container query (instead of a media query) for the mobile
breakpoint, so the toggle exercises the exact same CSS path real
narrow browsers hit. Only rendered when VITE_DEMO_MODE is set.
2026-08-02 13:43:17 +02:00
Moepchi 530415b50b Fix mobile menu bar clipping its own dropdown menus
overflow-x: auto on the menu bar also forces overflow-y to auto,
which clipped the absolutely-positioned dropdown to the bar's own
height instead of letting it float over the page. Let the bar wrap
onto a second line instead, since overflow isn't needed at this
breakpoint anyway.
2026-08-02 13:37:59 +02:00
Moepchi fcbf3ea40d Fix Connect dialog closing on text-selection drag; add mobile layout
Backdrop click-to-close now requires the mousedown to also start on
the backdrop, so selecting text inside any dialog and releasing the
drag outside it no longer closes the dialog.

Add a responsive breakpoint that stacks the tree/side/chat panels and
dialogs into a single column on narrow viewports instead of clipping
the fixed-width desktop layout.
2026-08-02 13:28:53 +02:00
MoepchiandClaude Sonnet 5 42f82d49aa Add Server Log tab notifications for client/channel/permission events
Surfaces join/leave/channel-switch/group-assignment/channel- and
server-edit events inline in the Server tab, matching the native TS3
client's behavior. Own missing-permission errors are shown; other
clients' permission failures are not. Sourced from tsclientlib's
book-event diffs rather than admin-only ServerQuery logs, so it works
for any connected user regardless of log-view permissions. Also
upgrades the channel-switch command to report permission errors
instead of failing silently, and adds a scripted demo-mode preview of
the feature for the GitHub Pages demo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 10:54:18 +02:00
MoepchiandClaude Sonnet 5 0d8e9336f8 Link the live GitHub Pages demo from the README
Now that the demo build/deploy is up and running, point to it from the top of the README alongside the other quick links, with a callout that it's simulated data only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 00:36:07 +02:00
MoepchiandClaude Sonnet 5 f6170f0576 Fix pre-existing TypeScript errors blocking CI build
npm run build runs tsc -b before vite build, and the Pages workflow uses it - these four errors were already present but never surfaced locally since testing here used vite build directly. Removes truly-dead outputDeviceLabel state (its value was never read, only the dropdown's own device list rendered labels), narrows the PmThread lookup to a proper number check, and replaces two constructor parameter properties with explicit fields (disallowed under erasableSyntaxOnly).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 00:27:40 +02:00
MoepchiandClaude Sonnet 5 65813b6367 Fix logo not loading under a non-root base path
The logo <img> used a hardcoded absolute "/logo.png" path, which only resolves correctly when the app is served from the domain root. Under the GitHub Pages demo (served from /webspeak3/), this 404'd. Vite already rewrites asset references in index.html for the configured base path, but plain string literals in JSX aren't touched, so this needs import.meta.env.BASE_URL explicitly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 00:23:56 +02:00
MoepchiandClaude Sonnet 5 fe1b5ff991 Add a static demo mode for a GitHub Pages showcase
GitHub Pages only serves static files, but the real app needs a Node gateway and Rust connector to speak the TS3 protocol - neither of which can run there. This adds a fake WebSocket (DemoSocket) that simulates a connection with canned channels/clients entirely client-side, gated behind VITE_DEMO_MODE so the normal Docker build is unaffected, plus a GitHub Actions workflow that builds and publishes it to Pages.

Also fixes a real bug surfaced while testing the disconnect flow: a clean disconnect incorrectly showed "Connection closed before the server responded" because the socket's onclose handler couldn't tell a clean disconnect apart from one that never connected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 00:19:22 +02:00
Moepchi 9b83e9d93f Merge branch 'main' of https://github.com/Moepchi/webspeak3 2026-07-31 23:57:16 +02:00
MoepchiandClaude Sonnet 5 186a3f958b Add GitHub issue templates for bugs and feature requests
Gives bug reports and feature requests a structured format instead of blank issues, and points questions to Discussions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 23:56:55 +02:00
Möpchi b6ccc6f627 Create FUNDING.yml 2026-07-31 23:53:55 +02:00
MoepchiandClaude Sonnet 5 8fb6d72957 Implement Nachrichten options panel: named away-message presets + disconnect message
Wires up the previously placeholder-only "Nachrichten" options section: users can now save/delete named away-message templates and set a default leave message that's sent to the server (via DisconnectOptions) when disconnecting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 23:22:08 +02:00
MoepchiandClaude Sonnet 5 234feb4d55 Add per-event checkbox to mute individual sound notifications
Lets users disable e.g. join/leave chimes while keeping others on, without touching the master sounds toggle.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 23:10:19 +02:00
Moepchi 7a69d8602c Add sound notifications for connect/disconnect, join/leave, chat, and poke
New Sounds options panel (Extras > Optionen > Sounds) with a master
enable toggle, volume control, and per-event upload/test/reset. Falls
back to synthesized soft two-note chimes when no custom file is set.
Sounds are routed through the same output device as voice playback.

Custom .ts3soundpack (ZIP+XML) import is left for later - this covers
the simpler per-event custom-file approach first.
2026-07-30 22:58:53 +02:00
Moepchi 3881742338 Add MIT LICENSE file, point README badge at it
The README already claimed MIT via a Shields.io badge, but no
LICENSE file actually existed in the repo.
2026-07-30 19:01:42 +02:00
Moepchi a5551dad54 Remove redundant docker compose up -d from README
It was shown twice: once in the clone snippet (before the port
override is even set up) and again right after the override
explanation.
2026-07-30 18:38:27 +02:00
Moepchi 9f41f4bcbe Fix port double-publish from previous compose change
Compose concatenates ports: lists across an override file instead of
replacing them, so the ports mapping added in the last commit caused
the deployed container to try publishing both 8080 and the override's
8188, colliding with another service already on 8080. Move ports back
out of the base file (override-only, as before) and keep the new
container_name/image/environment fields.
2026-07-30 18:32:59 +02:00
Moepchi 302c025018 Flesh out docker-compose.yml with a complete, self-documenting example
Add container_name, an image tag, direct port mapping, and an
explicit PORT env var instead of pointing to a separate override
file just to publish a port.
2026-07-30 18:31:05 +02:00
Moepchi 6a0ba6f732 Merge INSTALL.md into README with a Docker-first install section
Add a Docker Compose (build-from-source) and a Docker Hub pull path as
the recommended install method, with the previous manual/from-source
steps kept as a collapsible section for anyone without Docker.
2026-07-30 18:26:15 +02:00
Moepchi 6158779184 Add real UI screenshots to README preview
Replace the placehold.co placeholders with actual dark/light mode
screenshots of WebSpeak3 connected to voice.teamspeak.com.
2026-07-30 18:13:23 +02:00
Moepchi 507f9e8e3c Fix disconnect on large servers, remove nickname placeholder
Fork tsclientlib to Moepchi/tsclientlib and bump the out-of-order
command queue limit (200 -> 4096). Large servers like
voice.teamspeak.com burst hundreds of command packets during the
initial channel/client sync; a single dropped packet in that burst
previously exceeded the queue and aborted the connection with
"Maximum length exceeded for command queue".

Also clear the "Claude Code" default nickname so the field starts
empty.
2026-07-30 17:35:01 +02:00
Moepchi 85b48fe214 Add German/English UI localization with language switcher
Introduces an i18n layer (src/i18n.tsx) with auto-detection (defaulting
to English) and a persisted override, wires every user-facing string in
App.tsx through it, and adds a language selector to the Anwendung
options panel in the same spot the native TeamSpeak client uses.
2026-07-30 16:58:30 +02:00
Moepchi 4f24d98e9f Redesign README with modern GitHub-style layout
Adds badges, tagline/quick-links, a screenshot showcase table, a
features grid, tech-stack badges, and a collapsible architecture
section; makes the Docker Compose quick start prominent. Legal
disclaimer and credits kept unchanged.
2026-07-30 16:43:44 +02:00
Moepchi ddf4f149f7 Add WebSpeak3 logo, favicons, and Open Graph preview image
Wires the official logo into the header, README, and browser tab; generates
favicon.ico/apple-touch-icon/OG image via a new ImageMagick script from a
single source PNG at web/public/logo.png.
2026-07-30 16:34:39 +02:00
Moepchi a77172b55a Rename project from TS Web Client to WebSpeak3
Rebrands the app as an independent project, adds a trademark disclaimer
to the README, and migrates localStorage keys with a compatibility shim
so existing favorites/settings survive the rename. The TeamSpeak
protocol bridge itself (Ts3Connection, ts-connector binary) is untouched.
2026-07-30 16:21:46 +02:00
Moepchi 0b7d2b7346 Allow switching servers via Favoriten while already connected 2026-07-30 16:04:35 +02:00
Moepchi f523005972 Remove myTeamSpeak from Options sidebar (proprietary, not implementable) 2026-07-29 23:05:56 +02:00
Moepchi 26eff72528 Remove non-implementable/non-sensible cosmetic options from Wiedergabe/Aufnahme panels 2026-07-29 23:02:08 +02:00
Moepchi 8af60bd0c2 Enlarge Options dialog so the Aufnahme panel fits without scrolling 2026-07-29 22:56:09 +02:00
Moepchi deb3f7b131 Fix Options dialog content overflow by making the body scrollable 2026-07-29 22:47:19 +02:00
Moepchi 0f24c4b092 Wire up the real Wiedergabe/Aufnahme options panels
Builds out the Wiedergabe and Aufnahme sections of the Options dialog to
match the real TS3 client's layout, with the "Standard" profile only.
Everything technically feasible in a browser is wired to real behavior:
output/input device pickers (input device selection is new - MicCapture
can now target a specific deviceId), playback volume (new gain stage in
AudioPlayer), a real test tone, the voice-activation threshold/hangover
(hangover was previously hardcoded), noise suppression/echo cancellation
toggles (restart capture to apply new getUserMedia constraints), a live
mic level meter, and a mic self-monitoring ("Test starten") loopback.
Settings persist to localStorage. Everything the browser genuinely can't
do (Windows audio session mode, mono/surround downmix, ducking, typing
attenuation, mic-click sounds, comfort noise) stays as a disabled
placeholder control. Local-only for now, not deployed.
2026-07-29 21:43:47 +02:00
Moepchi e5c5cc3f80 Add Options dialog with the real client's settings sidebar
Opens via Extras -> Optionen. Sidebar navigation matches the real TS3
client (Anwendung/myTeamSpeak/Wiedergabe/.../Meldungen) and switches the
content panel, but the settings themselves are still placeholders - none
of the actual options are wired up yet. Local-only for now, not deployed.
2026-07-29 21:08:25 +02:00
Moepchi a2863520a5 Add Extras menu as a layout-only dropdown
Matches the real TS3 client's Extras menu items/grouping/shortcuts, but
every entry is disabled - none of these (identities, ban list, recording,
ServerQuery, etc.) are implemented yet. Local-only for now, not deployed.
2026-07-29 20:54:55 +02:00
Moepchi 0d65c3b123 Enable the mic automatically on page load instead of requiring a click
Voice activation already gates what's actually transmitted, so there's no
reason to make the user click "Enable microphone" every time - it's now
requested once on mount via the same handleToggleMic() path a manual click
uses. Also resume the AudioContext if it starts suspended (autoplay policy),
since granting the permission prompt itself counts as a user gesture and
unblocks it even when start() wasn't triggered by a click.
2026-07-29 20:46:17 +02:00
Moepchi 41559c7712 Allow enabling the mic (and picking an output device) before connecting
The AudioContext/AudioPlayer were only created inside handleConnect, so
clicking the mic button while disconnected silently did nothing - no
permission prompt, no error. Lazily create them on first use instead
(ensureAudioContext), and drop the mic button's connected-only disabled
state, matching the real TS3 client where you can test your devices before
joining a server.
2026-07-29 20:39:51 +02:00
Moepchi 234213d33e Move port publishing out of the base compose file into a local override
Committing a fixed port mapping doesn't work across hosts (this one already
had 8080 taken), so ports now belong in a gitignored docker-compose.override.yml.
2026-07-29 20:20:05 +02:00
Moepchi c48534dbc4 Add Docker deployment and fix crash in insecure (non-HTTPS) contexts
Adds a multi-stage Dockerfile (Rust connector + gateway + web build) and
docker-compose.yml for running the whole stack as a single container behind
a reverse proxy; the gateway now serves the built web app and the WebSocket
endpoint (/ws) from one port, and the frontend derives its gateway URL from
window.location in production instead of a hardcoded localhost address.

Also guards all navigator.mediaDevices usage against being undefined, which
happens when the page is loaded over plain HTTP on a non-localhost address
(not a secure context) - previously this crashed the whole React app on
mount instead of just disabling the affected voice features.
2026-07-29 18:45:23 +02:00
Moepchi 3715a52de6 Add Favoriten menu, Away/AFK status, and mic/output mute toggles
Implements the real TS3 client's Favoriten menu (add/manage/list, with a
FavoritesDialog), the toolbar Away/AFK dropdown with saved presets and an
AwayDialog, plus input/output mute toggle buttons on the toolbar. Reorders
the toolbar to AFK -> Mic -> Speaker -> Theme and removes the standalone
Connect button in favor of the Verbindungen menu.
2026-07-29 17:24:56 +02:00
Moepchi 53e2887e14 Add Verbindungen menu, TS3-style Connect dialog, and layout restructure
- Replace inline toolbar connect fields with a modal Connect dialog matching
  the real TS3 client's layout, including a functional Standard Channel field
  wired through a new connector --default-channel flag
- Add a Verbindungen dropdown menu (Verbinden/Aktuelle Verbindung trennen/
  Alle Verbindungen trennen) with click-outside/Escape close and Ctrl+S/Ctrl+D
  shortcuts
- Restructure layout: chat area (messages/tabs/input) now spans the full
  width at the bottom; right side shows a separate, non-scrollable server
  banner (object-fit scaled, shown only when set) above the client/server
  info panel; tree width and upper-area height are now drag-resizable
- Surface server version, license, and banner URL from tsclientlib through
  the connector and gateway
2026-07-29 16:38:40 +02:00
105 changed files with 47050 additions and 668 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
**/node_modules
**/dist
**/target
tsclientlib/.git
.git
*.log
.env
.env.local
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: moepchi
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+85
View File
@@ -0,0 +1,85 @@
name: Bug Report
description: Something isn't working as expected
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug! Please fill in as much detail as you can.
- type: textarea
id: description
attributes:
label: What happened?
description: A clear description of the bug.
placeholder: e.g. The Connect dialog closes unexpectedly when I select text inside it.
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: How can we reproduce this?
placeholder: |
1. Open the Connect dialog
2. Click and drag to select the server address text
3. Release the mouse outside the dialog
4. Dialog closes unexpectedly
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
description: What did you expect to happen instead?
validations:
required: false
- type: dropdown
id: browser
attributes:
label: Browser
options:
- Chrome / Chromium
- Firefox
- Safari
- Edge
- Other (mention in description)
validations:
required: true
- type: input
id: deployment
attributes:
label: Deployment method
description: How are you running WebSpeak3?
placeholder: e.g. Docker Hub image moepchi/webspeak3:latest, built from source, docker-compose
validations:
required: true
- type: input
id: version
attributes:
label: Version / commit
description: Docker tag, commit hash, or release version if known
validations:
required: false
- type: textarea
id: logs
attributes:
label: Relevant logs / console output
description: Browser console errors, gateway logs, or connector output, if any.
render: shell
validations:
required: false
- type: textarea
id: additional
attributes:
label: Additional context
description: Screenshots, TeamSpeak server version, anything else relevant.
validations:
required: false
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Question / Discussion
url: https://github.com/WebSpeak3/webspeak3/discussions
about: Ask a question or discuss an idea before filing an issue.
@@ -0,0 +1,42 @@
name: Feature Request
description: Suggest an idea or improvement for WebSpeak3
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Thanks for the suggestion! Note that some native TeamSpeak 3 client features (myTeamSpeak integration,
badges, plugins) are intentionally out of scope — see the README for details.
- type: textarea
id: problem
attributes:
label: What problem does this solve?
description: Is this related to something that's currently missing or annoying?
placeholder: e.g. I can't send a targeted whisper to specific clients like in the native client.
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed solution
description: What would you like to see happen?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Any workarounds or alternative approaches you've thought of?
validations:
required: false
- type: textarea
id: additional
attributes:
label: Additional context
description: Screenshots of the native client, links, or other context that helps explain the request.
validations:
required: false
+133
View File
@@ -0,0 +1,133 @@
"""Post a short release announcement to Bluesky.
Reads the release (tag, url, body) as JSON from stdin, e.g. from
`gh release view <tag> --json tagName,url,body`. The post is the first
paragraph of the release notes plus the link and a preview card. Notes containing
<!-- no-social --> are skipped. DRY_RUN=true logs in (if credentials are set)
and prints the post without publishing it.
"""
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
BLUESKY_LIMIT = 300
def build_post(release: dict) -> str | None:
body = release.get("body") or ""
if "<!-- no-social -->" in body:
return None
summary = body.strip().split("\n\n")[0].strip()
if summary.startswith("#"):
summary = ""
summary = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", summary)
summary = " ".join(re.sub(r"[`*_]", "", summary).split())
head = f"WebSpeak3 {release['tagName']}"
tail = f"\n\n{release['url']}"
room = BLUESKY_LIMIT - len(head) - len(tail) - 2
if len(summary) > room:
# Prefer dropping whole sentences over cutting one off mid-word.
cut = summary[:room].rfind(". ")
summary = summary[: cut + 1] if cut > 0 else summary[: room - 1].rstrip() + "…"
return f"{head}: {summary}{tail}" if summary else head + tail
def xrpc(method: str, payload: dict | bytes, token: str | None = None, content_type: str = "application/json") -> dict:
req = urllib.request.Request(
f"https://bsky.social/xrpc/{method}",
data=payload if isinstance(payload, bytes) else json.dumps(payload).encode(),
headers={"Content-Type": content_type, **({"Authorization": f"Bearer {token}"} if token else {})},
)
with urllib.request.urlopen(req, timeout=30) as res:
return json.load(res)
def fetch(url: str, attempt: int = 1) -> tuple[bytes, str]:
req = urllib.request.Request(url, headers={"User-Agent": "webspeak3-release-announcer"})
try:
with urllib.request.urlopen(req, timeout=30) as res:
return res.read(), res.headers.get_content_type()
except urllib.error.HTTPError as err:
# GitHub's image service throttles right after a release, often for over a minute.
# 15+30+45+60 s stays well inside the job's 5-minute timeout.
if err.code != 429 or attempt > 4:
raise
wait = 15 * attempt
retry_after = err.headers.get("Retry-After", "")
if retry_after.isdigit():
wait = min(int(retry_after), 60)
print(f"Preview image throttled (429), retrying in {wait} s.")
time.sleep(wait)
return fetch(url, attempt + 1)
def link_card(release: dict, text: str) -> dict:
"""The preview card the Bluesky app would show for a pasted link. The API doesn't build one itself.
The image is GitHub's own social preview for the release page. Its URL takes any cache-busting
segment, so we don't have to scrape the release page (GitHub rate-limits that)."""
url = release["url"]
card = {"uri": url, "title": f"WebSpeak3 {release['tagName']}",
"description": text.split("\n\n")[0].split(": ", 1)[-1]}
path = url.removeprefix("https://github.com/")
image, mime = fetch(f"https://opengraph.githubassets.com/{release['tagName']}/{path}")
if len(image) <= 1_000_000: # Bluesky's blob limit for thumbnails
card["image"] = (image, mime)
return card
def main() -> None:
release = json.load(sys.stdin)
text = build_post(release)
if text is None:
print("Release notes contain <!-- no-social -->, skipping.")
return
print(text)
url = release["url"]
try:
card = link_card(release, text)
print(f"Link card: {card['title']} (image: {len(card['image'][0]) if 'image' in card else 'none'} bytes)")
except Exception as err: # a missing preview shouldn't cost us the post
print(f"No link card: {err}")
card = None
dry_run = os.environ.get("DRY_RUN") == "true"
handle, password = os.environ.get("BLUESKY_HANDLE"), os.environ.get("BLUESKY_APP_PASSWORD")
if not password:
sys.exit(0 if dry_run else "BLUESKY_APP_PASSWORD is not set.")
session = xrpc("com.atproto.server.createSession", {"identifier": handle, "password": password})
print(f"Logged in as {session['handle']}.")
if dry_run:
print("Dry run, not posting.")
return
# Bluesky doesn't auto-link URLs in API posts; the link needs a facet with UTF-8 byte offsets.
start = len(text[: text.rindex(url)].encode())
record = {
"$type": "app.bsky.feed.post",
"text": text,
"langs": ["en"],
"createdAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"facets": [{
"index": {"byteStart": start, "byteEnd": start + len(url.encode())},
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}],
}],
}
if card:
external = {"uri": card["uri"], "title": card["title"], "description": card["description"]}
if "image" in card:
image, mime = card["image"]
external["thumb"] = xrpc("com.atproto.repo.uploadBlob", image, session["accessJwt"], mime)["blob"]
record["embed"] = {"$type": "app.bsky.embed.external", "external": external}
post = xrpc("com.atproto.repo.createRecord",
{"repo": session["did"], "collection": "app.bsky.feed.post", "record": record},
session["accessJwt"])
print(f"Posted: {post['uri']}")
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
name: Announce release
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: Release tag to announce
required: true
dry_run:
description: Only log in and print the post, don't publish it
type: boolean
default: true
permissions:
contents: read
jobs:
bluesky:
name: Post to Bluesky
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Check out repository
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- name: Post release
# Tag passed via env, never spliced into the script (user-controlled text).
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || inputs.tag }}
DRY_RUN: ${{ inputs.dry_run && 'true' || 'false' }}
BLUESKY_HANDLE: moepchi.bsky.social
BLUESKY_APP_PASSWORD: ${{ secrets.BLUESKY_APP_PASSWORD }}
run: |
gh release view "$TAG" -R "$GITHUB_REPOSITORY" --json tagName,url,body \
| python3 .github/scripts/announce-release.py
+62
View File
@@ -0,0 +1,62 @@
name: Build and publish Docker image
on:
release:
types: [published]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: docker-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
build-and-push:
name: Build and push moepchi/webspeak3
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Check out repository
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Log in to Docker Hub
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Determine image tags
id: tags
# Passed via env, never spliced into the script: a tag name is
# user-controlled text and would otherwise run as shell code.
env:
EVENT_NAME: ${{ github.event_name }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
run: |
TAGS="moepchi/webspeak3:latest"
if [ "$EVENT_NAME" = "release" ]; then
TAGS="$TAGS,moepchi/webspeak3:$RELEASE_TAG"
fi
echo "tags=$TAGS" >> "$GITHUB_OUTPUT"
- name: Build and push
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: true
tags: ${{ steps.tags.outputs.tags }}
build-args: WEBSPEAK3_VERSION=${{ github.event.release.tag_name || 'latest' }}
platforms: linux/amd64,linux/arm64
cache-from: type=gha
cache-to: type=gha,mode=max
+75
View File
@@ -0,0 +1,75 @@
name: Safari WebSpeak3 client check
on:
workflow_dispatch:
push:
branches: [main]
paths:
- "web/src/**"
- "web/index.html"
- "web/public/**"
- ".github/workflows/safari-check.yml"
- "tests/safari_smoke.py"
schedule:
- cron: "17 5 * * 1"
permissions:
contents: read
concurrency:
group: safari-client-${{ github.ref }}
cancel-in-progress: true
jobs:
safari:
name: Safari on macOS
runs-on: macos-15
timeout-minutes: 15
steps:
- name: Check out repository
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- name: Set up Node.js
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
with:
node-version: 22
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install and build WebSpeak3 client
working-directory: web
run: |
npm ci
npm run build
- name: Start local preview
working-directory: web
run: |
npm run preview -- --host 127.0.0.1 --port 4173 > /tmp/webspeak3-preview.log 2>&1 &
for attempt in {1..30}; do
curl --fail --silent http://127.0.0.1:4173/ > /dev/null && exit 0
sleep 1
done
cat /tmp/webspeak3-preview.log
exit 1
- name: Prepare Safari automation
run: |
sudo safaridriver --enable
python3 -m venv .venv-safari
.venv-safari/bin/python -m pip install selenium
- name: Test WebSpeak3 client in Safari
env:
BASE_URL: http://127.0.0.1:4173/
run: .venv-safari/bin/python tests/safari_smoke.py
- name: Upload Safari screenshots
if: always()
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5
with:
name: safari-client-screenshots
path: test-results/safari-client-*.png
if-no-files-found: ignore
retention-days: 14
+10
View File
@@ -6,3 +6,13 @@ dist-ssr/
.env
.env.local
.DS_Store
docker-compose.override.yml
.claude/
CLAUDE.md
.serena/
# TLS material for local HTTPS - a private key never belongs in the repo.
gateway/certs/
# Prebuilt WASM assets synced from node_modules by scripts/sync-aec3-assets.mjs
web/public/vendor/
+2 -1
View File
@@ -1,3 +1,4 @@
[submodule "tsclientlib"]
path = tsclientlib
url = https://github.com/ReSpeak/tsclientlib.git
url = https://github.com/Moepchi/tsclientlib.git
branch = webspeak3
+110
View File
@@ -0,0 +1,110 @@
# --- Rust connector -----------------------------------------------------
# Cross-compiled on the build machine for the target platform via xx, so an
# arm64 image doesn't have to run rustc under QEMU. xx is copied into the
# builder's root, hence pinned by digest rather than a movable tag.
FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.9.0@sha256:c64defb9ed5a91eacb37f96ccc3d4cd72521c4bd18d5442905b95e2226b0e707 AS xx
FROM --platform=$BUILDPLATFORM rust:1-bookworm AS connector-builder
COPY --from=xx / /
ARG TARGETPLATFORM
RUN apt-get update && apt-get install -y --no-install-recommends cmake clang libclang-dev && rm -rf /var/lib/apt/lists/*
RUN xx-apt-get update && xx-apt-get install -y libc6-dev gcc g++ && rm -rf /var/lib/apt/lists/*
RUN rustup target add $(xx-cargo --print-target-triple)
WORKDIR /src
COPY tsclientlib/ tsclientlib/
COPY connector/ connector/
WORKDIR /src/connector
ENV CMAKE_POLICY_VERSION_MINIMUM=3.5
RUN xx-cargo build --release
# --- Web frontend ---------------------------------------------------------
# The bundle is plain JS/CSS, identical for every target platform - build it
# natively on the build machine instead of under emulation.
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS web-builder
WORKDIR /src/web
COPY web/package*.json ./
RUN npm ci
# Vite 8 pulls in Rolldown, which ships its bundler as a platform-specific
# optional dependency (@rolldown/binding-linux-<arch>-gnu, <arch> being
# Node's process.arch). `npm ci` intermittently fails to install it due to a
# long-standing npm bug
# (https://github.com/npm/cli/issues/4828) without raising a non-zero exit
# code, so `vite build` only fails later with a confusing MODULE_NOT_FOUND.
# Verify the binding actually loaded and self-heal via the workaround from
# npm's own error message before wasting a full build on a broken install.
RUN node -e "require('@rolldown/binding-linux-' + process.arch + '-gnu')" \
|| (rm -rf node_modules package-lock.json && npm install)
COPY web/ ./
# The UI carries a small Ko-fi donation button (see web/src/App.tsx).
# `--build-arg DONATE_URL=` (empty) drops it, any other value points it
# elsewhere; left alone, the project default is used. The "keep" sentinel
# exists because an unset build arg and an empty one are indistinguishable
# inside RUN - without it, "not passed" would silently mean "remove".
ARG DONATE_URL=keep
# A self-hosted build can bake in a server to auto-connect to with zero user
# input (see web/src/App.tsx's AUTO_CONNECT_FROM_URL/DEFAULT_SERVER, GitHub
# issue #10). Unlike DONATE_URL, unset already means "no default" - no "keep"
# sentinel needed.
ARG DEFAULT_SERVER=
ARG DEFAULT_CHANNEL=
# Design Store catalog to use - unset means "use the maintainer's shared
# one" (App.tsx's own default), same unset-means-no-override convention as
# DEFAULT_SERVER above.
ARG STORE_URL=
# tsc -b currently fails on pre-existing type errors unrelated to this build;
# vite build alone is enough to produce the production bundle.
RUN if [ "$DONATE_URL" = "keep" ]; then DONATE_URL_ENV=; else DONATE_URL_ENV="VITE_DONATE_URL=$DONATE_URL"; fi; \
env $DONATE_URL_ENV VITE_DEFAULT_SERVER="$DEFAULT_SERVER" VITE_DEFAULT_CHANNEL="$DEFAULT_CHANNEL" VITE_STORE_URL="$STORE_URL" npx vite build
# --- Gateway ----------------------------------------------------------------
# tsc output is platform-independent too; only the runtime stage below
# installs the (pure-JS) production deps for the target platform.
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS gateway-builder
WORKDIR /src/gateway
COPY gateway/package*.json ./
RUN npm ci
COPY gateway/ ./
RUN npm run build
# --- Runtime ----------------------------------------------------------------
FROM node:22-bookworm-slim AS runtime
LABEL org.opencontainers.image.title="WebSpeak3"
LABEL org.opencontainers.image.description="Self-hosted web client for TeamSpeak 3 servers"
WORKDIR /app
# ts-connector (Rust, native-tls) needs the OS CA bundle for its HTTPS calls
# (e.g. TeamSpeak nickname lookup) - Node bundles its own certs and works
# without this, but native-tls doesn't, so it's not optional here.
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY gateway/package*.json ./
# npm/npx are only needed to install the gateway's runtime deps; the
# container never runs either afterwards, so strip them (plus npm's own
# cache/package tree) to shrink the image and drop npm's own CVEs from the
# final attack surface. This does mean `docker exec ... npm ...` won't work
# for ad-hoc debugging in a running container anymore.
RUN npm ci --omit=dev \
&& npm cache clean --force \
&& rm -rf /root/.npm /usr/local/lib/node_modules/npm \
&& rm -f /usr/local/bin/npm /usr/local/bin/npx
COPY --from=gateway-builder /src/gateway/dist ./dist
COPY --from=connector-builder /src/connector/target/*/release/ts-connector /app/connector-bin/ts-connector
COPY --from=web-builder /src/web/dist /app/web/dist
ENV PORT=8080
# Release tag, set by .github/workflows/docker-publish.yml. Only used for the
# anonymous usage ping (gateway/src/telemetry.ts).
ARG WEBSPEAK3_VERSION=unknown
ENV WEBSPEAK3_VERSION=$WEBSPEAK3_VERSION
ENV WEB_DIST=/app/web/dist
ENV CONNECTOR_BIN=/app/connector-bin/ts-connector
EXPOSE 8080
# Run unprivileged. /app itself is the default spot for feedback.log and
# store-themes.json, so it has to be writable by that user; a volume mounted
# there from an older (root) image may need a one-off `chown 1000:1000`.
RUN chown node:node /app
USER node
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:8080/healthz').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"]
CMD ["node", "dist/index.js"]
-87
View File
@@ -1,87 +0,0 @@
# Installation
## Prerequisites
- **Node.js** 20+ and npm
- **Rust** (stable toolchain) — [rustup.rs](https://rustup.rs)
- **CMake** and a C/C++ toolchain — needed to build the Opus codec library
(`audiopus_sys`) used for voice. On Windows, the Visual Studio "Desktop
development with C++" workload covers this; on Linux, install `cmake` and
`build-essential` (or equivalent); on macOS, `cmake` via Homebrew plus Xcode
command line tools.
- **git**
## 1. Clone the repository
The Rust connector depends on the `tsclientlib` crate, vendored as a git
submodule — make sure to pull it in too:
```bash
git clone --recurse-submodules <your-repo-url>
cd ts-web-client
```
If you already cloned without `--recurse-submodules`:
```bash
git submodule update --init --recursive
```
## 2. Build the Rust connector
```bash
cd connector
cargo build
```
> **Note:** if the build fails with a CMake error like `Compatibility with
> CMake < 3.5 has been removed`, it's because the vendored Opus source uses an
> old `cmake_minimum_required`. Work around it with:
>
> ```bash
> CMAKE_POLICY_VERSION_MINIMUM=3.5 cargo build
> ```
> (On Windows PowerShell: `$env:CMAKE_POLICY_VERSION_MINIMUM = "3.5"; cargo build`)
This produces `connector/target/debug/ts-connector` (or `ts-connector.exe` on
Windows), which the gateway spawns automatically — no manual step needed
after this.
## 3. Install and start the gateway
```bash
cd gateway
npm install
npm run dev
```
This starts the WebSocket gateway on `ws://localhost:8080`.
## 4. Install and start the web frontend
In a separate terminal:
```bash
cd web
npm install
npm run dev
```
Vite will print a local dev URL (typically `http://localhost:5173`) — open
it in a browser.
## 5. Connect
In the web UI, enter the address of a TeamSpeak server and a nickname, then
click **Connect**. Voice requires microphone permission when you enable the
mic button; the output-device picker (if your browser supports it) requires
no extra permission.
## Rebuilding after changes
- Frontend and gateway changes hot-reload automatically (`npm run dev` in
both cases).
- Connector changes require a rebuild (`cargo build` in `connector/`) and a
reconnect from the browser — if the old `ts-connector` binary is still
running (an active browser connection), disconnect first or the build will
fail to overwrite the binary.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Moepchi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+415 -28
View File
@@ -1,29 +1,124 @@
# TS Web Client
<p align="center">
<img src="web/public/logo.png" width="140" alt="WebSpeak3 logo">
</p>
Browser-based client for TeamSpeak servers — same idea as the native
installable client, but running in a web browser. The TeamSpeak server side
stays exactly as-is (a regular TS server); only the client is being
reimagined.
<h1 align="center">WebSpeak3</h1>
**Status: private prototype, not for production use.**
<p align="center">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License"></a>
<a href="Dockerfile"><img src="https://img.shields.io/badge/docker-build%20passing-2496ED?logo=docker&logoColor=white" alt="Docker Build"></a>
<a href="gateway/package.json"><img src="https://img.shields.io/badge/node-%3E%3D18-339933?logo=node.js&logoColor=white" alt="Node Version"></a>
<a href="connector/Cargo.toml"><img src="https://img.shields.io/badge/rust-2021-000000?logo=rust&logoColor=white" alt="Rust Version"></a>
<a href="https://github.com/WebSpeak3/webspeak3/releases"><img src="https://img.shields.io/github/v/release/WebSpeak3/webspeak3?include_prereleases&label=release" alt="Latest Release"></a>
<img src="https://img.shields.io/badge/status-public%20beta-f0b429" alt="Project Status">
</p>
## Features
<p align="center">
<b>A modern, self-hosted browser client for TeamSpeak, TeaSpeak, and VoySpeak servers — no install, just open a tab.</b>
</p>
- Connect to a real TeamSpeak (3/6) server, with optional server and
default-channel passwords
- Remembers the last server/nickname you connected with
- Channel/client tree with correct ordering, click to switch channels
- Per-client status icons (channel commander, away, mic muted, deafened)
- Text chat: channel, server-wide, and private (1:1) — each in its own tab
- Voice with voice activation ("Sprachaktivierung", not push-to-talk),
adjustable sensitivity, and per-client speaking indicators
- Audio output device picker (routes playback to a chosen device) — works in
Chrome/Edge and Firefox 130+; playback is routed through a hidden `<audio>`
element so device switching works even in browsers without
`AudioContext.setSinkId`
- Light/dark theme
<p align="center">
<a href="https://webspeak3.de">🌐 Website</a> ·
<a href="https://client.webspeak3.de">💬 Open Client</a> ·
<a href="https://demo.webspeak3.de">🕹️ Live Demo</a> ·
<a href="#-quick-start">🚀 Quick Start</a> ·
<a href="#-installation">📖 Installation</a> ·
<a href="ROADMAP.md">🗺️ Roadmap</a> ·
<a href="https://github.com/WebSpeak3/webspeak3/issues">🐛 Report Bug</a>
</p>
## Architecture
> The [live demo](https://demo.webspeak3.de) runs entirely in your browser with simulated data — no real TeamSpeak server involved. It's there to show the UI, not the real connection.
---
## 📑 Contents
- [Preview](#-preview)
- [Quick Start](#-quick-start)
- [Features](#-features)
- [Tech Stack](#-tech-stack)
- [Browser Support](#-browser-support)
- [Installation](#-installation)
- [Docker (recommended)](#-docker-recommended)
- [Account sync](#account-sync)
- [Environment variables](#environment-variables)
- [Auto-Connect Links](#-auto-connect-links)
- [Translating](#translating)
- [Credits](#credits)
- [In Memory of Akimo](#-in-memory-of-akimo)
- [Legal / Disclaimer](#legal--disclaimer)
## 📸 Preview
<table>
<tr>
<th>Desktop</th>
<th>Mobile</th>
</tr>
<tr>
<td width="72%"><img src="docs/screenshots/webspeak_desktop.png" width="100%" alt="WebSpeak3 desktop client connected to a TeamSpeak server"></td>
<td width="28%" align="center"><img src="docs/screenshots/webspeak_mobile_phone.png" width="260" alt="WebSpeak3 mobile client connected to a TeamSpeak server"></td>
</tr>
</table>
## 🚀 Quick Start
Run the ready-made container and open **http://localhost:8080**:
```bash
docker run -d --name webspeak3 --restart unless-stopped -p 8080:8080 moepchi/webspeak3:latest
```
Enter the address and port of **any reachable TeamSpeak 3, TeamSpeak 6,
TeaSpeak, or VoySpeak server** in the connection dialog. The server does
not need to be installed on the same machine, modified, or operated by you.
> Voice requires a secure context. Microphone access works on `localhost`; for
> access from other devices, place WebSpeak3 behind an HTTPS reverse proxy.
## ✨ Features
| | |
|---|---|
| 🔌 **Real TeamSpeak protocol** | Connects to actual TS3/TS6, TeaSpeak, and VoySpeak servers over a WebSocket gateway — the server stays exactly as-is |
| 🎙️ **Low-latency voice** | Opus-encoded voice with voice activation ("Sprachaktivierung") and adjustable sensitivity |
| 🤫 **Whisper** | Target your voice at specific channels or clients instead of your whole current channel |
| 🔊 **Custom audio output picker** | Route playback to any output device — works even in browsers without `AudioContext.setSinkId` |
| 💬 **Full text chat** | Channel, server-wide, and private (1:1) chat, each in its own tab — Shift+Enter for a newline |
| 🌳 **Live channel/client tree** | Correct ordering, status icons (channel commander, away, muted, deafened), country flags, click to switch channels |
| 🖱️ **Right-click context menu** | Private chat, poke, copy name, whisper-target toggle, and a per-person volume slider straight from a client's row |
| 🔎 **Tree search** | Filter channels and users by name; matches stay in place with their parent channels |
| 🖼️ **Avatars** | Shows the TeamSpeak avatars people have set, in the tree, the speaking bar, and the info panel |
| 📜 **Server log** | Join/leave/switch, channel-group, and channel/server-change events shown inline, like the native client |
| 🔔 **Custom sound notifications** | Per-event sounds (connect, poke, messages, ...) with volume control and `.ts3soundpack` import |
| 🪪 **Persistent identity** | Keeps the same client UID across sessions instead of generating a new one every connect |
| 👉 **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 |
| 📱 **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 |
| 🌗 **Dark / light theme** | Clean, modern UI that adapts to your preference |
| 🔁 **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 |
| ⌨️ **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 |
| 📟 **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) |
## 🧱 Tech Stack
<p>
<img src="https://img.shields.io/badge/React-61DAFB?logo=react&logoColor=black" alt="React">
<img src="https://img.shields.io/badge/Vite-646CFF?logo=vite&logoColor=white" alt="Vite">
<img src="https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white" alt="TypeScript">
<img src="https://img.shields.io/badge/Node.js-339933?logo=node.js&logoColor=white" alt="Node.js">
<img src="https://img.shields.io/badge/Rust-000000?logo=rust&logoColor=white" alt="Rust">
<img src="https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white" alt="Docker">
</p>
<details>
<summary><b>🏗️ Architecture details</b></summary>
<br>
Browsers can't send raw UDP, which is what TeamSpeak's native protocol runs
over, so a pure client-side implementation isn't possible — a server-side
@@ -31,23 +126,315 @@ gateway is required that speaks the real TS protocol on one side and
WebSocket to the browser on the other.
```
Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Rust connector (connector/) <--TS3/TS6 protocol--> TeamSpeak Server
Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Rust connector (connector/) <--TS3/TS6/TeaSpeak/VoySpeak protocol--> Server
```
- **`web/`** — Vite + React frontend. TS3-lookalike UI: channel tree, chat
tabs, voice controls.
- **`gateway/`** — Node.js/TypeScript WebSocket server. Spawns the Rust
connector per browser connection and relays newline-delimited JSON events
between it and the browser.
connector **per browser WebSocket** and relays newline-delimited JSON events
between it and the browser. Multi-join opens one `/ws` connection per server
tab (parallel connectors).
- **`connector/`** — Rust binary wrapping [`tsclientlib`](https://github.com/ReSpeak/tsclientlib)
(vendored as a git submodule in `tsclientlib/`), the actual TS3/TS6
(vendored as a git submodule in `tsclientlib/`, currently tracking a fork
with TeaSpeak/VoySpeak protocol support), the actual TS3/TS6/TeaSpeak
protocol implementation. Handles connecting, channel/client state, chat,
and Opus-encoded voice.
and Opus-encoded voice. Auto-detects the server dialect on connect (or it
can be forced via `--server-type`).
## Installation
</details>
See [INSTALL.md](INSTALL.md).
## 🌐 Browser Support
| Browser | Status | Notes |
|---|---|---|
| Chrome / Edge / Chromium | ✅ Primary target | Recommended for the most complete audio and device support |
| Firefox | ✅ Supported | Core client and voice functionality are supported |
| Safari | 🧪 Experimental | Audio and microphone behavior still needs broader real-device testing |
| Mobile Chromium | ✅ Supported | Responsive client with microphone support over HTTPS |
| Mobile Safari | 🧪 Experimental | UI is responsive; audio behavior remains under active validation |
WebSpeak3 is a public beta. See the [beta roadmap](ROADMAP.md) for the current
scope, known limitations, and the next milestones.
## 🚀 Installation
### 🐳 Docker (recommended)
Clone the repo (the Rust connector depends on a git submodule, so pull it in too):
```bash
git clone --recurse-submodules https://github.com/WebSpeak3/webspeak3.git
cd webspeak3
```
This is what ships in [`docker-compose.yml`](docker-compose.yml):
```yaml
services:
webspeak3:
build: .
image: moepchi/webspeak3:latest
container_name: webspeak3
restart: unless-stopped
environment:
- PORT=8080
```
Port publishing is left out on purpose — set it in a local, gitignored `docker-compose.override.yml` so it doesn't clash with whatever else is already using a port on your host:
```yaml
services:
webspeak3:
ports:
- "8080:8080"
```
Then `docker compose up -d` and open `http://localhost:8080` (or whatever host port you chose).
Prefer to skip the build entirely? A prebuilt image for `linux/amd64` and `linux/arm64` (e.g. a Raspberry Pi 4/5 on a 64-bit OS) is published on [Docker Hub](https://hub.docker.com/r/moepchi/webspeak3):
```bash
docker run -d -p 8080:8080 --name webspeak3 moepchi/webspeak3:latest
```
The UI shows a small **Ko-fi donation button** in the bottom right corner. Building it yourself and would rather not carry someone else's donation link? `docker compose build --build-arg DONATE_URL=` removes it (any other value points it somewhere else). Outside Docker the same thing is a build-time variable: `VITE_DONATE_URL= npm run build` in `web/`.
The **Design Store** (browse/upload community themes) points at the maintainer's shared catalog by default, same as the official client — no setup needed. Want to run your own store instead, backed by your own gateway (`STORE_ENABLED=1`, see below)? `docker compose build --build-arg STORE_URL=https://your-gateway.example.com/api/store/themes`. Outside Docker: `VITE_STORE_URL=https://your-gateway.example.com/api/store/themes npm run build` in `web/`.
#### Account sync
Options → Account lets people carry identities, favorites, settings, designs and whisper lists to their other devices. Like Mullvad, an account is just a random 16-digit number, optionally with a random password: no email, no name. Everything is encrypted in the browser (PBKDF2 → AES-GCM) before upload, so the sync server only ever stores unreadable blobs; it keeps no IP addresses and deletes accounts nobody opened for a year.
By default every client uses the official sync server. To run your own, start the same image with a different command and point your gateway at it:
```yaml
webspeak3-sync:
image: moepchi/webspeak3:latest
command: ["node", "dist/sync-server.js"]
environment:
- SYNC_DATA_DIR=/app/sync-data
- TRUST_PROXY=cloudflare
volumes:
- ./sync-data:/app/sync-data # owned by uid 1000 (the image runs as "node")
```
Route `/api/sync/*` to it in your proxy/tunnel and set `SYNC_URL=https://your-host/api/sync` on the gateway. Accounts only exist on the server they were created on. Optional: `SYNC_POW_BITS` (proof-of-work difficulty for new accounts, default `15`), `SYNC_MAX_ACCOUNTS` (default `100000`), `SYNC_ALLOWED_ORIGIN` (CORS, default `*`).
#### Environment variables
All optional; add them under `environment:` in your compose override next to `PORT`. These are the common ones - the full list (logging, feedback form, Design Store details, build-time variables) is on the wiki's [Configuration & Environment Variables](https://github.com/WebSpeak3/webspeak3/wiki/Configuration-and-Environment-Variables) page.
| Variable | Default | Purpose |
|---|---|---|
| `PORT` | `8080` | Port the gateway listens on. |
| `WEB_STATIC` | on | Set to `0` to disable serving the built UI (`web/dist`) entirely — the gateway then only answers `/ws`, `/api/feedback` and `/healthz`. Use this when the UI is hosted elsewhere (e.g. a CDN/static host) and the gateway is purely a backend. |
| `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). |
| `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. |
| `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_ALLOWED_ORIGIN` | `*` | CORS origin allowed to call the store endpoint, if you want to restrict it to your own frontend's origin. |
| `STORE_ADMIN_TOKEN` | unset | Bearer token for moderation. New submissions wait as "pending" until approved on the review page at `/api/store/admin` (enter the token there); the token holder's own submissions and the reserved author name(s) skip the queue. Without it, nothing ever gets published. Submitted CSS is also checked server-side: no `@import`/`@font-face`, no external `url()` — only inline `data:` images. |
| `ALLOWED_SERVERS` | unset (any server) | Comma-separated list of server addresses this gateway is allowed to connect to (e.g. `ts.example.com,*.example.net`). A port is matched separately from the host, so listing `ts.example.com` allows any port on it. An entry starting with `*.` matches any subdomain (`*.example.com` allows `ts.example.com`, not `example.com` itself - list that separately too if it should also be reachable). Locks a self-hosted instance down to specific server(s) instead of acting as a general "connect anywhere" client; a rejected `connect` gets an error back before any connector process is even spawned. An entry may carry a port (`ts.example.com:9988`): it still allows every port, but that's the address the connect dialog offers (see `SERVER_PICKER`). |
| `SERVER_PICKER` | on | With `ALLOWED_SERVERS` set (and no `*.` entries in it), the connect dialog's address field becomes a dropdown of those servers, or a locked field if there's only one. Set to `0` for the plain text field instead. Only works when the gateway serves the web client itself (the Docker image does). |
| `ALLOW_PRIVATE_TARGETS` | off | By default the gateway refuses to connect to private/internal addresses (loopback, `10.x`, `192.168.x`, CGNAT, link-local, …), no matter how they were reached (IP, DNS, SRV, TSDNS, nickname, file-transfer redirect), so it can't be abused to probe the network it runs in. **If your TeamSpeak server is on the same LAN as the gateway, set this to `1`.** |
| `TURN_URLS` | unset | Comma-separated TURN URLs (e.g. `turn:turn.example.com:3478`) offered to browsers for screen streams, for viewers or publishers behind NATs where direct P2P fails. Pair with `TURN_SECRET` (coturn's `use-auth-secret`; each browser gets its own credential valid for 24 h) or with static `TURN_USERNAME` / `TURN_CREDENTIAL`, which every visitor can read. |
| `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. |
| `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. |
| `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. |
| `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). |
| `NEWS_TICKER` | on | Set to `0` to hide the news ticker at the bottom of the client. |
| `NEWS_TICKER_CENTRAL` | on | Set to `0` to drop the official WebSpeak3 news (releases, new store designs, announcements) and only show your own messages. |
| `NEWS_TICKER_MESSAGES` | – | Your own ticker messages, separated by `\|`, e.g. `Maintenance tonight at 10pm \| Welcome!` |
| `ENABLE_TS2` | off | Set to `1` to offer **TeamSpeak 2** as a server type in the connect dialog. Experimental: voice (Speex), channel list, private messages and server messages work; channel chat depends on the server's permissions; file transfer, avatars, screen streams and admin functions aren't available on TS2. Also lets the server type "Auto" fall back to TS2 when a server gives no TS3 answer, and adds account name and password fields for registered TS2 logins. The code ships in every image, it just stays unused while this is off. |
| `SYNC_URL` | official sync server | Account sync server your visitors use (Options → Account), e.g. `https://sync.example.com/api/sync`. Only needed if you run your own (see below). |
> **Anonymous usage ping:** when the gateway starts and then once a day, it sends a random instance ID (made up on first start, stored in `instance-id` in the working directory, used for nothing else) and its version number to `gateway.webspeak3.de`. That's the only way to tell whether anyone self-hosts WebSpeak3 at all, and how many instances still run an old version, e.g. after a security fix. Nothing else is sent: no hostnames, no TeamSpeak servers, no users, no settings. The receiving side doesn't store IP addresses. The startup log says when it's on. Turn it off with `TELEMETRY=0`.
> **News ticker:** like the native TS3 client, a small scrolling line at the bottom shows news. Your users' browsers load the official news straight from `gateway.webspeak3.de`, the same way the Design Store works. Your own messages come from `NEWS_TICKER_MESSAGES`. Users can hide the ticker with ✕ until something new comes in.
> **Trust model:** the gateway speaks the TeamSpeak protocol on the user's behalf, so whoever runs it necessarily handles their identity key, server/channel passwords and privilege keys (they're kept out of process listings, but the operator can still see them). Only use gateways you trust, and serve them over HTTPS/WSS (`TLS_CERT`/`TLS_KEY` or a TLS-terminating proxy) - plain HTTP exposes all of that on the wire. File uploads are limited to 24 MiB, downloads to 25 MiB.
> **Stored in the browser:** identities (including their private keys), favorites with any passwords you typed into them, and settings live in the browser's `localStorage`, unencrypted by default - the same way the native client keeps them in its settings files. Anyone with access to your browser profile can read them. To encrypt identities and saved passwords, set a master password under Options → Security; it's then asked for once per session (every reload or new tab), and without it that data can't be recovered, so export identities you care about first. Server banners load directly from the host the server admin configured; turn them off under Options → Application if you don't want that host to see your IP.
<details>
<summary><b>🛠️ Manual installation (without Docker)</b></summary>
<br>
**Prerequisites**
- **Node.js** 20+ and npm
- **Rust** (stable toolchain) — [rustup.rs](https://rustup.rs)
- **CMake** and a C/C++ toolchain — needed to build the Opus codec library (`audiopus_sys`) used for voice. On Windows, the Visual Studio "Desktop development with C++" workload covers this; on Linux, install `cmake` and `build-essential` (or equivalent); on macOS, `cmake` via Homebrew plus Xcode command line tools.
- **git**
**1. Clone the repository**
The Rust connector depends on the `tsclientlib` crate, vendored as a git submodule — make sure to pull it in too:
```bash
git clone --recurse-submodules https://github.com/WebSpeak3/webspeak3.git
cd webspeak3
```
If you already cloned without `--recurse-submodules`:
```bash
git submodule update --init --recursive
```
**2. Build the Rust connector**
```bash
cd connector
cargo build
```
> **Note:** if the build fails with a CMake error like `Compatibility with CMake < 3.5 has been removed`, it's because the vendored Opus source uses an old `cmake_minimum_required`. Work around it with:
>
> ```bash
> CMAKE_POLICY_VERSION_MINIMUM=3.5 cargo build
> ```
> (On Windows PowerShell: `$env:CMAKE_POLICY_VERSION_MINIMUM = "3.5"; cargo build`)
This produces `connector/target/debug/ts-connector` (or `ts-connector.exe` on Windows), which the gateway spawns automatically — no manual step needed after this.
**3. Install and start the gateway**
```bash
cd gateway
npm install
npm run dev
```
This starts the WebSocket gateway on `ws://localhost:8080`. Open **http://localhost:8080** for the UI (serves `web/dist`). After UI changes run `cd web && npm run build`, then reload. Optional Vite (`npm run dev` in `web/`, typically `:5173`) is only for HMR. `WEB_STATIC=0 npm run dev` serves API/WebSocket only.
**4. Install and start the web frontend**
In a separate terminal:
```bash
cd web
npm install
npm run dev
```
Vite will print a local dev URL (typically `http://localhost:5173`) — open it in a browser.
The Vite app connects to the gateway at `ws://localhost:8080/ws`.
> **Preferred UI:** **http://localhost:8080** (static `web/dist` — refresh after `cd web && npm run build`). Vite `:5173` is optional HMR only.
**5. Connect**
In the web UI, enter the address of a TeamSpeak server and a nickname, then click **Connect**. Voice requires microphone permission when you enable the mic button; the output-device picker (if your browser supports it) requires no extra permission.
**Rebuilding after changes**
- Frontend and gateway changes hot-reload automatically (`npm run dev` in both cases).
- Connector changes require a rebuild (`cargo build` in `connector/`) and a reconnect from the browser — if the old `ts-connector` binary is still running (an active browser connection), disconnect first or the build will fail to overwrite the binary.
</details>
## 🔗 Auto-Connect Links
Skip the connect dialog entirely and drop visitors straight into a TeamSpeak server. Two ways to do it — use either, or both together.
### 1. Share a link
Add a `connect` parameter to your instance's URL and send that link out — in a Discord post, a landing page button, a QR code, wherever:
```
https://your-instance/?connect=voice.example.com&nickname=Guest&channel=Lobby#token=abc123
```
| Parameter | Required | What it does |
|------------|----------|--------------|
| `connect` | yes | Server address to join, `host` or `host:port` |
| `nickname` | no | Nickname to connect with — omit it and the visitor gets an auto-generated `Guest-XXXX` |
| `channel` | no | Default channel to join |
| `token` | no | Server/channel privilege key, if the target requires one. Put it after `#` (as above) so it never reaches server logs or `Referer` headers; `?token=` still works too |
This works on **any** deployment — no rebuild, no configuration. WebSpeak3 connects as soon as the page loads and immediately strips these parameters from the address bar, so refreshing the tab (or someone screenshotting/forwarding the URL later) won't silently reconnect off a stale link.
### 2. Bake in a default server
Running a dedicated instance for one community or event? Set a default server so **every** visitor auto-connects with zero parameters, no link needed. With the Docker image that's just two environment variables, no rebuild:
```yaml
environment:
- DEFAULT_SERVER=voice.example.com
- DEFAULT_CHANNEL=Lobby
```
The gateway hands them to the UI it serves itself, so this needs `WEB_STATIC` left on. Returning visitors' browsers keep the cached app (including its default) until the next image update, so a later change of these values reaches them only then — new visitors get it right away.
Building it yourself, you can bake the default in instead: `docker compose build --build-arg DEFAULT_SERVER=voice.example.com --build-arg DEFAULT_CHANNEL=Lobby` (the environment variables above win over these if both are set). Outside Docker, the same thing is a build-time variable:
```bash
VITE_DEFAULT_SERVER=voice.example.com VITE_DEFAULT_CHANNEL=Lobby npm run build
```
(in `web/`). Leave `DEFAULT_CHANNEL`/`VITE_DEFAULT_CHANNEL` out to just join the server's default channel.
A share link (above) always takes priority over the baked-in default when both are present — so you can point most visitors at your default server while still sending specific people somewhere else via link.
Either way: on your own hosted instance, the mandatory first-visit Terms of Use is shown and accepted before anything auto-connects; and if the connection fails, the connect dialog opens prefilled so the visitor can fix it and retry by hand.
<a id="translating"></a>
## 🌍 Translating
The UI texts live in flat JSON files in [`web/src/locales/`](web/src/locales/), one per language, with `en.json` as the reference. Untranslated keys fall back to English.
- **Fix or complete a language:** edit its file and open a pull request.
- **Add a new language:** copy `en.json` to `<code>.json` (for example `it.json`), translate the values and open a pull request. Leave the keys and placeholders like `{count}` as they are. I'll wire the language into the selector.
- **No GitHub account?** Send the file via the in-app feedback form or to feedback@webspeak3.de.
## Credits
The vast majority of this project's code was written by [Claude Code](https://claude.com/claude-code) (Anthropic's Claude), working iteratively with the repo owner one feature at a time.
Country flags use the [Twemoji Country Flags](https://github.com/talkjs/country-flag-emoji-polyfill) font, artwork from [Twemoji](https://github.com/twitter/twemoji) under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/).
## 🌈 In Memory of Akimo
<!-- Permanent: never remove this section. -->
<img src="web/src/assets/akimo.jpg" alt="Akimo" width="120" align="left" />
WebSpeak3 is dedicated to Akimo, the project owner's dog, who crossed the rainbow bridge on October 21, 2026. 🐾
<br clear="left" />
## Star History
<a href="https://www.star-history.com/?repos=webspeak3%2Fwebspeak3&type=date&legend=bottom-right">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=webspeak3/webspeak3&type=date&theme=dark&legend=bottom-right" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=webspeak3/webspeak3&type=date&legend=bottom-right" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=webspeak3/webspeak3&type=date&legend=bottom-right" />
</picture>
</a>
---
### Legal / Disclaimer
**WebSpeak3** is an independent, open-source, self-hosted project and is
**not** affiliated with, associated with, authorized by, endorsed by, or in
any way officially connected with TeamSpeak Systems GmbH.
"TeamSpeak", "TS3", and related logos or names are registered trademarks of
TeamSpeak Systems GmbH. Likewise, WebSpeak3 is not affiliated with,
associated with, authorized by, or endorsed by TeaSpeak or VoySpeak (formerly GreenTeaSpeak);
"TeaSpeak" and "VoySpeak" are names of their respective projects/
operators. All product and company names are trademarks™ or registered®
trademarks of their respective holders. Use of them does not imply any
affiliation with or endorsement by them.
+86
View File
@@ -0,0 +1,86 @@
# WebSpeak3 Beta Roadmap
WebSpeak3 is a public beta: it already connects to real TeamSpeak 3 and
TeamSpeak 6 servers, but some browser-specific behavior and less common server
features still need wider testing.
This roadmap is intentionally outcome-focused. It does not promise fixed dates.
## Available today
- Connect to any reachable TS3 or TS6 server through the WebSpeak3 gateway
- Low-latency Opus voice, voice activation, whisper, and audio-device selection
- Live channel/client tree with status updates, search, avatars, and context actions
- Per-person volume, remembered per user across sessions
- Server, channel, and private text chat
- Favorites, identities, contacts, pokes, away state, and reconnect
- File transfers, local session recording, sound packs, and administration tools
- Design Store: browse, upload, rate, and download community-made themes
- Opt-in WASM AEC3 echo cancellation for speaker+mic setups
- Responsive desktop and mobile interfaces in German, English, Simplified Chinese, and Persian (Beta)
- Docker image and Compose-based self-hosting
## Experimental or still being validated
- **Screen streaming to and from TeamSpeak 6 (alpha, unstable).** WebSpeak3 can
publish a screen share that a native TS6 client can watch, and watch a stream
a TS6 client publishes. It speaks TS6's Stream/Call protocol, which TeamSpeak
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
admission are not yet dependable. The "Server" connection mode (TS6's SFU) is
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,
so newer features stay hidden behind an older gateway instead of hanging.
- Safari and Mobile Safari audio/microphone behavior
- Uncommon TeamSpeak permission combinations and large permission sets
- Very large servers and long-running browser sessions
- Mobile browser behavior across a wider range of devices
- Reverse-proxy and hosting configurations beyond the documented examples
## Next milestones
### Beta hardening
- Expand real-browser audio testing, especially Safari
- Improve reconnect and recovery behavior under unstable networks
- Turn recurring deployment and compatibility reports into documentation
### Accessibility
Basics are in place: the UI language sets the document's `lang`/`dir`,
dialogs take focus on open, keep Tab inside, close on Escape, and hand focus
back; toolbar icon and menu bar buttons are real, labelled buttons. The
channel tree is an ARIA tree with one Tab stop: arrow keys walk it (selection
follows focus), Left/Right collapse, expand and jump to parent or child,
Enter joins a channel or opens a private chat, and the context-menu key or
Shift+F10 opens the menu. Menus take focus on open, move with the arrow keys,
and Escape hands focus back to the button that opened them. An axe-core scan
of the connected UI is clean in every built-in design except for landmark
best practices and GreenTeaSpeak's native selection colours. Still to do:
- Do a full screen-reader pass (NVDA/VoiceOver) through a real connect
session to find what else is missing (e.g. announcing who is talking)
### Deployment experience
- Keep the one-command Docker path reliable
- Add clearer HTTPS and reverse-proxy examples
- Document backup and upgrade expectations for persistent browser identities
- Improve release notes and migration guidance when configuration changes
### Toward a stable release
- Define and complete a repeatable browser compatibility checklist
- Resolve confirmed high-impact beta issues
- Stabilize configuration and deployment contracts
- Publish a support matrix based on verified devices and browsers
## Feedback
Please use [GitHub Issues](https://github.com/WebSpeak3/webspeak3/issues) for
reproducible bugs and feature requests. Include the browser and version,
operating system, deployment method, and whether the issue affects voice,
microphone access, or only the interface.
WebSpeak3 is independent and is not affiliated with or endorsed by TeamSpeak
Systems GmbH.
+183 -9
View File
@@ -172,12 +172,41 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bindgen"
version = "0.65.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfdf7b466f9a4903edc73f95d6d2bcd5baf8ae620638762244d3f60143643cc5"
dependencies = [
"bitflags 1.3.2",
"cexpr",
"clang-sys",
"lazy_static",
"lazycell",
"log",
"peeking_take_while",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash 1.1.0",
"shlex 1.3.0",
"syn 2.0.119",
"which",
]
[[package]]
name = "bit-vec"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.13.1"
@@ -223,7 +252,16 @@ dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
"shlex 2.0.1",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
@@ -259,6 +297,17 @@ dependencies = [
"inout",
]
[[package]]
name = "clang-sys"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "clap"
version = "4.6.4"
@@ -623,6 +672,16 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "ff"
version = "0.13.1"
@@ -808,6 +867,12 @@ dependencies = [
"time",
]
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "group"
version = "0.13.0"
@@ -938,6 +1003,15 @@ dependencies = [
"digest 0.10.7",
]
[[package]]
name = "home"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "http"
version = "1.4.2"
@@ -1277,12 +1351,34 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "lazycell"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "litemap"
version = "0.8.2"
@@ -1501,6 +1597,12 @@ dependencies = [
"windows-link",
]
[[package]]
name = "peeking_take_while"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -1585,6 +1687,16 @@ dependencies = [
"num-traits",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "primeorder"
version = "0.13.6"
@@ -1625,7 +1737,7 @@ dependencies = [
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustc-hash 2.1.3",
"rustls",
"socket2",
"thiserror 2.0.19",
@@ -1647,7 +1759,7 @@ dependencies = [
"rand 0.10.2",
"rand_pcg",
"ring",
"rustc-hash",
"rustc-hash 2.1.3",
"rustls",
"rustls-pki-types",
"slab",
@@ -1748,7 +1860,7 @@ version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
"bitflags 2.13.1",
]
[[package]]
@@ -1771,6 +1883,18 @@ dependencies = [
"syn 3.0.3",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.16"
@@ -1856,6 +1980,12 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -1871,6 +2001,19 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags 2.13.1",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
]
[[package]]
name = "rustls"
version = "0.23.42"
@@ -2002,7 +2145,7 @@ version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags",
"bitflags 2.13.1",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
@@ -2114,6 +2257,12 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shlex"
version = "2.0.1"
@@ -2180,6 +2329,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "speex-sys"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4acde4a315153e8586867cb7e974cb289fa9bc9caa0928f9dfac174f969284e0"
dependencies = [
"bindgen",
"cc",
]
[[package]]
name = "spki"
version = "0.7.3"
@@ -2262,7 +2421,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags",
"bitflags 2.13.1",
"core-foundation 0.9.4",
"system-configuration-sys",
]
@@ -2520,7 +2679,7 @@ version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bitflags 2.13.1",
"bytes",
"futures-util",
"http",
@@ -2639,8 +2798,11 @@ dependencies = [
"base64",
"clap",
"futures",
"num-traits",
"serde",
"serde_json",
"speex-sys",
"time",
"tokio",
"tracing-subscriber",
"tsclientlib",
@@ -2708,7 +2870,7 @@ name = "tsproto-packets"
version = "0.1.0"
dependencies = [
"base64",
"bitflags",
"bitflags 2.13.1",
"num-derive",
"num-traits",
"omnom",
@@ -2734,7 +2896,7 @@ name = "tsproto-types"
version = "0.1.0"
dependencies = [
"base64",
"bitflags",
"bitflags 2.13.1",
"curve25519-dalek-ng",
"elliptic-curve",
"generic-array",
@@ -2928,6 +3090,18 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "which"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
dependencies = [
"either",
"home",
"once_cell",
"rustix",
]
[[package]]
name = "widestring"
version = "1.2.1"
+5 -2
View File
@@ -7,11 +7,14 @@ edition = "2021"
tsclientlib = { path = "../tsclientlib/tsclientlib", default-features = false, features = ["default-tls", "audio"] }
tsproto-packets = { path = "../tsclientlib/utils/tsproto-packets" }
audiopus = "0.3.0-rc.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "io-std", "io-util"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "io-std", "io-util", "net"] }
futures = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive", "env"] }
anyhow = "1"
num-traits = "0.2"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
base64 = "0.22"
time = "0.3"
speex-sys = "0.4"
+2904 -53
View File
File diff suppressed because it is too large. Load diff
+990
View File
@@ -0,0 +1,990 @@
//! TeamSpeak 2 client (experimental, `--server-type=ts2`).
//!
//! TS2 is a plain UDP protocol, unrelated to TS3. Layouts come from the
//! Wireshark dissector (`packet-teamspeak2.c`) and the soliloque-server
//! reimplementation, checked against a real 2.0.24.1 server.
//!
//! Packet classes (all little endian):
//! - `0xbef4` connection: class, type, session, client id, counter, CRC @16, payload @20
//! - `0xbef0` reliable: same plus resend count @16, fragment @18, CRC @20, payload @24
//! - `0xbef1` ACK: class, 0, session, client id, acked seq (16 bytes, no CRC)
//! - `0xbef2`/`0xbef3` voice, client -> server / server -> client
//!
//! CRC is zlib CRC32 over the whole packet with the CRC field zeroed.
//! Speaks the same stdout/stdin line protocol as the TS3 path in main.rs.
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::mem::MaybeUninit;
use std::net::SocketAddr;
use std::os::raw::{c_char, c_int, c_void};
use std::time::{Duration, Instant};
use anyhow::{Result, anyhow, bail};
use base64::Engine;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::UdpSocket;
use crate::{Args, ChannelInfo, ClientInfo, Event, emit};
const DEFAULT_PORT: u16 = 8767;
const KEEPALIVE_EVERY: Duration = Duration::from_secs(3);
const RESEND_AFTER: Duration = Duration::from_secs(1);
const MAX_RESENDS: u16 = 10;
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.
const SPEEX_FRAME: usize = 160;
const FRAMES_PER_PACKET: usize = 5;
/// Start playing a speaker once this many 8 kHz samples are queued. Packets
/// carry 100 ms each, so this waits for the second packet - TS2 clients
/// send in bursts and anything less underruns on ordinary jitter.
const PREBUFFER: usize = SPEEX_FRAME * FRAMES_PER_PACKET + 1;
const ST_CHANNEL_COMMANDER: u16 = 1;
const ST_AWAY: u16 = 8;
const ST_MUTE_MIC: u16 = 16;
const ST_MUTE_SPEAKERS: u16 = 32;
const CH_PASSWORD: u8 = 4;
fn crc(pkt: &mut [u8], at: usize) {
pkt[at..at + 4].fill(0);
let h = crc32(pkt);
pkt[at..at + 4].copy_from_slice(&h.to_le_bytes());
}
/// zlib's CRC32 (IEEE, reflected). Small enough that a dependency isn't worth it.
fn crc32(data: &[u8]) -> u32 {
let mut c = !0u32;
for &b in data {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 };
}
}
!c
}
/// TS2 strings are Latin-1. Fixed fields are a length byte plus 29 bytes.
fn latin1(b: &[u8]) -> String {
b.iter().map(|&c| c as char).collect()
}
fn to_latin1(s: &str) -> Vec<u8> {
s.chars().map(|c| if (c as u32) < 256 { c as u8 } else { b'?' }).collect()
}
fn pstr(s: &str) -> [u8; 30] {
let mut out = [0u8; 30];
let b = to_latin1(s);
let n = b.len().min(29);
out[0] = n as u8;
out[1..1 + n].copy_from_slice(&b[..n]);
out
}
fn rpstr(b: &[u8], at: usize) -> String {
let Some(&n) = b.get(at) else { return String::new() };
let end = (at + 1 + (n as usize).min(29)).min(b.len());
latin1(b.get(at + 1..end).unwrap_or(&[]))
}
/// Null-terminated string at `*at`, advancing past the terminator.
fn rcstr(b: &[u8], at: &mut usize) -> String {
let start = (*at).min(b.len());
let end = b[start..].iter().position(|&c| c == 0).map_or(b.len(), |p| start + p);
*at = end + 1;
latin1(&b[start..end])
}
fn u16_at(b: &[u8], at: usize) -> u16 {
b.get(at..at + 2).map_or(0, |s| u16::from_le_bytes([s[0], s[1]]))
}
fn u32_at(b: &[u8], at: usize) -> u32 {
b.get(at..at + 4).map_or(0, |s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn codec_name(codec: u16) -> String {
match codec {
0 => "CELP 5.1",
1 => "CELP 6.3",
2 => "GSM 14.8",
3 => "GSM 16.4",
4 => "CELP Windows 5.2",
5 => "Speex 3.4",
6 => "Speex 5.2",
7 => "Speex 7.2",
8 => "Speex 9.3",
9 => "Speex 12.3",
10 => "Speex 16.3",
11 => "Speex 19.5",
12 => "Speex 25.9",
_ => "unknown",
}
.into()
}
/// Speex narrowband submode per TS2 codec id. Derived from the fixed voice
/// payload sizes (e.g. 138 bytes = 5 frames of submode 4's 220 bits); the
/// server rejects packets of any other size.
fn speex_submode(codec: u8) -> Option<c_int> {
Some(match codec {
5 => 1,
6 => 8,
7 => 2,
8 => 3,
9 => 4,
10 => 5,
11 => 6,
12 => 7,
_ => return None,
})
}
/// Bytes of Speex data per voice packet, indexed by codec id.
const SPEEX_BYTES: [usize; 13] = [0, 0, 0, 0, 0, 27, 50, 75, 100, 138, 188, 228, 308];
// --- Speex -------------------------------------------------------------------
struct Bits(Box<speex_sys::SpeexBits>);
impl Bits {
fn new() -> Self {
let mut b: Box<MaybeUninit<speex_sys::SpeexBits>> = Box::new(MaybeUninit::uninit());
// SAFETY: speex_bits_init fully initialises the struct.
unsafe {
speex_sys::speex_bits_init(b.as_mut_ptr());
Bits(Box::from_raw(Box::into_raw(b).cast()))
}
}
}
impl Drop for Bits {
fn drop(&mut self) {
unsafe { speex_sys::speex_bits_destroy(&mut *self.0) }
}
}
// The raw state pointers are only ever touched from the one task that owns them.
unsafe impl Send for Bits {}
struct Decoder {
st: *mut c_void,
bits: Bits,
}
unsafe impl Send for Decoder {}
impl Decoder {
fn new() -> Self {
unsafe {
let st = speex_sys::speex_decoder_init(speex_sys::speex_lib_get_mode(speex_sys::SPEEX_MODEID_NB));
let mut on: c_int = 1;
speex_sys::speex_decoder_ctl(st, speex_sys::SPEEX_SET_ENH, (&mut on as *mut c_int).cast());
Decoder { st, bits: Bits::new() }
}
}
/// Decodes one voice packet's worth of frames to 8 kHz samples.
fn decode(&mut self, data: &[u8]) -> Vec<i16> {
let mut out = vec![0i16; SPEEX_FRAME * FRAMES_PER_PACKET];
unsafe {
speex_sys::speex_bits_read_from(&mut *self.bits.0, data.as_ptr() as *mut c_char, data.len() as c_int);
for frame in out.chunks_mut(SPEEX_FRAME) {
if speex_sys::speex_decode_int(self.st, &mut *self.bits.0, frame.as_mut_ptr()) != 0 {
break;
}
}
}
out
}
}
impl Drop for Decoder {
fn drop(&mut self) {
unsafe { speex_sys::speex_decoder_destroy(self.st) }
}
}
struct Encoder {
st: *mut c_void,
bits: Bits,
codec: u8,
frames: usize,
}
unsafe impl Send for Encoder {}
impl Encoder {
fn new(codec: u8) -> Option<Self> {
let mut submode = speex_submode(codec)?;
unsafe {
let st = speex_sys::speex_encoder_init(speex_sys::speex_lib_get_mode(speex_sys::SPEEX_MODEID_NB));
speex_sys::speex_encoder_ctl(st, speex_sys::SPEEX_SET_MODE, (&mut submode as *mut c_int).cast());
Some(Encoder { st, bits: Bits::new(), codec, frames: 0 })
}
}
/// Feeds one 8 kHz frame; returns a full packet payload every fifth frame.
fn push(&mut self, frame: &mut [i16; SPEEX_FRAME]) -> Option<Vec<u8>> {
unsafe { speex_sys::speex_encode_int(self.st, frame.as_mut_ptr(), &mut *self.bits.0) };
self.frames += 1;
if self.frames < FRAMES_PER_PACKET {
return None;
}
self.frames = 0;
let mut out = vec![0u8; SPEEX_BYTES[self.codec as usize]];
debug_assert_eq!(unsafe { speex_sys::speex_bits_nbytes(&mut *self.bits.0) } as usize, out.len());
unsafe {
speex_sys::speex_bits_write(&mut *self.bits.0, out.as_mut_ptr() as *mut c_char, out.len() as c_int);
speex_sys::speex_bits_reset(&mut *self.bits.0);
}
Some(out)
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe { speex_sys::speex_encoder_destroy(self.st) }
}
}
// --- State ---------------------------------------------------------------------
struct Channel {
id: u32,
flags: u8,
codec: u16,
parent: u32,
order: u16,
max_users: u16,
name: String,
topic: String,
}
struct Player {
channel: u32,
status: u16,
name: String,
}
/// Parses one channel record (list and "created" share the layout).
fn parse_channel(b: &[u8], at: &mut usize) -> Option<Channel> {
let o = *at;
if b.len() < o + 16 {
return None;
}
*at += 16;
let name = rcstr(b, at);
let topic = rcstr(b, at);
let _description = rcstr(b, at);
Some(Channel {
id: u32_at(b, o),
flags: b[o + 4],
codec: u16_at(b, o + 6),
parent: u32_at(b, o + 8),
order: u16_at(b, o + 12),
max_users: u16_at(b, o + 14),
name,
topic,
})
}
struct Speaker {
decoder: Decoder,
queue: VecDeque<i16>,
playing: bool,
}
struct Ts2 {
sock: UdpSocket,
session: u32,
client_id: u32,
conn_counter: u32,
seq: u32,
/// Reliable packets waiting to go out. TS2 is stop-and-wait: only the
/// front one is in flight until the server ACKs it.
outbox: VecDeque<Vec<u8>>,
in_flight: Option<(Instant, u16)>,
next_in: u32,
early: BTreeMap<u32, Vec<u8>>,
fragments: Vec<u8>,
fragment_type: u16,
channels: BTreeMap<u32, Channel>,
players: BTreeMap<u32, Player>,
lists_done: bool,
speakers: HashMap<u32, Speaker>,
talking: HashSet<u32>,
encoder: Option<Encoder>,
voice_counter: u16,
voice_conversation: u16,
last_audio_in: Option<Instant>,
codec_warned: bool,
}
impl Ts2 {
fn reliable(&mut self, typ: u16, payload: &[u8]) {
let mut p = Vec::with_capacity(24 + payload.len());
p.extend_from_slice(&0xbef0u16.to_le_bytes());
p.extend_from_slice(&typ.to_le_bytes());
p.extend_from_slice(&self.session.to_le_bytes());
p.extend_from_slice(&self.client_id.to_le_bytes());
p.extend_from_slice(&self.seq.to_le_bytes());
p.extend_from_slice(&[0; 8]); // resend count, fragment, CRC
p.extend_from_slice(payload);
crc(&mut p, 20);
self.seq += 1;
self.outbox.push_back(p);
}
async fn pump_outbox(&mut self) -> Result<()> {
let Some(front) = self.outbox.front_mut() else { return Ok(()) };
let resends = match self.in_flight {
None => 0,
Some((at, _)) if at.elapsed() < RESEND_AFTER => return Ok(()),
Some((_, n)) if n >= MAX_RESENDS => bail!("The TeamSpeak 2 server stopped answering"),
Some((_, n)) => n + 1,
};
front[16..18].copy_from_slice(&resends.to_le_bytes());
crc(front, 20);
self.sock.send(front).await?;
self.in_flight = Some((Instant::now(), resends));
Ok(())
}
/// Sends the logout, then waits (max 1.5 s) for the server's own "player left"
/// for us and acks it. Until that ack the server keeps us half-present (it
/// resends every 100 ms) and lists us to clients joining meanwhile, who never
/// get a leave for that ghost.
async fn logout(&mut self) {
self.reliable(0x012c, &[]);
let deadline = Instant::now() + Duration::from_millis(1500);
let mut buf = [0u8; 2048];
while Instant::now() < deadline {
if self.pump_outbox().await.is_err() {
return;
}
let Ok(Ok(n)) = tokio::time::timeout(Duration::from_millis(100), self.sock.recv(&mut buf)).await else { continue };
let b = &buf[..n];
match u16_at(b, 0) {
0xbef0 if b.len() >= 24 => {
let mut ack = Vec::with_capacity(16);
ack.extend_from_slice(&0xbef1u16.to_le_bytes());
ack.extend_from_slice(&0u16.to_le_bytes());
ack.extend_from_slice(&self.session.to_le_bytes());
ack.extend_from_slice(&self.client_id.to_le_bytes());
ack.extend_from_slice(&b[12..16]);
let _ = self.sock.send(&ack).await;
if u16_at(b, 2) == 0x0065 && u32_at(b, 24) == self.client_id {
return;
}
}
_ => {
let _ = self.on_datagram(b).await;
}
}
}
}
async fn keepalive(&mut self) -> Result<()> {
let mut p = Vec::with_capacity(24);
p.extend_from_slice(&0xbef4u16.to_le_bytes());
p.extend_from_slice(&1u16.to_le_bytes());
p.extend_from_slice(&self.session.to_le_bytes());
p.extend_from_slice(&self.client_id.to_le_bytes());
p.extend_from_slice(&self.conn_counter.to_le_bytes());
p.extend_from_slice(&[0; 4]); // CRC
crc(&mut p, 16);
self.conn_counter += 1;
self.sock.send(&p).await?;
Ok(())
}
fn own_channel(&self) -> u32 {
self.players.get(&self.client_id).map_or(0, |p| p.channel)
}
fn set_status(&mut self, bit: u16, on: bool) {
let mut status = self.players.get(&self.client_id).map_or(0, |p| p.status);
status = if on { status | bit } else { status & !bit };
if let Some(p) = self.players.get_mut(&self.client_id) {
p.status = status;
}
self.reliable(0x0130, &status.to_le_bytes());
self.snapshot();
}
fn send_text(&mut self, kind: u8, target: u32, message: &str) {
let mut p = Vec::new();
p.extend_from_slice(&0u32.to_le_bytes()); // colour
p.push(kind);
p.extend_from_slice(&target.to_le_bytes());
p.extend_from_slice(&to_latin1(message));
p.push(0);
self.reliable(0x01ae, &p);
}
fn snapshot(&self) {
if !self.lists_done {
return;
}
let channels = self
.channels
.values()
.map(|c| ChannelInfo {
id: c.id as u64,
parent: if c.parent == u32::MAX { 0 } else { c.parent as u64 },
order: c.order as u64,
name: c.name.clone(),
topic: c.topic.clone(),
codec: codec_name(c.codec),
max_clients: (c.max_users > 0).then_some(c.max_users),
has_password: c.flags & CH_PASSWORD != 0,
})
.collect::<Vec<_>>();
let clients = self
.players
.iter()
.map(|(&id, p)| ClientInfo {
id: id as u16,
channel: p.channel as u64,
name: p.name.clone(),
input_muted: p.status & ST_MUTE_MIC != 0,
output_muted: p.status & ST_MUTE_SPEAKERS != 0,
input_hardware_enabled: true,
away: p.status & ST_AWAY != 0,
away_message: String::new(),
is_channel_commander: p.status & ST_CHANNEL_COMMANDER != 0,
country: String::new(),
uid: String::new(),
database_id: 0,
channel_group: 0,
server_groups: Vec::new(),
has_talk_power: true,
is_query: false,
is_streaming: false,
avatar_hash: String::new(),
})
.collect::<Vec<_>>();
emit(&Event::Channels {
server_clients_online: clients.len() as u16,
server_channels_online: channels.len() as u64,
channels,
clients,
own_client_id: self.client_id as u16,
server_max_clients: 0,
});
}
/// Handles one in-order reliable packet. Returns false once we are gone.
fn handle(&mut self, typ: u16, b: &[u8]) -> bool {
if std::env::var_os("TS2_DEBUG").is_some() { eprintln!("in {typ:#06x} {:02x?}", &b[..b.len().min(96)]); }
match typ {
0x0006 => {
let n = u32_at(b, 0);
let mut at = 4;
for _ in 0..n {
let Some(c) = parse_channel(b, &mut at) else { break };
self.channels.insert(c.id, c);
}
}
0x0007 => {
let n = u32_at(b, 0) as usize;
for i in 0..n {
let o = 4 + i * 44;
if b.len() < o + 44 {
break;
}
let player = Player { channel: u32_at(b, o + 4), status: u16_at(b, o + 12), name: rpstr(b, o + 14) };
self.players.insert(u32_at(b, o), player);
}
self.lists_done = true;
}
0x0064 => {
let player = Player { channel: u32_at(b, 4), status: u16_at(b, 12), name: rpstr(b, 14) };
self.players.insert(u32_at(b, 0), player);
}
0x0065 | 0x0066 => {
let id = u32_at(b, 0);
if id == self.client_id {
let reason = if typ == 0x0066 { "kicked from the server" } else { "removed from the server" };
emit(&Event::Disconnected { reason: reason.into() });
return false;
}
self.players.remove(&id);
self.speakers.remove(&id);
}
0x0067 | 0x006d => {
if let Some(p) = self.players.get_mut(&u32_at(b, 0)) {
p.channel = u32_at(b, 8);
}
if u32_at(b, 0) == self.client_id {
self.encoder = None;
self.speakers.clear();
}
}
0x0068 => {
if let Some(p) = self.players.get_mut(&u32_at(b, 0)) {
p.status = u16_at(b, 4);
}
}
0x006e => {
let mut at = 4;
if let Some(c) = parse_channel(b, &mut at) {
self.channels.insert(c.id, c);
}
}
0x006f | 0x0070 => {
let mut at = 8;
let text = rcstr(b, &mut at);
if let Some(c) = self.channels.get_mut(&u32_at(b, 0)) {
if typ == 0x006f { c.name = text } else { c.topic = text }
}
}
0x0071 => {
if let Some(c) = self.channels.get_mut(&u32_at(b, 0)) {
c.flags = u16_at(b, 4) as u8;
c.codec = u16_at(b, 6);
}
self.encoder = None;
}
// Channel deleted: u16 channel id, then the deleting player's u32 id.
0x0073 => {
self.channels.remove(&(u16_at(b, 0) as u32));
}
0x0074 | 0x0075 => {
if let Some(c) = self.channels.get_mut(&u32_at(b, 0)) {
if typ == 0x0074 { c.max_users = u16_at(b, 4) } else { c.order = u16_at(b, 4) }
}
}
// The server refuses a command (seen for chat without the matching text permission).
// The server refuses a request: function code u16, then a u16 error code
// (seen: 0x012f channel switch into a channel that no longer exists).
0xff9a => emit(&Event::Error { message: format!("The TeamSpeak 2 server refused this (error {:#x}).", u16_at(b, 2)) }),
0xfc0f => emit(&Event::Error { message: "The TeamSpeak 2 server refused this: you lack the permission.".into() }),
0x0082 => {
let from = rpstr(b, 5);
let mut at = 35;
let message = rcstr(b, &mut at).trim_end().to_string();
let own_name = self.players.get(&self.client_id).map(|p| p.name.as_str());
match b.get(4) {
Some(0) => emit(&Event::ServerMessage { from, message }),
Some(2) => {
// TS2 names the sender only; nicknames are unique per server.
let partner_id = self.players.iter().find(|(_, p)| p.name == from).map_or(0, |(&id, _)| id as u16);
let from_self = own_name == Some(from.as_str());
emit(&Event::PrivateMessage { partner_id, partner_name: from, from_self, message });
}
Some(1) => emit(&Event::ChatMessage { from, message }),
// Kind 0xce: admin broadcast (tcpquery msg), with an empty sender field.
_ => emit(&Event::ServerMessage { from: String::new(), message }),
}
return true;
}
_ => return true,
}
self.snapshot();
true
}
fn on_voice(&mut self, b: &[u8]) {
let codec = b.get(3).copied().unwrap_or(0);
let Some(len) = SPEEX_BYTES.get(codec as usize).copied().filter(|&l| l > 0) else { return };
// Server voice: 16 bytes header, sender id @16, counter @20, then one
// codec-specific byte before the Speex data.
let Some(data) = b.get(23..23 + len) else { return };
let sender = u32_at(b, 16);
let speaker = self.speakers.entry(sender).or_insert_with(|| Speaker {
decoder: Decoder::new(),
queue: VecDeque::new(),
playing: false,
});
speaker.queue.extend(speaker.decoder.decode(data));
}
/// 20 ms tick: mix one frame from every buffered speaker, upsample 8 -> 48 kHz.
fn audio_tick(&mut self) {
let mut mix = [0i32; SPEEX_FRAME];
let mut talking = HashSet::new();
for (&id, s) in &mut self.speakers {
if !s.playing && s.queue.len() >= PREBUFFER {
s.playing = true;
}
if !s.playing {
continue;
}
if s.queue.len() < SPEEX_FRAME {
s.playing = false;
continue;
}
for m in mix.iter_mut() {
*m += s.queue.pop_front().unwrap_or(0) as i32;
}
talking.insert(id);
}
if talking != self.talking {
self.talking = talking;
emit(&Event::Talkers { clients: self.talking.iter().map(|&id| id as u16).collect() });
}
if self.talking.is_empty() {
return;
}
// ponytail: linear interpolation, swap for a proper resampler if it sounds dull.
let mut bytes = Vec::with_capacity(SPEEX_FRAME * 6 * 4);
for i in 0..SPEEX_FRAME {
let a = mix[i];
let b = mix.get(i + 1).copied().unwrap_or(a);
for k in 0..6 {
let v = (a + (b - a) * k / 6).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
bytes.extend_from_slice(&v.to_le_bytes());
bytes.extend_from_slice(&v.to_le_bytes());
}
}
emit(&Event::AudioOut { pcm: base64::engine::general_purpose::STANDARD.encode(bytes) });
}
/// One 960-sample 48 kHz mono frame from the browser.
async fn on_mic(&mut self, b64: &str) -> Result<()> {
let Ok(raw) = base64::engine::general_purpose::STANDARD.decode(b64.trim()) else { return Ok(()) };
let codec = self.channels.get(&self.own_channel()).map_or(0, |c| c.codec) as u8;
if self.encoder.as_ref().is_none_or(|e| e.codec != codec) {
self.encoder = Encoder::new(codec);
if self.encoder.is_none() {
if !self.codec_warned {
self.codec_warned = true;
emit(&Event::Error {
message: format!("Sending voice in {} channels is not supported, only Speex.", codec_name(codec as u16)),
});
}
return Ok(());
}
}
if self.last_audio_in.is_none_or(|t| t.elapsed() > Duration::from_millis(200)) {
self.voice_conversation = self.voice_conversation.wrapping_add(1);
}
self.last_audio_in = Some(Instant::now());
// 48 -> 8 kHz by averaging each 6 samples, a cheap low-pass.
let mut frame = [0i16; SPEEX_FRAME];
for (i, chunk) in raw.chunks_exact(12).take(SPEEX_FRAME).enumerate() {
let sum: i32 = chunk.chunks_exact(2).map(|s| i16::from_le_bytes([s[0], s[1]]) as i32).sum();
frame[i] = (sum / 6) as i16;
}
let Some(data) = self.encoder.as_mut().and_then(|e| e.push(&mut frame)) else { return Ok(()) };
let mut p = Vec::with_capacity(17 + data.len());
p.extend_from_slice(&0xbef2u16.to_le_bytes());
p.push(0);
p.push(codec);
p.extend_from_slice(&self.session.to_le_bytes());
p.extend_from_slice(&self.client_id.to_le_bytes());
// Native client 2.0.32 order (captured): packet counter, then conversation id.
// Swapped, the native client sees every packet as a new conversation and stutters.
p.extend_from_slice(&self.voice_counter.to_le_bytes());
p.extend_from_slice(&self.voice_conversation.to_le_bytes());
// Native client sends 5 here too (frames per packet).
p.push(FRAMES_PER_PACKET as u8);
p.extend_from_slice(&data);
self.voice_counter = self.voice_counter.wrapping_add(1);
self.sock.send(&p).await?;
Ok(())
}
async fn on_datagram(&mut self, b: &[u8]) -> Result<bool> {
if b.len() < 16 {
return Ok(true);
}
match u16_at(b, 0) {
0xbef0 if b.len() >= 24 => {
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);
ack.extend_from_slice(&0xbef1u16.to_le_bytes());
ack.extend_from_slice(&0u16.to_le_bytes());
ack.extend_from_slice(&self.session.to_le_bytes());
ack.extend_from_slice(&self.client_id.to_le_bytes());
ack.extend_from_slice(&seq.to_le_bytes());
self.sock.send(&ack).await?;
if seq >= self.next_in {
self.early.insert(seq, b.to_vec());
}
while let Some(p) = self.early.remove(&self.next_in) {
self.next_in += 1;
let typ = u16_at(&p, 2);
let fragment = u16_at(&p, 18);
// ponytail: assumes fragments count down to 0 on the last
// one; only seen unfragmented so far (small test server).
if fragment != 0 || !self.fragments.is_empty() {
if self.fragments.is_empty() {
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..]);
if fragment != 0 {
continue;
}
let body = std::mem::take(&mut self.fragments);
if !self.handle(self.fragment_type, &body) {
return Ok(false);
}
} else if !self.handle(typ, &p[24..]) {
return Ok(false);
}
}
}
0xbef1 => {
let seq = u32_at(b, 12);
let front_seq = self.outbox.front().map(|p| u32_at(p, 12));
if front_seq == Some(seq) {
self.outbox.pop_front();
self.in_flight = None;
}
}
0xbef3 => self.on_voice(b),
_ => {}
}
Ok(true)
}
}
async fn login(sock: &UdpSocket, args: &Args) -> Result<Vec<u8>> {
let mut p = Vec::with_capacity(180);
p.extend_from_slice(&0xbef4u16.to_le_bytes());
p.extend_from_slice(&3u16.to_le_bytes());
p.extend_from_slice(&[0; 8]); // session, client id
p.extend_from_slice(&1u32.to_le_bytes());
p.extend_from_slice(&[0; 4]); // CRC
p.extend_from_slice(&pstr("TeamSpeak"));
p.extend_from_slice(&pstr("Linux"));
p.extend_from_slice(&[2, 0, 0, 0, 0x20, 0, 0x3c, 0, 1]);
// Registered login (2): account name + its password. Anonymous (1): no
// account name, the server password goes in the password field.
match &args.login_name {
Some(name) if !name.is_empty() => {
p.push(2);
p.extend_from_slice(&pstr(name));
p.extend_from_slice(&pstr(args.login_password.as_deref().unwrap_or("")));
}
_ => {
p.push(1);
p.extend_from_slice(&pstr(""));
p.extend_from_slice(&pstr(args.server_password.as_deref().unwrap_or("")));
}
}
p.extend_from_slice(&pstr(&args.nickname));
crc(&mut p, 16);
let mut buf = [0u8; 2048];
for _ in 0..5 {
sock.send(&p).await?;
let deadline = tokio::time::sleep(Duration::from_secs(2));
tokio::pin!(deadline);
loop {
tokio::select! {
r = sock.recv(&mut buf) => {
let n = r?;
if n >= 180 && u16_at(&buf, 0) == 0xbef4 && u16_at(&buf, 2) == 4 {
return Ok(buf[..n].to_vec());
}
}
_ = &mut deadline => break,
}
}
}
bail!("No answer from the TeamSpeak 2 server. Check the address and port (default 8767).")
}
pub(crate) async fn run(args: Args) -> Result<()> {
let target = if args.address.contains(':') { args.address.clone() } else { format!("{}:{DEFAULT_PORT}", args.address) };
let addr: SocketAddr = tokio::net::lookup_host(&target)
.await
.map_err(|e| anyhow!("Could not resolve \"{}\": {e}", args.address))?
.find(|a| a.is_ipv4())
.ok_or_else(|| anyhow!("\"{}\" has no IPv4 address", args.address))?;
if !tsclientlib::resolver::is_allowed_target(&addr.ip()) {
bail!(
"Could not connect to \"{}\": it points to a private/internal network address, \
which this gateway does not connect to. (Self-hosting admin? Set ALLOW_PRIVATE_TARGETS=1 for LAN servers.)",
args.address
);
}
let sock = UdpSocket::bind("0.0.0.0:0").await?;
sock.connect(addr).await?;
let reply = login(&sock, &args).await?;
if reply[89..92] != [0, 0, 0] {
bail!("The TeamSpeak 2 server rejected the login (wrong server password, wrong account name or password, or nickname not allowed).");
}
// Unlike the 30-byte fields, the welcome message's length byte can go up to 255.
let welcome_len = reply[180] as usize;
let welcome_message = latin1(&reply[181..(181 + welcome_len).min(reply.len())]);
emit(&Event::Connected {
welcome_message,
server_name: rpstr(&reply, 20),
server_max_clients: 0,
server_version: "TeamSpeak 2".into(),
server_license: String::new(),
server_license_id: 0,
server_banner_url: String::new(),
identity: String::new(),
});
let mut ts = Ts2 {
sock,
session: u32_at(&reply, 172),
client_id: u32_at(&reply, 176),
conn_counter: 2,
seq: 1,
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,
};
// "Channel/Sub" picks a sub-channel; TS2 only nests one level deep.
let (channel, sub) = args.default_channel.as_deref().unwrap_or("").split_once('/').unwrap_or((args.default_channel.as_deref().unwrap_or(""), ""));
let mut part2 = vec![1, 0];
part2.extend_from_slice(&pstr(channel));
part2.extend_from_slice(&pstr(sub));
// The password field is only 26 bytes (length + 25), followed by the login reply's CRC.
let mut pw = pstr(args.channel_password.as_deref().unwrap_or(""));
pw[0] = pw[0].min(25);
part2.extend_from_slice(&pw[..26]);
part2.extend_from_slice(&reply[16..20]);
part2.extend_from_slice(&[0; 4]);
ts.reliable(0x0005, &part2);
let mut stdin = BufReader::new(tokio::io::stdin()).lines();
let mut keepalive = tokio::time::interval(KEEPALIVE_EVERY);
let mut audio = tokio::time::interval(Duration::from_millis(20));
let mut resend = tokio::time::interval(Duration::from_millis(100));
let mut last_heard = Instant::now();
let mut buf = [0u8; 4096];
loop {
ts.pump_outbox().await?;
tokio::select! {
r = ts.sock.recv(&mut buf) => {
let n = r?;
last_heard = Instant::now();
if !ts.on_datagram(&buf[..n]).await? {
return Ok(());
}
}
line = stdin.next_line() => {
let Some(l) = line? else {
ts.logout().await;
return Ok(());
};
let l = l.trim();
if l == "disconnect" || l.starts_with("disconnect ") {
ts.logout().await;
emit(&Event::Disconnected { reason: "client requested".into() });
return Ok(());
} else if let Some(rest) = l.strip_prefix("audio ") {
ts.on_mic(rest).await?;
} else if let Some(rest) = l.strip_prefix("switch ") {
let mut parts = rest.trim().splitn(2, ' ');
if let Ok(id) = parts.next().unwrap_or("").parse::<u32>() {
let password = parts
.next()
.and_then(|p| base64::engine::general_purpose::STANDARD.decode(p).ok())
.and_then(|b| String::from_utf8(b).ok())
.unwrap_or_default();
let mut p = id.to_le_bytes().to_vec();
p.extend_from_slice(&pstr(&password));
ts.reliable(0x012f, &p);
}
} else if let Some(message) = l.strip_prefix("chat ") {
let own = ts.own_channel();
ts.send_text(1, own, message);
} else if let Some(message) = l.strip_prefix("serverchat ") {
ts.send_text(0, 0, message);
} else if let Some((id, message)) = l.strip_prefix("pm ").and_then(|r| r.trim().split_once(' ')) {
if let Ok(id) = id.parse::<u32>() {
ts.send_text(2, id, message);
// TS2 doesn't echo private messages back to the sender.
let partner_name = ts.players.get(&id).map(|p| p.name.clone()).unwrap_or_default();
emit(&Event::PrivateMessage { partner_id: id as u16, partner_name, from_self: true, message: message.into() });
}
} else if l == "away" || l.starts_with("away ") {
ts.set_status(ST_AWAY, true);
} else if l == "unaway" {
ts.set_status(ST_AWAY, false);
} else if let Some(v) = l.strip_prefix("muteinput ") {
ts.set_status(ST_MUTE_MIC, v.trim() == "1");
} else if let Some(v) = l.strip_prefix("muteoutput ") {
ts.set_status(ST_MUTE_SPEAKERS, v.trim() == "1");
}
// Everything else (permissions, files, streams, ...) has no TS2 equivalent.
}
_ = keepalive.tick() => {
if last_heard.elapsed() > SERVER_TIMEOUT {
emit(&Event::Disconnected { reason: "connection to the TeamSpeak 2 server timed out".into() });
return Ok(());
}
ts.keepalive().await?;
}
_ = audio.tick() => ts.audio_tick(),
_ = resend.tick() => {}
}
}
}
#[cfg(test)]
mod tests {
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]
fn crc_matches_zlib() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
}
#[test]
fn speex_sizes_match_submodes() {
// Encoding 5 frames must give exactly the size the server expects
// (checked by the debug_assert in Encoder::push).
for codec in 5..=12u8 {
let mut enc = Encoder::new(codec).unwrap();
let mut out = None;
for _ in 0..FRAMES_PER_PACKET {
out = enc.push(&mut [0; SPEEX_FRAME]);
}
let data = out.unwrap();
let mut dec = Decoder::new();
assert_eq!(dec.decode(&data).len(), SPEEX_FRAME * FRAMES_PER_PACKET);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
services:
webspeak3:
build: .
image: moepchi/webspeak3:latest
container_name: webspeak3
restart: unless-stopped
environment:
- PORT=8080
# This file publishes no port - the gateway is only reachable through
# the cloudflared tunnel below, so the client IP it forwards can be
# trusted (per-IP limits would otherwise see every user as the tunnel).
# Remove this if you publish a port directly instead; behind your own
# reverse proxy use TRUST_PROXY=1.
- TRUST_PROXY=cloudflare
# Nothing in here needs Linux capabilities (unprivileged port, plain
# TCP/UDP sockets), so drop them all.
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
# Port publishing is deployment-specific and left out of this file on
# purpose - Compose concatenates `ports:` lists across an override file
# instead of replacing them, so adding one here would double-publish
# instead of letting an override change it. Set it in a local, gitignored
# docker-compose.override.yml:
#
# services:
# webspeak3:
# ports:
# - "8080:8080"
cloudflared:
image: cloudflare/cloudflared:latest
container_name: webspeak3-cloudflared
restart: unless-stopped
command: tunnel --no-autoupdate run --token ${CLOUDFLARE_TUNNEL_TOKEN}
# Token comes from a gitignored .env file next to this compose file:
# CLOUDFLARE_TUNNEL_TOKEN=eyJ...
# No depends_on/network wiring needed - the tunnel's Public Hostname
# config (set in the Cloudflare dashboard) points at the webspeak3
# service by its Compose service name (http://webspeak3:8080), and
# Compose puts both services on the same default network automatically.
Binary file not shown.

After

Width:  |  Height:  |  Size: 820 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 811 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

+23
View File
@@ -0,0 +1,23 @@
# TeaSpeak / VoySpeak (formerly GreenTeaSpeak) support (WebSpeak3)
WebSpeak3 can speak the TeamSpeak 3/6 protocol via `ts-connector` / `tsclientlib`.
TeaSpeak / GreenTeaSpeak servers need an extra identity handshake before `clientinit`.
## Implemented
- `--server-type teamspeak|teaspeak|auto` (connector; UI Connect dialog; gateway relay)
- `--privilege-key` / `client_default_token` on connect
- `clientinitiv` with **`-teaspeak` switch** (not `teaspeak=1`), `ip=unknown`, alpha bit0
- Classic TeaSpeak crypto via **`initivexpand`** (P-256 ECDH, 20-byte IV) when the server
answers that way — required for GreenTeaSpeak hubs that disable TeamSpeak clients
- TEAMSPEAK identity handshake after crypto when needed
- DNS SRV `_gts._udp` in addition to `_ts3._udp`
Verified against `ts.greenteaspeak.de` (Official GreenTeaSpeak Public Server).
## Not yet (follow-up)
- TEAFORO / forum identity (`greenteaspeak.de` login + method 0)
- Native TeaSpeak POW / `teaclient_connection.node` parity
- GTS badges / HWID extras beyond the basic handshake
- Forum-reject → automatic ECC identity retry (GreenTeaSpeak 2 desktop behavior)
+9 -2
View File
@@ -1,13 +1,14 @@
{
"name": "ts-web-gateway",
"name": "webspeak3-gateway",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ts-web-gateway",
"name": "webspeak3-gateway",
"version": "0.1.0",
"dependencies": {
"qrcode-generator": "^1.4.4",
"ws": "^8.18.0"
},
"devDependencies": {
@@ -536,6 +537,12 @@
"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": {
"version": "4.23.1",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",
+5 -3
View File
@@ -1,15 +1,17 @@
{
"name": "ts-web-gateway",
"name": "webspeak3-gateway",
"version": "0.1.0",
"private": true,
"description": "Gateway server: bridges browser (WebSocket) clients to a native TeamSpeak server",
"description": "WebSpeak3 gateway server: bridges browser (WebSocket) clients to a native TeamSpeak server",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"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": {
"qrcode-generator": "^1.4.4",
"ws": "^8.18.0"
},
"devDependencies": {
+68
View File
@@ -0,0 +1,68 @@
// --- Activity logging (feedback + connection events) -----------------------
//
// Narrow interface so the private VPS overlay can swap in SQLite persistence
// (see mem:reference_webspeak3_private_sqlite_persistence) without forking
// index.ts - only this module differs between public and private; index.ts's
// two call sites just call logFeedback/logConnectionEvent unconditionally.
// This file itself has zero private modifications, same as store.ts.
import { appendFile, rename, stat } from "node:fs/promises";
import path from "node:path";
// Plain JSON-lines file. Defaults under the container's WORKDIR (/app in
// the Docker image); mount a volume over it if you want submissions to
// survive a container recreate.
const FEEDBACK_LOG_FILE = process.env.FEEDBACK_LOG_FILE ?? path.resolve(process.cwd(), "feedback.log");
// Simple size-based rotation: once the log crosses this size, the current
// file is moved to feedback.log.1 (overwriting any previous one) and a
// fresh file is started. Keeps disk usage bounded on a plain JSON-lines
// file with no other retention policy.
const FEEDBACK_LOG_MAX_BYTES = 5 * 1024 * 1024;
async function rotateFeedbackLogIfNeeded(): Promise<void> {
try {
const { size } = await stat(FEEDBACK_LOG_FILE);
if (size < FEEDBACK_LOG_MAX_BYTES) return;
await rename(FEEDBACK_LOG_FILE, `${FEEDBACK_LOG_FILE}.1`);
} catch (err) {
// ENOENT just means there's no log yet - nothing to rotate.
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
console.error("[feedback] Failed to rotate feedback log:", err);
}
}
}
export interface FeedbackEntry {
at: string;
category: string;
message: string;
email?: string;
}
export async function logFeedback(entry: FeedbackEntry): Promise<void> {
try {
await rotateFeedbackLogIfNeeded();
await appendFile(FEEDBACK_LOG_FILE, JSON.stringify(entry) + "\n", "utf-8");
} catch (err) {
console.error("[feedback] Failed to write feedback log:", err);
}
}
// Opt-in only, off by default: this is an open-source, self-hostable image,
// 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
// on. Logs only host/server-name/timestamp — no nickname, no IP.
export interface ConnectionEvent {
type: "connected" | "disconnected";
host: string;
server?: string;
}
export function logConnectionEvent(event: ConnectionEvent): void {
if (process.env.LOG_CONNECTIONS !== "1") return;
if (event.type === "connected") {
console.log(`[connections] connected host=${event.host} server=${event.server} at=${new Date().toISOString()}`);
} else {
console.log(`[connections] disconnected host=${event.host} at=${new Date().toISOString()}`);
}
}
+691
View File
@@ -0,0 +1,691 @@
// 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 { rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import qrcode from "qrcode-generator";
import { clientIp, createRateLimiter } 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) {
const tmp = `${AUTH_FILE}.${process.pid}.tmp`;
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
await rename(tmp, AUTH_FILE);
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();
`;
+142
View File
@@ -0,0 +1,142 @@
// 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 { rename, writeFile } from "node:fs/promises";
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: "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;
}
const tmp = `${CONFIG_FILE}.${process.pid}.tmp`;
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
await rename(tmp, CONFIG_FILE);
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] ?? "")),
};
});
}
+1078 -8
View File
File diff suppressed because it is too large. Load diff
+40
View File
@@ -0,0 +1,40 @@
import type { IncomingMessage } from "node:http";
// 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
// TRUST_PROXY when the gateway is reachable *solely* through that proxy:
// - "cloudflare": CF-Connecting-IP, which Cloudflare always sets itself.
// - "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.
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") {
const cf = req.headers["cf-connecting-ip"];
if (typeof cf === "string" && cf.trim()) return cf.trim();
} else if (TRUST_PROXY === "1") {
const last = String(req.headers["x-forwarded-for"] ?? "").split(",").at(-1)?.trim();
if (last) return last;
}
return (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
}
/** 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
* one-shot IPs. */
export function createRateLimiter(limit: number | (() => number), windowMs: number): (key: string) => boolean {
const hits = new Map<string, number[]>();
setInterval(() => {
const now = Date.now();
for (const [key, times] of hits) {
if (times.every((t) => now - t >= windowMs)) hits.delete(key);
}
}, windowMs).unref();
return (key) => {
const now = Date.now();
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
recent.push(now);
hits.set(key, recent);
return recent.length > (typeof limit === "function" ? limit() : limit);
};
}
+155
View File
@@ -0,0 +1,155 @@
// --- News ticker -----------------------------------------------------------
//
// Two halves:
// * handleNewsFeed - the central feed every client shows by default. Served
// by store-server.ts at /api/store/news, so it rides the existing
// /api/store tunnel route. Manual items live in NEWS_DATA_FILE and are
// managed with STORE_ADMIN_TOKEN (the stats panel); the latest release and
// the newest store design are added automatically.
// * handleNewsConfig - every gateway's /api/news. Tells its own client
// whether to show the ticker at all (NEWS_TICKER=0 turns it off), whether
// to include the central feed (NEWS_TICKER_CENTRAL=0 drops it), and the
// instance's own messages (NEWS_TICKER_MESSAGES, separated by "|").
//
// Like store.ts, this file has zero private modifications.
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { isAdminRequest, latestPublicTheme } from "./store.js";
type NewsItem =
| { id: string; kind: "text"; text: string; url?: string; at: string }
| { id: string; kind: "release"; version: string; url: string; at: string }
| { id: string; kind: "theme"; name: string; author: string; at: string };
type TextItem = Extract<NewsItem, { kind: "text" }>;
const NEWS_DATA_FILE = process.env.NEWS_DATA_FILE;
const MAX_ITEMS = 20;
const MAX_TEXT = 300;
const AUTO_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
let cache: TextItem[] | null = null;
async function load(): Promise<TextItem[]> {
if (cache) return cache;
if (!NEWS_DATA_FILE) return (cache = []);
try {
cache = JSON.parse(await readFile(NEWS_DATA_FILE, "utf-8")) as TextItem[];
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
cache = [];
}
return cache;
}
async function save(items: TextItem[]) {
const tmp = `${NEWS_DATA_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(items), "utf-8");
await rename(tmp, NEWS_DATA_FILE!);
cache = items;
}
// Unauthenticated GitHub API allows 60 requests/hour; one per hour is plenty.
let release: { item: NewsItem | null; fetchedAt: number } = { item: null, fetchedAt: 0 };
async function latestRelease(): Promise<NewsItem | null> {
if (Date.now() - release.fetchedAt < 60 * 60 * 1000) return release.item;
release.fetchedAt = Date.now();
try {
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" },
});
if (!res.ok) return release.item;
const [r] = (await res.json()) as { tag_name: string; html_url: string; published_at: string }[];
release.item = r ? { id: `release-${r.tag_name}`, kind: "release", version: r.tag_name, url: r.html_url, at: r.published_at } : null;
} catch (err) {
console.error("[news] Release lookup failed:", err);
}
return release.item;
}
function isRecent(item: NewsItem | null | undefined): item is NewsItem {
return item != null && Date.now() - Date.parse(item.at) < AUTO_MAX_AGE_MS;
}
function json(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
}
async function readBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 5_000) return null;
}
try {
const parsed = JSON.parse(raw) as unknown;
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
} catch {
return null;
}
}
export async function handleNewsFeed(req: IncomingMessage, res: ServerResponse, pathname: string) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (pathname === "/api/store/news") {
const theme = await latestPublicTheme();
const auto = [
await latestRelease(),
theme && ({ id: `theme-${theme.id}`, kind: "theme", name: theme.name, author: theme.author, at: theme.createdAt } as NewsItem),
].filter(isRecent);
res.setHeader("Cache-Control", "public, max-age=300");
json(res, 200, { items: [...(await load()), ...auto] });
return;
}
// /api/store/news/admin: GET lists, POST {action:"add",text,url?} or {action:"delete",id}.
if (!NEWS_DATA_FILE) return json(res, 404, { error: "not_found" });
if (!isAdminRequest(req)) return json(res, 401, { error: "unauthorized" });
if (req.method === "GET") return json(res, 200, { items: await load() });
if (req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
const body = await readBody(req);
const items = [...(await load())];
if (body?.action === "delete" && typeof body.id === "string") {
await save(items.filter((i) => i.id !== body.id));
return json(res, 200, { ok: true });
}
if (body?.action === "add" && typeof body.text === "string" && body.text.trim()) {
const url = typeof body.url === "string" && /^https:\/\/\S+$/.test(body.url.trim()) ? body.url.trim() : undefined;
if (items.length >= MAX_ITEMS) return json(res, 400, { error: "too_many_items" });
items.push({ id: randomUUID(), kind: "text", text: body.text.trim().slice(0, MAX_TEXT), url, at: new Date().toISOString() });
await save(items);
return json(res, 200, { ok: true });
}
json(res, 400, { error: "bad_request" });
}
// Read per request: the admin panel (config.ts) can change these at runtime.
const localItems = (): NewsItem[] =>
(process.env.NEWS_TICKER_MESSAGES ?? "")
.split("|")
.map((text) => text.trim().slice(0, MAX_TEXT))
.filter(Boolean)
.map((text, i) => ({ id: `local-${i}-${text}`, kind: "text", text, at: "" }));
export function handleNewsConfig(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "public, max-age=300");
json(
res,
200,
process.env.NEWS_TICKER !== "0"
? { enabled: true, central: process.env.NEWS_TICKER_CENTRAL !== "0", items: localItems() }
: { enabled: false },
);
}
+94
View File
@@ -0,0 +1,94 @@
// --- Receiving end of telemetry.ts ---------------------------------------------
//
// Only served by store-server.ts, and only with PING_DATA_FILE set. Keeps one
// row per instance id: version, first and last seen. No IP addresses, no
// request log. The admin view returns counts only.
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises";
import { clientIp, createRateLimiter } from "./net.js";
import { isAdminRequest } from "./store.js";
const PING_DATA_FILE = process.env.PING_DATA_FILE;
const MAX_INSTANCES = 20_000;
const DAY_MS = 24 * 60 * 60 * 1000;
const isRateLimited = createRateLimiter(20, 60 * 60 * 1000);
interface Instance {
version: string;
firstSeen: string;
lastSeen: string;
}
let cache: Record<string, Instance> | null = null;
async function load(): Promise<Record<string, Instance>> {
if (cache) return cache;
try {
cache = JSON.parse(await readFile(PING_DATA_FILE!, "utf-8")) as Record<string, Instance>;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
cache = {};
}
return cache;
}
async function save(instances: Record<string, Instance>) {
// Instances silent for 90 days are gone for good.
const cutoff = Date.now() - 90 * DAY_MS;
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
const tmp = `${PING_DATA_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(instances), "utf-8");
await rename(tmp, PING_DATA_FILE!);
}
function json(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
}
export async function handlePing(req: IncomingMessage, res: ServerResponse, pathname: string) {
if (!PING_DATA_FILE) return json(res, 404, { error: "not_found" });
if (pathname === "/api/ping/stats" && req.method === "GET") {
if (!isAdminRequest(req)) return json(res, 401, { error: "unauthorized" });
const now = Date.now();
const instances = Object.values(await load());
const activeSince = (days: number) => instances.filter((i) => now - Date.parse(i.lastSeen) < days * DAY_MS);
const versions: Record<string, number> = {};
for (const i of activeSince(30)) versions[i.version] = (versions[i.version] ?? 0) + 1;
return json(res, 200, {
active2d: activeSince(2).length,
active7d: activeSince(7).length,
active30d: activeSince(30).length,
newLast7d: instances.filter((i) => now - Date.parse(i.firstSeen) < 7 * DAY_MS).length,
versions,
});
}
if (pathname !== "/api/ping" || req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
if (isRateLimited(clientIp(req))) return json(res, 429, { error: "rate_limited" });
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 500) return json(res, 413, { error: "payload_too_large" });
}
let body: { id?: unknown; version?: unknown };
try {
body = JSON.parse(raw || "{}");
} catch {
return json(res, 400, { error: "invalid_json" });
}
const { id, version } = body;
if (typeof id !== "string" || !/^[0-9a-f-]{36}$/.test(id) || typeof version !== "string" || !/^[\w.+-]{1,40}$/.test(version)) {
return json(res, 400, { error: "invalid_ping" });
}
const instances = await load();
const now = new Date().toISOString();
const known = instances[id];
if (!known && Object.keys(instances).length >= MAX_INSTANCES) return json(res, 507, { error: "full" });
instances[id] = { version, firstSeen: known?.firstSeen ?? now, lastSeen: now };
await save(instances);
json(res, 200, { ok: true });
}
+54
View File
@@ -0,0 +1,54 @@
// Standalone Design Store: the same /api/store/* routes index.ts serves, in a
// process of its own. Lets the store be redeployed or restarted without
// dropping anyone's voice connection. Same image, different command:
// node dist/store-server.js (with STORE_ENABLED=1)
// The gateway in front of the same hostname then runs with STORE_ENABLED off
// and the reverse proxy routes /api/store/* here.
import { createServer } from "node:http";
import { handleStore } from "./store.js";
import { handlePing } from "./ping.js";
import { handleNewsFeed } from "./news.js";
const PORT = Number(process.env.PORT ?? 8080);
createServer((req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
const { pathname } = new URL(req.url ?? "/", "http://localhost");
if (pathname === "/healthz") {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("ok\n");
return;
}
if (pathname === "/api/store/admin" || pathname === "/api/store/themes" || pathname.startsWith("/api/store/themes/")) {
handleStore(req, res, pathname).catch((err) => {
console.error("[store] Request failed:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "internal" }));
}
});
return;
}
if (pathname === "/api/store/news" || pathname === "/api/store/news/admin") {
handleNewsFeed(req, res, pathname).catch((err) => {
console.error("[news] Request failed:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "internal" }));
}
});
return;
}
if (pathname === "/api/ping" || pathname === "/api/ping/stats") {
handlePing(req, res, pathname).catch((err) => {
console.error("[ping] Request failed:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "internal" }));
}
});
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
}).listen(PORT, () => console.log(`WebSpeak3 store listening on http://localhost:${PORT}`));
+539
View File
@@ -0,0 +1,539 @@
// --- Design Store endpoint -------------------------------------------------
//
// Opt-in only, same convention as LOG_CONNECTIONS/FEEDBACK_ENABLED/BROADCAST_TOKEN
// in index.ts: public CSS uploads need moderation attention a plain self-hosted
// instance shouldn't inherit just because the code exists. Set STORE_ENABLED=1
// to turn it on.
//
// Kept in its own module (unlike feedback/broadcast, which stay inline in
// index.ts) so the private VPS overlay - a hand-patched fork of index.ts that
// swaps feedback/connection persistence to SQLite - never needs this file
// touched. It has zero private modifications, so the overlay just copies it
// verbatim; only index.ts's small SQLite-persistence sections need patching.
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises";
import { timingSafeEqual, randomUUID } from "node:crypto";
import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js";
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
// 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
// the expected volume (community theme submissions) is small enough that
// rewriting the whole file each time is simpler than a real DB - see the
// "never add SQLite to the public gateway" note in mem:reference_webspeak3_private_sqlite_persistence.
const STORE_DATA_FILE = process.env.STORE_DATA_FILE ?? path.resolve(process.cwd(), "store-themes.json");
const STORE_NAME_MAX_LENGTH = 60;
const STORE_AUTHOR_MAX_LENGTH = 40;
const STORE_DESCRIPTION_MAX_LENGTH = 300;
const STORE_CSS_MAX_LENGTH = 50_000;
// ~300KB image after base64 overhead - screenshots live inline in the same
// flat JSON file as everything else, so this also bounds that file's growth.
const STORE_SCREENSHOT_MAX_DATA_URL_LENGTH = 400_000;
const STORE_SCREENSHOT_RE = /^data:image\/(png|jpe?g|webp);base64,[A-Za-z0-9+/]+=*$/;
// Hard cap so the flat file - and the in-memory cache mirroring it - can't
// grow unbounded from spam that slips past rate limiting (a fresh IP per
// submission, say). Bounds worst case to ~300 * 450KB =~ 135MB in RAM.
const STORE_MAX_THEMES = 300;
const STORE_BASE_THEMES = new Set(["standard", "nova", "pulse", "ide"]);
// A handful of names (the operator's own) that only whoever holds
// STORE_ADMIN_TOKEN may publish under - stops anyone else from impersonating
// the maintainer in the author field. Everyone else's name is first-come,
// unenforced, same as any other free-text field here.
const storeReservedAuthors = () => new Set(
(process.env.STORE_RESERVED_AUTHORS ?? "Möpchi,Moepchi")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
);
function isValidStoreAdminToken(provided: string): boolean {
const token = process.env.STORE_ADMIN_TOKEN;
if (!token) return false;
const a = Buffer.from(provided);
const b = Buffer.from(token);
return a.length === b.length && timingSafeEqual(a, b);
}
interface StoreTheme {
id: string;
name: string;
baseTheme: string;
css: string;
author: string;
description: string;
screenshot: string | null;
ratingSum: number;
ratingCount: number;
createdAt: string;
// New submissions start "pending" and only become public once someone
// holding STORE_ADMIN_TOKEN approves them (GET /api/store/admin); rejected
// ones are deleted outright. "rejected" only survives in old data files.
status: "approved" | "pending" | "rejected";
}
// Undo what a plain pattern check would miss: comments splitting a keyword
// (u/**/rl), CSS escapes (\75 rl( is url(), and case.
// Comment stripping isn't string-aware ("/*" inside content:"..."), so the
// checks run on both variants: with and without comments removed.
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) => {
const cp = parseInt(hex, 16);
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd";
})
.replace(/\\(.)/gs, "$1")
.toLowerCase();
}
// Theme CSS runs in every installer's browser, so it may style the app but
// never load anything: no imports/fonts, no functions that fetch a resource,
// and url() only for inline data: images. Everything else (colors,
// selectors, animations) can at worst look bad - which moderation catches.
const FORBIDDEN_CSS = [
/@import/,
/@font-face/,
/@namespace/,
/(?:^|[^a-z])(?:-[a-z]+-)?(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
/-moz-binding/,
/behavior\s*:/,
/javascript:/,
/<\/?style/,
];
export function isSafeThemeCss(css: string): boolean {
return isSafeNormalized(normalizeCss(css, true)) && isSafeNormalized(normalizeCss(css, false));
}
function isSafeNormalized(normalized: string): boolean {
if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false;
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;
}
return true;
}
let storeCache: StoreTheme[] | null = null;
async function loadStoreThemes(): Promise<StoreTheme[]> {
if (storeCache) return storeCache;
try {
storeCache = JSON.parse(await readFile(STORE_DATA_FILE, "utf-8")) as StoreTheme[];
} catch (err) {
// Only a missing file means "no themes yet". Anything else (unreadable,
// corrupt) must fail loudly - treating it as empty would let the next
// submission overwrite every stored theme.
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
storeCache = [];
}
return storeCache;
}
async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
storeCache = themes;
// Write-then-rename: a crash mid-write must not leave a truncated file,
// which loadStoreThemes() would read as "no themes" and then overwrite.
const tmp = `${STORE_DATA_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(themes), "utf-8");
await rename(tmp, STORE_DATA_FILE);
}
export function isAdminRequest(req: IncomingMessage): boolean {
const authHeader = req.headers.authorization ?? "";
return authHeader.startsWith("Bearer ") && isValidStoreAdminToken(authHeader.slice("Bearer ".length));
}
// Approved, and still passing today's CSS check - themes published before
// that check got stricter are hidden instead of served.
function isPublic(theme: StoreTheme): boolean {
return theme.status === "approved" && isSafeThemeCss(theme.css);
}
/** Newest public design, for the news ticker (news.ts). */
export async function latestPublicTheme(): Promise<StoreTheme | undefined> {
return (await loadStoreThemes()).filter(isPublic).sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
}
// Same in-memory-per-IP approach as FEEDBACK_RATE_LIMIT in index.ts; kept as a
// separate map since the two endpoints are independent.
const STORE_RATE_LIMIT = 5;
const STORE_RATE_WINDOW_MS = 60 * 60 * 1000;
const isStoreRateLimited = createRateLimiter(STORE_RATE_LIMIT, STORE_RATE_WINDOW_MS);
// One rating per IP per theme - not robust against a determined multi-IP
// spammer, but it stops the trivial "click again" case with no accounts to
// build. Memory-only, so it resets on redeploy; a repeat vote after that just
// counts twice, which is an acceptable ceiling for a beta feature.
const storeRatingsSeen = new Set<string>();
function setStoreCors(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", storeAllowedOrigin());
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
function storeRating(theme: StoreTheme): { average: number; count: number } {
// theme.ratingCount is undefined for themes submitted before this field existed.
const count = theme.ratingCount ?? 0;
return { average: count ? theme.ratingSum / count : 0, count };
}
async function handleStoreList(res: ServerResponse) {
const themes = await loadStoreThemes();
const listing = themes
.filter(isPublic)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
.map((t) => ({
id: t.id,
name: t.name,
baseTheme: t.baseTheme,
author: t.author,
description: t.description ?? "",
hasScreenshot: Boolean(t.screenshot),
rating: storeRating(t),
createdAt: t.createdAt,
}));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(listing));
}
async function handleStoreDownload(req: IncomingMessage, res: ServerResponse, id: string) {
const themes = await loadStoreThemes();
const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req)));
if (!theme) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
// Same shape as the client's own .webspeak3theme.json export/import, so the
// browsed result feeds straight into the existing import validator.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ name: theme.name, baseTheme: theme.baseTheme, css: theme.css }));
}
async function handleStoreScreenshot(req: IncomingMessage, res: ServerResponse, id: string) {
const themes = await loadStoreThemes();
const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req)));
if (!theme?.screenshot) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
const match = /^data:(image\/[a-z]+);base64,(.+)$/.exec(theme.screenshot);
if (!match) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
res.writeHead(200, { "Content-Type": match[1], "Cache-Control": "public, max-age=3600" });
res.end(Buffer.from(match[2], "base64"));
}
async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: string) {
const ip = clientIp(req);
const seenKey = `${ip}:${id}`;
if (storeRatingsSeen.has(seenKey)) {
res.writeHead(409, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "already_rated" }));
return;
}
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 200) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "payload_too_large" }));
return;
}
}
let body: { stars?: unknown };
try {
body = JSON.parse(raw || "{}");
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_json" }));
return;
}
const stars = typeof body.stars === "number" ? Math.round(body.stars) : NaN;
if (!Number.isInteger(stars) || stars < 1 || stars > 5) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_stars" }));
return;
}
const themes = await loadStoreThemes();
const theme = themes.find((t) => t.id === id && isPublic(t));
if (!theme) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
theme.ratingSum = (theme.ratingSum ?? 0) + stars;
theme.ratingCount = (theme.ratingCount ?? 0) + 1;
try {
await saveStoreThemes(themes);
} catch (err) {
console.error("[store] Failed to save rating:", err);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "save_failed" }));
return;
}
// ponytail: wholesale reset instead of per-entry expiry; only bounds memory,
// at worst it lets old voters vote once more, same as a redeploy does.
if (storeRatingsSeen.size > 100_000) storeRatingsSeen.clear();
storeRatingsSeen.add(seenKey);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, rating: storeRating(theme) }));
}
async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
const ip = clientIp(req);
if (isStoreRateLimited(ip)) {
res.writeHead(429, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "rate_limited" }));
return;
}
let raw = "";
const maxBytes = STORE_CSS_MAX_LENGTH + STORE_SCREENSHOT_MAX_DATA_URL_LENGTH + 5_000;
for await (const chunk of req) {
raw += chunk;
if (raw.length > maxBytes) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "payload_too_large" }));
return;
}
}
let body: {
name?: unknown;
baseTheme?: unknown;
css?: unknown;
author?: unknown;
description?: unknown;
screenshot?: unknown;
website?: unknown;
};
try {
body = JSON.parse(raw || "{}");
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_json" }));
return;
}
// Honeypot, same as /api/feedback in index.ts.
if (typeof body.website === "string" && body.website.trim() !== "") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
return;
}
const name = typeof body.name === "string" ? body.name.trim().slice(0, STORE_NAME_MAX_LENGTH) : "";
const baseTheme = typeof body.baseTheme === "string" && STORE_BASE_THEMES.has(body.baseTheme) ? body.baseTheme : "";
const rawCss = typeof body.css === "string" ? body.css.slice(0, STORE_CSS_MAX_LENGTH) : "";
const author =
typeof body.author === "string" ? body.author.trim().slice(0, STORE_AUTHOR_MAX_LENGTH) || "Anonymous" : "Anonymous";
const description = typeof body.description === "string" ? body.description.trim().slice(0, STORE_DESCRIPTION_MAX_LENGTH) : "";
if (!name || !baseTheme || !rawCss) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_theme" }));
return;
}
const isAdmin = isAdminRequest(req);
if (storeReservedAuthors().has(author.toLowerCase())) {
if (!isAdmin) {
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "author_reserved" }));
return;
}
}
const css = rawCss;
if (!isSafeThemeCss(css)) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "css_rejected" }));
return;
}
let screenshot: string | null = null;
if (typeof body.screenshot === "string" && body.screenshot !== "") {
if (body.screenshot.length > STORE_SCREENSHOT_MAX_DATA_URL_LENGTH || !STORE_SCREENSHOT_RE.test(body.screenshot)) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_screenshot" }));
return;
}
screenshot = body.screenshot;
}
const themes = await loadStoreThemes();
// Re-uploading an installed store theme unchanged would just duplicate it.
const cssKey = normalizeCss(css, true).replace(/\s+/g, "");
if (themes.some((t) => normalizeCss(t.css, true).replace(/\s+/g, "") === cssKey)) {
res.writeHead(409, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "duplicate" }));
return;
}
if (themes.length >= STORE_MAX_THEMES) {
res.writeHead(507, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "store_full" }));
return;
}
const theme: StoreTheme = {
id: randomUUID(),
name,
baseTheme,
css,
author,
description,
screenshot,
ratingSum: 0,
ratingCount: 0,
createdAt: new Date().toISOString(),
// The admin's own submissions skip the queue - they'd approve them anyway.
status: isAdmin ? "approved" : "pending",
};
themes.push(theme);
try {
await saveStoreThemes(themes);
} catch (err) {
console.error("[store] Failed to save theme:", err);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "save_failed" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, id: theme.id, status: theme.status }));
if (theme.status === "pending") console.log(`[store] New theme awaiting review: "${theme.name}" (${theme.id})`);
}
async function handleStorePending(req: IncomingMessage, res: ServerResponse) {
if (!isAdminRequest(req)) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "unauthorized" }));
return;
}
const themes = await loadStoreThemes();
const pending = themes
.filter((t) => t.status === "pending")
.map(({ screenshot, ratingSum: _s, ratingCount: _c, ...t }) => ({ ...t, hasScreenshot: Boolean(screenshot) }));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(pending));
}
async function handleStoreModerate(req: IncomingMessage, res: ServerResponse, id: string, action: string) {
if (!isAdminRequest(req)) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "unauthorized" }));
return;
}
const themes = await loadStoreThemes();
const index = themes.findIndex((t) => t.id === id);
if (index === -1) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
// Reject and delete are the same thing: drop it, freeing its slot.
if (action === "approve") themes[index].status = "approved";
else themes.splice(index, 1);
try {
await saveStoreThemes(themes);
} catch (err) {
console.error("[store] Failed to save moderation result:", err);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "save_failed" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
}
// Minimal moderation page. The theme CSS is shown as text only (textContent),
// never applied, so reviewing a hostile submission is harmless.
const ADMIN_PAGE = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Store moderation</title><style>
body{font:14px system-ui;margin:0 auto;padding:1rem;max-width:60rem;background:#111;color:#eee}
input,button{font:inherit;padding:.4rem .7rem}article{border:1px solid #444;border-radius:8px;padding:1rem;margin:1rem 0}
pre{max-height:20rem;overflow:auto;background:#000;padding:.5rem;white-space:pre-wrap}img{max-width:100%}
.ok{background:#2a6}.no{background:#a33}button{color:#fff;border:0;border-radius:4px;cursor:pointer}
</style></head><body><h1>Design Store – pending themes</h1>
<p><input id="token" type="password" placeholder="STORE_ADMIN_TOKEN" size="40"> <button class="ok" id="load">Load</button></p>
<div id="list"></div><script>
const base = location.pathname.replace(/\/admin$/, "/themes");
const auth = () => ({ Authorization: "Bearer " + document.getElementById("token").value });
async function load() {
const list = document.getElementById("list");
list.textContent = "Loading…";
const res = await fetch(base + "/pending", { headers: auth() });
if (!res.ok) { list.textContent = "Error " + res.status; return; }
const themes = await res.json();
list.textContent = themes.length ? "" : "Nothing to review.";
for (const t of themes) {
const el = document.createElement("article");
const h = document.createElement("h2"); h.textContent = t.name + " – " + t.author + " (" + t.baseTheme + ")"; el.append(h);
const d = document.createElement("p"); d.textContent = t.description + " · " + t.createdAt; el.append(d);
if (t.hasScreenshot) {
const img = document.createElement("img"); el.append(img);
fetch(base + "/" + t.id + "/screenshot", { headers: auth() }).then(r => r.blob()).then(b => img.src = URL.createObjectURL(b));
}
const pre = document.createElement("pre"); pre.textContent = t.css; el.append(pre);
for (const [action, label, cls] of [["approve", "Approve", "ok"], ["reject", "Reject (delete)", "no"]]) {
const b = document.createElement("button"); b.textContent = label; b.className = cls; b.style.marginRight = ".5rem";
b.onclick = async () => {
const r = await fetch(base + "/" + t.id + "/" + action, { method: "POST", headers: auth() });
if (r.ok) el.remove(); else alert("Error " + r.status);
};
el.append(b);
}
list.append(el);
}
}
document.getElementById("load").onclick = load;
</script></body></html>`;
export async function handleStore(req: IncomingMessage, res: ServerResponse, pathname: string) {
setStoreCors(res);
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (process.env.STORE_ENABLED !== "1") {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
if (pathname === "/api/store/admin") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
res.end(ADMIN_PAGE);
return;
}
if (pathname === "/api/store/themes") {
if (req.method === "GET") return handleStoreList(res);
if (req.method === "POST") return handleStoreSubmit(req, res);
} else {
const [id, sub] = pathname.slice("/api/store/themes/".length).split("/");
if (id === "pending" && !sub && req.method === "GET") return handleStorePending(req, res);
if (id && !sub && req.method === "GET") return handleStoreDownload(req, res, id);
if (id && sub === "screenshot" && req.method === "GET") return handleStoreScreenshot(req, res, id);
if (id && (sub === "approve" || sub === "reject") && req.method === "POST") {
return handleStoreModerate(req, res, id, sub);
}
if (id && sub === "rate" && req.method === "POST") return handleStoreRate(req, res, id);
}
res.writeHead(405, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "method_not_allowed" }));
}
+29
View File
@@ -0,0 +1,29 @@
// Standalone account sync server (Options -> Konto), same image as the gateway:
// node dist/sync-server.js (with SYNC_DATA_DIR set)
// Its own process so a restart never drops voice connections or the store.
import { createServer } from "node:http";
import { handleSync } from "./sync.js";
const PORT = Number(process.env.PORT ?? 8080);
createServer((req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
const { pathname } = new URL(req.url ?? "/", "http://localhost");
if (pathname === "/healthz") {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("ok\n");
return;
}
if (pathname.startsWith("/api/sync/")) {
handleSync(req, res, pathname).catch((err) => {
console.error("[sync] Request failed:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "internal" }));
}
});
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
}).listen(PORT, () => console.log(`WebSpeak3 sync listening on http://localhost:${PORT}`));
+246
View File
@@ -0,0 +1,246 @@
// --- Account sync (Options -> Konto) --------------------------------------------
//
// Mullvad-style: no e-mail, no name. The client derives an account id, an AES key
// and an auth secret from a random account number (+ optional random password),
// so this server only ever holds id -> encrypted blob. It never sees the number,
// the password or the key. No IP addresses or request logs are kept.
//
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
import type { IncomingMessage, ServerResponse } from "node:http";
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js";
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
// Creating an account costs the browser a few seconds of hashing, so mass sign-ups
// get expensive without asking anyone for personal data.
// 15 bits = ~33k hashes on average, a few seconds on a phone.
const POW_BITS = Number(process.env.SYNC_POW_BITS ?? 15);
const MAX_ACCOUNTS = Number(process.env.SYNC_MAX_ACCOUNTS ?? 100_000);
// ~1 MB plaintext after base64 and AES-GCM overhead.
const MAX_DATA_LENGTH = 1_500_000;
const DAY_MS = 24 * 60 * 60 * 1000;
const EXPIRY_MS = 365 * DAY_MS;
const CHALLENGE_TTL_MS = 10 * 60 * 1000;
const isRateLimited = createRateLimiter(300, 60 * 60 * 1000);
const isCreateRateLimited = createRateLimiter(5, 60 * 60 * 1000);
// Fresh per process: a restart only invalidates challenges handed out in the last 10 minutes.
const challengeSecret = randomBytes(32);
const usedChallenges = new Map<string, number>();
interface Account {
authHash: string;
version: number;
hasPassword: boolean;
data: string;
updatedAt: number;
accessedAt: number;
}
const ID_RE = /^[0-9a-f]{64}$/;
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
const file = (id: string) => path.join(SYNC_DATA_DIR!, `${id}.json`);
let accountCount = 0;
let ready: Promise<void> | null = null;
async function init() {
await mkdir(SYNC_DATA_DIR!, { recursive: true });
await sweep();
setInterval(() => void sweep().catch((err) => console.error("[sync] Sweep failed:", err)), DAY_MS).unref();
}
/** Accounts nobody opened for a year are deleted for good. */
async function sweep() {
const names = (await readdir(SYNC_DATA_DIR!)).filter((n) => n.endsWith(".json"));
let left = 0;
for (const name of names) {
const id = name.slice(0, -5);
const account = await load(id);
if (account && Date.now() - account.accessedAt > EXPIRY_MS) await rm(file(id), { force: true });
else left++;
}
accountCount = left;
}
async function load(id: string): Promise<Account | null> {
try {
return JSON.parse(await readFile(file(id), "utf-8")) as Account;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
throw err;
}
}
async function save(id: string, account: Account) {
const tmp = `${file(id)}.tmp`;
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.
const locks = new Map<string, Promise<unknown>>();
function locked<T>(id: string, fn: () => Promise<T>): Promise<T> {
const run = (locks.get(id) ?? Promise.resolve()).then(fn, fn);
const tail = run.catch(() => {});
locks.set(id, tail);
void tail.then(() => locks.get(id) === tail && locks.delete(id));
return run;
}
function authorized(req: IncomingMessage, account: Account): boolean {
const auth = /^Bearer ([0-9a-f]{64})$/.exec(req.headers.authorization ?? "")?.[1];
if (!auth) return false;
return timingSafeEqual(Buffer.from(sha256(auth)), Buffer.from(account.authHash));
}
function newChallenge(): string {
const body = `${Date.now()}.${randomBytes(16).toString("hex")}`;
return `${body}.${createHmac("sha256", challengeSecret).update(body).digest("hex")}`;
}
/** sha256(challenge + ":" + nonce) has to start with POW_BITS zero bits. */
export function leadingZeroBits(hex: string): number {
let bits = 0;
for (const c of hex) {
const n = parseInt(c, 16);
if (n === 0) {
bits += 4;
continue;
}
return bits + Math.clz32(n) - 28;
}
return bits;
}
function validPow(pow: unknown): boolean {
if (!pow || typeof pow !== "object") return false;
const { challenge, nonce } = pow as { challenge?: unknown; nonce?: unknown };
if (typeof challenge !== "string" || typeof nonce !== "string" || nonce.length > 32) return false;
const [ts, rand, mac] = challenge.split(".");
if (!ts || !rand || !mac) return false;
const expected = createHmac("sha256", challengeSecret).update(`${ts}.${rand}`).digest("hex");
if (mac.length !== expected.length || !timingSafeEqual(Buffer.from(mac), Buffer.from(expected))) return false;
const age = Date.now() - Number(ts);
if (!(age >= 0 && age < CHALLENGE_TTL_MS) || usedChallenges.has(challenge)) return false;
if (leadingZeroBits(sha256(`${challenge}:${nonce}`)) < POW_BITS) return false;
for (const [c, at] of usedChallenges) if (Date.now() - at > CHALLENGE_TTL_MS) usedChallenges.delete(c);
usedChallenges.set(challenge, Date.now());
return true;
}
function json(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
}
async function readBody(req: IncomingMessage, max: number): Promise<Record<string, unknown> | "too_large" | null> {
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > max) return "too_large";
}
try {
const body = JSON.parse(raw || "{}");
return body && typeof body === "object" ? body : null;
} catch {
return null;
}
}
export async function handleSync(req: IncomingMessage, res: ServerResponse, pathname: string) {
if (!SYNC_DATA_DIR) return json(res, 404, { error: "not_found" });
res.setHeader("Access-Control-Allow-Origin", SYNC_ALLOWED_ORIGIN);
res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (isRateLimited(clientIp(req))) return json(res, 429, { error: "rate_limited" });
ready ??= init();
await ready;
if (pathname === "/api/sync/challenge" && req.method === "POST") {
return json(res, 200, { challenge: newChallenge(), bits: POW_BITS });
}
const match = /^\/api\/sync\/([0-9a-f]{64})(\/meta)?$/.exec(pathname);
if (!match || !ID_RE.test(match[1])) return json(res, 404, { error: "not_found" });
const id = match[1];
// Tells a new device whether to ask for the password. Only someone holding the
// account number can compute the id in the first place.
if (match[2]) {
if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
const account = await load(id);
return json(res, 200, account ? { exists: true, hasPassword: account.hasPassword, version: account.version } : { exists: false });
}
if (req.method === "GET") {
const account = await load(id);
if (!account || !authorized(req, account)) return json(res, 404, { error: "not_found" });
// Touch at most once a day instead of rewriting the file on every read.
if (Date.now() - account.accessedAt > DAY_MS) {
await locked(id, async () => {
const fresh = await load(id);
if (fresh) await save(id, { ...fresh, accessedAt: Date.now() });
});
}
return json(res, 200, { version: account.version, data: account.data, updatedAt: account.updatedAt });
}
if (req.method === "DELETE") {
return locked(id, async () => {
const account = await load(id);
if (!account || !authorized(req, account)) return json(res, 404, { error: "not_found" });
await rm(file(id), { force: true });
accountCount--;
json(res, 200, { ok: true });
});
}
if (req.method !== "PUT") return json(res, 405, { error: "method_not_allowed" });
const body = await readBody(req, MAX_DATA_LENGTH + 2_000);
if (body === "too_large") return json(res, 413, { error: "payload_too_large" });
if (!body) return json(res, 400, { error: "invalid_json" });
const { version, data, hasPassword, newAuth, pow } = body;
if (typeof version !== "number" || typeof data !== "string" || !/^[A-Za-z0-9+/]+=*$/.test(data)) {
return json(res, 400, { error: "invalid_body" });
}
if (newAuth !== undefined && (typeof newAuth !== "string" || !ID_RE.test(newAuth))) {
return json(res, 400, { error: "invalid_body" });
}
return locked(id, async () => {
const account = await load(id);
const now = Date.now();
if (!account) {
// Creating: the bearer token becomes the account's auth secret.
const auth = /^Bearer ([0-9a-f]{64})$/.exec(req.headers.authorization ?? "")?.[1];
if (!auth || version !== 0) return json(res, 400, { error: "invalid_body" });
if (accountCount >= MAX_ACCOUNTS) return json(res, 507, { error: "full" });
if (isCreateRateLimited(clientIp(req))) return json(res, 429, { error: "rate_limited" });
if (!validPow(pow)) return json(res, 403, { error: "pow_required" });
await save(id, { authHash: sha256(auth), version: 1, hasPassword: hasPassword === true, data, updatedAt: now, accessedAt: now });
accountCount++;
return json(res, 200, { version: 1 });
}
if (!authorized(req, account)) return json(res, 404, { error: "not_found" });
// Another device wrote in between: the client decides what wins.
if (version !== account.version) return json(res, 409, { error: "conflict", version: account.version });
await save(id, {
authHash: typeof newAuth === "string" ? sha256(newAuth) : account.authHash,
version: account.version + 1,
hasPassword: typeof hasPassword === "boolean" ? hasPassword : account.hasPassword,
data,
updatedAt: now,
accessedAt: now,
});
json(res, 200, { version: account.version + 1 });
});
}
+60
View File
@@ -0,0 +1,60 @@
// --- Anonymous usage ping ----------------------------------------------------
//
// Once at startup and then once a day, the gateway tells webspeak3.de that an
// instance is running. That's the only way to know whether anyone self-hosts
// at all, and which versions are still out there (e.g. before dropping
// support for something or after a security fix).
//
// Sent: a random instance id (generated here, used for nothing else) and the
// version. Not sent: hostnames, TeamSpeak servers, user counts, settings.
// The receiving side stores no IP addresses (see ping.ts).
//
// On by default, off with TELEMETRY=0. Said so in the startup log, too.
import { readFile, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import path from "node:path";
const TELEMETRY_URL = process.env.TELEMETRY_URL || "https://gateway.webspeak3.de/api/ping";
const VERSION = process.env.WEBSPEAK3_VERSION || "unknown";
// ponytail: without a volume over the working directory a container recreate
// makes a new id, so an update counts twice for a day or so.
const ID_FILE = process.env.TELEMETRY_ID_FILE ?? path.resolve(process.cwd(), "instance-id");
const DAY_MS = 24 * 60 * 60 * 1000;
async function instanceId(): Promise<string> {
try {
const id = (await readFile(ID_FILE, "utf-8")).trim();
if (/^[0-9a-f-]{36}$/.test(id)) return id;
} catch {
// first start - fall through
}
const id = randomUUID();
await writeFile(ID_FILE, id + "\n").catch(() => {});
return id;
}
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 {
await fetch(TELEMETRY_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: await id, version: VERSION }),
signal: AbortSignal.timeout(10_000),
});
} catch {
// Offline or blocked - not worth a log line every day.
}
}
if (process.env.TELEMETRY !== "0") {
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.`
);
}
void ping();
setInterval(() => void ping(), DAY_MS).unref();
+836 -26
View File
@@ -21,6 +21,24 @@ export interface ChannelInfo {
hasPassword: boolean;
}
/**
* The `setupstream` arguments. TS6 always sends all of them, so none are
* optional here - the defaults live in the caller, not on the wire.
*/
export interface StreamSetupOptions {
name: string;
/** Source kind; a real TS6 screen share sends 3. */
type: number;
bitrate: number;
/** TS6's Privacy setting: who may join without being asked. */
accessibility: number;
/** Connection mode - peer-to-peer or via the server's SFU. */
mode: number;
/** 0 means unlimited. */
viewerLimit: number;
audio: boolean;
}
export interface ClientInfo {
id: number;
channel: number;
@@ -29,38 +47,209 @@ export interface ClientInfo {
outputMuted: boolean;
inputHardwareEnabled: boolean;
away: boolean;
awayMessage: string;
isChannelCommander: boolean;
country: string;
uid: string;
databaseId: number;
channelGroup: number;
serverGroups: number[];
hasTalkPower: boolean;
/** ServerQuery client; UI may hide these unless enabled per favorite. */
isQuery: boolean;
/** Broadcasting a TS6 Stream/Call. The stream id is fetched separately. */
isStreaming: boolean;
/** MD5 of the avatar (`client_flag_avatar`), empty without one. */
avatarHash: string;
}
export interface GroupEntry {
id: number;
name: string;
iconId: number;
}
export interface PermissionOverviewEntry {
name: string;
description: string;
value: number;
negated: boolean;
skip: boolean;
}
export interface PermissionCatalogEntry {
id: number;
name: string;
description: string;
}
export type PermScope = "server" | "channelgroup" | "channel" | "client" | "channelclient";
export interface BanListEntry {
banId: number;
ip: string;
name: string;
uid: string;
lastNickname: string;
created: string;
durationSecs: number;
invokerName: string;
reason: string;
enforcements: number;
}
export interface ComplainListEntry {
targetClientDbId: number;
targetName: string;
fromClientDbId: number;
fromName: string;
message: string;
timestamp: string;
}
export interface OfflineMessageListEntry {
messageId: number;
clientUid: string;
subject: string;
timestamp: string;
isRead: boolean;
}
export interface FileListEntry {
path: string;
name: string;
size: number;
isFile: boolean;
timestamp: string;
}
export type ServerLogEntry =
| { kind: "clientJoin"; client: string; channel: string }
| { kind: "clientLeave"; client: string }
| { kind: "clientChannelSwitch"; client: string; fromChannel: string; toChannel: string }
| { kind: "clientChannelGroupAssigned"; client: string; group: string }
| { kind: "channelCreated"; channel: string }
| { kind: "channelDeleted"; channel: string }
| { kind: "channelEdited"; channel: string }
| { kind: "serverEdited" }
| { kind: "permissionError"; action: string };
export type Ts3ConnectionEvent =
| { type: "connected"; welcomeMessage: string; serverName: string; serverMaxClients: number }
| { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[] }
| {
type: "connected";
welcomeMessage: string;
serverName: string;
serverMaxClients: number;
serverVersion: string;
serverLicense: string;
serverLicenseId: number;
serverBannerUrl: string;
identity: string;
}
| { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[]; ownClientId: number; serverMaxClients: number; serverClientsOnline: number; serverChannelsOnline: number }
| { type: "chatMessage"; from: string; message: string }
| { type: "serverMessage"; from: string; message: string }
| { type: "privateMessage"; partnerId: number; partnerName: string; fromSelf: boolean; message: string }
| { type: "poke"; from: string; message: string }
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "whisperReceived"; clientId: number }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string };
| { type: "reconnecting"; reason: string }
| { type: "reconnected" }
| { type: "error"; message: string; cid?: number; path?: string }
| { type: "channelPasswordRequired"; channelId: number }
| ({ type: "serverLog" } & ServerLogEntry)
| {
type: "clientConnectionInfo";
clientId: number;
pingMs: number | null;
connectedSecs: number | null;
ip: string | null;
packetsSent: number;
bytesSent: number;
packetsReceived: number;
bytesReceived: number;
packetLossPercent: number;
}
| {
type: "serverConnectionInfo";
pingMs: number;
connectedSecs: number;
packetLossPercent: number;
packetsSentTotal: number;
bytesSentTotal: number;
packetsReceivedTotal: number;
bytesReceivedTotal: number;
bandwidthSentLastSecond: number;
bandwidthReceivedLastSecond: number;
bandwidthSentLastMinute: number;
bandwidthReceivedLastMinute: number;
filetransferBandwidthSent: number;
filetransferBandwidthReceived: number;
filetransferBytesSent: number;
filetransferBytesReceived: number;
}
| { type: "serverProtocolLog"; lines: string[] }
| { type: "banList"; entries: BanListEntry[] }
| { type: "complainList"; entries: ComplainListEntry[] }
| { type: "offlineMessageList"; entries: OfflineMessageListEntry[] }
| {
type: "offlineMessage";
messageId: number;
clientUid: string;
subject: string;
message: string;
timestamp: string;
}
| { type: "channelGroupList"; entries: GroupEntry[] }
| { type: "serverGroupList"; entries: GroupEntry[] }
| { type: "permissionOverview"; entries: PermissionOverviewEntry[] }
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
| { type: "fileDownloadChunk"; cid: number; path: string; offset: number; data: string; done: boolean }
| { type: "fileUploadDone"; cid: number; path: string }
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
/** TS6 Stream/Call signaling, forwarded verbatim; `args` is already unescaped. */
| { type: "streamEvent"; name: string; args: Record<string, string> };
export type ServerType = "teamspeak" | "teaspeak" | "auto" | "ts2";
export interface Ts3ConnectOptions {
host: string;
nickname: string;
serverPassword?: string;
channelPassword?: string;
defaultChannel?: string;
/** Previously-issued identity (from a prior "connected" event) to keep
* the same client UID across sessions. Omit to get a freshly generated one. */
identity?: string;
/** Protocol / server dialect hint for the connector (`auto` when omitted). */
serverType?: ServerType;
/** One-time privilege key / token to redeem on connect. */
privilegeKey?: string;
/** TeamSpeak 2 registered account (anonymous when omitted). */
loginName?: string;
loginPassword?: string;
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CONNECTOR_BIN = path.resolve(
__dirname,
"../../../connector/target/debug",
process.platform === "win32" ? "ts-connector.exe" : "ts-connector"
);
const CONNECTOR_BIN =
process.env.CONNECTOR_BIN ??
path.resolve(
__dirname,
"../../../connector/target/debug",
process.platform === "win32" ? "ts-connector.exe" : "ts-connector"
);
export class Ts3Connection {
private listeners = new Set<(event: Ts3ConnectionEvent) => void>();
private child?: ChildProcessWithoutNullStreams;
// Set once the child is confirmed gone - either it exited, or it never
// managed to spawn at all. disconnect() uses this to skip waiting on an
// "exit" event that already fired (and so will never fire again) before
// disconnect() got a chance to listen for it.
private childGone = false;
constructor(private options: Ts3ConnectOptions) {}
@@ -72,11 +261,52 @@ export class Ts3Connection {
for (const listener of this.listeners) listener(event);
}
/** Every connector command is exactly one line on this stdin protocol.
* Several call sites forward fields (permission scope/ids, whisper
* targets, ...) without stripping embedded CR/LF first - routing every
* write through here means a stray newline in any of them can never
* smuggle in a second, attacker-chosen command. */
private writeLine(line: string): void {
if (!this.child || this.child.killed) return;
this.child.stdin.write(`${line.replace(/[\r\n]+/g, " ")}\n`);
}
async connect(): Promise<void> {
const args = ["--address", this.options.host, "--nickname", this.options.nickname];
if (this.options.serverPassword) args.push("--server-password", this.options.serverPassword);
if (this.options.channelPassword) args.push("--channel-password", this.options.channelPassword);
this.child = spawn(CONNECTOR_BIN, args);
// "--flag=value" so a value starting with "-" can never be parsed as a
// flag of its own. Secrets go through the environment instead of argv,
// which any process on the host can read via `ps`.
const args = [`--address=${this.options.host}`, `--nickname=${this.options.nickname}`];
if (this.options.defaultChannel) args.push(`--default-channel=${this.options.defaultChannel}`);
if (this.options.serverType) args.push(`--server-type=${this.options.serverType}`);
const env: NodeJS.ProcessEnv = { ...process.env };
if (this.options.serverPassword) env.TS_SERVER_PASSWORD = this.options.serverPassword;
if (this.options.channelPassword) env.TS_CHANNEL_PASSWORD = this.options.channelPassword;
if (this.options.identity) env.TS_IDENTITY = this.options.identity;
if (this.options.privilegeKey) env.TS_PRIVILEGE_KEY = this.options.privilegeKey;
if (this.options.loginName) env.TS_LOGIN_NAME = this.options.loginName;
if (this.options.loginPassword) env.TS_LOGIN_PASSWORD = this.options.loginPassword;
this.child = spawn(CONNECTOR_BIN, args, { env });
// The connector can exit on its own (e.g. the TS3 server drops it) and close
// its stdin pipe before writeLine()'s `this.child.killed` guard has any way
// to know - killed only reflects Node-side .kill() calls. A write to that
// closed pipe emits an unhandled 'error' (EPIPE) on the stream, which Node
// treats as fatal and crashes the whole gateway process, killing every
// other client's session too. Listening here turns it into a normal,
// isolated write failure instead of a process-wide crash.
this.child.stdin.on("error", () => {});
// spawn() itself can fail asynchronously - wrong CONNECTOR_BIN path, no
// exec permission, or (under load, with many connections already open)
// EMFILE/ENFILE from running out of file descriptors. That failure surfaces
// as an unhandled 'error' event on the child process object, which is just
// as fatal to the whole gateway process as the stdin case above - and far
// more likely to hit at the worst possible time, since a file-descriptor
// limit is reached exactly when the most other connections are active.
this.child.on("error", (err) => {
this.childGone = true;
this.emit({ type: "error", message: `Connector failed to start: ${err.message}` });
});
createInterface({ input: this.child.stdout }).on("line", (line) => {
try {
@@ -88,7 +318,17 @@ export class Ts3Connection {
output_muted: boolean;
input_hardware_enabled: boolean;
away: boolean;
away_message: string;
is_channel_commander: boolean;
country: string;
uid: string;
database_id: number;
channel_group: number;
server_groups: number[];
has_talk_power: boolean;
is_query?: boolean;
is_streaming?: boolean;
avatar_hash?: string;
}
interface RawChannelInfo {
@@ -103,16 +343,126 @@ export class Ts3Connection {
}
const event = JSON.parse(line) as
| { type: "connected"; welcome_message: string; server_name: string; server_max_clients: number }
| { type: "channels"; channels: RawChannelInfo[]; clients: RawClientInfo[] }
| {
type: "connected";
welcome_message: string;
server_name: string;
server_max_clients: number;
server_version: string;
server_license: string;
server_license_id?: number;
server_banner_url: string;
identity: string;
}
| {
type: "channels";
channels: RawChannelInfo[];
clients: RawClientInfo[];
own_client_id?: number;
server_max_clients?: number;
server_clients_online?: number;
server_channels_online?: number;
}
| { type: "chatMessage"; from: string; message: string }
| { type: "serverMessage"; from: string; message: string }
| { type: "privateMessage"; partner_id: number; partner_name: string; from_self: boolean; message: string }
| { type: "poke"; from: string; message: string }
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "whisperReceived"; clientId: number }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string };
| { type: "reconnecting"; reason: string }
| { type: "reconnected" }
| { type: "error"; message: string; cid?: number; path?: string }
| { type: "channelPasswordRequired"; channel_id: number }
| ({ type: "serverLog" } & ServerLogEntry)
| {
type: "clientConnectionInfo";
client_id: number;
ping_ms: number | null;
connected_secs: number | null;
ip: string | null;
packets_sent: number;
bytes_sent: number;
packets_received: number;
bytes_received: number;
packet_loss_percent: number;
}
| {
type: "serverConnectionInfo";
ping_ms: number;
connected_secs: number;
packet_loss_percent: number;
packets_sent_total: number;
bytes_sent_total: number;
packets_received_total: number;
bytes_received_total: number;
bandwidth_sent_last_second: number;
bandwidth_received_last_second: number;
bandwidth_sent_last_minute?: number;
bandwidth_received_last_minute?: number;
filetransfer_bandwidth_sent?: number;
filetransfer_bandwidth_received?: number;
filetransfer_bytes_sent?: number;
filetransfer_bytes_received?: number;
}
| { type: "serverProtocolLog"; lines: string[] }
| {
type: "banList";
entries: {
ban_id: number;
ip: string;
name: string;
uid: string;
last_nickname: string;
created: string;
duration_secs: number;
invoker_name: string;
reason: string;
enforcements: number;
}[];
}
| {
type: "complainList";
entries: {
target_client_db_id: number;
target_name: string;
from_client_db_id: number;
from_name: string;
message: string;
timestamp: string;
}[];
}
| {
type: "offlineMessageList";
entries: {
message_id: number;
client_uid: string;
subject: string;
timestamp: string;
is_read: boolean;
}[];
}
| {
type: "offlineMessage";
message_id: number;
client_uid: string;
subject: string;
message: string;
timestamp: string;
}
| { type: "channelGroupList"; entries: GroupEntry[] }
| { type: "serverGroupList"; entries: GroupEntry[] }
| {
type: "permissionOverview";
entries: { name: string; description: string; value: number; negated: boolean; skip: boolean }[];
}
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
| { type: "fileDownloadChunk"; cid: number; path: string; offset: number; data: string; done: boolean }
| { type: "fileUploadDone"; cid: number; path: string }
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
| { type: "streamEvent"; name: string; args: Record<string, string> };
if (event.type === "connected") {
this.emit({
@@ -120,6 +470,11 @@ export class Ts3Connection {
welcomeMessage: event.welcome_message,
serverName: event.server_name,
serverMaxClients: event.server_max_clients,
serverVersion: event.server_version,
serverLicense: event.server_license,
serverLicenseId: event.server_license_id ?? 0,
serverBannerUrl: event.server_banner_url,
identity: event.identity,
});
} else if (event.type === "channels") {
this.emit({
@@ -142,8 +497,22 @@ export class Ts3Connection {
outputMuted: c.output_muted,
inputHardwareEnabled: c.input_hardware_enabled,
away: c.away,
awayMessage: c.away_message,
isChannelCommander: c.is_channel_commander,
country: c.country,
uid: c.uid,
databaseId: c.database_id,
channelGroup: c.channel_group,
serverGroups: c.server_groups,
hasTalkPower: c.has_talk_power,
isQuery: Boolean(c.is_query),
isStreaming: Boolean(c.is_streaming),
avatarHash: c.avatar_hash ?? "",
})),
ownClientId: event.own_client_id ?? 0,
serverMaxClients: event.server_max_clients ?? 0,
serverClientsOnline: event.server_clients_online ?? event.clients.length,
serverChannelsOnline: event.server_channels_online ?? event.channels.length,
});
} else if (event.type === "privateMessage") {
this.emit({
@@ -153,6 +522,88 @@ export class Ts3Connection {
fromSelf: event.from_self,
message: event.message,
});
} else if (event.type === "clientConnectionInfo") {
this.emit({
type: "clientConnectionInfo",
clientId: event.client_id,
pingMs: event.ping_ms,
connectedSecs: event.connected_secs,
ip: event.ip,
packetsSent: event.packets_sent,
bytesSent: event.bytes_sent,
packetsReceived: event.packets_received,
bytesReceived: event.bytes_received,
packetLossPercent: event.packet_loss_percent,
});
} else if (event.type === "serverConnectionInfo") {
this.emit({
type: "serverConnectionInfo",
pingMs: event.ping_ms,
connectedSecs: event.connected_secs,
packetLossPercent: event.packet_loss_percent,
packetsSentTotal: event.packets_sent_total,
bytesSentTotal: event.bytes_sent_total,
packetsReceivedTotal: event.packets_received_total,
bytesReceivedTotal: event.bytes_received_total,
bandwidthSentLastSecond: event.bandwidth_sent_last_second,
bandwidthReceivedLastSecond: event.bandwidth_received_last_second,
bandwidthSentLastMinute: event.bandwidth_sent_last_minute ?? 0,
bandwidthReceivedLastMinute: event.bandwidth_received_last_minute ?? 0,
filetransferBandwidthSent: event.filetransfer_bandwidth_sent ?? 0,
filetransferBandwidthReceived: event.filetransfer_bandwidth_received ?? 0,
filetransferBytesSent: event.filetransfer_bytes_sent ?? 0,
filetransferBytesReceived: event.filetransfer_bytes_received ?? 0,
});
} else if (event.type === "banList") {
this.emit({
type: "banList",
entries: event.entries.map((e) => ({
banId: e.ban_id,
ip: e.ip,
name: e.name,
uid: e.uid,
lastNickname: e.last_nickname,
created: e.created,
durationSecs: e.duration_secs,
invokerName: e.invoker_name,
reason: e.reason,
enforcements: e.enforcements,
})),
});
} else if (event.type === "complainList") {
this.emit({
type: "complainList",
entries: event.entries.map((e) => ({
targetClientDbId: e.target_client_db_id,
targetName: e.target_name,
fromClientDbId: e.from_client_db_id,
fromName: e.from_name,
message: e.message,
timestamp: e.timestamp,
})),
});
} else if (event.type === "offlineMessageList") {
this.emit({
type: "offlineMessageList",
entries: event.entries.map((e) => ({
messageId: e.message_id,
clientUid: e.client_uid,
subject: e.subject,
timestamp: e.timestamp,
isRead: e.is_read,
})),
});
} else if (event.type === "offlineMessage") {
this.emit({
type: "offlineMessage",
messageId: event.message_id,
clientUid: event.client_uid,
subject: event.subject,
message: event.message,
timestamp: event.timestamp,
});
} else if (event.type === "channelPasswordRequired") {
this.emit({ type: "channelPasswordRequired", channelId: event.channel_id });
} else {
this.emit(event);
}
@@ -168,44 +619,403 @@ export class Ts3Connection {
});
this.child.on("exit", (code) => {
this.childGone = true;
if (code !== 0) {
this.emit({ type: "error", message: `Connector exited with code ${code}` });
}
});
}
async switchChannel(channelId: number): Promise<void> {
this.child?.stdin.write(`switch ${channelId}\n`);
async switchChannel(channelId: number, channelPassword?: string): Promise<void> {
const id = Number(channelId);
if (!Number.isFinite(id)) return;
// The password travels base64-encoded on this line-based stdin protocol
// so it can safely contain spaces or other characters.
const passwordArg = channelPassword ? ` ${Buffer.from(channelPassword, "utf8").toString("base64")}` : "";
this.writeLine(`switch ${id}${passwordArg}`);
}
async moveClient(clientId: number, channelId: number, channelPassword?: string): Promise<void> {
const clid = Number(clientId);
const cid = Number(channelId);
if (!Number.isFinite(clid) || !Number.isFinite(cid)) return;
const passwordArg = channelPassword ? ` ${Buffer.from(channelPassword, "utf8").toString("base64")}` : "";
this.writeLine(`moveclient ${clid} ${cid}${passwordArg}`);
}
async getClientConnectionInfo(clientId: number): Promise<void> {
this.writeLine(`clientconninfo ${clientId}`);
}
async getServerConnectionInfo(): Promise<void> {
this.writeLine(`serverconninfo`);
}
async kickFromChannel(clientId: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.writeLine(`kickchannel ${clientId} ${sanitized}`);
}
async kickFromServer(clientId: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.writeLine(`kickserver ${clientId} ${sanitized}`);
}
async banClient(clientId: number, seconds: number, reason: string): Promise<void> {
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
this.writeLine(`banclient ${clientId} ${Math.max(0, Math.floor(seconds))} ${sanitized}`);
}
/** Every field is optional - only send what actually changed. JSON.stringify
* already escapes embedded newlines, so this is safe as a single stdin line
* without extra sanitization. */
async editServer(payload: {
name?: string;
welcomeMessage?: string;
password?: string;
maxClients?: number;
hostmessage?: string;
hostmessageMode?: string;
hostbannerUrl?: string;
hostbannerGfxUrl?: string;
hostbannerGfxIntervalSecs?: number;
hostbannerMode?: string;
hostbuttonTooltip?: string;
hostbuttonUrl?: string;
hostbuttonGfxUrl?: string;
nickname?: string;
phoneticName?: string;
codecEncryptionMode?: string;
}): Promise<void> {
this.writeLine(`serveredit ${JSON.stringify(payload)}`);
}
async getServerLog(): Promise<void> {
this.writeLine(`serverlog`);
}
async getBanList(): Promise<void> {
this.writeLine(`banlist`);
}
async deleteBan(banId: number): Promise<void> {
this.writeLine(`bandel ${banId}`);
}
async deleteAllBans(): Promise<void> {
this.writeLine(`bandelall`);
}
async getComplainList(): Promise<void> {
this.writeLine(`complainlist`);
}
async deleteComplaint(targetClientDbId: number, fromClientDbId: number): Promise<void> {
this.writeLine(`complaindel ${targetClientDbId} ${fromClientDbId}`);
}
async deleteAllComplaintsFor(targetClientDbId: number): Promise<void> {
this.writeLine(`complaindelall ${targetClientDbId}`);
}
async getOfflineMessageList(): Promise<void> {
this.writeLine(`messagelist`);
}
async getOfflineMessage(messageId: number): Promise<void> {
this.writeLine(`messageget ${messageId}`);
}
async sendOfflineMessage(clientUid: string, subject: string, message: string): Promise<void> {
const sanitize = (s: string) => s.replace(/[\r\n\t]+/g, " ").trim();
this.writeLine(`messageadd ${sanitize(clientUid)}\t${sanitize(subject)}\t${sanitize(message)}`);
}
async deleteOfflineMessage(messageId: number): Promise<void> {
this.writeLine(`messagedel ${messageId}`);
}
async markOfflineMessageRead(messageId: number): Promise<void> {
this.writeLine(`messageupdateflag ${messageId} 1`);
}
async getChannelGroupList(): Promise<void> {
this.writeLine(`channelgrouplist`);
}
async getServerGroupList(): Promise<void> {
this.writeLine(`servergrouplist`);
}
async setChannelGroup(channelGroupId: number, channelId: number, clientDbId: number): Promise<void> {
this.writeLine(`setchannelgroup ${channelGroupId} ${channelId} ${clientDbId}`);
}
async addServerGroup(serverGroupId: number, clientDbId: number): Promise<void> {
this.writeLine(`addservergroup ${serverGroupId} ${clientDbId}`);
}
async removeServerGroup(serverGroupId: number, clientDbId: number): Promise<void> {
this.writeLine(`delservergroup ${serverGroupId} ${clientDbId}`);
}
async serverQueryLogin(username: string, password: string): Promise<void> {
const u = Buffer.from(username, "utf8").toString("base64");
const p = Buffer.from(password, "utf8").toString("base64");
this.writeLine(`serverquerylogin ${u} ${p}`);
}
async getPermissionOverview(): Promise<void> {
this.writeLine(`permoverview`);
}
async getPermissionCatalog(): Promise<void> {
this.writeLine(`permissionlist`);
}
async getPermList(scope: PermScope, id1: number, id2?: number): Promise<void> {
const args = id2 !== undefined ? `${scope} ${id1} ${id2}` : `${scope} ${id1}`;
this.writeLine(`permlist ${args}`);
}
/** `negated`/`skip` only apply to the "server" and "client" scopes - the
* connector ignores extra trailing args for scopes that don't use them, so
* it's safe to always pass through what the caller gave. */
async addPermission(
scope: PermScope,
ids: number[],
permId: number,
value: number,
negated = false,
skip = false
): Promise<void> {
let args = `${scope} ${ids.join(" ")} ${permId} ${value}`;
if (scope === "server") args += ` ${negated ? 1 : 0} ${skip ? 1 : 0}`;
else if (scope === "client") args += ` ${skip ? 1 : 0}`;
this.writeLine(`permadd ${args}`);
}
async removePermission(scope: PermScope, ids: number[], permId: number): Promise<void> {
this.writeLine(`permdel ${scope} ${ids.join(" ")} ${permId}`);
}
async getFileList(channelId: number, path: string): Promise<void> {
const sanitized = (path || "/").replace(/[\r\n]+/g, " ").trim() || "/";
this.writeLine(`ftlist ${channelId} ${sanitized}`);
}
async createDirectory(channelId: number, dirname: string): Promise<void> {
const sanitized = dirname.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.writeLine(`ftmkdir ${channelId} ${sanitized}`);
}
async deleteFile(channelId: number, name: string): Promise<void> {
const sanitized = name.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.writeLine(`ftdelete ${channelId} ${sanitized}`);
}
async renameFile(channelId: number, oldName: string, newName: string): Promise<void> {
const sanitize = (s: string) => s.replace(/[\r\n\t]+/g, " ").trim();
this.writeLine(`ftrename ${channelId}\t${sanitize(oldName)}\t${sanitize(newName)}`);
}
async downloadFile(channelId: number, path: string): Promise<void> {
const sanitized = path.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.writeLine(`ftdownload ${channelId} ${sanitized}`);
}
/** `dataBase64` is the raw file content, base64-encoded - the browser reads
* the picked File as a data URL/ArrayBuffer and sends it up already encoded. */
async uploadFile(channelId: number, path: string, dataBase64: string): Promise<void> {
const sanitizedPath = path.replace(/[\r\n\t]+/g, " ").trim();
this.writeLine(`ftupload ${channelId}\t${sanitizedPath}\t${dataBase64}`);
}
/** One piece of a chunked upload (see "chunkedUpload" in GATEWAY_FEATURES).
* Pieces must arrive in order; offset 0 starts the upload and the piece
* that reaches `total` sends it. Keeps every message small, unlike
* uploadFile above, which only stays for clients from before the split. */
async uploadFileChunk(channelId: number, path: string, offset: number, total: number, dataBase64: string): Promise<void> {
if (![channelId, offset, total].every(Number.isSafeInteger)) return;
if (typeof dataBase64 !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(dataBase64)) return;
const sanitizedPath = path.replace(/[\r\n\t]+/g, " ").trim();
this.writeLine(`ftuploadchunk ${channelId}\t${offset}\t${total}\t${sanitizedPath}\t${dataBase64}`);
}
async sendChatMessage(message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`);
if (sanitized) this.writeLine(`chat ${sanitized}`);
}
async sendServerMessage(message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`serverchat ${sanitized}\n`);
if (sanitized) this.writeLine(`serverchat ${sanitized}`);
}
async sendPrivateMessage(clientId: number, message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`pm ${clientId} ${sanitized}\n`);
if (sanitized) this.writeLine(`pm ${clientId} ${sanitized}`);
}
async sendPoke(clientId: number, message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
this.child?.stdin.write(`poke ${clientId} ${sanitized}\n`);
this.writeLine(`poke ${clientId} ${sanitized}`);
}
async sendAudio(pcmBase64: string): Promise<void> {
this.child?.stdin.write(`audio ${pcmBase64}\n`);
this.writeLine(`audio ${pcmBase64}`);
}
async disconnect(): Promise<void> {
if (this.child && !this.child.killed) {
this.child.stdin.write("disconnect\n");
this.child.stdin.end();
/** Pulls a streaming client's stream details; answered with a
* `notifystreaminfo` streamEvent carrying the stream id. */
async requestStreamInfo(clientId: number): Promise<void> {
this.writeLine(`streaminfo ${clientId}`);
}
/** Ask the client publishing a TS6 stream to let us watch. The answer comes
* back as a `streamEvent` of type `notifyrespondjoinstreamrequest`, which
* carries the SDP offer. */
async joinStream(streamId: string, clientId: number, message = ""): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (id) this.writeLine(`streamjoin ${id} ${clientId} ${sanitized}`);
}
async leaveStream(streamId: string, clientId: number): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
if (id) this.writeLine(`streamleave ${id} ${clientId}`);
}
/** Relays one signaling payload (SDP answer, ICE candidate) to a stream peer.
* `payload` is passed straight through - the connector only escapes it for
* the TS wire, nobody in this path interprets it. Serializing here rather
* than accepting a string keeps literal newlines out of the line-based
* stdin protocol. */
async sendStreamSignal(streamId: string, clientId: number, payload: unknown): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
if (id) this.writeLine(`streamsignal ${id} ${clientId} ${JSON.stringify(payload)}`);
}
/** Announces a stream we publish. The server assigns the id and reports it
* back as a `notifystreamstarted` streamEvent naming our own client id. */
async setupStream(options: StreamSetupOptions): Promise<void> {
const payload = {
name: options.name.replace(/[\r\n]+/g, " ").trim() || "Stream",
type: options.type,
bitrate: options.bitrate,
accessibility: options.accessibility,
mode: options.mode,
viewerLimit: options.viewerLimit,
audio: options.audio,
};
this.writeLine(`streamsetup ${JSON.stringify(payload)}`);
}
/** Accepts or refuses a viewer that asked to watch our stream. On accept,
* `offer` is our SDP - the publisher offers, which is the mirror of how a
* TS6 publisher answered us. JSON-encoded because an SDP is multi-line. */
async respondJoinStream(
streamId: string,
clientId: number,
accept: boolean,
offer = "",
message = "",
): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
if (!id) return;
const payload = {
id,
clid: clientId,
msg: message.replace(/[\r\n]+/g, " ").trim(),
offer,
decision: accept ? 1 : 0,
};
this.writeLine(`streamrespond ${JSON.stringify(payload)}`);
}
async stopStream(streamId: string, reason = ""): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
if (id) this.writeLine(`streamstop ${id} ${sanitized}`);
}
async setAway(away: boolean, message: string): Promise<void> {
if (away) {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
this.writeLine(`away ${sanitized}`);
} else {
this.writeLine("unaway");
}
}
async setInputMuted(muted: boolean): Promise<void> {
this.writeLine(`muteinput ${muted ? "1" : "0"}`);
}
async setOutputMuted(muted: boolean): Promise<void> {
this.writeLine(`muteoutput ${muted ? "1" : "0"}`);
}
/** Playback volume for one speaker, mixed in the connector (1 = unchanged). */
setClientVolume(clientId: number, volume: number): void {
if (Number.isInteger(clientId) && Number.isFinite(volume)) this.writeLine(`clientvolume ${clientId} ${volume}`);
}
async setNickname(nickname: string): Promise<void> {
const sanitized = nickname.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.writeLine(`nickname ${sanitized}`);
}
/** Incoming whispers: allowed or blocked by default; `exceptions` (client ids) get the opposite. */
setWhisperPolicy(block: boolean, exceptions: unknown[]): void {
const ids = exceptions.map(Number).filter(Number.isInteger);
this.writeLine(`whisperpolicy ${block ? "block" : "allow"};${ids.join(",")}`);
}
/** File transfer bandwidth caps in bytes/s, 0 = unlimited. */
setTransferLimit(up: unknown, down: unknown): void {
const rate = (v: unknown) => Math.max(0, Math.floor(Number(v) || 0));
this.writeLine(`ftlimit ${rate(up)} ${rate(down)}`);
}
/** Empty channelIds/clientIds clears whisper mode, returning outgoing
* voice to the normal current-channel broadcast. */
async setWhisperTargets(channelIds: number[], clientIds: number[]): Promise<void> {
const chans = channelIds.map(Number);
const clients = clientIds.map(Number);
if (chans.some((n) => !Number.isFinite(n)) || clients.some((n) => !Number.isFinite(n))) return;
if (chans.length === 0 && clients.length === 0) {
this.writeLine("unwhisper");
} else {
this.writeLine(`whisper ${chans.join(",")};${clients.join(",")}`);
}
}
async disconnect(message = ""): Promise<void> {
// childGone means the "exit" event already fired - which happens exactly
// once, so a .once("exit", ...) listener attached only now (below) would
// never see it, and this would always fall through to the 3s hard-kill
// timeout for a process that's already gone. Skip straight past it.
if (this.child && !this.child.killed && !this.childGone) {
const child = this.child;
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
child.stdin.write(`disconnect ${sanitized}\n`);
child.stdin.end();
// Wait for the connector process to actually exit before returning, so a
// caller that immediately reconnects (index.ts's "connect" handler) never
// spawns a replacement while this one is still shutting down - two
// connector processes would otherwise briefly hold the same audio/socket
// resources. Fall back to a hard kill if it doesn't exit on its own.
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
child.kill();
resolve();
}, 3000);
child.once("exit", () => {
clearTimeout(timeout);
resolve();
});
});
}
this.listeners.clear();
}
+50
View File
@@ -0,0 +1,50 @@
// Optional Cloudflare Turnstile bot check before a "connect". Off unless both
// TURNSTILE_SITE_KEY and TURNSTILE_SECRET are set. A solved check earns a
// signed pass (bound to the client IP, valid PASS_TTL_MS) that later connects
// and silent reconnects present instead, so a real user sees the check at
// most once in that window.
import { createHmac, timingSafeEqual } from "node:crypto";
// Read at use time: the admin panel (config.ts) can change both at runtime.
export const turnstileSiteKey = () => process.env.TURNSTILE_SITE_KEY ?? "";
const secret = () => process.env.TURNSTILE_SECRET ?? "";
export const turnstileEnabled = () => turnstileSiteKey() !== "" && secret() !== "";
const PASS_TTL_MS = 12 * 60 * 60 * 1000;
// Derived from the secret, so passes survive a gateway restart.
const passKey = () => createHmac("sha256", secret()).update("webspeak3-turnstile-pass").digest();
const sign = (ip: string, expires: number) =>
createHmac("sha256", passKey()).update(`${ip}|${expires}`).digest("base64url");
export function issuePass(ip: string): string {
const expires = Date.now() + PASS_TTL_MS;
return `${expires}.${sign(ip, expires)}`;
}
export function isValidPass(pass: unknown, ip: string): boolean {
if (typeof pass !== "string") return false;
const [exp, mac] = pass.split(".");
const expires = Number(exp);
if (!Number.isFinite(expires) || expires < Date.now() || !mac) return false;
const expected = Buffer.from(sign(ip, expires));
const given = Buffer.from(mac);
return given.length === expected.length && timingSafeEqual(given, expected);
}
export async function verifyToken(token: unknown, ip: string): Promise<boolean> {
if (typeof token !== "string" || token.length === 0 || token.length > 2048) return false;
try {
const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST",
body: new URLSearchParams({ secret: secret(), response: token, remoteip: ip }),
signal: AbortSignal.timeout(10_000),
});
const data = (await res.json()) as { success?: boolean; "error-codes"?: string[] };
if (!data.success) console.warn(`[turnstile] rejected: ${(data["error-codes"] ?? []).join(",")}`);
return data.success === true;
} catch (err) {
console.warn(`[turnstile] siteverify failed: ${err}`);
return false;
}
}
+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 });
}
});
+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 });
}
});
+70
View File
@@ -0,0 +1,70 @@
import os
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
BASE_URL = os.environ.get("BASE_URL", "https://client.webspeak3.de/")
RESULTS = Path("test-results")
RESULTS.mkdir(exist_ok=True)
def wait_for_text(driver: webdriver.Safari, selector: str, text: str) -> None:
WebDriverWait(driver, 15).until(
lambda current: text in current.find_element(By.CSS_SELECTOR, selector).text
)
def check_page(driver: webdriver.Safari, width: int, height: int, label: str) -> None:
driver.set_window_size(width, height)
driver.get(BASE_URL)
wait_for_text(driver, ".ts-app-title", "WebSpeak3")
assert "WebSpeak3" in driver.title
capabilities = driver.execute_script(
"""
return {
secureContext: window.isSecureContext,
mediaDevices: Boolean(navigator.mediaDevices),
getUserMedia: typeof navigator.mediaDevices?.getUserMedia === 'function',
audioContext: typeof (window.AudioContext || window.webkitAudioContext) === 'function',
webSocket: typeof window.WebSocket === 'function'
};
"""
)
assert capabilities["secureContext"]
assert capabilities["mediaDevices"]
assert capabilities["getUserMedia"]
assert capabilities["audioContext"]
assert capabilities["webSocket"]
connections_menu = driver.find_element(By.CSS_SELECTOR, ".ts-menubar-dropdown .ts-menubar-item")
driver.execute_script("arguments[0].click()", connections_menu)
connect_item = WebDriverWait(driver, 10).until(
lambda current: current.find_element(By.CSS_SELECTOR, ".ts-menu .ts-menu-item")
)
driver.execute_script("arguments[0].click()", connect_item)
dialog = WebDriverWait(driver, 10).until(
lambda current: current.find_element(By.CSS_SELECTOR, ".ts-connect-dialog")
)
assert dialog.is_displayed()
assert len(dialog.find_elements(By.CSS_SELECTOR, "input")) >= 3
driver.save_screenshot(str(RESULTS / f"safari-client-{label}.png"))
def main() -> None:
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
try:
check_page(driver, 1440, 1000, "desktop")
check_page(driver, 390, 844, "mobile")
finally:
driver.quit()
if __name__ == "__main__":
main()
+1
View File
@@ -9,6 +9,7 @@ lerna-debug.log*
node_modules
dist
dist-demo
dist-ssr
*.local
+24 -2
View File
@@ -2,9 +2,31 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png" />
<link rel="icon" type="image/png" sizes="192x192" href="/favicon-192.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
<meta name="theme-color" content="#03060d" />
<!-- iOS ignores most of the Web App Manifest — these are the fields it
actually reads for "Add to Home Screen" (standalone display, status
bar style, home-screen title). -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="WebSpeak3" />
<title>WebSpeak3</title>
<meta name="description" content="WebSpeak3 — an independent, self-hosted web client for TeamSpeak 3 servers." />
<meta property="og:type" content="website" />
<meta property="og:title" content="WebSpeak3" />
<meta property="og:description" content="An independent, self-hosted web client for TeamSpeak 3 servers." />
<meta property="og:url" content="https://client.webspeak3.de/" />
<meta property="og:image" content="https://client.webspeak3.de/og-image.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="WebSpeak3" />
<meta name="twitter:description" content="An independent, self-hosted web client for TeamSpeak 3 servers." />
<meta name="twitter:image" content="https://client.webspeak3.de/og-image.png" />
</head>
<body>
<div id="root"></div>
+5297 -57
View File
File diff suppressed because it is too large. Load diff
+8 -2
View File
@@ -1,15 +1,20 @@
{
"name": "web",
"name": "webspeak3-web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"predev": "node scripts/sync-aec3-assets.mjs",
"dev": "vite",
"prebuild": "node scripts/sync-aec3-assets.mjs",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@ennuicastr/webrtcaec3.js": "^0.3.0",
"fflate": "^0.8.3",
"qrcode-generator": "^1.4.4",
"react": "^19.2.7",
"react-dom": "^19.2.7"
},
@@ -20,6 +25,7 @@
"@vitejs/plugin-react": "^6.0.3",
"oxlint": "^1.71.0",
"typescript": "~6.0.2",
"vite": "^8.1.1"
"vite": "^8.1.1",
"vite-plugin-pwa": "^1.3.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

Before

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 KiB

+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Generates every derived favicon/OG-image size from the single source logo
# at web/public/logo.png. Requires ImageMagick (`magick` on the PATH).
#
# Usage: run from web/ after dropping the source logo at public/logo.png:
# bash scripts/generate-icons.sh
set -euo pipefail
cd "$(dirname "$0")/.."
SRC=public/logo.png
if [ ! -f "$SRC" ]; then
echo "Missing $SRC - drop the source logo there first (square PNG, >=512x512, transparent background)." >&2
exit 1
fi
magick "$SRC" -resize 32x32 public/favicon-32.png
magick "$SRC" -resize 192x192 public/favicon-192.png
magick "$SRC" -resize 180x180 -background white -alpha remove -alpha off public/apple-touch-icon.png
magick "$SRC" -define icon:auto-resize=16,32,48 public/favicon.ico
magick "$SRC" -resize 400x400 -background "#1e1e1e" -gravity center -extent 1200x630 public/og-image.png
echo "Generated favicon-32.png, favicon-192.png, apple-touch-icon.png, favicon.ico, og-image.png in public/"
+20
View File
@@ -0,0 +1,20 @@
// Copies the AEC3 WASM module's prebuilt assets into public/vendor/ so they're
// served unhashed, at the exact filenames the module's own glue code expects
// (it resolves its .wasm next to its own <script src> by a hardcoded literal
// name - see web/src/aec3.ts). Run via predev/prebuild rather than committed,
// so the binary blobs never enter git.
import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const webRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const pkgDir = path.join(webRoot, "node_modules/@ennuicastr/webrtcaec3.js");
const { version } = JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8"));
const outDir = path.join(webRoot, "public/vendor");
mkdirSync(outDir, { recursive: true });
// The .js is renamed to a stable name (we choose its <script src>, so nothing
// depends on this filename); the .wasm keeps its exact original name (the glue
// code's own lookup is hardcoded to it).
copyFileSync(path.join(pkgDir, "dist", `webrtcaec3-${version}.js`), path.join(outDir, "webrtcaec3.js"));
copyFileSync(path.join(pkgDir, "dist", `webrtcaec3-${version}.wasm`), path.join(outDir, `webrtcaec3-${version}.wasm`));
+5418 -18
View File
File diff suppressed because it is too large. Load diff
+14518 -335
View File
File diff suppressed because it is too large. Load diff
+72
View File
@@ -0,0 +1,72 @@
import { useT } from "./i18n";
export type ConnectionTabItem = {
id: string;
label: string;
connected?: boolean;
connecting?: boolean;
};
/** Server tab strip for multi-join: one tab per open connection. */
export function ConnectionTabs({
tabs,
activeTabId,
onSelectTab,
onCloseTab,
}: {
tabs: ConnectionTabItem[];
activeTabId?: string | null;
onSelectTab?: (id: string) => void;
onCloseTab?: (id: string) => void;
}) {
const t = useT();
return (
<div
className="gts-connection-tabs"
role="tablist"
aria-label={t("tabs.connections")}
>
{tabs.map((tab) => {
const isActive = tab.id === (activeTabId ?? tabs[0]?.id);
return (
<div
key={tab.id}
role="tab"
aria-selected={isActive}
className={`gts-connection-tab${isActive ? " gts-connection-tab-active" : ""}${
tab.connecting ? " gts-connection-tab-connecting" : ""
}`}
onClick={() => onSelectTab?.(tab.id)}
tabIndex={0}
aria-keyshortcuts={onCloseTab ? "Delete" : undefined}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
// The × below is mouse-only (a button can't sit inside a tab); Delete closes.
if (e.key === "Delete" && onCloseTab) onCloseTab(tab.id);
else if (e.key === "Enter" || e.key === " ")
onSelectTab?.(tab.id);
else return;
e.preventDefault();
}}
title={tab.label}
>
<span className="gts-connection-tab-label">{tab.label}</span>
{onCloseTab ? (
<span
className="gts-connection-tab-close"
aria-hidden="true"
title={t("tabs.disconnect")}
onClick={(e) => {
e.stopPropagation();
onCloseTab(tab.id);
}}
>
×
</span>
) : null}
</div>
);
})}
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
// Lazy loader for Google WebRTC's AEC3 (compiled to WASM via
// @ennuicastr/webrtcaec3.js), an opt-in, stronger alternative to the browser's
// native echo cancellation for speaker+mic (no headset) setups where native
// AEC often isn't enough (github.com/WebSpeak3/webspeak3 issue #2). Loaded as a
// plain <script> tag rather than bundled: the module's own glue code resolves
// its .wasm file next to its own <script src>, by a name it decides itself -
// see scripts/sync-aec3-assets.mjs for how that file gets there.
export interface Aec3Instance {
free(): void;
analyze(data: Float32Array[]): void;
processSize(data: Float32Array[]): number;
process(out: Float32Array[], data: Float32Array[]): void;
}
interface Aec3Module {
AEC3: new (sampleRate: number, renderChannels: number, captureChannels: number) => Aec3Instance;
}
declare global {
interface Window {
WebRtcAec3?: () => Promise<Aec3Module>;
}
}
let modulePromise: Promise<Aec3Module> | null = null;
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const el = document.createElement("script");
el.src = src;
el.onload = () => resolve();
el.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.appendChild(el);
});
}
function loadModule(): Promise<Aec3Module> {
if (!modulePromise) {
// BASE_URL keeps sub-path deployments (VITE_BASE_PATH) working; a failed
// load is forgotten so the next attempt retries instead of reusing it.
modulePromise = loadScript(`${import.meta.env.BASE_URL}vendor/webrtcaec3.js`)
.then(() => {
if (!window.WebRtcAec3) throw new Error("AEC3 script loaded but did not register window.WebRtcAec3");
return window.WebRtcAec3();
})
.catch((err) => {
modulePromise = null;
throw err;
});
}
return modulePromise;
}
/** Creates a fresh AEC3 instance. `renderChannels` must match the channel
* count passed to `analyze()`, `captureChannels` the count passed to
* `process()`. */
export async function createAec3(
sampleRate: number,
renderChannels: number,
captureChannels: number,
): Promise<Aec3Instance> {
const mod = await loadModule();
return new mod.AEC3(sampleRate, renderChannels, captureChannels);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+93
View File
@@ -0,0 +1,93 @@
Copyright 2018 The Manrope Project Authors (https://github.com/googlefonts/manrope)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2011, The VT323 Project Authors (peter.hull@oikoi.com)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+84
View File
@@ -0,0 +1,84 @@
/** Options -> Chat ("Chat Fenster", "Automatisch protokollieren", ...). */
export interface ChatSettings {
/** Lines kept per chat tab. */
maxLines: number;
/** "" = the design's font. */
fontFamily: string;
/** px, 0 = the design's size. */
fontSize: number;
logChannel: boolean;
logPrivate: boolean;
logServer: boolean;
/** Prefill a new channel chat / private chat with this many logged lines (0 = off). */
restoreChannelLines: number;
restorePrivateLines: number;
notifyServer: boolean;
notifyChannel: boolean;
notifyPrivate: boolean;
}
export const DEFAULT_CHAT_SETTINGS: ChatSettings = {
maxLines: 500,
fontFamily: "",
fontSize: 0,
logChannel: true,
logPrivate: true,
logServer: true,
restoreChannelLines: 100,
restorePrivateLines: 100,
notifyServer: false,
notifyChannel: true,
notifyPrivate: true,
};
const SETTINGS_KEY = "webspeak3:chat-settings";
export function loadChatSettings(): ChatSettings {
try {
return { ...DEFAULT_CHAT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "{}") };
} catch {
return DEFAULT_CHAT_SETTINGS;
}
}
export function saveChatSettings(settings: ChatSettings): void {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}
export interface LoggedLine {
from: string;
message: string;
self?: boolean;
at: number;
}
// ponytail: localStorage, 1000 lines per chat. Move to IndexedDB if logs outgrow the ~5 MB quota.
const MAX_LOGGED = 1000;
/** kind: "channel" | "server" | "pm:<uid>" */
const logKey = (server: string, kind: string) => `webspeak3:chatlog:${server.trim().toLowerCase()}:${kind}`;
export function readChatLog(server: string, kind: string, lines: number): LoggedLine[] {
if (!lines) return [];
try {
const all: LoggedLine[] = JSON.parse(localStorage.getItem(logKey(server, kind)) ?? "[]");
return all.slice(-lines);
} catch {
return [];
}
}
export function appendChatLog(server: string, kind: string, line: Omit<LoggedLine, "at">): void {
try {
const all = readChatLog(server, kind, MAX_LOGGED);
all.push({ ...line, at: Date.now() });
localStorage.setItem(logKey(server, kind), JSON.stringify(all.slice(-MAX_LOGGED)));
} catch {
// Quota full: logging is best effort.
}
}
/** Keeps the newest `max` entries. */
export function capLines<T>(lines: T[], max: number): T[] {
return lines.length > max ? lines.slice(-max) : lines;
}
+336
View File
@@ -0,0 +1,336 @@
/**
* Multi-join session bookkeeping. The active tab keeps its UI in React state
* (App.tsx); inactive tabs park a snapshot here and keep their WebSocket alive.
* Audio is intentionally active-tab-only (see README / known limits).
*/
export type ConnectionSessionId = string;
export type SelectedItem =
| { type: "server" }
| { type: "channel"; id: number }
| { type: "client"; id: number };
export type ChatEntry = { from: string; message: string; isLog?: boolean };
export type PmMessage = { fromSelf: boolean; message: string };
export type PmThread = {
partnerId: number;
partnerName: string;
messages: PmMessage[];
unread: boolean;
};
export type ActiveChatTab = "channel" | "server" | number;
export type PokeNotice = { id: number; from: string; message: string };
export type LogEntry = { text: string; kind: "info" | "error" };
export type ChannelInfo = {
id: number;
parent: number;
order: number;
name: string;
topic: string;
codec: string;
maxClients: number | null;
hasPassword: boolean;
};
export type ClientInfo = {
id: number;
channel: number;
name: string;
inputMuted: boolean;
outputMuted: boolean;
inputHardwareEnabled: boolean;
away: boolean;
awayMessage: string;
isChannelCommander: boolean;
country: string;
uid: string;
databaseId: number;
channelGroup: number;
serverGroups: number[];
hasTalkPower: boolean;
/** ServerQuery client; hidden in the tree unless the favorite enables them. */
isQuery?: boolean;
};
export type WhisperLogEntry = {
id: number;
timestamp: number;
description: string;
};
/** Snapshot of per-connection UI state for a parked (inactive) tab. */
export type ParkedSessionState = {
host: string;
nickname: string;
connected: boolean;
connecting: boolean;
connectError: string | null;
channels: ChannelInfo[];
clients: ClientInfo[];
ownClientId: number | null;
serverName: string;
serverMaxClients: number;
serverClientsOnline: number;
serverChannelsOnline: number;
serverVersion: string;
serverLicense: string;
serverLicenseId: number;
serverBannerUrl: string;
serverWelcomeMessage: string;
selected: SelectedItem | null;
chat: ChatEntry[];
serverChat: ChatEntry[];
pmThreads: Record<number, PmThread>;
pokes: PokeNotice[];
chatTab: ActiveChatTab;
talkers: number[];
whisperChannelIds: number[];
whisperClientIds: number[];
whisperLog: WhisperLogEntry[];
log: LogEntry[];
hasConnected: boolean;
previousClients: ClientInfo[] | null;
/** Whether the mic was on for this tab when it was parked, so switching back restores it. */
micWasOn: boolean;
/** Favorite used to open this session (drives ServerQuery visibility). */
favoriteId: string | null;
};
export type SessionTabInfo = {
id: ConnectionSessionId;
label: string;
connected: boolean;
connecting: boolean;
};
export type SessionSocket = WebSocket | { close: () => void; readyState: number; send: (data: string) => void };
export type SessionRecord = {
id: ConnectionSessionId;
socket: SessionSocket | null;
/** null while this session is the active React UI. */
parked: ParkedSessionState | null;
};
export function emptyParkedState(partial?: Partial<ParkedSessionState>): ParkedSessionState {
return {
host: "",
nickname: "",
connected: false,
connecting: false,
connectError: null,
channels: [],
clients: [],
ownClientId: null,
serverName: "",
serverMaxClients: 0,
serverClientsOnline: 0,
serverChannelsOnline: 0,
serverVersion: "",
serverLicense: "",
serverLicenseId: 0,
serverBannerUrl: "",
serverWelcomeMessage: "",
selected: null,
chat: [],
serverChat: [],
pmThreads: {},
pokes: [],
chatTab: "channel",
talkers: [],
whisperChannelIds: [],
whisperClientIds: [],
whisperLog: [],
log: [],
hasConnected: false,
previousClients: null,
micWasOn: false,
favoriteId: null,
...partial,
};
}
export function sessionLabel(state: Pick<ParkedSessionState, "serverName" | "host">): string {
const name = state.serverName.trim() || state.host.trim();
return name || "…";
}
/** Apply a gateway event to a parked session. Returns whether the tab label may have changed. */
export function applyParkedGatewayEvent(
state: ParkedSessionState,
data: { type: string; [key: string]: unknown },
opts: { connectNickname: string; chatTab: ActiveChatTab }
): { state: ParkedSessionState; labelChanged: boolean } {
let labelChanged = false;
switch (data.type) {
case "connected": {
const serverName = String(data.serverName ?? "");
labelChanged = serverName !== state.serverName;
return {
labelChanged,
state: {
...state,
connecting: false,
connectError: null,
connected: true,
hasConnected: true,
serverName,
serverMaxClients: Number(data.serverMaxClients) || 0,
serverClientsOnline: 0,
serverChannelsOnline: 0,
serverVersion: String(data.serverVersion ?? ""),
serverLicense: String(data.serverLicense ?? ""),
serverLicenseId: typeof data.serverLicenseId === "number" ? data.serverLicenseId : 0,
serverBannerUrl: String(data.serverBannerUrl ?? ""),
serverWelcomeMessage: String(data.welcomeMessage ?? ""),
selected: { type: "server" },
serverChat: [
...state.serverChat,
{ from: "Server", message: String(data.welcomeMessage ?? "") },
],
previousClients: null,
},
};
}
case "channels": {
const newClients = (data.clients as ClientInfo[]) ?? [];
const ownClientId =
typeof data.ownClientId === "number" && data.ownClientId > 0
? data.ownClientId
: state.ownClientId;
return {
labelChanged: false,
state: {
...state,
channels: (data.channels as ChannelInfo[]) ?? state.channels,
clients: newClients,
ownClientId,
serverMaxClients:
typeof data.serverMaxClients === "number" && data.serverMaxClients > 0
? data.serverMaxClients
: state.serverMaxClients,
serverClientsOnline:
typeof data.serverClientsOnline === "number" && data.serverClientsOnline >= 0
? data.serverClientsOnline
: state.serverClientsOnline,
serverChannelsOnline:
typeof data.serverChannelsOnline === "number" && data.serverChannelsOnline >= 0
? data.serverChannelsOnline
: state.serverChannelsOnline,
previousClients: newClients,
},
};
}
case "chatMessage":
return {
labelChanged: false,
state: {
...state,
chat: [...state.chat, { from: String(data.from), message: String(data.message) }],
},
};
case "serverMessage":
return {
labelChanged: false,
state: {
...state,
serverChat: [
...state.serverChat,
{ from: String(data.from), message: String(data.message) },
],
},
};
case "privateMessage": {
const partnerId = Number(data.partnerId);
const existing = state.pmThreads[partnerId];
const thread: PmThread = existing ?? {
partnerId,
partnerName: String(data.partnerName),
messages: [],
unread: false,
};
return {
labelChanged: false,
state: {
...state,
pmThreads: {
...state.pmThreads,
[partnerId]: {
...thread,
partnerName: String(data.partnerName),
messages: [
...thread.messages,
{ fromSelf: Boolean(data.fromSelf), message: String(data.message) },
],
unread:
thread.unread || (!data.fromSelf && opts.chatTab !== partnerId),
},
},
},
};
}
case "talkers":
return {
labelChanged: false,
state: {
...state,
talkers: Array.isArray(data.clients) ? (data.clients as number[]) : [],
},
};
case "poke": {
const id = Date.now() + Math.floor(Math.random() * 1000);
return {
labelChanged: false,
state: {
...state,
pokes: [
...state.pokes,
{ id, from: String(data.from), message: String(data.message ?? "") },
],
},
};
}
case "disconnected":
return {
labelChanged: true,
state: {
...emptyParkedState({
host: state.host,
nickname: state.nickname,
}),
connecting: false,
connected: false,
hasConnected: false,
log: [
...state.log,
{ text: `Disconnected: ${String(data.reason ?? "")}`, kind: "info" },
],
},
};
case "error":
if (state.hasConnected) {
return {
labelChanged: false,
state: {
...state,
log: [...state.log, { text: String(data.message), kind: "error" }],
},
};
}
return {
labelChanged: false,
state: {
...state,
connecting: false,
connectError: String(data.message),
},
};
case "audioOut":
// Background tabs never play audio (active-tab-only shortcut).
return { state, labelChanged: false };
default:
return { state, labelChanged: false };
}
}
+782
View File
@@ -0,0 +1,782 @@
// Standalone frontend demo: no gateway, no real TeamSpeak server. Everything
// below simulates the WebSocket protocol the real gateway speaks (see
// gateway/src/index.ts) so App.tsx doesn't need to know it isn't talking to
// a real backend. Only enabled in the GitHub Pages build (VITE_DEMO_MODE=true)
// so the normal Docker image is completely unaffected.
export const DEMO_MODE = import.meta.env.VITE_DEMO_MODE === "true";
export const DEMO_HOST = "demo.webspeak3.example";
interface DemoChannel {
id: number;
parent: number;
order: number;
name: string;
topic: string;
codec: string;
maxClients: number | null;
hasPassword: boolean;
}
interface DemoClient {
id: number;
channel: number;
name: string;
inputMuted: boolean;
outputMuted: boolean;
inputHardwareEnabled: boolean;
away: boolean;
awayMessage: string;
isChannelCommander: boolean;
country: string;
uid: string;
databaseId: number;
channelGroup: number;
serverGroups: number[];
hasTalkPower: boolean;
}
const DEMO_CHANNELS: DemoChannel[] = [
{ id: 1, parent: 0, order: 0, name: "Lobby", topic: "Welcome to the WebSpeak3 demo!", codec: "Opus Voice", maxClients: null, hasPassword: false },
{ id: 2, parent: 0, order: 1, name: "Gaming", topic: "", codec: "Opus Voice", maxClients: 10, hasPassword: false },
{ id: 4, parent: 2, order: 0, name: "Squad 1", topic: "", codec: "Opus Voice", maxClients: 5, hasPassword: false },
{ id: 5, parent: 2, order: 1, name: "Squad 2", topic: "", codec: "Opus Voice", maxClients: 5, hasPassword: false },
{ id: 6, parent: 0, order: 2, name: "Music", topic: "Requests in chat", codec: "Opus Music", maxClients: null, hasPassword: false },
{ id: 7, parent: 0, order: 3, name: "Talk", topic: "", codec: "Opus Voice", maxClients: null, hasPassword: false },
{ id: 8, parent: 7, order: 0, name: "Meeting Room", topic: "Password: ask an admin", codec: "Opus Voice", maxClients: 8, hasPassword: true },
{ id: 3, parent: 0, order: 4, name: "AFK", topic: "", codec: "Opus Voice", maxClients: null, hasPassword: false },
];
const DEMO_CHANNEL_GROUPS = [
{ id: 1, name: "Channel Admin", iconId: 0 },
{ id: 2, name: "Operator", iconId: 0 },
{ id: 3, name: "Voice", iconId: 0 },
{ id: 4, name: "Guest", iconId: 0 },
];
const DEMO_SERVER_GROUPS = [
{ id: 1, name: "Server Admin", iconId: 0 },
{ id: 2, name: "Moderator", iconId: 0 },
{ id: 3, name: "Trusted", iconId: 0 },
{ id: 4, name: "Guest", iconId: 0 },
];
const DEMO_NPCS: DemoClient[] = [
{ id: 102, channel: 1, name: "Alex", inputMuted: false, outputMuted: false, inputHardwareEnabled: true, away: false, awayMessage: "", isChannelCommander: true, country: "US", uid: "demo-uid-alex", databaseId: 2, channelGroup: 2, serverGroups: [2], hasTalkPower: true },
{ id: 103, channel: 2, name: "Sam", inputMuted: false, outputMuted: false, inputHardwareEnabled: true, away: false, awayMessage: "", isChannelCommander: false, country: "GB", uid: "demo-uid-sam", databaseId: 3, channelGroup: 4, serverGroups: [4], hasTalkPower: true },
{ id: 104, channel: 2, name: "Jordan", inputMuted: true, outputMuted: false, inputHardwareEnabled: true, away: false, awayMessage: "", isChannelCommander: false, country: "CA", uid: "demo-uid-jordan", databaseId: 4, channelGroup: 4, serverGroups: [4], hasTalkPower: true },
{ id: 105, channel: 3, name: "Riley", inputMuted: false, outputMuted: false, inputHardwareEnabled: true, away: true, awayMessage: "brb, grabbing coffee", isChannelCommander: false, country: "DE", uid: "demo-uid-riley", databaseId: 5, channelGroup: 4, serverGroups: [3, 4], hasTalkPower: true },
];
interface DemoFileEntry {
path: string;
name: string;
size: number;
isFile: boolean;
timestamp: string;
}
/** Keyed by "<channelId>:<path>" - a tiny in-memory filesystem so the
* channel file browser has something real to navigate/mutate in the demo. */
const DEMO_FILES: Record<string, DemoFileEntry[]> = {
"1:/": [
{ path: "/", name: "readme.txt", size: 182, isFile: true, timestamp: "2024-01-01 12:00:00" },
{ path: "/", name: "Musik", size: 0, isFile: false, timestamp: "2024-01-01 12:00:00" },
],
"1:/Musik": [
{ path: "/Musik", name: "lobby-theme.mp3", size: 4 * 1024 * 1024, isFile: true, timestamp: "2024-01-02 09:30:00" },
],
"2:/": [],
"3:/": [],
// Channel 0 is TS3's special server-wide icon repository, not a real channel.
"0:/": [
{ path: "/", name: "icon_100", size: 68, isFile: true, timestamp: "2024-01-01 12:00:00" },
{ path: "/", name: "icon_200", size: 68, isFile: true, timestamp: "2024-01-01 12:00:00" },
],
};
// A tiny 1x1 transparent PNG, reused as the fake image data for every demo icon.
const DEMO_ICON_PNG_BASE64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
function demoFileKey(channelId: number, path: string): string {
return `${channelId}:${path}`;
}
function demoNowTimestamp(): string {
return new Date().toISOString().slice(0, 19).replace("T", " ");
}
interface DemoPermEntry {
name: string;
description: string;
value: number;
negated: boolean;
skip: boolean;
}
// A small fake permission catalog (real TS3 servers expose ~500 of these) -
// enough for the permissions editor's "add permission" picker to be usable.
const DEMO_PERMISSION_CATALOG: { id: number; name: string; description: string }[] = [
{ id: 1, name: "b_client_info_view", description: "View own client info" },
{ id: 2, name: "b_client_permissionoverview_view", description: "View permission overview" },
{ id: 3, name: "i_channel_join_power", description: "Power to join channels" },
{ id: 4, name: "i_client_talk_power", description: "Talk power" },
{ id: 5, name: "b_client_use_priority_speaker", description: "Use priority speaker" },
{ id: 6, name: "i_client_max_channel_subscriptions", description: "Max channel subscriptions" },
{ id: 7, name: "b_channel_join_permanent", description: "Join permanent channels" },
{ id: 8, name: "b_client_kick_from_channel", description: "Kick client from channel" },
{ id: 9, name: "b_client_kick_from_server", description: "Kick client from server" },
{ id: 10, name: "b_client_ban_client", description: "Ban client" },
{ id: 11, name: "i_channel_create_modify_power", description: "Power to create/modify channels" },
{ id: 12, name: "b_virtualserver_modify_name", description: "Modify server name" },
{ id: 13, name: "b_ft_file_upload", description: "Upload files" },
{ id: 14, name: "b_ft_file_download", description: "Download files" },
];
// Keyed by "<scope>:<id1>:<id2 ?? ->" - the fake permission set currently
// assigned to one server group / channel group / channel / client /
// channel+client combination.
const DEMO_PERM_LISTS: Record<string, DemoPermEntry[]> = {
"server:1:-": [
{ name: "b_client_kick_from_server", description: "Kick client from server", value: 1, negated: false, skip: false },
{ name: "b_client_ban_client", description: "Ban client", value: 1, negated: false, skip: false },
],
"server:4:-": [
{ name: "i_channel_join_power", description: "Power to join channels", value: 25, negated: false, skip: false },
],
"channelgroup:1:-": [
{ name: "i_channel_create_modify_power", description: "Power to create/modify channels", value: 75, negated: false, skip: false },
],
"client:1:-": [
{ name: "b_client_info_view", description: "View own client info", value: 1, negated: false, skip: false },
],
};
function demoPermKey(scope: string, id1: number, id2?: number): string {
return `${scope}:${id1}:${id2 ?? "-"}`;
}
const SELF_ID = 101;
// Random visitors that join, wander around, chat and leave again (see scriptServerLife).
const DEMO_VISITOR_NAMES = ["Mia", "Noah", "Lena", "Kai", "Zoe", "Finn", "Ava", "Leo", "Ivy", "Max"];
const DEMO_COUNTRIES = ["DE", "US", "GB", "FR", "NL", "PL", "SE", "CZ", ""];
const DEMO_CHAT_LINES = [
"hey all",
"anyone up for a round later?",
"brb, getting coffee",
"lol",
"can you hear me?",
"gg",
"my mic was muted, sorry",
"back",
"who's hosting tonight?",
"check out https://github.com/WebSpeak3/webspeak3",
];
const DEMO_PM_LINES = [
"hey, got a sec?",
"you coming to Gaming later?",
"thanks for the help earlier!",
"can you move me to Gaming?",
];
const pick = <T,>(items: T[]): T => items[Math.floor(Math.random() * items.length)];
/**
* Drop-in stand-in for a real WebSocket. Implements the subset of the
* WebSocket interface App.tsx actually uses (onopen/onmessage/onerror/
* onclose/send/close/readyState), so it can be assigned to the same
* socketRef without any changes to the event-handling code.
*/
export class DemoSocket {
onopen: ((ev: Event) => void) | null = null;
onmessage: ((ev: MessageEvent) => void) | null = null;
onerror: ((ev: Event) => void) | null = null;
onclose: ((ev: CloseEvent) => void) | null = null;
readyState: number = WebSocket.CONNECTING;
private closed = false;
private timers: number[] = [];
private selfChannel = 1;
private selfChannelGroup = 1;
private selfServerGroups = new Set<number>([1]);
constructor() {
this.after(400, () => {
this.readyState = WebSocket.OPEN;
this.onopen?.(new Event("open"));
});
}
send(raw: string) {
if (this.closed) return;
let msg: any;
try {
msg = JSON.parse(raw);
} catch {
return;
}
this.handle(msg);
}
close() {
if (this.closed) return;
// Mirrors the real gateway: a "disconnected" event arrives before the
// socket itself finishes closing (see gateway's disconnected event vs.
// the client-initiated WebSocket close in handleDisconnect).
this.emit({ type: "disconnected", reason: "client requested" });
this.closed = true;
this.readyState = WebSocket.CLOSED;
this.timers.forEach((id) => window.clearTimeout(id));
this.timers = [];
this.onclose?.({} as CloseEvent);
}
private after(ms: number, fn: () => void) {
const id = window.setTimeout(() => {
// Drop fired ids so the looping talker script doesn't grow the list forever.
this.timers = this.timers.filter((t) => t !== id);
if (this.closed) return;
fn();
}, ms);
this.timers.push(id);
}
private emit(data: unknown) {
if (this.closed) return;
this.onmessage?.({ data: JSON.stringify(data) } as MessageEvent);
}
private handle(msg: any) {
switch (msg.type) {
case "connect": {
const nickname = String(msg.nickname || "Guest").trim() || "Guest";
this.after(900, () => {
this.emit({
type: "connected",
serverName: "WebSpeak3 Demo Server",
serverMaxClients: 32,
serverVersion: "3.13.7 [Build: demo]",
serverLicense: "Demo License",
serverLicenseId: 2,
serverBannerUrl: null,
welcomeMessage: "This is a simulated demo - no real TeamSpeak server is involved. Connect with any name/address you like.",
});
this.after(150, () => this.sendChannels(nickname));
this.scriptServerLog(nickname);
this.scriptTalkers();
this.after(6000, () => this.scriptServerLife());
});
break;
}
case "switchChannel": {
const fromChannel = this.channelName(this.selfChannel);
this.selfChannel = msg.channelId;
const toChannel = this.channelName(this.selfChannel);
this.emit({
type: "serverLog",
kind: "clientChannelSwitch",
client: this.lastNickname,
fromChannel,
toChannel,
});
this.after(120, () => this.sendChannels(this.lastNickname));
break;
}
case "sendChatMessage":
this.after(80, () => this.emit({ type: "chatMessage", from: this.lastNickname, message: msg.message }));
break;
case "sendServerMessage":
this.after(80, () => this.emit({ type: "serverMessage", from: this.lastNickname, message: msg.message }));
break;
case "sendPrivateMessage": {
const partner = this.npcs().find((c) => c.id === msg.clientId);
this.after(80, () =>
this.emit({
type: "privateMessage",
partnerId: msg.clientId,
partnerName: partner?.name ?? "Unknown",
message: msg.message,
fromSelf: true,
})
);
if (partner && !partner.away) {
this.after(1500 + Math.random() * 2500, () =>
this.emit({
type: "privateMessage",
partnerId: partner.id,
partnerName: partner.name,
message: pick(["ok 👍", "haha sure", "one sec", "sounds good", "yep"]),
fromSelf: false,
})
);
}
break;
}
case "sendPoke": {
const partner = this.npcs().find((c) => c.id === msg.clientId);
this.after(400, () =>
this.emit({ type: "poke", from: partner?.name ?? "Someone", message: "(demo poke - no reply expected)" })
);
break;
}
case "moveClient": {
const clientId = Number(msg.clientId);
const channelId = Number(msg.channelId);
if (Number.isFinite(clientId) && Number.isFinite(channelId)) {
if (clientId === SELF_ID) {
this.selfChannel = channelId;
} else {
const npc = this.npcs().find((c) => c.id === clientId);
if (npc) npc.channel = channelId;
}
this.after(120, () => this.sendChannels(this.lastNickname));
}
break;
}
case "getClientConnectionInfo": {
this.after(400, () =>
this.emit({
type: "clientConnectionInfo",
clientId: msg.clientId,
pingMs: 12.4,
connectedSecs: 217,
ip: msg.clientId === SELF_ID ? "127.0.0.1" : null,
packetsSent: 4213,
bytesSent: 512_340,
packetsReceived: 3987,
bytesReceived: 498_120,
packetLossPercent: 0,
})
);
break;
}
case "getServerConnectionInfo": {
this.after(400, () =>
this.emit({
type: "serverConnectionInfo",
pingMs: 8.1,
connectedSecs: 217,
packetLossPercent: 0,
packetsSentTotal: 21_004,
bytesSentTotal: 2_411_000,
packetsReceivedTotal: 19_872,
bytesReceivedTotal: 2_198_500,
bandwidthSentLastSecond: 4200,
bandwidthReceivedLastSecond: 3900,
})
);
break;
}
case "getServerLog": {
this.after(400, () =>
this.emit({
type: "serverProtocolLog",
lines: [
"2026-08-05 10:12:03.421128|INFO |VirtualServerBase|1 |connect to server successful, connection accepted",
"2026-08-05 10:12:04.001912|INFO |VirtualServerBase|1 |client 'Guest'(id:101) connected",
"2026-08-05 10:14:19.552031|INFO |VirtualServerBase|1 |client 'Sam'(id:103) connected",
"2026-08-05 10:15:02.884120|INFO |VirtualServerBase|1 |client 'Jordan'(id:104) switched channel",
],
})
);
break;
}
case "getBanList": {
this.after(400, () =>
this.emit({
type: "banList",
entries: [
{
banId: 1,
ip: "203.0.113.42",
name: "TrollUser",
uid: "demo-uid-troll",
lastNickname: "TrollUser",
created: "2026-07-28 14:02:11",
durationSecs: 0,
invokerName: "Alex",
reason: "Spamming the server chat",
enforcements: 0,
},
{
banId: 2,
ip: "198.51.100.7",
name: "",
uid: "demo-uid-annoying",
lastNickname: "AnnoyingGuest",
created: "2026-08-01 09:44:53",
durationSecs: 3600,
invokerName: "Sam",
reason: "Repeated channel spam",
enforcements: 1,
},
],
})
);
break;
}
case "deleteBan":
case "deleteAllBans":
// No observable effect - the frontend already optimistically removes
// the deleted row(s) from its own state.
break;
case "getComplainList": {
this.after(400, () =>
this.emit({
type: "complainList",
entries: [
{
targetClientDbId: 104,
targetName: "Jordan",
fromClientDbId: 103,
fromName: "Sam",
message: "Kept talking over everyone in voice chat.",
timestamp: "2026-08-02 18:21:07",
},
],
})
);
break;
}
case "deleteComplaint":
case "deleteAllComplaintsFor":
break;
case "getOfflineMessageList": {
this.after(400, () =>
this.emit({
type: "offlineMessageList",
entries: [
{
messageId: 1,
clientUid: "demo-uid-sam",
subject: "Missed you online",
timestamp: "2026-08-03 20:11:44",
isRead: false,
},
],
})
);
break;
}
case "getOfflineMessage": {
this.after(300, () =>
this.emit({
type: "offlineMessage",
messageId: msg.messageId,
clientUid: "demo-uid-sam",
subject: "Missed you online",
message: "Hey, we were on last night in the Gaming channel - join us next time!",
timestamp: "2026-08-03 20:11:44",
})
);
break;
}
case "sendOfflineMessage":
case "deleteOfflineMessage":
case "markOfflineMessageRead":
// No observable effect - the frontend already optimistically updates
// its own state for delete/read, and there's no NPC to reply to a send.
break;
case "getChannelGroupList":
this.after(300, () => this.emit({ type: "channelGroupList", entries: DEMO_CHANNEL_GROUPS }));
break;
case "getServerGroupList":
this.after(300, () => this.emit({ type: "serverGroupList", entries: DEMO_SERVER_GROUPS }));
break;
case "setChannelGroup": {
const npc = this.npcs().find((c) => c.databaseId === msg.clientDbId);
if (npc) npc.channelGroup = msg.channelGroupId;
else if (msg.clientDbId === 1) this.selfChannelGroup = msg.channelGroupId;
this.after(200, () => this.sendChannels(this.lastNickname));
break;
}
case "addServerGroup": {
const npc = this.npcs().find((c) => c.databaseId === msg.clientDbId);
if (npc) {
if (!npc.serverGroups.includes(msg.serverGroupId)) npc.serverGroups.push(msg.serverGroupId);
} else if (msg.clientDbId === 1) {
this.selfServerGroups.add(msg.serverGroupId);
}
this.after(200, () => this.sendChannels(this.lastNickname));
break;
}
case "removeServerGroup": {
const npc = this.npcs().find((c) => c.databaseId === msg.clientDbId);
if (npc) {
npc.serverGroups = npc.serverGroups.filter((g) => g !== msg.serverGroupId);
} else if (msg.clientDbId === 1) {
this.selfServerGroups.delete(msg.serverGroupId);
}
this.after(200, () => this.sendChannels(this.lastNickname));
break;
}
case "serverQueryLogin":
// No observable effect - the demo has no real ServerQuery backend to
// authenticate against.
break;
case "getPermissionOverview": {
this.after(400, () =>
this.emit({
type: "permissionOverview",
entries: [
{ name: "b_client_info_view", description: "View own client info", value: 1, negated: false, skip: false },
{ name: "b_client_permissionoverview_view", description: "View permission overview", value: 1, negated: false, skip: false },
{ name: "i_channel_join_power", description: "Power to join channels", value: 25, negated: false, skip: false },
{ name: "i_client_talk_power", description: "Talk power", value: 25, negated: false, skip: false },
{ name: "b_client_use_priority_speaker", description: "Use priority speaker", value: 0, negated: true, skip: false },
{ name: "i_client_max_channel_subscriptions", description: "Max channel subscriptions", value: -1, negated: false, skip: false },
{ name: "b_channel_join_permanent", description: "Join permanent channels", value: 1, negated: false, skip: false },
],
})
);
break;
}
case "getPermissionCatalog": {
this.after(300, () => this.emit({ type: "permissionCatalog", entries: DEMO_PERMISSION_CATALOG }));
break;
}
case "getPermList": {
const key = demoPermKey(msg.scope, msg.id1, msg.id2);
this.after(300, () =>
this.emit({ type: "permList", scope: msg.scope, id1: msg.id1, id2: msg.id2 ?? null, entries: DEMO_PERM_LISTS[key] ?? [] })
);
break;
}
case "addPermission": {
const [id1, id2] = msg.ids as number[];
const key = demoPermKey(msg.scope, id1, id2);
const catalogEntry = DEMO_PERMISSION_CATALOG.find((p) => p.id === msg.permId);
const name = catalogEntry?.name ?? `#${msg.permId}`;
const description = catalogEntry?.description ?? "";
const list = (DEMO_PERM_LISTS[key] ?? []).filter((e) => e.name !== name);
list.push({ name, description, value: msg.value, negated: !!msg.negated, skip: !!msg.skip });
DEMO_PERM_LISTS[key] = list;
break;
}
case "removePermission": {
const [id1, id2] = msg.ids as number[];
const key = demoPermKey(msg.scope, id1, id2);
const catalogEntry = DEMO_PERMISSION_CATALOG.find((p) => p.id === msg.permId);
const name = catalogEntry?.name ?? `#${msg.permId}`;
if (DEMO_PERM_LISTS[key]) DEMO_PERM_LISTS[key] = DEMO_PERM_LISTS[key].filter((e) => e.name !== name);
break;
}
case "getFileList": {
const key = demoFileKey(msg.channelId, msg.path);
this.after(300, () =>
this.emit({ type: "fileList", cid: msg.channelId, path: msg.path, entries: DEMO_FILES[key] ?? [] })
);
break;
}
case "createDirectory": {
const dir = msg.dirname as string;
const parent = dir.slice(0, dir.lastIndexOf("/")) || "/";
const name = dir.slice(dir.lastIndexOf("/") + 1);
const parentKey = demoFileKey(msg.channelId, parent);
DEMO_FILES[parentKey] = (DEMO_FILES[parentKey] ?? []).filter((e) => e.name !== name);
DEMO_FILES[parentKey].push({ path: parent, name, size: 0, isFile: false, timestamp: demoNowTimestamp() });
DEMO_FILES[demoFileKey(msg.channelId, dir)] = [];
break;
}
case "deleteFile": {
const full = msg.name as string;
const parent = full.slice(0, full.lastIndexOf("/")) || "/";
const name = full.slice(full.lastIndexOf("/") + 1);
const parentKey = demoFileKey(msg.channelId, parent);
if (DEMO_FILES[parentKey]) DEMO_FILES[parentKey] = DEMO_FILES[parentKey].filter((e) => e.name !== name);
break;
}
case "renameFile": {
const oldFull = msg.oldName as string;
const newFull = msg.newName as string;
const parent = oldFull.slice(0, oldFull.lastIndexOf("/")) || "/";
const oldName = oldFull.slice(oldFull.lastIndexOf("/") + 1);
const newName = newFull.slice(newFull.lastIndexOf("/") + 1);
const entry = DEMO_FILES[demoFileKey(msg.channelId, parent)]?.find((e) => e.name === oldName);
if (entry) entry.name = newName;
break;
}
case "downloadFile": {
const full = msg.path as string;
const name = full.slice(full.lastIndexOf("/") + 1);
const data =
msg.channelId === 0
? DEMO_ICON_PNG_BASE64
: btoa(`This is a demo file. There is no real content behind "${name}" in WebSpeak3's demo mode.`);
this.after(400, () => this.emit({ type: "fileDownloadData", cid: msg.channelId, path: full, data }));
break;
}
case "uploadFile": {
const full = msg.path as string;
const parent = full.slice(0, full.lastIndexOf("/")) || "/";
const name = full.slice(full.lastIndexOf("/") + 1);
const parentKey = demoFileKey(msg.channelId, parent);
const sizeBytes = Math.floor(((msg.dataBase64 as string).length * 3) / 4);
DEMO_FILES[parentKey] = (DEMO_FILES[parentKey] ?? []).filter((e) => e.name !== name);
DEMO_FILES[parentKey].push({ path: parent, name, size: sizeBytes, isFile: true, timestamp: demoNowTimestamp() });
this.after(400, () => this.emit({ type: "fileUploadDone", cid: msg.channelId, path: full }));
break;
}
// "disconnect" is intentionally unhandled here: handleDisconnect() in
// App.tsx always calls socket.close() right after sending it, and
// close() already emits the "disconnected" event below.
// setAway, setInputMuted, setOutputMuted, sendAudio: no observable effect
// in a simulated single-user session, intentionally no-ops.
default:
break;
}
}
private lastNickname = "Guest";
private channelName(id: number): string {
return DEMO_CHANNELS.find((c) => c.id === id)?.name ?? "";
}
/** A short, scripted burst of Server-tab log lines so the feature is visible
* in the demo without needing a second real user to trigger them. */
private scriptServerLog(nickname: string) {
this.after(2500, () =>
this.emit({ type: "serverLog", kind: "clientJoin", client: "Sam", channel: this.channelName(2) })
);
this.after(5000, () =>
this.emit({
type: "serverLog",
kind: "clientChannelSwitch",
client: "Jordan",
fromChannel: this.channelName(2),
toChannel: this.channelName(1),
})
);
this.after(7500, () =>
this.emit({
type: "serverLog",
kind: "clientChannelGroupAssigned",
client: nickname,
group: "Channel Admin",
})
);
}
private visitors: DemoClient[] = [];
private nextVisitorId = 200;
private npcs(): DemoClient[] {
return [...DEMO_NPCS, ...this.visitors];
}
/** Random voice activity so the talking indicators (tree, speaker cards) are
* visible: every unmuted client in your channel talks now and then, sometimes
* over each other. Like real TS, only your own channel is audible. */
private scriptTalkers() {
const audible = this.npcs()
.filter(
(c) =>
c.channel === this.selfChannel &&
c.hasTalkPower &&
!c.inputMuted &&
c.inputHardwareEnabled &&
!c.away
)
.filter(() => Math.random() < 0.35)
.map((c) => c.id);
this.emit({ type: "talkers", clients: audible });
this.after(1200 + Math.random() * 2300, () => this.scriptTalkers());
}
/** One random server event every few seconds: visitors join, switch
* channels and leave, people write in the channel or send you a PM. */
private scriptServerLife() {
const roll = Math.random();
const freeNames = DEMO_VISITOR_NAMES.filter((n) => !this.visitors.some((v) => v.name === n));
if (roll < 0.3 && this.visitors.length < 6 && freeNames.length > 0) {
const id = this.nextVisitorId++;
const visitor: DemoClient = {
id,
channel: pick(DEMO_CHANNELS.filter((c) => c.id !== 3 && !c.hasPassword)).id,
name: pick(freeNames),
inputMuted: Math.random() < 0.15,
outputMuted: Math.random() < 0.1,
inputHardwareEnabled: true,
away: false,
awayMessage: "",
isChannelCommander: false,
country: pick(DEMO_COUNTRIES),
uid: `demo-uid-visitor-${id}`,
databaseId: id,
channelGroup: 3,
serverGroups: [pick([3, 4, 4])],
hasTalkPower: true,
};
this.visitors.push(visitor);
this.emit({ type: "serverLog", kind: "clientJoin", client: visitor.name, channel: this.channelName(visitor.channel) });
this.sendChannels(this.lastNickname);
} else if (roll < 0.37 && this.visitors.length > 0) {
const visitor = pick(this.visitors);
this.visitors = this.visitors.filter((v) => v !== visitor);
this.emit({ type: "serverLog", kind: "clientLeave", client: visitor.name });
this.sendChannels(this.lastNickname);
} else if (roll < 0.72) {
// Anyone wanders, not just visitors - otherwise the tree looks frozen.
const visitor = pick(this.npcs());
const target = pick(DEMO_CHANNELS.filter((c) => c.id !== visitor.channel));
this.emit({
type: "serverLog",
kind: "clientChannelSwitch",
client: visitor.name,
fromChannel: this.channelName(visitor.channel),
toChannel: target.name,
});
visitor.channel = target.id;
visitor.away = target.id === 3;
this.sendChannels(this.lastNickname);
} else if (roll < 0.92) {
const here = this.npcs().filter((c) => c.channel === this.selfChannel && !c.away);
if (here.length > 0) this.emit({ type: "chatMessage", from: pick(here).name, message: pick(DEMO_CHAT_LINES) });
} else {
const sender = pick(this.npcs().filter((c) => !c.away));
if (sender) {
this.emit({
type: "privateMessage",
partnerId: sender.id,
partnerName: sender.name,
message: pick(DEMO_PM_LINES),
fromSelf: false,
});
}
}
this.after(4000 + Math.random() * 6000, () => this.scriptServerLife());
}
private sendChannels(nickname: string) {
this.lastNickname = nickname;
const self: DemoClient = {
id: SELF_ID,
channel: this.selfChannel,
name: nickname,
inputMuted: false,
outputMuted: false,
inputHardwareEnabled: true,
away: false,
awayMessage: "",
isChannelCommander: false,
country: "",
uid: "demo-uid-self",
databaseId: 1,
channelGroup: this.selfChannelGroup,
serverGroups: [...this.selfServerGroups],
hasTalkPower: true,
};
this.emit({
type: "channels",
channels: DEMO_CHANNELS,
clients: [self, ...this.npcs()],
ownClientId: SELF_ID,
serverMaxClients: 32,
serverClientsOnline: 1 + this.npcs().length,
serverChannelsOnline: DEMO_CHANNELS.length,
});
}
}
+130
View File
@@ -0,0 +1,130 @@
/** Options -> Download (TS3's "Downloads" page). */
export interface DownloadSettings {
/** "dir": save into the picked folder (browser default when none); "ask": save dialog every time. */
saveMode: "dir" | "ask";
showWindowOnStart: boolean;
closeWindowWhenDone: boolean;
popupWhenDone: boolean;
/** KiB/s, 0 = unlimited. */
uploadLimit: number;
downloadLimit: number;
maxUploads: number;
maxDownloads: number;
}
export const DEFAULT_DOWNLOAD_SETTINGS: DownloadSettings = {
saveMode: "dir",
showWindowOnStart: true,
closeWindowWhenDone: false,
popupWhenDone: true,
uploadLimit: 0,
downloadLimit: 0,
maxUploads: 2,
maxDownloads: 2,
};
const SETTINGS_KEY = "webspeak3:download-settings";
export function loadDownloadSettings(): DownloadSettings {
try {
return { ...DEFAULT_DOWNLOAD_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "{}") };
} catch {
return DEFAULT_DOWNLOAD_SETTINGS;
}
}
export function saveDownloadSettings(settings: DownloadSettings): void {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}
// File System Access API: Chromium only. Elsewhere downloads go wherever the browser puts them.
type PickerWindow = Window & {
showDirectoryPicker?: (options?: { mode?: "readwrite" }) => Promise<FileSystemDirectoryHandle>;
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<FileSystemFileHandle>;
};
type PermissionHandle = FileSystemHandle & {
queryPermission?: (d: { mode: "readwrite" }) => Promise<PermissionState>;
requestPermission?: (d: { mode: "readwrite" }) => Promise<PermissionState>;
};
export const canPickFolder = typeof (window as PickerWindow).showDirectoryPicker === "function";
// A directory handle survives reloads only in IndexedDB (it can't be JSON'd).
function withStore<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
const open = indexedDB.open("webspeak3-downloads", 1);
open.onupgradeneeded = () => open.result.createObjectStore("handles");
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const req = run(open.result.transaction("handles", mode).objectStore("handles"));
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
};
});
}
export async function loadDownloadDir(): Promise<FileSystemDirectoryHandle | null> {
if (!canPickFolder) return null;
try {
return (await withStore("readonly", (s) => s.get("dir"))) ?? null;
} catch {
return null;
}
}
/** Opens the folder picker; null when cancelled. */
export async function pickDownloadDir(): Promise<FileSystemDirectoryHandle | null> {
try {
const dir = await (window as PickerWindow).showDirectoryPicker!({ mode: "readwrite" });
await withStore("readwrite", (s) => s.put(dir, "dir"));
return dir;
} catch {
return null;
}
}
export async function clearDownloadDir(): Promise<void> {
await withStore("readwrite", (s) => s.delete("dir")).catch(() => {});
}
/** Where a finished download goes; resolved at click time, while the user gesture
* still lets us show a save dialog or ask for folder permission. null = browser default. */
export type SaveTarget = FileSystemFileHandle | null;
export async function resolveSaveTarget(
settings: DownloadSettings,
dir: FileSystemDirectoryHandle | null,
filename: string
): Promise<SaveTarget | "cancelled"> {
const w = window as PickerWindow;
if (settings.saveMode === "ask" && w.showSaveFilePicker) {
try {
return await w.showSaveFilePicker({ suggestedName: filename });
} catch {
return "cancelled";
}
}
if (!dir) return null;
const handle = dir as PermissionHandle;
try {
if ((await handle.queryPermission?.({ mode: "readwrite" })) !== "granted" &&
(await handle.requestPermission?.({ mode: "readwrite" })) !== "granted")
return null;
return await dir.getFileHandle(filename, { create: true });
} catch {
return null;
}
}
/** Writes into the chosen file; false means fall back to a normal browser download. */
export async function writeToTarget(target: SaveTarget, blob: Blob): Promise<boolean> {
if (!target) return false;
try {
const writable = await target.createWritable();
await writable.write(blob);
await writable.close();
return true;
} catch {
return false;
}
}
+97
View File
@@ -0,0 +1,97 @@
/* eslint-disable react/only-export-components -- provider and its hooks belong together; only costs fast refresh */
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import de from "./locales/de.json";
import en from "./locales/en.json";
import zhCN from "./locales/zh-CN.json";
import fa from "./locales/fa.json";
import csCZ from "./locales/cs-CZ.json";
import ru from "./locales/ru.json";
export type Lang = "de" | "en" | "zh-CN" | "fa" | "cs-CZ" | "ru";
const RTL_LANGS = new Set<Lang>(["fa"]);
export type LangPref = "auto" | Lang;
const LANGUAGE_KEY = "webspeak3:language";
// Keyed flat dictionary, one JSON file per language under locales/. Every
// user-facing string in the app should have an entry in every file - falls
// back to the English string (or the raw key) if a translation is missing,
// so a partial dictionary never blanks out the UI. Plain JSON (not inline
// TS objects) so translation tools can read/write these files
// directly.
const translations: Record<Lang, Record<string, string>> = {
de,
en,
"zh-CN": zhCN,
fa,
"cs-CZ": csCZ,
ru,
};
function detectSystemLang(): Lang {
const nav = typeof navigator !== "undefined" ? navigator.language : "en";
const normalized = nav?.toLowerCase() ?? "en";
if (normalized.startsWith("zh")) return "zh-CN";
if (normalized.startsWith("fa")) return "fa";
if (normalized.startsWith("cs")) return "cs-CZ";
if (normalized.startsWith("ru")) return "ru";
return normalized.startsWith("de") ? "de" : "en";
}
export function resolveLang(pref: LangPref): Lang {
return pref === "auto" ? detectSystemLang() : pref;
}
export function loadLangPref(): LangPref {
const raw = localStorage.getItem(LANGUAGE_KEY);
return raw === "de" || raw === "en" || raw === "zh-CN" || raw === "fa" || raw === "cs-CZ" || raw === "ru" || raw === "auto" ? raw : "auto";
}
export function saveLangPref(pref: LangPref) {
localStorage.setItem(LANGUAGE_KEY, pref);
}
type TranslateFn = (key: string, vars?: Record<string, string>) => string;
function interpolate(template: string, vars?: Record<string, string>): string {
if (!vars) return template;
return template.replace(/\{(\w+)\}/g, (match, name) => vars[name] ?? match);
}
const LanguageContext = createContext<{ lang: Lang; langPref: LangPref; setLangPref: (p: LangPref) => void; t: TranslateFn }>({
lang: "en",
langPref: "auto",
setLangPref: () => {},
t: (key) => translations.en[key] ?? key,
});
export function LanguageProvider({ children }: { children: ReactNode }) {
const [langPref, setLangPrefState] = useState<LangPref>(() => loadLangPref());
const lang = resolveLang(langPref);
useEffect(() => {
saveLangPref(langPref);
}, [langPref]);
useEffect(() => {
document.documentElement.lang = lang;
document.documentElement.dir = RTL_LANGS.has(lang) ? "rtl" : "ltr";
}, [lang]);
const t: TranslateFn = (key, vars) =>
interpolate(translations[lang][key] ?? translations.en[key] ?? key, vars);
return (
<LanguageContext.Provider value={{ lang, langPref, setLangPref: setLangPrefState, t }}>
{children}
</LanguageContext.Provider>
);
}
export function useLanguage() {
return useContext(LanguageContext);
}
export function useT() {
return useContext(LanguageContext).t;
}
+126
View File
@@ -0,0 +1,126 @@
import { unzipSync } from "fflate";
/** Icons an icon pack can replace. Each element that shows one carries
* data-pack-icon="<id>"; iconPackCss() swaps its default for the pack's image. */
export type PackIconId =
| "talkIdle"
| "talking"
| "micMuted"
| "hardwareMicMuted"
| "soundMuted"
| "away"
| "commanderIdle"
| "commanderTalking"
| "channel"
| "server";
/** TS3 icon pack file names (gfx/<pack>/16x16_<name>.png or <name>.svg). */
const TS3_NAMES: Record<PackIconId, string> = {
talkIdle: "player_off",
talking: "player_on",
micMuted: "input_muted",
hardwareMicMuted: "hardware_input_muted",
soundMuted: "output_muted",
away: "away",
commanderIdle: "player_commander_off",
commanderTalking: "player_commander_on",
channel: "channel_green",
server: "server_green",
};
const MIME_BY_EXTENSION: Record<string, string> = {
svg: "image/svg+xml",
png: "image/png",
gif: "image/gif",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
};
export interface IconPack {
id: string;
name: string;
/** data: URLs */
icons: Partial<Record<PackIconId, string>>;
}
const PACKS_KEY = "webspeak3:icon-packs";
const SELECTED_KEY = "webspeak3:icon-pack";
export function loadIconPacks(): IconPack[] {
try {
const parsed = JSON.parse(localStorage.getItem(PACKS_KEY) ?? "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
/** Throws when localStorage is full (a pack with huge images). */
export function saveIconPacks(packs: IconPack[]): void {
localStorage.setItem(PACKS_KEY, JSON.stringify(packs));
}
export function loadSelectedIconPack(): string {
return localStorage.getItem(SELECTED_KEY) ?? "";
}
export function saveSelectedIconPack(id: string): void {
localStorage.setItem(SELECTED_KEY, id);
}
function toDataUrl(data: Uint8Array, mime: string): string {
let binary = "";
for (let i = 0; i < data.length; i += 0x8000) binary += String.fromCharCode(...data.subarray(i, i + 0x8000));
return `data:${mime};base64,${btoa(binary)}`;
}
/** Reads a .ts3_iconpack (a zip) or any zip of images named like TS3's icons.
* Returns null when nothing in it matches a known icon. */
export async function parseIconPack(file: File): Promise<IconPack | null> {
const entries = unzipSync(new Uint8Array(await file.arrayBuffer()), {
filter: (entry) => (entry.name.split(".").pop()?.toLowerCase() ?? "") in MIME_BY_EXTENSION,
});
const byStem = new Map<string, { data: Uint8Array; ext: string }>();
for (const [path, data] of Object.entries(entries)) {
const base = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
const ext = base.slice(base.lastIndexOf(".") + 1);
const stem = base.slice(0, base.lastIndexOf(".")).replace(/^\d+x\d+_/, "");
// Several sizes of the same icon: an SVG beats any PNG, else the largest file.
const prev = byStem.get(stem);
if (!prev || (ext === "svg" && prev.ext !== "svg") || (prev.ext !== "svg" && data.length > prev.data.length))
byStem.set(stem, { data, ext });
}
const icons: IconPack["icons"] = {};
for (const [id, name] of Object.entries(TS3_NAMES) as [PackIconId, string][]) {
const hit = byStem.get(name);
if (hit) icons[id] = toDataUrl(hit.data, MIME_BY_EXTENSION[hit.ext]);
}
if (Object.keys(icons).length === 0) return null;
return {
id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
name: file.name.replace(/\.(ts3_iconpack|zip)$/i, ""),
icons,
};
}
export function iconPackCss(pack: IconPack | undefined): string {
if (!pack) return "";
return Object.entries(pack.icons)
.map(
([id, url]) => `.ts-app [data-pack-icon="${id}"] {
background: url("${url}") center / contain no-repeat !important;
border: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
color: transparent !important;
display: inline-block !important;
width: 16px !important;
height: 16px !important;
overflow: hidden;
vertical-align: middle;
}
.ts-app [data-pack-icon="${id}"] > *, .ts-app [data-pack-icon="${id}"]::after { visibility: hidden !important; }`
)
.join("\n");
}
+112
View File
@@ -0,0 +1,112 @@
// Computes a TeamSpeak client UID from a stored identity, so the Identitäten dialog
// can show it without connecting. UID = base64(sha1(base64(tomcrypt public key DER))),
// same as tsproto's EccKeyPubP256::get_uid. Accepts what an identity blob can be:
// tsclientlib's JSON ({"key": base64 scalar}), a native "<counter>V<obfuscated>" string,
// or a plain base64 tomcrypt key. Needs crypto.subtle, so null on plain-http origins.
const OBFUSCATION = new TextEncoder().encode(
"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e"
);
const unb64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
const b64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes));
const sha1 = async (data: Uint8Array) => new Uint8Array(await crypto.subtle.digest("SHA-1", data as BufferSource));
/** One DER element at pos -> [tag, content, end]. */
function derRead(buf: Uint8Array, pos: number): [number, Uint8Array, number] {
let len = buf[pos + 1];
let start = pos + 2;
if (len & 0x80) {
const n = len & 0x7f;
len = 0;
for (let i = 0; i < n; i++) len = (len << 8) | buf[start + i];
start += n;
}
if (start + len > buf.length) throw new Error("bad der");
return [buf[pos], buf.subarray(start, start + len), start + len];
}
/** Top-level DER sequence -> its elements as [tag, content]. */
function derSequence(der: Uint8Array): [number, Uint8Array][] {
const [tag, body] = derRead(der, 0);
if (tag !== 0x30) throw new Error("no sequence");
const items: [number, Uint8Array][] = [];
for (let pos = 0; pos < body.length; ) {
const [t, content, end] = derRead(body, pos);
items.push([t, content]);
pos = end;
}
return items;
}
function derLength(n: number): number[] {
return n < 0x80 ? [n] : [0x81, n];
}
/** DER INTEGER content for an unsigned big-endian number. */
function derUint(bytes: Uint8Array): Uint8Array {
let i = 0;
while (i < bytes.length - 1 && bytes[i] === 0) i++;
const trimmed = bytes.subarray(i);
return trimmed[0] & 0x80 ? Uint8Array.of(0, ...trimmed) : trimmed;
}
async function uidFromPoint(x: Uint8Array, y: Uint8Array): Promise<string> {
const parts = [
[0x03, 0x02, 0x07, 0x00], // BIT STRING: 1 bit, 0 = public key only
[0x02, 0x01, 0x20], // INTEGER 32
[0x02, ...derLength(x.length), ...x],
[0x02, ...derLength(y.length), ...y],
].flat();
const der = Uint8Array.of(0x30, ...derLength(parts.length), ...parts);
return b64(await sha1(new TextEncoder().encode(b64(der))));
}
/** Public point from a bare P-256 scalar, via a PKCS#8 import without public key. */
async function uidFromScalar(scalar: Uint8Array): Promise<string> {
const d = new Uint8Array(32);
d.set(scalar.subarray(Math.max(0, scalar.length - 32)), 32 - Math.min(32, scalar.length));
const pkcs8 = Uint8Array.of(
...[0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],
...[0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20],
...d
);
const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
const jwk = await crypto.subtle.exportKey("jwk", key);
const fromUrl = (s: string) => unb64(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "="));
return uidFromPoint(derUint(fromUrl(jwk.x!)), derUint(fromUrl(jwk.y!)));
}
/** tomcrypt private key DER (with or without the public point, like tsproto's from_tomcrypt). */
async function uidFromTomcrypt(der: Uint8Array): Promise<string> {
const items = derSequence(der);
const [bitTag, bits] = items[0];
if (bitTag !== 0x03) throw new Error("no bit string");
// TS3AudioBot keys set two bits and leave out the public point.
const withPoint = bits[0] === 0x07;
if (withPoint) return uidFromPoint(items[2][1], items[3][1]);
return uidFromScalar(items[2][1]);
}
async function deobfuscate(data: Uint8Array): Promise<Uint8Array> {
const out = data.slice();
let end = out.indexOf(0, 20);
if (end < 0) end = out.length;
const hash = await sha1(out.subarray(20, end));
for (let i = 0; i < 20; i++) out[i] ^= hash[i];
for (let i = 0; i < Math.min(out.length, 100); i++) out[i] ^= OBFUSCATION[i];
return out;
}
export async function identityUid(blob: string): Promise<string | null> {
if (!crypto.subtle) return null;
try {
const text = blob.trim().replace(/^"|"$/g, "");
if (text.startsWith("{")) return await uidFromScalar(unb64(JSON.parse(text).key));
const native = /^\d+V(.+)$/.exec(text);
const tomcrypt = native ? atob(new TextDecoder().decode(await deobfuscate(unb64(native[1])))) : atob(text);
return await uidFromTomcrypt(Uint8Array.from(tomcrypt, (c) => c.charCodeAt(0)));
} catch {
return null;
}
}
+284
View File
@@ -0,0 +1,284 @@
import { Fragment, type ReactNode } from "react";
import { StillImg } from "./still";
// TeamSpeak chat text -> React elements (never HTML strings, so message text
// can't inject markup). Understands the TS3/TS6 BBCode tags plus the basic
// Markdown TS6 sends: Markdown is first rewritten into BBCode, then a single
// parser renders both. Unknown tags stay literal, unclosed tags close at the end.
// ponytail: no [table], nested Markdown lists/quotes, ==highlight==, ||spoiler||,
// math or mermaid - add them once people actually send them.
const TAG_REGEX =
/\[(\/?)(b|i|u|s|url|img|color|size|left|center|right|list|\*|hr|noparse|md-code|md-quote|md-h)(?:=([^\]]*))?\]/gi;
const BLOCK_TAGS = new Set(["left", "center", "right", "list", "*", "hr", "md-quote", "md-h"]);
export const BARE_URL_REGEX = /https?:\/\/[^\s<>"\[\]]+/g;
const COLOR_REGEX = /^(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z]+)$/i;
const LIST_STYLES: Record<string, string> = { "1": "decimal", a: "lower-alpha", A: "upper-alpha", i: "lower-roman", I: "upper-roman" };
// Spans Markdown must not touch: noparse, tagged links, inline code, Markdown
// links/images, <autolinks>, bare URLs and backslash escapes.
const MD_SPANS = new RegExp(
[
String.raw`\[noparse\][\s\S]*?\[\/noparse\]`,
String.raw`\[(url|img)(?:=[^\]]*)?\][\s\S]*?\[\/\1\]`,
String.raw`\x60([^\x60\n]+)\x60`,
String.raw`(!?)\[([^\]\n]*)\]\(<?(https?:\/\/[^\s)>]+)>?(?:\s[^)\n]*)?\)`,
String.raw`<(https?:\/\/[^\s>]+)>`,
BARE_URL_REGEX.source,
String.raw`\\([\\\x60*_{}\[\]()#+\-.!~>|=])`,
].join("|"),
"gi",
);
// Outgoing: an already-tagged link or Markdown span (left alone) or a bare URL (wrapped).
const WRAP_REGEX = new RegExp(
String.raw`(\[(url|img)(?:=[^\]]*)?\][\s\S]*?\[\/\2\]|!?\[[^\]\n]*\]\([^)\n]*\)|\x60[^\x60\n]*\x60|<https?:\/\/[^\s>]+>)|` +
BARE_URL_REGEX.source,
"gi",
);
interface Node {
tag: string;
arg?: string;
children: (Node | string)[];
}
export interface RenderOptions {
/** Load [img] / ![](...) inline. Off: they render as links, so no remote host sees the reader's IP. */
images?: boolean;
/** GIF animation off: show only the first frame of inline images. */
stillImages?: boolean;
}
function emphasis(s: string): string {
return s
.replace(/\*\*(?=\S)([^\n]*?\S)\*\*/g, "[b]$1[/b]")
.replace(/~~(?=\S)([^\n]*?\S)~~/g, "[s]$1[/s]")
.replace(/\+\+(?=\S)([^\n]*?\S)\+\+/g, "[u]$1[/u]")
.replace(/(^|[^\w*[])\*(?=[^\s\]])([^*\n]*?\S)\*(?![\w*])/g, "$1[i]$2[/i]")
.replace(/(^|[^\w_[])_(?=[^\s\]])([^_\n]*?\S)_(?![\w_])/g, "$1[i]$2[/i]");
}
function markdownInline(text: string): string {
let out = "";
let last = 0;
for (const m of text.matchAll(MD_SPANS)) {
out += emphasis(text.slice(last, m.index));
last = m.index + m[0].length;
if (m[2] !== undefined) out += `[md-code][noparse]${m[2]}[/noparse][/md-code]`;
else if (m[5] !== undefined) out += m[3] ? `[img]${m[5]}[/img]` : `[url=${m[5]}]${m[4] || m[5]}[/url]`;
else if (m[6] !== undefined) out += m[6];
else if (m[7] !== undefined) out += `[noparse]${m[7]}[/noparse]`;
else out += m[0];
}
return out + emphasis(text.slice(last));
}
// Line-based Markdown blocks (TS6: one line is one paragraph): lists, quotes,
// headings and rules. Consecutive list/quote lines are grouped.
function markdownBlocks(text: string): string {
const out: { block: boolean; s: string }[] = [];
let group = null as { kind: string; items: string[] } | null;
const flush = () => {
if (!group) return;
const s =
group.kind === "quote"
? `[md-quote]${group.items.join("\n")}[/md-quote]`
: `[list${group.kind === "ol" ? "=1" : ""}]${group.items.map((i) => `[*]${i}`).join("")}[/list]`;
out.push({ block: true, s });
group = null;
};
for (const line of text.split("\n")) {
const item = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(line);
const quote = /^>(?:\s(.*))?$/.exec(line);
const kind = item ? (/\d/.test(item[1]) ? "ol" : "ul") : quote ? "quote" : null;
if (kind) {
if (group?.kind !== kind) flush();
group ??= { kind, items: [] };
group.items.push(item ? item[2] : (quote![1] ?? ""));
continue;
}
flush();
const heading = /^(#{1,3})\s+(.+)$/.exec(line);
if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) out.push({ block: true, s: "[hr]" });
else if (heading) out.push({ block: true, s: `[md-h=${heading[1].length}]${heading[2]}[/md-h]` });
else out.push({ block: false, s: line });
}
flush();
return out.map((e, i) => (i > 0 && !e.block && !out[i - 1].block ? "\n" : "") + e.s).join("");
}
function parse(text: string): Node {
const root: Node = { tag: "", children: [] };
const stack = [root];
const re = new RegExp(TAG_REGEX.source, "gi");
let last = 0;
for (let m; (m = re.exec(text)); ) {
const top = stack[stack.length - 1];
if (m.index > last) top.children.push(text.slice(last, m.index));
last = re.lastIndex;
const tag = m[2].toLowerCase();
if (m[1]) {
const at = stack.findLastIndex((n) => n.tag === tag);
if (at > 0) stack.length = at;
else top.children.push(m[0]);
} else if (tag === "noparse") {
const end = text.toLowerCase().indexOf("[/noparse]", last);
const stop = end < 0 ? text.length : end;
top.children.push({ tag, children: [text.slice(last, stop)] });
last = re.lastIndex = end < 0 ? stop : end + "[/noparse]".length;
} else if (tag === "hr") {
top.children.push({ tag, children: [] });
} else if (tag === "*") {
const at = stack.findLastIndex((n) => n.tag === "list");
if (at > 0) {
stack.length = at + 1;
const li: Node = { tag, children: [] };
stack[at].children.push(li);
stack.push(li);
} else top.children.push(m[0]);
} else {
const node: Node = { tag, arg: m[3], children: [] };
top.children.push(node);
stack.push(node);
}
}
if (last < text.length) stack[stack.length - 1].children.push(text.slice(last));
return root;
}
function safeHref(raw: string): string | null {
const url = raw.trim();
return /^https?:\/\//i.test(url) ? url : /^www\./i.test(url) ? `https://${url}` : null;
}
function link(href: string, children: ReactNode, key: number) {
return (
<a key={key} href={href} target="_blank" rel="noopener noreferrer">
{children}
</a>
);
}
function textNode(text: string, key: number, linkUrls = true): ReactNode {
const parts: ReactNode[] = [];
text.split("\n").forEach((line, li) => {
if (li > 0) parts.push(<br key={`br${li}`} />);
let last = 0;
if (linkUrls) {
for (const m of line.matchAll(BARE_URL_REGEX)) {
if (m.index > last) parts.push(line.slice(last, m.index));
parts.push(link(m[0], m[0], li * 10000 + m.index));
last = m.index + m[0].length;
}
}
if (last < line.length) parts.push(line.slice(last));
});
return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : <Fragment key={key}>{parts}</Fragment>;
}
function textOf(node: Node): string {
return node.children.map((c) => (typeof c === "string" ? c : textOf(c))).join("");
}
function fontSize(arg: string | undefined): string | undefined {
const rel = /^([+-])(\d)$/.exec(arg ?? "");
if (rel) return `${Math.min(2, Math.max(0.6, 1 + (rel[1] === "+" ? 1 : -1) * Number(rel[2]) * 0.2))}em`;
return /^\d{1,3}$/.test(arg ?? "") ? `${Math.min(28, Math.max(6, Number(arg)))}pt` : undefined;
}
function render(node: Node, key: number, opts: RenderOptions): ReactNode {
const isBlock = (c: Node | string | undefined) => typeof c === "object" && BLOCK_TAGS.has(c.tag);
const kids = () =>
node.children.map((c, i, all) => {
if (typeof c !== "string") return render(c, i, opts);
// Line breaks around block elements are already breaks; drop them.
let s = c;
if (i === 0 ? isBlock(node) : isBlock(all[i - 1])) s = s.replace(/^\n/, "");
if (i === all.length - 1 ? isBlock(node) : isBlock(all[i + 1])) s = s.replace(/\n$/, "");
if (node.tag === "list" && !s.trim()) return null;
return textNode(s, i);
});
switch (node.tag) {
case "b":
return <strong key={key}>{kids()}</strong>;
case "i":
return <em key={key}>{kids()}</em>;
case "u":
return <u key={key}>{kids()}</u>;
case "s":
return <s key={key}>{kids()}</s>;
case "color":
return (
<span key={key} style={node.arg && COLOR_REGEX.test(node.arg) ? { color: node.arg } : undefined}>
{kids()}
</span>
);
case "size":
return (
<span key={key} style={{ fontSize: fontSize(node.arg) }}>
{kids()}
</span>
);
case "left":
case "center":
case "right":
return (
<div key={key} style={{ textAlign: node.tag }}>
{kids()}
</div>
);
case "list": {
const style = node.arg ? LIST_STYLES[node.arg] : undefined;
return style ? (
<ol key={key} className="ts-bb-list" style={{ listStyleType: style }}>
{kids()}
</ol>
) : (
<ul key={key} className="ts-bb-list">
{kids()}
</ul>
);
}
case "*":
return <li key={key}>{kids()}</li>;
case "hr":
return <hr key={key} className="ts-bb-hr" />;
case "noparse":
return textNode(textOf(node), key, false);
case "md-code":
return <code key={key}>{kids()}</code>;
case "md-quote":
return (
<blockquote key={key} className="ts-bb-quote">
{kids()}
</blockquote>
);
case "md-h":
return (
<div key={key} className={`ts-bb-h ts-bb-h${node.arg}`}>
{kids()}
</div>
);
case "url":
case "img": {
const href = safeHref(node.arg ?? textOf(node));
// Plain-text label: a linkified URL or nested tag inside <a> would nest links.
const label = textOf(node);
if (!href) return <span key={key}>{label}</span>;
if (node.tag === "img" && opts.images)
return link(href, <StillImg still={!!opts.stillImages} className="ts-bb-img" src={href} alt="" loading="lazy" referrerPolicy="no-referrer" />, key);
return link(href, label, key);
}
default:
return <Fragment key={key}>{kids()}</Fragment>;
}
}
export function renderBbcode(text: string, opts: RenderOptions = {}): ReactNode {
return render(parse(markdownInline(markdownBlocks(text.replace(/\r\n?/g, "\n")))), 0, opts);
}
// Outgoing: native clients send links as [URL]...[/URL] and only link those.
export function wrapUrls(text: string): string {
return text.replace(WRAP_REGEX, (m, kept) => (kept ? m : `[URL]${m}[/URL]`));
}
+49
View File
@@ -0,0 +1,49 @@
/** Minimal shape needed to lay channels out like the channel tree. */
export interface OrderedChannelLike {
id: number;
parent: number;
/** Position among the siblings of the same parent (not a global index). */
order: number;
}
/**
* Flattens channels in channel-tree order: each parent is followed by its
* subchannels (recursively), siblings sorted by `order`. `order` is only
* meaningful between siblings, so a flat sort by it interleaves the levels.
* Channels whose parent is missing are appended at the end as roots.
*/
export function channelsInTreeOrder<T extends OrderedChannelLike>(
channels: readonly T[],
): { channel: T; depth: number }[] {
const byParent = new Map<number, T[]>();
for (const ch of channels) {
const list = byParent.get(ch.parent);
if (list) list.push(ch);
else byParent.set(ch.parent, [ch]);
}
for (const list of byParent.values()) list.sort((a, b) => a.order - b.order || a.id - b.id);
const out: { channel: T; depth: number }[] = [];
const seen = new Set<number>();
const walk = (parent: number, depth: number) => {
for (const ch of byParent.get(parent) ?? []) {
if (seen.has(ch.id)) continue;
seen.add(ch.id);
out.push({ channel: ch, depth });
walk(ch.id, depth + 1);
}
};
walk(0, 0);
// Orphans (parent not in the list) and anything in a parent cycle.
for (const ch of channels) {
if (seen.has(ch.id)) continue;
const orphanParent = ch.parent;
for (const sibling of byParent.get(orphanParent) ?? []) {
if (seen.has(sibling.id)) continue;
seen.add(sibling.id);
out.push({ channel: sibling, depth: 0 });
walk(sibling.id, 1);
}
}
return out;
}
+114
View File
@@ -0,0 +1,114 @@
/** TeamSpeak / TeaSpeak / GreenTeaSpeak channel spacer helpers.
*
* Mirrors GreenTeaSpeak `ChannelTreeBuilder.parseChannelName` / oldclient
* `ChannelNameParser`: only root channels, tag must contain "spacer", alignment
* prefix l/c/r/* (empty → left), unique id after "spacer" may be any string
* (e.g. `[*spacer01]`, `[cspacerabc]`).
*/
export type SpacerAlignment = "left" | "center" | "right" | "repetitive";
export type ParsedChannelName = {
/** Label shown in the tree (tag stripped for spacers). */
name: string;
alignment: SpacerAlignment | null;
};
/** Pure line fillers that look better as a CSS rule than raw `---` / `***`. */
const LINE_FILLER_RE = /^[-\u2013\u2014\u2500\u2501\u2550=*.·_\s]+$/;
/** Corners / verticals of box-frame spacers (not pure horizontal fills). */
const BOX_FRAME_RE = /[╔╗╚╝╒╓╕╖╘╙╛╜┌┐└┘├┤┬┴┼║│╟╢╤╧╪╫╬╒╓╕╖╘╙╛╜]/;
export function parseChannelName(name: string, isRoot: boolean): ParsedChannelName {
if (!isRoot || name.length < 3 || name.charAt(0) !== "[") {
return { name, alignment: null };
}
const end = name.indexOf("]");
if (end === -1) return { name, alignment: null };
let options = name.substring(1, end);
const spacerIndex = options.indexOf("spacer");
if (spacerIndex === -1) return { name, alignment: null };
options = options.substring(0, spacerIndex);
if (options.length === 0) {
options = "l";
} else if (options.length > 1) {
options = options.charAt(0);
}
const alignmentByPrefix: Record<string, SpacerAlignment> = {
l: "left",
c: "center",
r: "right",
"*": "repetitive",
};
const alignment = alignmentByPrefix[options];
if (!alignment) return { name, alignment: null };
return {
name: name.substring(end + 1),
alignment,
};
}
/** Same as oldclient `ChannelName`: repeat filler until it fills the tree row. */
export function expandRepetitiveSpacerName(name: string): string {
if (!name.length) return name;
let expanded = name;
while (expanded.length < 8000) {
expanded += expanded;
}
return expanded;
}
export function isLineSpacerFiller(text: string): boolean {
const trimmed = text.trim();
return trimmed.length > 0 && LINE_FILLER_RE.test(trimmed);
}
export function hasBoxArtChars(text: string): boolean {
return BOX_FRAME_RE.test(text);
}
export function spacerDisplayName(rawName: string, isRoot: boolean): {
label: string;
alignment: SpacerAlignment | null;
isSpacer: boolean;
/** Repetitive `---` / `***` / `═══` → render as CSS line, not character soup. */
isLine: boolean;
/** Box-frame spacers (╔╗ / ═) need monospace for GTS look. */
isBoxArt: boolean;
} {
const parsed = parseChannelName(rawName, isRoot);
if (!parsed.alignment) {
return {
label: rawName,
alignment: null,
isSpacer: false,
isLine: false,
isBoxArt: false,
};
}
const isBoxArt = hasBoxArtChars(parsed.name);
const isLine =
!isBoxArt &&
isLineSpacerFiller(parsed.name) &&
(parsed.alignment === "repetitive" || parsed.alignment === "center");
let label = parsed.name;
if (parsed.alignment === "repetitive" && !isLine) {
label = expandRepetitiveSpacerName(parsed.name);
}
return {
label,
alignment: parsed.alignment,
isSpacer: true,
isLine,
isBoxArt,
};
}
+55
View File
@@ -0,0 +1,55 @@
import { useEffect, useState, type ImgHTMLAttributes } from "react";
const stills = new Map<string, string | null>();
/** Options -> Sicherheit -> "Cache löschen". */
export function clearStillCache(): void {
stills.clear();
}
/** First frame of an (animated) image as a PNG data URL, or null when the
* browser won't let us read it (cross-origin image without CORS). */
function freeze(src: string): Promise<string | null> {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.referrerPolicy = "no-referrer";
img.onload = () => {
try {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext("2d")!.drawImage(img, 0, 0);
resolve(canvas.toDataURL());
} catch {
resolve(null);
}
};
img.onerror = () => resolve(null);
img.src = src;
});
}
/** <img> that shows only the first frame when `still` is set (GIF animation off).
* Falls back to the original image when it can't be frozen. */
export function StillImg({ still, src, ...rest }: ImgHTMLAttributes<HTMLImageElement> & { still: boolean; src: string }) {
const [frozen, setFrozen] = useState(() => (still ? stills.get(src) : undefined));
useEffect(() => {
if (!still) return;
if (stills.has(src)) {
setFrozen(stills.get(src));
return;
}
let live = true;
void freeze(src).then((url) => {
stills.set(src, url);
if (live) setFrozen(url);
});
return () => {
live = false;
};
}, [src, still]);
// While freezing, render nothing rather than letting the animation start.
if (still && frozen === undefined) return null;
return <img src={still && frozen ? frozen : src} {...rest} />;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+174 -7
View File
@@ -1,10 +1,177 @@
import { StrictMode } from 'react'
import './storageFallback'
import { StrictMode, useState, type FormEvent, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import './App.css'
import { LanguageProvider, useT } from './i18n'
import { discardVault, hasVault, unlockVault } from './vault'
import {
SYNC_CATEGORIES,
accountInfo,
formatAccountNumber,
loginSyncAccount,
normalizePassword,
pullAtStartup,
resolveConflict,
startAutoSync,
syncErrorKey,
takeSyncLink,
} from './sync'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
const root = createRoot(document.getElementById('root')!)
// 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.
async function start() {
const { default: App } = await import('./App.tsx')
startAutoSync()
root.render(
<StrictMode>
<App />
</StrictMode>,
)
}
const dialog = (node: ReactNode) => root.render(<LanguageProvider>{node}</LanguageProvider>)
async function boot() {
const link = takeSyncLink()
if (link) return dialog(<SyncLinkDialog link={link} />)
// Don't hold the client hostage to a slow sync server.
const deadline = Date.now() + 5000
const result = await Promise.race([
pullAtStartup(deadline),
new Promise<'ok'>((resolve) => setTimeout(() => resolve('ok'), 5000)),
])
if (result === 'conflict') return dialog(<SyncConflictDialog />)
void start()
}
/** Opened through the QR code / link from Options -> Konto on another device. */
function SyncLinkDialog({ link }: { link: { number: string; password?: string; server: string } }) {
const t = useT()
const [password, setPassword] = useState(link.password ?? '')
const [askPassword, setAskPassword] = useState(false)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
setError('')
try {
if (!password) {
const info = await accountInfo(link.number, link.server)
if (!info.exists) throw new Error('not_found')
if (info.hasPassword) {
setAskPassword(true)
setBusy(false)
return
}
}
await loginSyncAccount(link.number, password ? normalizePassword(password) : undefined, link.server, SYNC_CATEGORIES)
void start()
} catch (err) {
setError(t(syncErrorKey(err)))
setBusy(false)
}
}
return (
<div className="ts-dialog-backdrop">
<form className="ts-dialog ts-vault-dialog" onSubmit={submit}>
<h3>{t('sync.link.title')}</h3>
<p>{t('sync.link.prompt', { number: formatAccountNumber(link.number) })}</p>
{askPassword && (
<label className="ts-dialog-field">
{t('sync.password')}
<input autoFocus value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
)}
{error && <p className="ts-vault-wrong">{error}</p>}
<div className="ts-dialog-buttons">
<button type="button" onClick={() => void start()}>
{t('dialog.cancel')}
</button>
<button type="submit" disabled={busy || (askPassword && !password)}>
{t('sync.link.connect')}
</button>
</div>
</form>
</div>
)
}
function SyncConflictDialog() {
const t = useT()
const [busy, setBusy] = useState(false)
const take = async (side: 'server' | 'local') => {
setBusy(true)
try {
await resolveConflict(side)
} finally {
void start()
}
}
return (
<div className="ts-dialog-backdrop">
<div className="ts-dialog ts-vault-dialog">
<h3>{t('sync.conflict.title')}</h3>
<p>{t('sync.conflict.text')}</p>
<div className="ts-dialog-buttons">
<button disabled={busy} onClick={() => void take('local')}>
{t('sync.conflict.local')}
</button>
<button disabled={busy} onClick={() => void take('server')}>
{t('sync.conflict.server')}
</button>
</div>
</div>
</div>
)
}
function Unlock() {
const t = useT()
const [password, setPassword] = useState('')
const [wrong, setWrong] = useState(false)
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
if (await unlockVault(password)) return void boot()
setBusy(false)
setWrong(true)
}
return (
<div className="ts-dialog-backdrop">
<form className="ts-dialog ts-vault-dialog" onSubmit={submit}>
<h3>{t('vault.title')}</h3>
<p>{t('vault.prompt')}</p>
<input type="password" autoFocus value={password} onChange={(e) => setPassword(e.target.value)} />
{wrong && <p className="ts-vault-wrong">{t('vault.wrong')}</p>}
<div className="ts-dialog-buttons">
<button
type="button"
onClick={() => {
if (!window.confirm(t('vault.forgotConfirm'))) return
discardVault()
void boot()
}}
>
{t('vault.forgot')}
</button>
<button type="submit" disabled={busy || !password}>
{t('vault.unlock')}
</button>
</div>
</form>
</div>
)
}
if (hasVault())
root.render(
<LanguageProvider>
<Unlock />
</LanguageProvider>,
)
else void boot()
+323
View File
@@ -0,0 +1,323 @@
import { unzipSync } from "fflate";
import { SOUND_EVENTS, playSound, playSoundBlob, type SoundEventId } from "./sounds";
/** Options -> Meldungen: TS3's notification tree. Keys are TeamSpeak's own
* sound pack keys, so a real .ts3_soundpack's settings.ini maps 1:1. */
export interface NotificationNode {
/** Locale key under "notify.". */
label: string;
key?: string;
children?: NotificationNode[];
}
const leaf = (label: string, key: string): NotificationNode => ({ label, key });
const group = (label: string, children: NotificationNode[]): NotificationNode => ({ label, children });
const byWho = (p: string) => [leaf("byYou", `${p}_BY_YOU`), leaf("byOther", `${p}_BY_OTHER`)];
const where = (p: string) => [leaf("server", `${p}_SERVER`), leaf("currentChannel", `${p}_CURRENT_CHANNEL`)];
const byServerUser = (p: string) => [leaf("byServer", `${p}_BY_SERVER`), leaf("byUser", `${p}_BY_USER`)];
const moves = (p: string) => [
group("toCurrent", [leaf("appears", `${p}_TO_CURRENT_CHANNEL_APPEARS`), leaf("stays", `${p}_TO_CURRENT_CHANNEL_STAYS`)]),
group("fromCurrent", [
leaf("disappears", `${p}_FROM_CURRENT_CHANNEL_DISAPPEARS`),
leaf("stays", `${p}_FROM_CURRENT_CHANNEL_STAYS`),
]),
group("toOther", [
leaf("appears", `${p}_TO_OTHER_CHANNEL_APPEARS`),
leaf("disappears", `${p}_TO_OTHER_CHANNEL_DISAPPEARS`),
leaf("stays", `${p}_TO_OTHER_CHANNEL_STAYS`),
]),
];
export const NOTIFICATION_TREE: NotificationNode[] = [
group("connection", [
leaf("connected", "CONNECTION_CONNECTED"),
leaf("disconnected", "CONNECTION_DISCONNECTED"),
leaf("lostConnection", "CONNECTION_LOST_CONNECTION"),
]),
group("channel", [
group("created", byWho("CHANNEL_CREATED")),
group("deleted", byWho("CHANNEL_DELETED")),
group("edited", [
group("currentChannel", byWho("CHANNEL_EDITED_CURRENT")),
group("otherChannel", byWho("CHANNEL_EDITED_OTHER")),
]),
group("moved", byWho("CHANNEL_MOVED")),
]),
group("server", [
group("edited", byWho("SERVER_EDITED")),
leaf("insufficientPermissions", "SERVER_INSUFFICIENT_PERMISSIONS"),
leaf("error", "SERVER_ERROR"),
]),
group("client", [
group("connection", [
group("connected", where("CLIENT_CONNECTION_CONNECTED")),
group("disconnected", where("CLIENT_CONNECTION_DISCONNECTED")),
group("lostConnection", where("CLIENT_CONNECTION_LOST_CONNECTION")),
]),
group("switched", moves("CLIENT_SWITCHED")),
group("movedClient", moves("CLIENT_MOVED")),
group("kickedChannel", moves("CLIENT_WAS_KICKED_FROM_CHANNEL")),
group("kickedServer", where("CLIENT_WAS_KICKED_FROM_SERVER")),
group("banned", where("CLIENT_WAS_BANNED")),
group("serverGroup", [
group("added", byServerUser("CLIENT_SERVERGROUP_ADDED")),
group("removed", byServerUser("CLIENT_SERVERGROUP_REMOVED")),
]),
group("channelGroup", byServerUser("CLIENT_CHANNELGROUP_CHANGED")),
group("recording", [
leaf("recordingStart", "CLIENT_RECORDING_START"),
leaf("recordingStop", "CLIENT_RECORDING_STOP"),
leaf("recordingInChannel", "CLIENT_RECORDING_IN_CHANNEL"),
]),
leaf("talkPowerRequested", "CLIENT_REQUESTED_TALK_POWER"),
]),
group("self", [
leaf("youSwitched", "YOU_SWITCHED_CHANNEL"),
leaf("youMoved", "YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL"),
leaf("youKickedServer", "YOU_WERE_KICKED_FROM_SERVER"),
leaf("youKickedChannel", "YOU_WERE_KICKED_FROM_CHANNEL"),
leaf("youBanned", "YOU_WERE_BANNED"),
leaf("talkPowerGranted", "YOU_WERE_GRANTED_TALK_POWER"),
leaf("talkPowerRevoked", "YOU_WERE_REVOKED_TALK_POWER"),
group("serverGroup", [
group("added", byServerUser("YOU_SERVERGROUP_ADDED")),
group("removed", byServerUser("YOU_SERVERGROUP_REMOVED")),
]),
group("channelGroup", byServerUser("YOU_CHANNELGROUP_CHANGED")),
]),
group("chat", [leaf("messageSent", "CHAT_SENT_MESSAGE"), leaf("messageReceived", "CHAT_RECEIVED_MESSAGE")]),
group("capture", [leaf("muted", "SOUND_CAPTURE_MUTED"), leaf("unmuted", "SOUND_CAPTURE_UNMUTED")]),
group("playback", [leaf("muted", "SOUND_PLAYBACK_MUTED"), leaf("unmuted", "SOUND_PLAYBACK_UNMUTED")]),
group("status", [leaf("away", "STATUS_SET_AWAY"), leaf("present", "STATUS_SET_PRESENT")]),
group("other", [
leaf("poked", "OTHER_RECEIVED_POKE"),
leaf("transferComplete", "OTHER_FILETRANSFER_COMPLETE"),
leaf("transferFailed", "OTHER_FILETRANSFER_FAILED"),
leaf("whisperListEmpty", "OTHER_WHISPERLIST_EMPTY"),
leaf("whisperTargetNotFound", "OTHER_WHISPERTARGET_NOT_FOUND"),
leaf("whisperTooMany", "OTHER_WHISPERTARGET_TOO_MANY"),
]),
// Like native: no checkboxes here, these are switched on/off on their own options pages.
group("special", [
leaf("micClickOtherOn", "SPECIAL_MIC_CLICK_OTHER_ON"),
leaf("micClickOtherOff", "SPECIAL_MIC_CLICK_OTHER_OFF"),
leaf("micClickSelfOn", "SPECIAL_MIC_CLICK_SELF_ON"),
leaf("micClickSelfOff", "SPECIAL_MIC_CLICK_SELF_OFF"),
leaf("whisperNotify", "SPECIAL_WHISPER_NOTIFY"),
leaf("soundTest", "SPECIAL_SOUND_TEST"),
leaf("test3d", "SPECIAL_3D_TEST"),
leaf("talkingWhileMuted", "SPECIAL_TALKING_WHILE_MUTED"),
]),
];
export const isSpecialKey = (key: string) => key.startsWith("SPECIAL_");
/** WebSpeak3's own pack: plays the chimes from Options -> Sounds (or the file you put there). */
const BUILTIN_SCRIPTS: Record<string, SoundEventId> = {
CONNECTION_CONNECTED: "connect",
CONNECTION_DISCONNECTED: "disconnect",
CONNECTION_LOST_CONNECTION: "disconnect",
CLIENT_CONNECTION_CONNECTED_SERVER: "clientJoin",
CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL: "clientJoin",
CLIENT_CONNECTION_DISCONNECTED_SERVER: "clientLeave",
CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL: "clientLeave",
CLIENT_CONNECTION_LOST_CONNECTION_SERVER: "clientLeave",
CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL: "clientLeave",
CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS: "clientJoin",
CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS: "clientJoin",
CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS: "clientLeave",
CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS: "clientLeave",
CHAT_RECEIVED_MESSAGE: "message",
OTHER_RECEIVED_POKE: "poke",
SOUND_CAPTURE_MUTED: "mute",
SOUND_CAPTURE_UNMUTED: "mute",
SOUND_PLAYBACK_MUTED: "mute",
SOUND_PLAYBACK_UNMUTED: "mute",
SPECIAL_MIC_CLICK_OTHER_ON: "micClickOn",
SPECIAL_MIC_CLICK_OTHER_OFF: "micClickOff",
SPECIAL_MIC_CLICK_SELF_ON: "micClickOn",
SPECIAL_MIC_CLICK_SELF_OFF: "micClickOff",
SPECIAL_WHISPER_NOTIFY: "whisper",
SPECIAL_TALKING_WHILE_MUTED: "mute",
};
export const BUILTIN_PACK = "builtin";
export const NO_SOUNDS_PACK = "none";
export interface SoundPack {
id: string;
name: string;
scripts: Record<string, string>;
/** Lowercased path relative to settings.ini -> audio. */
files: Record<string, Blob>;
}
/** Where an event's text line goes; several at once, like native's multiple choice.
* "client" = the private chat with the client it's about. */
export type TextPosition = "server" | "channel" | "client";
export interface NotificationOverride {
off?: boolean;
script?: string;
text?: TextPosition[];
}
export interface NotificationSettings {
pack: string;
/** "important": only IMPORTANT_KEYS while the output is muted. */
whenMuted: "all" | "important" | "none";
overrides: Record<string, NotificationOverride>;
}
const SETTINGS_KEY = "webspeak3:notification-settings";
const DEFAULT_SETTINGS: NotificationSettings = { pack: BUILTIN_PACK, whenMuted: "all", overrides: {} };
let settings: NotificationSettings = (() => {
try {
return { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "{}") };
} catch {
return DEFAULT_SETTINGS;
}
})();
export const getNotificationSettings = () => settings;
export function saveNotificationSettings(next: NotificationSettings): void {
settings = next;
localStorage.setItem(SETTINGS_KEY, JSON.stringify(next));
}
/** Set by the app: output muted state, and the active favorite's pack override. */
let playbackMuted = false;
let sessionPack: string | undefined;
export const setNotificationPlaybackMuted = (muted: boolean) => void (playbackMuted = muted);
export const setSessionSoundPack = (pack: string | undefined) => void (sessionPack = pack || undefined);
// --- imported packs (IndexedDB, blobs don't fit localStorage) ---
function withPacks<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
const open = indexedDB.open("webspeak3-soundpacks", 1);
open.onupgradeneeded = () => open.result.createObjectStore("packs", { keyPath: "id" });
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const req = run(open.result.transaction("packs", mode).objectStore("packs"));
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
};
});
}
let packsCache: Promise<SoundPack[]> | null = null;
export function loadSoundPacks(): Promise<SoundPack[]> {
packsCache ??= withPacks<SoundPack[]>("readonly", (s) => s.getAll()).catch(() => []);
return packsCache;
}
export async function deleteSoundPack(id: string): Promise<void> {
await withPacks("readwrite", (s) => s.delete(id)).catch(() => {});
packsCache = null;
}
const AUDIO = /\.(wav|mp3|ogg|m4a)$/i;
/** Parses a TS3 sound pack (.ts3_soundpack / .zip with a settings.ini). */
export function parseSoundPackZip(data: Uint8Array, fallbackName: string): SoundPack {
const entries = unzipSync(data);
const iniPath = Object.keys(entries)
.filter((p) => p.toLowerCase().endsWith("settings.ini"))
.sort((a, b) => a.length - b.length)[0];
if (!iniPath) throw new Error("settings.ini missing");
const base = iniPath.slice(0, iniPath.length - "settings.ini".length).toLowerCase();
const ini = new TextDecoder().decode(entries[iniPath]);
let section = "";
let name = fallbackName;
const scripts: Record<string, string> = {};
for (const raw of ini.split(/\r?\n/)) {
const line = raw.trim();
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
const head = /^\[(.+)\]$/.exec(line);
if (head) {
section = head[1].toLowerCase();
continue;
}
const eq = line.indexOf("=");
if (eq < 0) continue;
const k = line.slice(0, eq).trim();
const v = line.slice(eq + 1).trim();
if (section === "info" && k === "name" && v) name = v;
else if (section === "soundfiles") scripts[k] = v;
}
const files: Record<string, Blob> = {};
for (const [path, bytes] of Object.entries(entries)) {
const lower = path.toLowerCase();
if (lower.startsWith(base) && AUDIO.test(lower)) files[lower.slice(base.length)] = new Blob([bytes.slice()]);
}
return { id: `pack:${Date.now()}`, name, scripts, files };
}
export async function importSoundPack(file: File): Promise<SoundPack> {
const pack = parseSoundPackZip(new Uint8Array(await file.arrayBuffer()), file.name.replace(/\.[^.]+$/, ""));
await withPacks("readwrite", (s) => s.put(pack));
packsCache = null;
return pack;
}
// --- resolving + playing ---
/** The pack's own script for a key ("" = silent). */
export function packScript(pack: SoundPack | undefined, packId: string, key: string): string {
if (packId === NO_SOUNDS_PACK) return "";
if (packId === BUILTIN_PACK) return BUILTIN_SCRIPTS[key] ? `play("${BUILTIN_SCRIPTS[key]}")` : "";
return pack?.scripts[key] ?? "";
}
/** Text positions native offers for a key: everything gets Server, events about
* channels/yourself also Channel, events about another client also Client. */
export function textPositionChoices(key: string): TextPosition[] {
if (key.startsWith("CLIENT_") || key === "OTHER_RECEIVED_POKE") return ["server", "channel", "client"];
if (/^(CHANNEL|YOU|CHAT)_/.test(key)) return ["server", "channel"];
return ["server"];
}
// ponytail: guessed set, native doesn't document which sounds count as "wichtig".
const IMPORTANT_KEYS = /^(CONNECTION_|YOU_WERE_|SOUND_|OTHER_RECEIVED_POKE$|SERVER_ERROR$)/;
export const isNotificationEnabled = (key: string) => isSpecialKey(key) || !settings.overrides[key]?.off;
/** Where the event's text goes; nowhere when the row is unticked. */
export function notificationTextPositions(key: string): TextPosition[] {
if (!isNotificationEnabled(key)) return [];
const text = settings.overrides[key]?.text;
return Array.isArray(text) ? text : ["server"];
}
export type NotificationVars = Record<string, string>;
export async function runSoundScript(script: string, packId: string, vars: NotificationVars = {}): Promise<void> {
const pack = packId.startsWith("pack:") ? (await loadSoundPacks()).find((p) => p.id === packId) : undefined;
const fill = (s: string) => s.replace(/\$\{(\w+)\}/g, (_, v: string) => vars[v] ?? (v === "clientType" ? "neutral" : ""));
for (const [, fn, arg] of script.matchAll(/(play|say)\(\s*"([^"]*)"\s*\)/g)) {
const value = fill(arg);
if (fn === "say") {
if ("speechSynthesis" in window) speechSynthesis.speak(new SpeechSynthesisUtterance(value));
} else if (packId === BUILTIN_PACK || !pack) {
if ((SOUND_EVENTS as string[]).includes(value)) await playSound(value as SoundEventId);
} else {
const blob = pack.files[value.toLowerCase().replace(/\\/g, "/")];
if (blob) await playSoundBlob(blob);
}
}
}
/** Plays the sound for a TS3 notification key, honouring the Meldungen settings. */
export async function notify(key: string, vars?: NotificationVars): Promise<void> {
if (!isNotificationEnabled(key)) return;
if (playbackMuted && (settings.whenMuted === "none" || (settings.whenMuted === "important" && !IMPORTANT_KEYS.test(key))))
return;
const packId = sessionPack ?? settings.pack;
const override = settings.overrides[key]?.script;
const pack = packId.startsWith("pack:") ? (await loadSoundPacks()).find((p) => p.id === packId) : undefined;
await runSoundScript(override ?? packScript(pack, packId, key), packId, vars);
}
+499
View File
@@ -0,0 +1,499 @@
// Publishing a stream that TeamSpeak 6 clients can watch.
//
// The mirror image of stream.ts. Where a viewer answers an offer, a publisher
// makes one - TS6 puts the first SDP in `respondjoinstreamrequest`, so the
// side that owns the stream is the side that offers.
//
// The exchange, from our side:
//
// 1. setupStream -> notifystreamstarted naming our own clid + the id
// 2. wait <- notifyjoinstreamrequest, one per viewer
// 3. offer respondJoinStream(accept, <our SDP>)
// 4. answer <- {cmd:"answer", args:{answer:"<sdp>"}}
// 5. trickle ICE both directions via {cmd:"iceCandidate"}
//
// TS6's P2P mode is a mesh: there is no SFU in the path, so every viewer gets
// its own peer connection and its own copy of the encoded media.
import { DEFAULT_ICE_SERVERS, type StreamEvent } from "./stream";
// The three enums below are read straight out of TS6's own UI bundle
// (main.js), not inferred - see ts6-re/findings §10.
/** `type` in `setupstream`: what is being captured. */
export const StreamSource = {
NONE: 0,
CAMERA: 1,
SCREEN: 2,
WINDOW: 3,
EXISTING_SESSION: 4,
} as const;
/** `accessibility` in `setupstream`: TS6's Privacy setting. */
export const StreamAccess = {
NONE: 0,
PUBLIC: 1,
CONTACTS_ONLY: 2,
PRIVATE: 3,
} as const;
/** `mode` in `setupstream`: TS6's Connection Mode. */
export const StreamMode = {
NONE: 0,
P2P: 1,
SFU: 2,
} as const;
export interface StreamPublishOptions {
name: string;
/** Screen/window via the browser's picker, or the webcam. */
source: "display" | "camera";
/** Send the capture's audio track too, when the source has one. */
audio: boolean;
/** One of StreamAccess. */
accessibility: number;
/** One of StreamMode. Only P2P is implemented; SFU needs the mediasoup path. */
mode: number;
/** 0 means unlimited. */
viewerLimit: number;
/** Capture height in pixels; 0 keeps the source's own resolution. */
height: number;
/** Capture frame rate; 0 leaves it to the browser. */
fps: number;
videoBitrateKbps: number;
audioBitrateKbps: number;
/**
* What the encoder should protect when it runs out of bitrate. Slides and
* code want "detail" (keep text sharp, drop frames); a game wants "motion".
*/
contentHint: "motion" | "detail";
}
export interface StreamPublisherOptions {
send: (message: Record<string, unknown>) => void;
/** Needed to recognise our own `notifystreamstarted` among everyone's. */
ownClientId: number;
onStateChange?: (state: PublishState) => void;
onViewersChange?: (viewers: number[]) => void;
/** Join requests awaiting a decision, as [clid, message] pairs. */
onPendingChange?: (pending: [number, string][]) => void;
onError?: (error: string) => void;
iceServers?: RTCIceServer[];
}
export type PublishState = "idle" | "starting" | "live" | "stopped";
interface Viewer {
pc: RTCPeerConnection;
/** Candidates that arrived before the answer; replayed after. */
pending: RTCIceCandidateInit[];
answered: boolean;
}
export class StreamPublisher {
private readonly opts: StreamPublisherOptions;
private readonly viewers = new Map<number, Viewer>();
/** Requests waiting for the user to decide: clid -> the viewer's message. */
private readonly pending = new Map<number, string>();
/** Clients denied with "block"; they are refused without asking again. */
private readonly blocked = new Set<number>();
private media: MediaStream | null = null;
private state: PublishState = "idle";
private options: StreamPublishOptions | null = null;
/** Assigned by the server, not by us; null until notifystreamstarted. */
streamId: string | null = null;
/** The local capture, for showing the user what they are sending. */
get previewStream(): MediaStream | null {
return this.media;
}
constructor(opts: StreamPublisherOptions) {
this.opts = opts;
}
/**
* Captures a screen or the webcam and announces the stream.
*
* Both capture APIs are secure-context-only, so this fails on a plain-http
* origin - the same limitation the microphone already has.
*/
async start(options: StreamPublishOptions): Promise<void> {
if (this.state === "live" || this.state === "starting") return;
const camera = options.source === "camera";
if (!(camera ? navigator.mediaDevices?.getUserMedia : navigator.mediaDevices?.getDisplayMedia)) {
this.fail("Streaming requires HTTPS (or localhost) - the site is not a secure context.");
return;
}
this.setState("starting");
this.options = options;
const video: MediaTrackConstraints = {};
if (options.height > 0) video.height = { ideal: options.height };
if (options.fps > 0) video.frameRate = { ideal: options.fps };
try {
const constraints = { video: Object.keys(video).length > 0 ? video : true };
// A camera's "audio" would be the microphone, which already goes out as
// voice - sending it again would only echo.
this.media = camera
? await navigator.mediaDevices.getUserMedia({ ...constraints, audio: false })
: await navigator.mediaDevices.getDisplayMedia({ ...constraints, audio: options.audio });
} catch (err) {
this.setState("idle");
this.fail(`Could not capture the ${camera ? "camera" : "screen"}: ${describe(err)}`);
return;
}
for (const track of this.media.getVideoTracks()) track.contentHint = options.contentHint;
// The browser's own "stop sharing" bar bypasses our UI entirely, so the
// track ending is the authoritative signal that the stream is over.
for (const track of this.media.getTracks()) {
track.onended = () => this.stop();
}
this.opts.send({
type: "setupStream",
name: options.name,
// The browser's own picker decides whether this is a whole screen or a
// single window, so the type is read back off the track rather than
// asked for up front.
streamType: this.detectSourceType(),
bitrate: options.videoBitrateKbps * 1000,
accessibility: options.accessibility,
mode: options.mode,
viewerLimit: options.viewerLimit,
audio: options.audio && this.media.getAudioTracks().length > 0,
});
}
/** Feeds one `streamEvent` in; events for other streams are ignored. */
handleEvent(event: StreamEvent): void {
switch (event.name) {
case "notifystreamstarted":
// Everyone in the channel sees this, so the clid decides whether it
// is the answer to our own setupstream.
if (Number(event.args.clid) === this.opts.ownClientId && event.args.id) {
this.streamId = event.args.id;
this.setState("live");
}
break;
case "notifyjoinstreamrequest":
if (event.args.id === this.streamId) void this.admit(event.args);
break;
case "notifystreamsignaling":
if (event.args.id === this.streamId) void this.handleSignaling(event.args);
break;
case "notifystreamclientleft":
if (event.args.id === this.streamId) this.dropViewer(Number(event.args.clid));
break;
case "notifystreamstopped":
if (event.args.id === this.streamId) this.teardown("stopped");
break;
}
}
/**
* Decides what to do with an incoming join request.
*
* This mirrors TS6's own publisher-side rule, which is the only place either
* setting is enforced at all - the server stores `accessibility` and
* `viewer_limit`, echoes them back, and then forwards every request anyway
* (verified live: a PRIVATE stream at viewer_limit=1 still had both viewers
* announced to us).
*
* The important half is what happens to a request we do not take: TS6 leaves
* it *pending* rather than refusing it. A refusal is not sticky - TS6's own
* "block" path is deny plus a ban - so a refused client simply asks again, in
* a loop, and shows its user nothing. Left pending, it asks once and displays
* "waiting for access" until we answer.
*/
private async admit(args: Record<string, string>): Promise<void> {
const clid = Number(args.clid);
if (!Number.isFinite(clid) || !this.media || !this.streamId) return;
// is_remove=1 is how TS6 says "stop watching"; the same notify carries it.
if (args.is_remove === "1") {
this.dropViewer(clid);
return;
}
if (this.viewers.has(clid) || this.pending.has(clid)) return;
// Explicitly blocked earlier: refuse without bothering the user again.
if (this.blocked.has(clid)) {
this.refuse(clid, "Blocked");
return;
}
const limit = this.options?.viewerLimit ?? 0;
const full = limit > 0 && this.viewers.size >= limit;
const autoAccept = this.options?.accessibility === StreamAccess.PUBLIC && !full;
if (!autoAccept) {
// CONTACTS_ONLY behaves as PRIVATE here: the contact list is a TS6
// account feature webspeak3 has no access to, so it cannot be consulted.
this.pending.set(clid, args.msg ?? "");
this.notifyPending();
return;
}
await this.openTo(clid);
}
/** Lets a pending viewer in. Called by admit() or by the user. */
async approve(clid: number): Promise<void> {
if (!this.pending.delete(clid)) return;
this.notifyPending();
await this.openTo(clid);
}
/**
* Turns a pending viewer away. `block` also remembers the refusal, which is
* what makes it stick - TS6 pairs its deny with a ban for the same reason.
*/
deny(clid: number, block = false): void {
this.pending.delete(clid);
if (block) this.blocked.add(clid);
this.notifyPending();
this.refuse(clid, block ? "Blocked" : "Denied");
}
private refuse(clid: number, message: string): void {
if (!this.streamId) return;
this.opts.send({
type: "respondJoinStream",
streamId: this.streamId,
clientId: clid,
accept: false,
message,
});
}
/** Builds the peer connection for a viewer we have decided to let in. */
private async openTo(clid: number): Promise<void> {
if (!this.media || !this.streamId || this.viewers.has(clid)) return;
const pc = new RTCPeerConnection({ iceServers: this.opts.iceServers ?? DEFAULT_ICE_SERVERS });
const viewer: Viewer = { pc, pending: [], answered: false };
this.viewers.set(clid, viewer);
for (const track of this.media.getTracks()) pc.addTrack(track, this.media);
pc.onicecandidate = (ev) => {
if (!ev.candidate) return;
this.signal(clid, "iceCandidate", {
sdp: ev.candidate.candidate,
mid: ev.candidate.sdpMid ?? "0",
mLine: ev.candidate.sdpMLineIndex ?? 0,
});
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === "failed" || pc.connectionState === "closed") this.dropViewer(clid);
};
try {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
await this.applySendParameters(pc);
this.opts.send({
type: "respondJoinStream",
streamId: this.streamId,
clientId: clid,
accept: true,
offer: offer.sdp ?? "",
});
this.notifyViewers();
} catch (err) {
this.dropViewer(clid);
this.fail(`Could not offer the stream to client ${clid}: ${describe(err)}`);
}
}
private async handleSignaling(args: Record<string, string>): Promise<void> {
const clid = Number(args.clid);
const viewer = this.viewers.get(clid);
if (!viewer) return;
let msg: { cmd: string; args: unknown };
try {
msg = JSON.parse(args.json ?? "");
} catch {
return;
}
const payload = msg.args as Record<string, unknown> | string | null;
switch (msg.cmd) {
case "answer": {
// Same key rule as the sending side: the key is named after the cmd.
const sdp =
typeof payload === "string"
? payload
: typeof payload?.answer === "string"
? payload.answer
: typeof payload?.sdp === "string"
? payload.sdp
: null;
if (!sdp) return;
try {
await viewer.pc.setRemoteDescription({ type: "answer", sdp });
viewer.answered = true;
const pending = viewer.pending;
viewer.pending = [];
for (const c of pending) {
try {
await viewer.pc.addIceCandidate(c);
} catch (err) {
console.warn("[publish] ignoring buffered ICE candidate:", describe(err));
}
}
} catch (err) {
this.fail(`Could not accept the viewer's answer: ${describe(err)}`);
}
break;
}
case "iceCandidate": {
if (typeof payload !== "object" || payload === null) return;
const candidate = payload.sdp;
if (typeof candidate !== "string" || !candidate) return;
const init: RTCIceCandidateInit = {
candidate,
sdpMid: typeof payload.mid === "string" ? payload.mid : undefined,
sdpMLineIndex: typeof payload.mLine === "number" ? payload.mLine : undefined,
};
// TS6 trickles from the moment it gets the offer, so these routinely
// beat its own answer. Holding them is not an edge case.
if (!viewer.answered) {
viewer.pending.push(init);
return;
}
try {
await viewer.pc.addIceCandidate(init);
} catch (err) {
console.warn("[publish] ignoring ICE candidate:", describe(err));
}
break;
}
}
}
/**
* Caps each sender at the configured bitrate and pins the resolution.
*
* `setupstream`'s `bitrate` is only what the stream *advertises* - the
* server does not even echo our value back unchanged, and it certainly does
* not reach the encoder. The actual limit is a sender parameter, and the
* encodings it lives on only exist once a local description is set.
*
* `degradationPreference` matters just as much. Its default for a track
* hinted "motion" is to protect the frame rate and shrink the picture, which
* for a screen share is exactly backwards: the user picked 1080p, so 1080p is
* the thing to keep. Measured on a 1440x1080 capture at a 6000 kbps cap:
*
* default / maintain-framerate / balanced -> 480x270, a 3x downscale
* maintain-resolution -> 1440x810, no downscale
*
* Without this the encoder collapses within seconds of the connection coming
* up and never recovers, and every resolution setting above 360p is a lie.
*/
private async applySendParameters(pc: RTCPeerConnection): Promise<void> {
const options = this.options;
if (!options) return;
for (const sender of pc.getSenders()) {
if (!sender.track) continue;
const video = sender.track.kind === "video";
const kbps = video ? options.videoBitrateKbps : options.audioBitrateKbps;
const params = sender.getParameters();
if (video) params.degradationPreference = "maintain-resolution";
if (kbps > 0) {
if (!params.encodings || params.encodings.length === 0) params.encodings = [{}];
for (const encoding of params.encodings) encoding.maxBitrate = kbps * 1000;
}
try {
await sender.setParameters(params);
} catch (err) {
// Not fatal - the stream still runs, just uncapped and free to shrink.
console.warn("[publish] could not apply the send parameters:", describe(err));
}
}
}
/**
* Maps the capture to TS6's source enum.
*
* `displaySurface` is what the user actually picked in the browser's own
* share dialog, so it is more truthful than anything we could ask for in
* advance. A browser tab has no TS6 equivalent and reads closest to a window.
*/
private detectSourceType(): number {
if (this.options?.source === "camera") return StreamSource.CAMERA;
const surface = this.media?.getVideoTracks()[0]?.getSettings().displaySurface;
return surface === "monitor" ? StreamSource.SCREEN : StreamSource.WINDOW;
}
private dropViewer(clid: number): void {
// Someone can also leave while their request is still queued - by closing
// TS6, or by giving up on "waiting for access". The row has to go with
// them, or the user is left approving a viewer who is no longer there.
if (this.pending.delete(clid)) this.notifyPending();
const viewer = this.viewers.get(clid);
if (!viewer) return;
this.viewers.delete(clid);
viewer.pc.close();
this.notifyViewers();
}
/** Stops the capture and takes the stream down. Safe to call twice. */
stop(): void {
if (this.state === "idle" || this.state === "stopped") return;
if (this.streamId) this.opts.send({ type: "stopStream", streamId: this.streamId });
this.teardown("stopped");
}
private teardown(state: PublishState): void {
for (const [, viewer] of this.viewers) viewer.pc.close();
this.viewers.clear();
this.pending.clear();
this.blocked.clear();
for (const track of this.media?.getTracks() ?? []) track.stop();
this.media = null;
this.streamId = null;
this.options = null;
this.notifyViewers();
this.notifyPending();
this.setState(state);
}
private signal(clid: number, cmd: string, args: unknown): void {
this.opts.send({
type: "streamSignal",
streamId: this.streamId,
clientId: clid,
payload: { cmd, args },
});
}
private setState(state: PublishState): void {
this.state = state;
this.opts.onStateChange?.(state);
}
private notifyViewers(): void {
this.opts.onViewersChange?.([...this.viewers.keys()]);
}
private notifyPending(): void {
this.opts.onPendingChange?.([...this.pending.entries()]);
}
private fail(message: string): void {
this.opts.onError?.(message);
}
}
function describe(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
+75
View File
@@ -0,0 +1,75 @@
import { unzipSync } from "fflate";
import type { SoundEventId } from "./sounds";
const AUDIO_EXTENSIONS = [".wav", ".mp3", ".ogg", ".m4a"];
const MIME_BY_EXTENSION: Record<string, string> = {
".wav": "audio/wav",
".mp3": "audio/mpeg",
".ogg": "audio/ogg",
".m4a": "audio/mp4",
};
/** Real .ts3soundpack files use TeamSpeak's own internal event names, which
* vary between client versions and aren't documented anywhere stable - so
* this matches by keyword against the filename (soundpacks are zips of
* individual audio files, not proprietary-encoded) rather than depending on
* an exact manifest format. Falls back to a "not matched" list the caller
* can surface, instead of silently dropping unrecognized files. */
const EVENT_KEYWORDS: Record<SoundEventId, string[]> = {
connect: ["connectionaccepted", "connectionestablished", "youhaveconnected", "connect"],
disconnect: ["connectionlost", "connectiondisconnected", "youhavebeendisconnected", "disconnect"],
clientJoin: ["userenteredchannel", "userenteredvisibility", "cliententerview", "userjoined", "enter"],
clientLeave: ["userleftchannel", "userleftvisibility", "clientleftview", "userleave", "userleft", "leave"],
message: ["textmessagereceived", "chatmessage", "newmessage", "message"],
poke: ["gotpoked", "poke"],
mute: ["micmuted", "microphonemuted", "micactivated", "microphoneactivated"],
micClickOn: ["micclickon"],
micClickOff: ["micclickoff"],
whisper: ["whisperreceived", "whisper"],
};
function normalize(filename: string): string {
const base = filename.slice(filename.lastIndexOf("/") + 1);
const dot = base.lastIndexOf(".");
return (dot === -1 ? base : base.slice(0, dot)).toLowerCase().replace(/[^a-z0-9]/g, "");
}
function extensionOf(filename: string): string | null {
const lower = filename.toLowerCase();
return AUDIO_EXTENSIONS.find((ext) => lower.endsWith(ext)) ?? null;
}
export interface SoundpackImportResult {
matched: Partial<Record<SoundEventId, { name: string; blob: Blob }>>;
unmatchedFiles: string[];
}
export async function parseSoundpack(file: File): Promise<SoundpackImportResult> {
const buffer = new Uint8Array(await file.arrayBuffer());
const entries = unzipSync(buffer, {
filter: (entry) => extensionOf(entry.name) !== null,
});
const matched: SoundpackImportResult["matched"] = {};
const unmatchedFiles: string[] = [];
for (const [name, data] of Object.entries(entries)) {
const ext = extensionOf(name);
if (!ext) continue;
const key = normalize(name);
const eventId = (Object.keys(EVENT_KEYWORDS) as SoundEventId[]).find(
(id) => !matched[id] && EVENT_KEYWORDS[id].some((keyword) => key.includes(keyword))
);
if (eventId) {
matched[eventId] = {
name: name.slice(name.lastIndexOf("/") + 1),
blob: new Blob([data.slice()], { type: MIME_BY_EXTENSION[ext] }),
};
} else {
unmatchedFiles.push(name);
}
}
return { matched, unmatchedFiles };
}
+315
View File
@@ -0,0 +1,315 @@
export type SoundEventId =
| "connect"
| "disconnect"
| "clientJoin"
| "clientLeave"
| "message"
| "poke"
| "mute"
| "micClickOn"
| "micClickOff"
| "whisper";
export const SOUND_EVENTS: SoundEventId[] = [
"connect",
"disconnect",
"clientJoin",
"clientLeave",
"message",
"poke",
"mute",
"micClickOn",
"micClickOff",
"whisper",
];
/** "ide" swaps the default chimes for synthetic terminal blips (Command Center layout). */
type SoundStyle = "classic" | "ide";
let soundStyle: SoundStyle = "classic";
export function setSoundStyle(style: SoundStyle): void {
soundStyle = style;
}
const ENABLED_KEY = "webspeak3:sounds-enabled";
const VOLUME_KEY = "webspeak3:sounds-volume";
const EVENT_ENABLED_KEY_PREFIX = "webspeak3:sounds-enabled:";
const DB_NAME = "webspeak3-sounds";
const STORE_NAME = "custom";
interface StoredSound {
blob: Blob;
name: string;
}
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore(STORE_NAME);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
export async function saveCustomSound(event: SoundEventId, file: File): Promise<void> {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).put({ blob: file, name: file.name } satisfies StoredSound, event);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
}
export async function loadCustomSound(event: SoundEventId): Promise<StoredSound | undefined> {
const db = await openDb();
const result = await new Promise<StoredSound | undefined>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const req = tx.objectStore(STORE_NAME).get(event);
req.onsuccess = () => resolve(req.result as StoredSound | undefined);
req.onerror = () => reject(req.error);
});
db.close();
return result;
}
export async function clearCustomSound(event: SoundEventId): Promise<void> {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).delete(event);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
}
export function loadSoundsEnabled(): boolean {
const raw = localStorage.getItem(ENABLED_KEY);
return raw === null ? true : raw === "true";
}
export function saveSoundsEnabled(enabled: boolean): void {
localStorage.setItem(ENABLED_KEY, String(enabled));
}
export function loadEventSoundEnabled(event: SoundEventId): boolean {
const raw = localStorage.getItem(EVENT_ENABLED_KEY_PREFIX + event);
return raw === null ? true : raw === "true";
}
export function saveEventSoundEnabled(event: SoundEventId, enabled: boolean): void {
localStorage.setItem(EVENT_ENABLED_KEY_PREFIX + event, String(enabled));
}
export function loadSoundsVolume(): number {
const raw = localStorage.getItem(VOLUME_KEY);
const n = raw ? Number(raw) : 0.5;
return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.5;
}
export function saveSoundsVolume(volume: number): void {
localStorage.setItem(VOLUME_KEY, String(volume));
}
type SinkableElement = HTMLAudioElement & { setSinkId?: (id: string) => Promise<void> };
/**
* Notification sounds get their own AudioContext, independent from the
* voice AudioContext in voice.ts - that one is created on connect and torn
* down on disconnect, but sounds must keep working (and be testable from
* Options) regardless of connection state.
*/
class NotificationSoundPlayer {
private context: AudioContext | null = null;
private destination: MediaStreamAudioDestinationNode | null = null;
private element: SinkableElement | null = null;
private outputDeviceId = "";
private ensure(): { context: AudioContext; destination: MediaStreamAudioDestinationNode } {
if (!this.context) {
const context = new AudioContext();
const destination = context.createMediaStreamDestination();
const element: SinkableElement = new Audio();
element.srcObject = destination.stream;
element.autoplay = true;
this.context = context;
this.destination = destination;
this.element = element;
if (this.outputDeviceId && typeof element.setSinkId === "function") {
element.setSinkId(this.outputDeviceId).catch(() => {});
}
}
return { context: this.context, destination: this.destination! };
}
async setOutputDevice(deviceId: string): Promise<void> {
this.outputDeviceId = deviceId;
if (this.element && typeof this.element.setSinkId === "function") {
await this.element.setSinkId(deviceId).catch(() => {});
}
}
async playBlob(blob: Blob, volume: number): Promise<void> {
const { context, destination } = this.ensure();
if (context.state === "suspended") await context.resume().catch(() => {});
const arrayBuffer = await blob.arrayBuffer();
const audioBuffer = await context.decodeAudioData(arrayBuffer);
const source = context.createBufferSource();
source.buffer = audioBuffer;
const gain = context.createGain();
gain.gain.value = volume;
source.connect(gain).connect(destination);
source.start();
}
playSynth(event: SoundEventId, volume: number): void {
const { context, destination } = this.ensure();
if (context.state === "suspended") context.resume().catch(() => {});
const now = context.currentTime;
for (const note of soundStyle === "ide" ? ideNotes(event) : synthNotes(event)) {
this.playNote(context, destination, now + note.delay, volume * note.gain, note);
}
}
private playNote(
context: AudioContext,
destination: AudioNode,
startTime: number,
peakGain: number,
{ freq, endFreq, duration, type = "sine" }: SynthNote
): void {
const osc = context.createOscillator();
osc.type = type;
osc.frequency.setValueAtTime(freq, startTime);
if (endFreq) osc.frequency.exponentialRampToValueAtTime(endFreq, startTime + duration);
const gain = context.createGain();
gain.gain.setValueAtTime(0, startTime);
gain.gain.linearRampToValueAtTime(peakGain, startTime + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, startTime + duration);
osc.connect(gain).connect(destination);
osc.start(startTime);
osc.stop(startTime + duration + 0.05);
}
}
/** Soft, modern two/three-note chimes - a sine-wave, quick-attack/exponential-decay
* shape reads as gentle rather than the harsh square/saw beeps of classic UI sounds. */
interface SynthNote {
delay: number;
freq: number;
/** Glide to this frequency over the note's duration. */
endFreq?: number;
duration: number;
gain: number;
type?: OscillatorType;
}
function synthNotes(event: SoundEventId): SynthNote[] {
switch (event) {
case "connect":
return [
{ delay: 0, freq: 523.25, duration: 0.16, gain: 0.5 },
{ delay: 0.09, freq: 783.99, duration: 0.22, gain: 0.5 },
];
case "disconnect":
return [
{ delay: 0, freq: 659.25, duration: 0.16, gain: 0.45 },
{ delay: 0.09, freq: 440.0, duration: 0.24, gain: 0.45 },
];
case "clientJoin":
return [{ delay: 0, freq: 880.0, duration: 0.14, gain: 0.4 }];
case "clientLeave":
return [{ delay: 0, freq: 587.33, duration: 0.16, gain: 0.4 }];
case "message":
return [
{ delay: 0, freq: 987.77, duration: 0.09, gain: 0.35 },
{ delay: 0.06, freq: 1318.51, duration: 0.12, gain: 0.3 },
];
case "poke":
return [
{ delay: 0, freq: 987.77, duration: 0.1, gain: 0.5 },
{ delay: 0.12, freq: 987.77, duration: 0.1, gain: 0.5 },
];
case "mute":
return [{ delay: 0, freq: 660, duration: 0.06, gain: 0.3 }];
case "micClickOn":
return [{ delay: 0, freq: 1400, duration: 0.03, gain: 0.15 }];
case "micClickOff":
return [{ delay: 0, freq: 900, duration: 0.03, gain: 0.15 }];
case "whisper":
return [
{ delay: 0, freq: 783.99, duration: 0.12, gain: 0.2 },
{ delay: 0.1, freq: 659.25, duration: 0.16, gain: 0.18 },
];
}
}
/** Command Center: short, dry, synthetic blips - square/triangle clicks and
* quick arpeggios instead of soft chimes. Square waves are loud, so lower gains. */
function ideNotes(event: SoundEventId): SynthNote[] {
switch (event) {
case "connect":
return [
{ delay: 0, freq: 440, duration: 0.1, gain: 0.3 },
{ delay: 0.1, freq: 554.37, duration: 0.1, gain: 0.3 },
{ delay: 0.2, freq: 659.25, duration: 0.14, gain: 0.3 },
];
case "disconnect":
return [{ delay: 0, freq: 200, endFreq: 50, duration: 0.2, gain: 0.45, type: "triangle" }];
case "clientJoin":
return [
{ delay: 0, freq: 800, duration: 0.07, gain: 0.18 },
{ delay: 0.1, freq: 800, duration: 0.07, gain: 0.18 },
];
case "clientLeave":
return [{ delay: 0, freq: 600, endFreq: 400, duration: 0.09, gain: 0.18 }];
case "message":
return [{ delay: 0, freq: 1200, duration: 0.04, gain: 0.12, type: "square" }];
case "poke":
return [
{ delay: 0, freq: 1000, duration: 0.05, gain: 0.12, type: "square" },
{ delay: 0.08, freq: 1000, duration: 0.05, gain: 0.12, type: "square" },
{ delay: 0.16, freq: 1000, duration: 0.05, gain: 0.12, type: "square" },
];
case "mute":
return [{ delay: 0, freq: 300, endFreq: 50, duration: 0.04, gain: 0.15, type: "square" }];
case "micClickOn":
return [{ delay: 0, freq: 1600, duration: 0.02, gain: 0.08, type: "square" }];
case "micClickOff":
return [{ delay: 0, freq: 1000, duration: 0.02, gain: 0.08, type: "square" }];
case "whisper":
return [{ delay: 0, freq: 900, endFreq: 700, duration: 0.08, gain: 0.1, type: "triangle" }];
}
}
const player = new NotificationSoundPlayer();
export function setSoundsOutputDevice(deviceId: string): void {
void player.setOutputDevice(deviceId);
}
/** A file from an imported sound pack (Options -> Meldungen). */
export async function playSoundBlob(blob: Blob): Promise<void> {
if (!loadSoundsEnabled()) return;
await player.playBlob(blob, loadSoundsVolume()).catch(() => {});
}
export async function playSound(event: SoundEventId): Promise<void> {
if (!loadSoundsEnabled()) return;
if (!loadEventSoundEnabled(event)) return;
const volume = loadSoundsVolume();
const custom = await loadCustomSound(event).catch(() => undefined);
if (custom) {
try {
await player.playBlob(custom.blob, volume);
return;
} catch {
// Stored file failed to decode (corrupted/unsupported) - fall back to the default chime.
}
}
player.playSynth(event, volume);
}
+22
View File
@@ -0,0 +1,22 @@
// With storage blocked (privacy settings, some embedded webviews) merely
// touching `localStorage` throws, and dozens of module-level reads would
// leave a blank page. Swap in an in-memory stand-in so the app runs; settings
// just don't survive a reload then. Imported first thing in main.tsx.
try {
const probe = "__webspeak3_probe__";
localStorage.setItem(probe, probe);
localStorage.removeItem(probe);
} catch {
const data = new Map<string, string>();
const memory: Storage = {
get length() {
return data.size;
},
key: (i) => [...data.keys()][i] ?? null,
getItem: (k) => data.get(k) ?? null,
setItem: (k, v) => void data.set(k, String(v)),
removeItem: (k) => void data.delete(k),
clear: () => data.clear(),
};
Object.defineProperty(window, "localStorage", { value: memory, configurable: true });
}
+315
View File
@@ -0,0 +1,315 @@
// Viewing a TeamSpeak 6 Stream/Call broadcast in the browser.
//
// TS6's stream signaling rides the ordinary TS3 command channel, so everything
// here travels the same WebSocket as the rest of the session: the connector
// unescapes the TS wire format and hands us the JSON payload untouched (see
// ts6-re/findings/ts6-stream-protocol-static-analysis.md).
//
// The exchange, from our side:
//
// 1. discover client_is_streaming=1 on a client in view
// 2. joinStream -> notifyrespondjoinstreamrequest (decision=1 + SDP offer)
// 3. answer <- streamSignal {cmd:"answer"}
// 4. trickle ICE both directions via {cmd:"iceCandidate"}
//
// TS6 publishes sendonly, so this is a receive-only peer connection.
/** A `streamEvent` as the connector emits it. */
export interface StreamEvent {
type: "streamEvent";
name: string;
args: Record<string, string>;
}
/**
* The payload shape inside `notifystreamsignaling`'s `json` argument.
*
* Each `cmd` names its own key inside `args`, and the key is *not* `sdp`
* except for `iceCandidate`: an answer is `{answer: "<sdp>"}`, an offer
* `{offer: "<sdp>"}`, a candidate `{sdp, mid, mLine}`. Live-verified against
* TS6 6.0.0-beta12.1 - `{sdp: "<sdp>"}` and a bare string are both accepted
* by the server and then silently dropped by the client.
*/
interface SignalingMessage {
cmd: string;
args: unknown;
}
export interface StreamInfo {
id: string;
clientId: number;
name: string;
/** Current viewer count as of the last notifystreaminfo. */
viewers: number;
hasAudio: boolean;
bitrate: number;
}
export interface StreamViewerOptions {
/** Sends one message up the session WebSocket. */
send: (message: Record<string, unknown>) => void;
/** The remote media, once the first track arrives. */
onTrack: (stream: MediaStream) => void;
onStateChange?: (state: RTCPeerConnectionState) => void;
onError?: (error: string) => void;
/** The viewer shut down — by us, or because the publisher stopped. */
onClosed?: () => void;
/**
* ICE servers to use. TS6 itself only ever configures `stun:` URLs and so
* never gathers a relay candidate, but it will happily *connect* to one we
* offer - which is how webspeak3 can work on networks where TS6 cannot.
*/
iceServers?: RTCIceServer[];
}
export const DEFAULT_ICE_SERVERS: RTCIceServer[] = [
{ urls: "stun:turn.teamspeak.com:3478" },
{ urls: "stun:turn2.teamspeak.com:3478" },
{ urls: "stun:stun.l.google.com:19302" },
];
/**
* Reads a stream's properties out of a `notifystreaminfo` / `notifystreamstarted`.
*
* The two notifies disagree on one name: `notifystreaminfo` says
* `accessibility`, `notifystreamstarted` shortens it to `access`. Only
* `notifystreaminfo` carries `viewer`.
*/
export function parseStreamInfo(args: Record<string, string>): StreamInfo | null {
const id = args.id;
const clientId = Number(args.clid);
if (!id || !Number.isFinite(clientId)) return null;
return {
id,
clientId,
name: args.name ?? "",
viewers: Number(args.viewer ?? 0) || 0,
hasAudio: args.audio === "1",
bitrate: Number(args.bitrate ?? 0) || 0,
};
}
export class StreamViewer {
private pc: RTCPeerConnection | null = null;
private readonly opts: StreamViewerOptions;
private readonly remote = new MediaStream();
/** Candidates that arrived before setRemoteDescription; replayed after. */
private pendingRemoteCandidates: RTCIceCandidateInit[] = [];
private remoteDescriptionSet = false;
private closed = false;
readonly streamId: string;
readonly peerClientId: number;
constructor(streamId: string, peerClientId: number, opts: StreamViewerOptions) {
this.streamId = streamId;
this.peerClientId = peerClientId;
this.opts = opts;
}
/** Asks the publishing client to let us watch. The offer arrives asynchronously. */
join(message = ""): void {
this.opts.send({
type: "joinStream",
streamId: this.streamId,
clientId: this.peerClientId,
message,
});
}
/**
* Feeds one `streamEvent` in. Events for other streams are ignored, so the
* caller can pass everything it receives without filtering.
*/
handleEvent(event: StreamEvent): void {
if (this.closed) return;
if (event.args.id && event.args.id !== this.streamId) return;
switch (event.name) {
case "notifyrespondjoinstreamrequest":
void this.handleJoinResponse(event.args);
break;
case "notifystreamsignaling":
void this.handleSignaling(event.args);
break;
case "notifystreamstopped":
case "notifystreamclientleft":
this.close();
break;
}
}
private async handleJoinResponse(args: Record<string, string>): Promise<void> {
if (args.decision !== "1") {
this.fail(args.msg ? `Stream join refused: ${args.msg}` : "Stream join refused");
return;
}
if (!args.offer) {
this.fail("Stream join accepted but no SDP offer was sent");
return;
}
await this.acceptOffer(args.offer);
}
private async acceptOffer(sdp: string): Promise<void> {
const pc = this.ensurePeerConnection();
try {
await pc.setRemoteDescription({ type: "offer", sdp });
this.remoteDescriptionSet = true;
await this.flushRemoteCandidates();
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
this.signal("answer", { answer: answer.sdp ?? "" });
} catch (err) {
this.fail(`Could not answer the stream offer: ${describe(err)}`);
}
}
private async handleSignaling(args: Record<string, string>): Promise<void> {
let msg: SignalingMessage;
try {
msg = JSON.parse(args.json ?? "");
} catch {
this.fail("Received malformed stream signaling payload");
return;
}
switch (msg.cmd) {
case "iceCandidate": {
const candidate =
typeof msg.args === "object" && msg.args !== null
? candidateFromArgs(msg.args as Record<string, unknown>)
: null;
if (!candidate) return;
if (!this.remoteDescriptionSet) {
// TS6 starts trickling immediately, so these routinely beat the
// offer's setRemoteDescription. Holding them is not an edge case.
this.pendingRemoteCandidates.push(candidate);
return;
}
try {
await this.ensurePeerConnection().addIceCandidate(candidate);
} catch (err) {
// A single unusable candidate must not tear the session down; ICE
// only needs one working pair.
console.warn("[stream] ignoring ICE candidate:", describe(err));
}
break;
}
case "offer":
case "reconnectOffer": {
// Renegotiation from the publisher, e.g. after it switches source.
// `offer` mirrors the `answer` key we send; the other two are cheap
// to tolerate and cost nothing if they never arrive.
const a = msg.args as Record<string, unknown> | string | null;
const sdp =
typeof a === "string"
? a
: typeof a?.offer === "string"
? a.offer
: typeof a?.sdp === "string"
? a.sdp
: null;
if (sdp) await this.acceptOffer(sdp);
break;
}
default:
break;
}
}
private async flushRemoteCandidates(): Promise<void> {
const pending = this.pendingRemoteCandidates;
this.pendingRemoteCandidates = [];
const pc = this.ensurePeerConnection();
for (const candidate of pending) {
try {
await pc.addIceCandidate(candidate);
} catch (err) {
console.warn("[stream] ignoring buffered ICE candidate:", describe(err));
}
}
}
private ensurePeerConnection(): RTCPeerConnection {
if (this.pc) return this.pc;
const pc = new RTCPeerConnection({
iceServers: this.opts.iceServers ?? DEFAULT_ICE_SERVERS,
});
pc.ontrack = (ev) => {
this.remote.addTrack(ev.track);
this.opts.onTrack(this.remote);
};
pc.onicecandidate = (ev) => {
if (!ev.candidate) return; // end-of-candidates; TS6 sends no such marker
this.signal("iceCandidate", {
sdp: ev.candidate.candidate,
mid: ev.candidate.sdpMid ?? "0",
mLine: ev.candidate.sdpMLineIndex ?? 0,
});
};
pc.onconnectionstatechange = () => {
this.opts.onStateChange?.(pc.connectionState);
if (pc.connectionState === "failed") this.fail("The stream connection failed");
};
this.pc = pc;
return pc;
}
private signal(cmd: string, args: unknown): void {
this.opts.send({
type: "streamSignal",
streamId: this.streamId,
clientId: this.peerClientId,
payload: { cmd, args },
});
}
private fail(message: string): void {
this.opts.onError?.(message);
}
/** Leaves the stream and releases the peer connection. Safe to call twice. */
close(): void {
if (this.closed) return;
this.closed = true;
this.opts.send({
type: "leaveStream",
streamId: this.streamId,
clientId: this.peerClientId,
});
for (const track of this.remote.getTracks()) track.stop();
this.pc?.close();
this.pc = null;
this.opts.onClosed?.();
}
}
/**
* Builds an `RTCIceCandidateInit` from TS6's `iceCandidate` args.
*
* TS6 names them `sdp`, `mid` and `mLine`, which map to `candidate`, `sdpMid`
* and `sdpMLineIndex`.
*/
function candidateFromArgs(args: Record<string, unknown>): RTCIceCandidateInit | null {
const candidate = args.sdp;
if (typeof candidate !== "string" || !candidate) return null;
return {
candidate,
sdpMid: typeof args.mid === "string" ? args.mid : undefined,
sdpMLineIndex: typeof args.mLine === "number" ? args.mLine : undefined,
};
}
function describe(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
+717
View File
@@ -0,0 +1,717 @@
/* Command Center (IDE style): explorer | voice grid + terminal | inspector,
flat zinc/emerald, always dark regardless of the light/dark toggle.
Variables sit in :where() so custom themes can override them; component
rules use .ts-app.ts-design-ide like Pulse does, so they beat App.css
without !important. Imported right after App.css in App.tsx - the order
matters for the zero-specificity block. */
/* Pixel terminal font, self-hosted (OFL) so no visitor IP goes to Google Fonts.
The file only downloads once an element actually uses it. */
@font-face {
font-family: "VT323";
font-weight: 400;
font-display: swap;
src: url("../assets/fonts/vt323-latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "VT323";
font-weight: 400;
font-display: swap;
src: url("../assets/fonts/vt323-latin-ext.woff2") format("woff2");
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
:where(.ts-app.ts-design-ide) {
/* VT323 has no bold cut; faux-bold smears the pixels. */
font-synthesis-weight: none;
--ide-mono: VT323, "Fira Code", "JetBrains Mono", Consolas, ui-monospace, monospace;
--ide-font: var(--ide-mono);
--ide-panel: #18181b;
--ide-faint: #71717a;
--ide-accent-bg: rgba(16, 185, 129, 0.1);
font-family: var(--ide-font);
/* VT323 has a tiny x-height and narrow glyphs: scale it up and space it out. */
font-size-adjust: 0.55;
letter-spacing: 0.05em;
font-size: 13px;
--bg: #09090b;
--bg-toolbar-1: #18181b;
--bg-toolbar-2: #18181b;
--border: #27272a;
--border-soft: #27272a;
--text: #e4e4e7;
--text-muted: #a1a1aa;
--text-faint: #71717a;
--accent: #10b981;
--success: #10b981;
--input-bg: #09090b;
--input-text: #e4e4e7;
--button-bg-1: #18181b;
--button-bg-2: #18181b;
--button-bg-hover-1: #27272a;
--button-bg-hover-2: #27272a;
--row-hover: #27272a;
--client-text: #a1a1aa;
--self-text: #10b981;
--log-bg: #09090b;
}
.ts-app.ts-design-ide ::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.ts-app.ts-design-ide ::-webkit-scrollbar-track {
background: var(--bg);
border-left: 1px solid var(--border);
}
.ts-app.ts-design-ide ::-webkit-scrollbar-thumb {
background: #3f3f46;
border: 2px solid var(--bg);
}
.ts-app.ts-design-ide *:focus-visible {
outline: 1px solid var(--accent);
outline-offset: -1px;
}
/* Terminal font everywhere, beating base rules that pick their own family */
.ts-app.ts-design-ide:not(.ts-ide-plain-font) :is(*, *::before, *::after) {
font-family: var(--ide-font);
}
/* Pixel font switched off in the design options: sans UI, regular mono for the terminal bits */
.ts-app.ts-design-ide.ts-ide-plain-font {
--ide-mono: "Fira Code", "JetBrains Mono", Consolas, ui-monospace, monospace;
--ide-font: Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size-adjust: none;
letter-spacing: normal;
font-synthesis-weight: auto;
}
/* Form controls reset size adjust and spacing in the UA sheet instead of inheriting them */
.ts-app.ts-design-ide :is(button, input, select, textarea) {
font-size-adjust: inherit;
letter-spacing: inherit;
}
/* ---------- Header: menubar + toolbar + connection tabs ---------- */
/* No own row for the menubar: the hamburger floats into the toolbar row */
.ts-app.ts-design-ide > .ts-menubar {
position: relative;
z-index: 20;
height: 0;
padding: 0;
border: 0;
overflow: visible;
}
.ts-app.ts-design-ide > .ts-menubar .ts-nova-menu-dropdown {
position: absolute;
top: 0.4rem;
right: 0.5rem;
}
.ts-app.ts-design-ide > .ts-toolbar {
padding-right: 3rem;
}
.ts-app.ts-design-ide > .ts-toolbar {
background: var(--ide-panel);
border-bottom: 1px solid var(--border);
box-shadow: none;
}
.ts-app.ts-design-ide .ts-icon-button {
background: transparent;
border: none;
border-radius: 4px;
box-shadow: none;
color: var(--text-muted);
}
.ts-app.ts-design-ide .ts-icon-button:hover {
background: var(--row-hover);
color: #fff;
}
.ts-app.ts-design-ide .gts-connection-tabs {
font-family: var(--ide-mono);
background: var(--bg);
border-bottom: 1px solid var(--border);
font-size: 12px;
}
.ts-app.ts-design-ide .gts-connection-tab {
background: transparent;
border: none;
border-right: 1px solid var(--border);
border-radius: 0;
color: var(--text-muted);
}
.ts-app.ts-design-ide .gts-connection-tab-active {
background: var(--ide-panel);
color: var(--text);
box-shadow: inset 0 2px 0 var(--accent);
}
/* ---------- Body: explorer | center | inspector ---------- */
.ts-app.ts-design-ide > .ts-body {
display: grid;
grid-template-columns: auto minmax(0, 1fr) 18rem;
grid-template-rows: minmax(0, 1fr);
}
/* Flatten the Standard "upper row" so tree and info panel become grid cells */
.ts-app.ts-design-ide .ts-upper {
display: contents;
}
.ts-app.ts-design-ide .ts-resize-handle-vertical,
.ts-app.ts-design-ide .ts-resize-handle-horizontal {
display: none;
}
.ts-app.ts-design-ide .ts-tree-panel,
.ts-app.ts-design-ide .ts-side-panel {
grid-row: 1;
overflow-y: auto;
background: var(--ide-panel);
}
.ts-app.ts-design-ide .ts-tree-panel {
font-family: var(--ide-mono);
grid-column: 1;
overflow-x: hidden;
min-width: 16rem;
padding: 0 0 0.5rem;
border-right: 1px solid var(--border);
font-size: 12px;
}
.ts-app.ts-design-ide .ts-side-panel {
font-family: var(--ide-mono);
grid-column: 3;
border-left: 1px solid var(--border);
font-size: 11px;
}
.ts-app.ts-design-ide .ts-chat-panel {
grid-column: 2;
grid-row: 1;
background: var(--bg);
}
/* Section headers like an IDE side bar */
.ts-app.ts-design-ide .ts-tree-panel::before,
.ts-app.ts-design-ide .ts-side-panel::before {
font-family: var(--ide-mono);
display: flex;
align-items: center;
flex-shrink: 0;
height: 2rem;
padding: 0 1rem;
margin-bottom: 0.4rem;
border-bottom: 1px solid var(--border);
font-size: 10px;
font-weight: 600;
letter-spacing: 0.15em;
text-transform: uppercase;
color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-tree-panel::before {
content: "Explorer";
}
.ts-app.ts-design-ide .ts-side-panel::before {
content: "Inspector";
margin-bottom: 0;
}
.ts-app.ts-design-ide .ts-tree-panel > * {
margin-left: 0.5rem;
margin-right: 0.5rem;
}
.ts-app.ts-design-ide .ts-row {
border-radius: 0;
}
.ts-app.ts-design-ide .ts-row-selected {
background: var(--ide-accent-bg);
color: var(--text);
}
/* Explorer tree as in the mockup: carets and dots instead of folder/server icons and orbs */
.ts-app.ts-design-ide .ts-server-row > svg,
.ts-app.ts-design-ide .ts-channel-row > svg {
display: none;
}
.ts-app.ts-design-ide .ts-server-row {
color: var(--text);
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
}
.ts-app.ts-design-ide .ts-server-row::before {
content: "\25BE";
color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-row {
padding-top: 2px;
padding-bottom: 2px;
}
.ts-app.ts-design-ide .ts-channel-row {
color: var(--text-muted);
}
.ts-app.ts-design-ide .ts-channel-row:has(+ .ts-tree-list .ts-self) {
color: var(--text);
background: rgba(39, 39, 42, 0.5);
}
.ts-app.ts-design-ide .ts-tree-expander span {
border-top-color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-tree-expander-collapsed span {
border-top-color: transparent;
border-left-color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-client-row.ts-self {
font-weight: 400;
}
.ts-app.ts-design-ide .ts-client-row.ts-talking {
outline: 1px solid var(--accent);
outline-offset: -1px;
background: rgba(16, 185, 129, 0.05);
color: var(--text);
}
.ts-app.ts-design-ide .ts-talk-lamp-idle,
.ts-app.ts-design-ide .ts-talk-lamp-talking {
position: relative;
width: 6px;
height: 6px;
margin: 0 4px;
background: #52525b;
box-shadow: none;
}
.ts-app.ts-design-ide .ts-talk-lamp-talking {
background: var(--accent);
}
.ts-app.ts-design-ide .ts-talk-lamp-talking::after {
content: "";
position: absolute;
inset: 0;
border-radius: 50%;
background: var(--accent);
animation: ts-ide-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
}
@keyframes ts-ide-ping {
75%,
100% {
transform: scale(2.5);
opacity: 0;
}
}
/* The narrow explorer must not squeeze the name away in favour of the away message */
.ts-app.ts-design-ide .ts-client-row .ts-tree-label {
flex-shrink: 0;
}
.ts-app.ts-design-ide .ts-client-away-message {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.ts-app.ts-design-ide .ts-talk-lamp-muted {
opacity: 0.7;
}
.ts-app.ts-design-ide .ts-tree-search {
font-family: var(--ide-mono);
border-radius: 0;
}
/* Inspector content */
.ts-app.ts-design-ide .ts-info-panel {
padding: 1rem;
}
.ts-app.ts-design-ide .ts-info-title {
color: var(--text);
font-size: 13px;
font-weight: 600;
}
.ts-app.ts-design-ide .ts-info-row {
color: var(--text-muted);
}
.ts-app.ts-design-ide .ts-info-connection-link {
letter-spacing: 0.05em;
color: var(--accent);
text-transform: uppercase;
font-size: 10px;
}
/* ---------- Center: breadcrumb, voice grid, terminal ---------- */
.ts-app.ts-design-ide .ts-ide-breadcrumb {
font-family: var(--ide-mono);
flex-shrink: 0;
display: flex;
align-items: center;
gap: 0.3rem;
height: 2rem;
padding: 0 1rem;
border-bottom: 1px solid var(--border);
font-size: 12px;
color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-ide-breadcrumb span {
color: var(--text);
}
.ts-app.ts-design-ide .ts-speaking-now {
flex: 1;
min-height: 0;
overflow-y: auto;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
align-content: start;
gap: 1rem;
padding: 1.5rem;
}
.ts-app.ts-design-ide .ts-speaking-now-tile {
position: relative;
display: flex;
align-items: flex-start;
gap: 1rem;
padding: 1rem;
overflow: hidden;
background: var(--ide-panel);
border: 1px solid var(--border);
border-radius: 4px;
opacity: 0.8;
transition: opacity 0.15s ease;
}
.ts-app.ts-design-ide .ts-speaking-now-tile:hover,
.ts-app.ts-design-ide .ts-speaking-now-tile-active {
opacity: 1;
}
.ts-app.ts-design-ide .ts-speaking-now-tile-active {
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent), 0 0 12px rgba(16, 185, 129, 0.35);
}
/* Speaking glow along the top edge */
.ts-app.ts-design-ide .ts-speaking-now-tile-active::before {
content: "";
position: absolute;
inset: 0 0 auto;
height: 2px;
background: var(--accent);
box-shadow: 0 0 10px rgba(16, 185, 129, 0.8);
}
.ts-app.ts-design-ide .ts-speaking-now-avatar {
font-family: var(--ide-mono);
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 48px;
height: 48px;
overflow: hidden;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--bg);
font-size: 18px;
font-weight: 600;
color: #fff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
.ts-app.ts-design-ide .ts-speaking-now-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.ts-app.ts-design-ide .ts-speaking-now-name {
min-width: 0;
max-width: none;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
font-weight: 500;
color: var(--text-muted);
}
.ts-app.ts-design-ide .ts-speaking-now-tile-active .ts-speaking-now-name {
color: var(--text);
font-weight: 600;
}
.ts-app.ts-design-ide .ts-speaking-now-body {
flex: 1;
min-width: 0;
}
.ts-app.ts-design-ide .ts-speaking-now-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.25rem;
}
.ts-app.ts-design-ide .ts-speaking-now-head .ts-talk-lamp-muted {
opacity: 0.6;
}
/* Little audio visualizer for the speaker */
.ts-app.ts-design-ide .ts-speaking-now-bars {
display: flex;
align-items: flex-end;
gap: 2px;
height: 12px;
}
.ts-app.ts-design-ide .ts-speaking-now-bars i {
width: 4px;
height: 100%;
background: var(--accent);
animation: ts-ide-bar 0.8s ease-in-out infinite alternate;
}
.ts-app.ts-design-ide .ts-speaking-now-bars i:nth-child(2) {
animation-delay: -0.3s;
}
.ts-app.ts-design-ide .ts-speaking-now-bars i:nth-child(3) {
animation-delay: -0.55s;
}
@keyframes ts-ide-bar {
from {
height: 25%;
}
to {
height: 100%;
}
}
.ts-app.ts-design-ide .ts-speaking-now-groups {
display: flex;
flex-wrap: wrap;
gap: 0.375rem;
}
.ts-app.ts-design-ide .ts-speaking-now-group {
font-family: var(--ide-mono);
padding: 0 0.25rem;
border: 1px solid var(--group-color);
background: color-mix(in srgb, var(--group-color) 10%, transparent);
color: color-mix(in srgb, var(--group-color) 75%, #fff);
font-size: 9px;
line-height: 1.5;
text-transform: uppercase;
}
.ts-app.ts-design-ide .ts-speaking-now-tile {
cursor: pointer;
}
.ts-app.ts-design-ide .ts-speaking-now-tile-selected {
border-color: var(--text-muted);
background: #1f1f23;
opacity: 1;
}
/* Speaking wins over selected */
.ts-app.ts-design-ide .ts-speaking-now-tile-selected.ts-speaking-now-tile-active {
border-color: var(--accent);
}
.ts-app.ts-design-ide .ts-speaking-now-status {
font-family: var(--ide-mono);
margin-top: 0.375rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
color: var(--ide-faint);
}
/* Terminal: fixed-height bottom pane once the voice grid is above it */
.ts-app.ts-design-ide .ts-chat-panel:has(.ts-speaking-now) .ts-chat-messages {
flex: 0 0 11rem;
}
.ts-app.ts-design-ide .ts-chat-tabs {
order: 1;
gap: 1.5rem;
padding: 0.5rem 1rem 0;
background: var(--ide-panel);
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
.ts-app.ts-design-ide .ts-chat-messages {
font-family: var(--ide-mono);
order: 2;
padding: 1rem;
background: var(--ide-panel);
font-size: 12px;
line-height: 1.6;
color: var(--text-muted);
}
.ts-app.ts-design-ide .ts-chat-tab {
font-family: var(--ide-mono);
padding: 0 0 0.5rem;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
border-radius: 0;
font-size: 11px;
font-weight: 400;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--ide-faint);
}
.ts-app.ts-design-ide .ts-chat-tab:hover {
color: var(--text);
}
.ts-app.ts-design-ide .ts-chat-tab-active {
border-bottom-color: var(--accent);
color: var(--text);
}
.ts-app.ts-design-ide .ts-chat-from {
color: #d4d4d8;
font-weight: 500;
}
.ts-app.ts-design-ide .ts-chat-line-self .ts-chat-from {
color: var(--accent);
}
.ts-app.ts-design-ide .ts-chat-line-log {
color: #60a5fa;
}
.ts-app.ts-design-ide .ts-chat-bubble {
background: none;
padding: 0;
border-radius: 0;
}
/* Prompt-style input */
.ts-app.ts-design-ide .ts-chat-input-row {
font-family: var(--ide-mono);
order: 3;
align-items: center;
gap: 0.5rem;
padding: 0.3rem 1rem;
background: var(--bg);
border-top: 1px solid var(--border);
}
.ts-app.ts-design-ide .ts-chat-input-row::before {
content: "➜ ~/channel";
flex-shrink: 0;
font-weight: 600;
font-size: 12px;
color: #60a5fa;
}
.ts-app.ts-design-ide .ts-chat-input-row textarea,
.ts-app.ts-design-ide .ts-chat-input-row input {
font-family: var(--ide-mono);
background: transparent;
border: none;
box-shadow: none;
font-size: 12px;
color: var(--text);
}
.ts-app.ts-design-ide .ts-chat-input-row button,
.ts-app.ts-design-ide .ts-dialog button:not(.ts-icon-button) {
letter-spacing: 0.05em;
border-radius: 4px;
border: 1px solid var(--border);
box-shadow: none;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
}
/* Client log strip at the very bottom */
.ts-app.ts-design-ide > .ts-log {
font-family: var(--ide-mono);
background: var(--bg);
border-top: 1px solid var(--border);
}
/* Narrow screens: stack instead of three columns */
@media (max-width: 900px) {
.ts-app.ts-design-ide > .ts-body {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr);
}
.ts-app.ts-design-ide .ts-tree-panel {
grid-column: 1;
grid-row: 1;
width: auto !important;
max-height: 40vh;
border-right: none;
border-bottom: 1px solid var(--border);
}
.ts-app.ts-design-ide .ts-side-panel {
display: none;
}
.ts-app.ts-design-ide .ts-chat-panel {
grid-column: 1;
grid-row: 2;
}
}
@media (prefers-reduced-motion: reduce) {
.ts-app.ts-design-ide .ts-talk-lamp-talking::after,
.ts-app.ts-design-ide .ts-speaking-now-bars i {
animation: none;
}
}
+477
View File
@@ -0,0 +1,477 @@
// Options -> Konto: Mullvad-style account sync. A random 16-digit account number
// (+ an optional random password) is all there is. Both derive, on this device,
// the account id the server files the data under, the AES key and the auth
// secret, so the server only ever holds an encrypted blob (gateway/src/sync.ts).
//
// Pulled once at startup (main.tsx, before App reads localStorage) and pushed on
// a timer whenever a synced key changed. A remote change made while this tab is
// open shows up as a conflict on the next push, not live.
export type SyncCategory = "identities" | "favorites" | "settings" | "designs" | "whisper";
export const SYNC_CATEGORIES: SyncCategory[] = ["identities", "favorites", "settings", "designs", "whisper"];
// Device-specific keys (audio devices, volumes, PTT key, chat logs, caches) stay local.
const CATEGORY_KEYS: Record<SyncCategory, string[]> = {
identities: ["webspeak3:identities", "webspeak3:identity", "webspeak3:active-identity"],
favorites: ["webspeak3:favorites", "webspeak3:channel-passwords", "webspeak3:contacts"],
settings: [
"webspeak3:app-settings",
"webspeak3:chat-settings",
"webspeak3:chat-images",
"webspeak3:server-banner",
"webspeak3:download-settings",
"webspeak3:notification-settings",
"webspeak3:security-settings",
"webspeak3:away-presets",
"webspeak3:disconnect-message",
"webspeak3:language",
"webspeak3:sounds-enabled",
"webspeak3:sounds-volume",
"webspeak3:other-mic-clicks",
"webspeak3:own-mic-clicks",
],
designs: [
"webspeak3:custom-themes",
"webspeak3:design-selection",
"webspeak3:design-theme",
"webspeak3:icon-pack",
"webspeak3:icon-packs",
"webspeak3:ide-pixel-font",
"webspeak3:tree-options",
],
whisper: ["webspeak3:whisper-lists", "webspeak3:whisper-settings"],
};
/** Per-sound toggles are stored as "webspeak3:sounds-enabled:<id>". */
function categoryOf(key: string): SyncCategory | null {
for (const c of SYNC_CATEGORIES)
if (CATEGORY_KEYS[c].some((k) => key === k || (k === "webspeak3:sounds-enabled" && key.startsWith(`${k}:`)))) return c;
return null;
}
export const SYNC_ACCOUNT_KEY = "webspeak3:sync-account";
const meta = (name: string) => document.querySelector<HTMLMetaElement>(`meta[name="webspeak3-${name}"]`)?.content;
export const DEFAULT_SYNC_SERVER =
meta("sync-url") ||
import.meta.env.VITE_SYNC_URL ||
(import.meta.env.DEV ? "http://localhost:8081/api/sync" : "https://gateway.webspeak3.de/api/sync");
export interface SyncAccount {
number: string;
password?: string;
server: string;
categories: SyncCategory[];
/** Server version this device last wrote or read. */
version: number;
/** Hash of the synced keys at that point; differs = local changes to push. */
syncedHash: string;
lastSync?: number;
}
export type SyncState = "off" | "idle" | "syncing" | "error" | "conflict";
export interface SyncStatus {
state: SyncState;
error?: string;
lastSync?: number;
}
// --- tiny external store for the Konto panel ---------------------------------
let status: SyncStatus = { state: "off" };
const listeners = new Set<() => void>();
function setStatus(next: SyncStatus) {
status = next;
for (const l of listeners) l();
}
export const getSyncStatus = () => status;
export function subscribeSyncStatus(l: () => void) {
listeners.add(l);
return () => void listeners.delete(l);
}
export function loadSyncAccount(): SyncAccount | null {
try {
const raw = localStorage.getItem(SYNC_ACCOUNT_KEY);
return raw ? (JSON.parse(raw) as SyncAccount) : null;
} catch {
return null;
}
}
function saveSyncAccount(account: SyncAccount | null) {
if (account) localStorage.setItem(SYNC_ACCOUNT_KEY, JSON.stringify(account));
else localStorage.removeItem(SYNC_ACCOUNT_KEY);
}
// --- number, password, crypto -------------------------------------------------
function randomChars(alphabet: string, count: number): string {
let out = "";
const limit = 256 - (256 % alphabet.length); // reject to avoid modulo bias
while (out.length < count) {
for (const b of crypto.getRandomValues(new Uint8Array(count))) {
if (b < limit && out.length < count) out += alphabet[b % alphabet.length];
}
}
return out;
}
export const generateAccountNumber = () => randomChars("0123456789", 16);
/** 20 characters (~100 bits) without look-alikes, in groups of five. */
export const generatePassword = () => randomChars("ABCDEFGHJKLMNPQRSTUVWXYZ23456789", 20).replace(/(.{5})(?=.)/g, "$1-");
export const formatAccountNumber = (n: string) => n.replace(/(\d{4})(?=\d)/g, "$1 ");
/** null unless exactly 16 digits (spaces and dashes are ignored). */
export const normalizeAccountNumber = (s: string) => {
const digits = s.replace(/[\s-]/g, "");
return /^\d{16}$/.test(digits) ? digits : null;
};
export const normalizePassword = (s: string) => s.trim().toUpperCase();
const enc = (s: string) => new TextEncoder().encode(s);
const hex = (bytes: ArrayBuffer | Uint8Array) =>
[...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
const b64 = (bytes: Uint8Array) => {
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
};
const unb64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
const sha256Hex = async (s: string) => hex(await crypto.subtle.digest("SHA-256", enc(s)));
interface Keys {
id: string;
key: CryptoKey;
auth: string;
}
const keyCache = new Map<string, Promise<Keys>>();
function deriveKeys(number: string, password = ""): Promise<Keys> {
const cacheKey = `${number}\n${password}`;
let keys = keyCache.get(cacheKey);
if (!keys) {
keys = (async () => {
const base = await crypto.subtle.importKey("raw", enc(cacheKey), "PBKDF2", false, ["deriveBits"]);
const bits = new Uint8Array(
await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt: enc(`webspeak3-sync:${number}`), iterations: 310_000, hash: "SHA-256" },
base,
512
)
);
return {
// The id depends on the number only, so a new device can ask whether a password is needed.
id: await sha256Hex(`webspeak3-sync-id:${number}`),
key: await crypto.subtle.importKey("raw", bits.slice(0, 32), "AES-GCM", false, ["encrypt", "decrypt"]),
auth: hex(bits.slice(32)),
};
})();
keyCache.set(cacheKey, keys);
}
return keys;
}
interface Payload {
v: 1;
categories: SyncCategory[];
items: Record<string, string>;
}
/** Padded to a power of two (min 4 KB) so the blob size says little about its content. */
async function encrypt(key: CryptoKey, payload: Payload): Promise<string> {
const json = enc(JSON.stringify(payload));
let size = 4096;
while (size < json.length) size *= 2;
const plain = new Uint8Array(size).fill(0x20); // trailing spaces: JSON.parse ignores them
plain.set(json);
const iv = crypto.getRandomValues(new Uint8Array(12));
const data = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plain));
const out = new Uint8Array(12 + data.length);
out.set(iv);
out.set(data, 12);
return b64(out);
}
async function decrypt(key: CryptoKey, data: string): Promise<Payload> {
const bytes = unb64(data);
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(0, 12) }, key, bytes.subarray(12));
return JSON.parse(new TextDecoder().decode(plain)) as Payload;
}
// --- local snapshot -------------------------------------------------------------
/** Goes through length/key(i), which the vault's stand-in Storage also answers for secrets. */
function snapshot(categories: SyncCategory[]): Record<string, string> {
const items: Record<string, string> = {};
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (!k) continue;
const c = categoryOf(k);
if (c && categories.includes(c)) items[k] = localStorage.getItem(k) ?? "";
}
return items;
}
const hashItems = (items: Record<string, string>) =>
sha256Hex(JSON.stringify(Object.keys(items).sort().map((k) => [k, items[k]])));
/** Remote replaces local for every category both sides sync; keys gone remotely go locally too. */
function applyPayload(payload: Payload, categories: SyncCategory[]) {
const shared = categories.filter((c) => payload.categories.includes(c));
for (const k of Object.keys(snapshot(shared))) if (!(k in payload.items)) localStorage.removeItem(k);
for (const [k, v] of Object.entries(payload.items)) {
const c = categoryOf(k);
if (c && shared.includes(c)) localStorage.setItem(k, v);
}
}
// --- server calls ---------------------------------------------------------------
const ERROR_CODES = new Set(["password_required", "unreachable", "not_found", "rate_limited", "full", "pow_required", "conflict", "payload_too_large"]);
/** Locale key for an error thrown by the functions below. */
export const syncErrorKey = (err: unknown) => {
const code = err instanceof Error ? err.message : String(err);
return ERROR_CODES.has(code) ? `sync.error.${code}` : "sync.error.generic";
};
async function call(server: string, path: string, init: RequestInit = {}, auth?: string) {
let res: Response;
try {
res = await fetch(`${server.replace(/\/$/, "")}${path}`, {
...init,
headers: {
...(init.body ? { "Content-Type": "application/json" } : {}),
...(auth ? { Authorization: `Bearer ${auth}` } : {}),
},
});
} catch {
throw new Error("unreachable");
}
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) throw new Error(String(body.error ?? res.status));
return body;
}
export async function accountInfo(number: string, server: string): Promise<{ exists: boolean; hasPassword?: boolean }> {
const { id } = await deriveKeys(number);
return (await call(server, `/${id}/meta`)) as { exists: boolean; hasPassword?: boolean };
}
/** Same check as gateway/src/sync.ts: leading zero bits of sha256(challenge:nonce).
* Batched, because one awaited digest at a time is dominated by the await. */
async function solvePow(challenge: string, bits: number): Promise<string> {
const zeroBits = (hash: Uint8Array) => {
let zeros = 0;
for (const b of hash) {
if (b !== 0) return zeros + Math.clz32(b) - 24;
zeros += 8;
}
return zeros;
};
for (let start = 0; ; start += 256) {
const hashes = await Promise.all(
Array.from({ length: 256 }, (_, i) => crypto.subtle.digest("SHA-256", enc(`${challenge}:${start + i}`)))
);
const hit = hashes.findIndex((h) => zeroBits(new Uint8Array(h)) >= bits);
if (hit >= 0) return String(start + hit);
}
}
async function push(account: SyncAccount, items: Record<string, string>, extra: Record<string, unknown> = {}) {
const k = await deriveKeys(account.number, account.password);
const data = await encrypt(k.key, { v: 1, categories: account.categories, items });
return (await call(
account.server,
`/${k.id}`,
{ method: "PUT", body: JSON.stringify({ version: account.version, data, hasPassword: !!account.password, ...extra }) },
k.auth
)) as { version: number };
}
async function pull(account: Pick<SyncAccount, "number" | "password" | "server">) {
const k = await deriveKeys(account.number, account.password);
const body = (await call(account.server, `/${k.id}`, {}, k.auth)) as { version: number; data: string };
return { version: body.version, payload: await decrypt(k.key, body.data) };
}
// --- what the Konto panel and main.tsx use ------------------------------------
export async function createSyncAccount(withPassword: boolean, server: string, categories: SyncCategory[]) {
const account: SyncAccount = {
number: generateAccountNumber(),
password: withPassword ? generatePassword() : undefined,
server,
categories,
version: 0,
syncedHash: "",
};
const { challenge, bits } = (await call(server, "/challenge", { method: "POST" })) as { challenge: string; bits: number };
const nonce = await solvePow(challenge, bits);
const items = snapshot(categories);
const { version } = await push(account, items, { pow: { challenge, nonce } });
saveSyncAccount({ ...account, version, syncedHash: await hashItems(items), lastSync: Date.now() });
setStatus({ state: "idle", lastSync: Date.now() });
}
/** Logs this device into an existing account: the account's data replaces the local one. Reload afterwards. */
export async function loginSyncAccount(number: string, password: string | undefined, server: string, categories: SyncCategory[]) {
const { version, payload } = await pull({ number, password, server });
applyPayload(payload, categories);
saveSyncAccount({
number,
password,
server,
categories,
version,
syncedHash: await hashItems(snapshot(categories)),
lastSync: Date.now(),
});
}
/** Startup pull (main.tsx). Returns "conflict" when both sides changed. Past
* `deadline` App is already running on the local data, so nothing is applied. */
export async function pullAtStartup(deadline: number): Promise<"ok" | "conflict"> {
const account = loadSyncAccount();
if (!account) return "ok";
setStatus({ state: "syncing", lastSync: account.lastSync });
try {
const { version, payload } = await pull(account);
if (version === account.version || Date.now() > deadline) {
setStatus({ state: "idle", lastSync: account.lastSync });
return "ok";
}
if ((await hashItems(snapshot(account.categories))) !== account.syncedHash) {
setStatus({ state: "conflict", lastSync: account.lastSync });
return "conflict";
}
applyPayload(payload, account.categories);
const lastSync = Date.now();
saveSyncAccount({ ...account, version, syncedHash: await hashItems(snapshot(account.categories)), lastSync });
setStatus({ state: "idle", lastSync });
return "ok";
} catch (err) {
setStatus({ state: "error", error: (err as Error).message, lastSync: account.lastSync });
return "ok";
}
}
/** "server": take the account's data (reload afterwards). "local": overwrite it with this device's. */
export async function resolveConflict(take: "server" | "local") {
const account = loadSyncAccount();
if (!account) return;
const { version, payload } = await pull(account);
if (take === "server") {
applyPayload(payload, account.categories);
saveSyncAccount({ ...account, version, syncedHash: await hashItems(snapshot(account.categories)), lastSync: Date.now() });
return;
}
saveSyncAccount({ ...account, version, syncedHash: "" });
setStatus({ state: "idle", lastSync: account.lastSync });
await syncNow();
}
let pushing = false;
/** Pushes when a synced key changed since the last sync. */
export async function syncNow() {
const account = loadSyncAccount();
if (!account || pushing || status.state === "conflict") return;
const items = snapshot(account.categories);
const hash = await hashItems(items);
if (hash === account.syncedHash) return;
pushing = true;
setStatus({ state: "syncing", lastSync: account.lastSync });
try {
const { version } = await push(account, items);
const lastSync = Date.now();
saveSyncAccount({ ...account, version, syncedHash: hash, lastSync });
setStatus({ state: "idle", lastSync });
} catch (err) {
const code = (err as Error).message;
setStatus({ state: code === "conflict" ? "conflict" : "error", error: code, lastSync: account.lastSync });
} finally {
pushing = false;
}
}
let timer: number | undefined;
export function startAutoSync() {
if (timer !== undefined) return;
if (loadSyncAccount() && status.state === "off") setStatus({ state: "idle", lastSync: loadSyncAccount()?.lastSync });
timer = window.setInterval(() => void syncNow(), 15_000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") void syncNow();
});
}
export async function setSyncCategories(categories: SyncCategory[]) {
const account = loadSyncAccount();
if (!account) return;
// syncedHash no longer matches the new selection, so the next tick pushes it.
saveSyncAccount({ ...account, categories, syncedHash: "" });
await syncNow();
}
/** Adds (random) or removes the password. Re-encrypts under the new key on the server. */
export async function changeSyncPassword(withPassword: boolean) {
const account = loadSyncAccount();
if (!account) return;
const next: SyncAccount = { ...account, password: withPassword ? generatePassword() : undefined };
const newKeys = await deriveKeys(next.number, next.password);
const items = snapshot(account.categories);
// Encrypted with the new key, authorized with the old one, handing over the new auth.
const k = await deriveKeys(account.number, account.password);
const data = await encrypt(newKeys.key, { v: 1, categories: account.categories, items });
const { version } = (await call(
account.server,
`/${k.id}`,
{ method: "PUT", body: JSON.stringify({ version: account.version, data, hasPassword: withPassword, newAuth: newKeys.auth }) },
k.auth
)) as { version: number };
saveSyncAccount({ ...next, version, syncedHash: await hashItems(items), lastSync: Date.now() });
setStatus({ state: "idle", lastSync: Date.now() });
}
/** Unlinks this device only; the account and its data stay on the server. */
export function logoutSyncAccount() {
saveSyncAccount(null);
setStatus({ state: "off" });
}
export async function deleteSyncAccount() {
const account = loadSyncAccount();
if (!account) return;
const k = await deriveKeys(account.number, account.password);
await call(account.server, `/${k.id}`, { method: "DELETE" }, k.auth);
logoutSyncAccount();
}
/** Link for the QR code: the fragment never reaches any server. */
export function syncLink(account: SyncAccount): string {
const params = new URLSearchParams({ sync: account.number });
if (account.password) params.set("syncpw", account.password);
if (account.server !== DEFAULT_SYNC_SERVER) params.set("syncserver", account.server);
return `${location.origin}${location.pathname}#${params}`;
}
/** Reads (and strips from the address bar) a link made by syncLink(). */
export function takeSyncLink(): { number: string; password?: string; server: string } | null {
const params = new URLSearchParams(location.hash.slice(1));
const number = normalizeAccountNumber(params.get("sync") ?? "");
if (!number) return null;
const password = params.get("syncpw") ?? undefined;
const server = params.get("syncserver") ?? DEFAULT_SYNC_SERVER;
for (const k of ["sync", "syncpw", "syncserver"]) params.delete(k);
history.replaceState(null, "", location.pathname + location.search + (params.size ? `#${params}` : ""));
return { number, password, server };
}
export function recoveryText(account: SyncAccount): string {
return [
"WebSpeak3",
"",
`Account number: ${formatAccountNumber(account.number)}`,
...(account.password ? [`Password: ${account.password}`] : []),
...(account.server !== DEFAULT_SYNC_SERVER ? [`Server: ${account.server}`] : []),
"",
].join("\n");
}
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more