Compare commits

...
56 Commits
Author SHA1 Message Date
MoepchiandClaude Opus 5.5 f2d9115782 gateway: serialize write-then-rename per file
Every JSON store (ping, store, news, sync, admin auth, config) wrote to one
shared "<file>.tmp" and renamed it. Parallel requests raced on that path:
one rename won, the others failed with ENOENT, and overlapping writes could
leave a mangled file that reads as empty after a restart. Seen live from a
parallel /api/ping probe.

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 12:45:41 +00:00
Möpchi 8c0d0a3d1d Merge pull request #20 from WebSpeak3/feature/admin-panel
Admin panel for live gateway settings
2026-11-25 13:43:46 +01:00
MoepchiandClaude Opus 5.5 ab588f5ca2 Gateway: test admin login, 2FA and password changes
npm test builds the gateway and runs it on a free port in a temp dir.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-25 11:40:33 +00:00
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
49 changed files with 5666 additions and 1557 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.9.0@sha256:c64defb9ed5a91eacb37f9
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 && rm -rf /var/lib/apt/lists/*
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
+49 -15
View File
@@ -14,7 +14,7 @@
</p>
<p align="center">
<b>A modern, self-hosted browser client for TeamSpeak, TeaSpeak, and GreenTeaSpeak servers — no install, just open a tab.</b>
<b>A modern, self-hosted browser client for TeamSpeak, TeaSpeak, and VoySpeak servers — no install, just open a tab.</b>
</p>
<p align="center">
@@ -31,6 +31,23 @@
---
## 📑 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>
@@ -39,8 +56,8 @@
<th>Mobile</th>
</tr>
<tr>
<td width="72%"><img src="docs/screenshots/webspeak_current.png" width="100%" alt="WebSpeak3 desktop client connected to a TeamSpeak server"></td>
<td width="28%" align="center"><img src="docs/screenshots/webspeak_mobile.png" width="260" alt="WebSpeak3 mobile client connected to a TeamSpeak server"></td>
<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>
@@ -53,7 +70,7 @@ docker run -d --name webspeak3 --restart unless-stopped -p 8080:8080 moepchi/web
```
Enter the address and port of **any reachable TeamSpeak 3, TeamSpeak 6,
TeaSpeak, or GreenTeaSpeak server** in the connection dialog. The server does
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
@@ -63,7 +80,7 @@ not need to be installed on the same machine, modified, or operated by you.
| | |
|---|---|
| 🔌 **Real TeamSpeak protocol** | Connects to actual TS3/TS6, TeaSpeak, and GreenTeaSpeak servers over a WebSocket gateway — the server stays exactly as-is |
| 🔌 **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` |
@@ -80,10 +97,11 @@ not need to be installed on the same machine, modified, or operated by you.
| 📱 **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 GreenTeaSpeak 2. Audio stays on the active tab |
| 🔁 **Multi-join (server tabs)** | Several connections in parallel — one tab per server, like VoySpeak. Audio stays on the active tab |
| 🔁 **Seamless reconnect** | Switch or add connections mid-session without tearing down unrelated tabs; dropped connections come back on their own, with the channel tree intact |
| ⌨️ **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 |
| 🍵 **GreenTeaSpeak support** | Connects to real GreenTeaSpeak servers (not just TS3/TS6/TeaSpeak), plus an optional GTS-styled UI chrome (dark panels, gold menu bar, connection-tab strip) alongside the default look |
| 🍵 **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
@@ -108,19 +126,18 @@ 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/TeaSpeak/GreenTeaSpeak protocol--> 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. Optional GreenTeaSpeak-styled chrome for the
connection-tab strip and menu bar.
tabs, voice controls.
- **`gateway/`** — Node.js/TypeScript WebSocket server. Spawns the Rust
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/`, currently tracking a fork
with TeaSpeak/GreenTeaSpeak protocol support), the actual TS3/TS6/TeaSpeak
with TeaSpeak/VoySpeak protocol support), the actual TS3/TS6/TeaSpeak
protocol implementation. Handles connecting, channel/client state, chat,
and Opus-encoded voice. Auto-detects the server dialect on connect (or it
can be forced via `--server-type`).
@@ -215,6 +232,10 @@ All optional; add them under `environment:` in your compose override next to `PO
| `WEB_DIST` | `web/dist` next to the gateway | Overrides the directory served when `WEB_STATIC` is on. Only needed for non-standard layouts. |
| `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. |
@@ -225,13 +246,15 @@ All optional; add them under `environment:` in your compose override next to `PO
| `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` / `300` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. |
| `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `60` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. |
| `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | *(unset)* | Optional [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/) bot check before connecting. With both set, a browser solves the (usually invisible) check once and gets a pass bound to its IP for 12 h. Keeps scripts from opening TeamSpeak connections through your gateway. |
| `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`.
@@ -240,7 +263,7 @@ All optional; add them under `environment:` in your compose override next to `PO
> **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 - the same way the native client keeps them in its settings files. Anyone with access to your browser profile can read them; leave favorite password fields empty on shared machines and export identities you care about. 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.
> **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>
@@ -366,10 +389,21 @@ A share link (above) always takes priority over the baked-in default when both a
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. -->
@@ -399,8 +433,8 @@ 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 GreenTeaSpeak;
"TeaSpeak" and "GreenTeaSpeak" are names of their respective projects/
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.
+181 -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",
@@ -2642,6 +2801,7 @@ dependencies = [
"num-traits",
"serde",
"serde_json",
"speex-sys",
"time",
"tokio",
"tracing-subscriber",
@@ -2710,7 +2870,7 @@ name = "tsproto-packets"
version = "0.1.0"
dependencies = [
"base64",
"bitflags",
"bitflags 2.13.1",
"num-derive",
"num-traits",
"omnom",
@@ -2736,7 +2896,7 @@ name = "tsproto-types"
version = "0.1.0"
dependencies = [
"base64",
"bitflags",
"bitflags 2.13.1",
"curve25519-dalek-ng",
"elliptic-curve",
"generic-array",
@@ -2930,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"
+2 -1
View File
@@ -7,7 +7,7 @@ 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"
@@ -17,3 +17,4 @@ num-traits = "0.2"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
base64 = "0.22"
time = "0.3"
speex-sys = "0.4"
+138 -15
View File
@@ -32,6 +32,8 @@ use tsclientlib::{
ServerType, StreamItem, TextMessageTargetMode, TsError,
};
use tsproto_packets::commands::{CommandItem, CommandParser};
mod ts2;
use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType};
/// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects.
@@ -61,6 +63,27 @@ async fn ft_pace(limit: &AtomicU64, bytes: usize, started: std::time::Instant) {
tokio::time::sleep(rest).await;
}
}
/// Upload bodies held at once (waiting for the server or being sent, which
/// ftlimit can stretch to days). Without a cap a client could park any
/// amount of memory in the connector.
const MAX_UPLOADS_HELD: u64 = 2 * MAX_UPLOAD_BYTES;
static UPLOADS_HELD: AtomicU64 = AtomicU64::new(0);
/// A share of MAX_UPLOADS_HELD, given back when dropped.
struct HeldUpload(u64);
impl Drop for HeldUpload {
fn drop(&mut self) {
UPLOADS_HELD.fetch_sub(self.0, Ordering::Relaxed);
}
}
fn hold_upload(size: u64) -> Option<HeldUpload> {
UPLOADS_HELD
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| (held + size <= MAX_UPLOADS_HELD).then_some(held + size))
.ok()
.map(|_| HeldUpload(size))
}
const UPLOADS_BUSY: &str = "Upload refused: too many uploads in progress, try again when they are done";
/// Half-received chunked uploads per connection - each can hold up to
/// MAX_UPLOAD_BYTES until it completes.
const MAX_PARTIAL_UPLOADS: usize = 4;
@@ -70,7 +93,7 @@ const MAX_ICON_BYTES: u64 = 512 << 10;
const MAX_AVATAR_BYTES: u64 = 512 << 10;
const OUT_CHANNELS: usize = 2;
#[derive(Parser, Debug)]
#[derive(Parser, Debug, Clone)]
#[command(author, about = "One-shot bridge: connects to a real TeamSpeak server and reports events as JSON lines on stdout")]
struct Args {
/// Server address, e.g. "192.168.178.108" or "192.168.178.108:9987"
@@ -98,12 +121,19 @@ struct Args {
#[arg(long, env = "TS_IDENTITY", hide_env_values = true)]
identity: Option<String>,
/// Server flavour: `teamspeak` (skip TeaSpeak handshake), `teaspeak`
/// (always handshake), or `auto` (handshake when server sends `teaspeak=1`).
#[arg(long, default_value = "auto", value_parser = ["auto", "teamspeak", "teaspeak"])]
/// (always handshake), `auto` (handshake when server sends `teaspeak=1`),
/// or `ts2` for a TeamSpeak 2 server (experimental, see ts2.rs).
#[arg(long, default_value = "auto", value_parser = ["auto", "teamspeak", "teaspeak", "ts2"])]
server_type: String,
/// Privilege key / token (`client_default_token` in clientinit).
#[arg(long, alias = "token", env = "TS_PRIVILEGE_KEY", hide_env_values = true)]
privilege_key: Option<String>,
/// TeamSpeak 2 only: account name for a registered login (anonymous when omitted).
#[arg(long, env = "TS_LOGIN_NAME", hide_env_values = true)]
login_name: Option<String>,
/// TeamSpeak 2 only: password of the registered account.
#[arg(long, env = "TS_LOGIN_PASSWORD", hide_env_values = true)]
login_password: Option<String>,
}
#[derive(Serialize)]
@@ -867,12 +897,56 @@ fn send_server_get_variables(con: &mut tsclientlib::Connection) {
#[tokio::main]
async fn main() {
let args = Args::parse();
if let Err(e) = run(args).await {
// "auto" falls back to TeamSpeak 2 when the TS3 handshake gets no answer at
// all; only if the gateway enables TS2 (ENABLE_TS2=1, inherited env).
let ts2_fallback = args.server_type == "auto" && std::env::var("ENABLE_TS2").as_deref() == Ok("1");
let result = if args.server_type == "ts2" {
ts2::run(args).await
} else if ts2_fallback {
match run(args.clone()).await {
Err(e) if e.to_string().contains("connection timed out") => {
eprintln!("no TS3 answer, trying TeamSpeak 2");
// Only the TS3 default port is swapped; an explicit other port is kept.
let mut args = args;
if let Some(host) = args.address.strip_suffix(":9987") {
args.address = host.to_string();
}
ts2::run(args).await.map_err(|_| e)
}
r => r,
}
} else {
run(args).await
};
if let Err(e) = result {
emit(&Event::Error { message: e.to_string() });
}
}
/// GreenTeaSpeak servers report versions like `2.5.1 [Build: …]`.
/// Stable per-identity HWID in the TeamSpeak shape (`<32 hex>,<32 hex>`),
/// derived from the identity's UID hash so it survives reconnects.
fn hardware_id_for(uid: &[u8]) -> String {
let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
let mut padded = uid.to_vec();
padded.resize(20, 0);
format!("{},{}", hex(&padded[..16]), hex(&padded[4..20]))
}
/// Text for a `banclient` the server refused. Permission ids differ between
/// TeamSpeak and TeaSpeak, so the usual causes are named instead of the id.
fn ban_failure_message(e: &tsclientlib::CommandError) -> String {
match e.missing_permission {
Some(perm) => format!(
"Ban failed: missing permission (id {}). Usual causes: a permanent ban (duration 0) \
without unlimited i_client_ban_max_bantime, a duration above it, too little \
i_client_ban_power, or the target has b_client_ignore_bans.",
perm.0
),
None => format!("Ban failed: {e}"),
}
}
/// VoySpeak (formerly GreenTeaSpeak) servers report versions like `2.5.1 [Build: …]`.
/// Classic TeaSpeak reports `TeaSpeak 1.4.21-beta [Build: …]` — not a GTS host.
/// Classic TeamSpeak 3 reports `3.13.8 [Build: …]` — must not use GTS labels.
fn is_greenteaspeak_server_version(version: &str) -> bool {
@@ -902,12 +976,12 @@ fn format_server_license(license: LicenseType, version: &str) -> String {
return match license {
LicenseType::Offline => "Private".into(),
LicenseType::Sdk => "Premium".into(),
LicenseType::SdkOffline => "Authorized GreenTeaSpeak Host Provider".into(),
LicenseType::SdkOffline => "Authorized VoySpeak Host Provider".into(),
_ => "Keine Lizenz".into(),
};
}
if version.trim().to_ascii_lowercase().starts_with("teaspeak") {
return "Kein GreenTeaSpeak-Server".into();
return "Kein VoySpeak-Server".into();
}
match license {
LicenseType::NoLicense => "No License".into(),
@@ -936,8 +1010,8 @@ fn friendly_connect_error(address: &str, e: tsclientlib::Error) -> anyhow::Error
{
return anyhow::anyhow!(
"Could not connect to \"{address}\": this server rejects this client type (error 533). \
GreenTeaSpeak public servers often only allow the official GreenTeaSpeak desktop client. \
Try a self-hosted TeaSpeak with TeamSpeak-compat enabled, or use GreenTeaSpeak 2 for ts.greenteaspeak.de."
VoySpeak (formerly GreenTeaSpeak) public servers often only allow the official VoySpeak desktop client. \
Try a self-hosted TeaSpeak with TeamSpeak-compat enabled, or use the VoySpeak desktop client."
);
}
if raw.contains("BlockedTarget") {
@@ -985,7 +1059,13 @@ async fn run(args: Args) -> Result<()> {
.and_then(|s| serde_json::from_str::<Identity>(s).ok().or_else(|| Identity::new_from_str(s).ok()))
.unwrap_or_else(Identity::create);
let identity_str = serde_json::to_string(&identity).unwrap();
let mut con_config = Connection::build(args.address).name(args.nickname).identity(identity);
// Without this every web user sends tsclientlib's built-in HWID, so a
// hardware-id ban on one web user would lock out all of them.
let hardware_id = hardware_id_for(&identity.key().to_pub().get_uid_no_base64());
let mut con_config = Connection::build(args.address)
.name(args.nickname)
.hardware_id(hardware_id)
.identity(identity);
let server_type = match args.server_type.as_str() {
"teaspeak" => ServerType::Teaspeak,
"teamspeak" => ServerType::Teamspeak,
@@ -1142,7 +1222,7 @@ async fn run(args: Args) -> Result<()> {
// (StreamItem::FileDownload/FileUpload below); these just remember which
// request that stream belongs to.
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>, HeldUpload)> = HashMap::new();
// Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far).
let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new();
// Set by "permissionlist" while waiting to emit the full permission
@@ -2274,9 +2354,19 @@ async fn run(args: Args) -> Result<()> {
) {
(Ok(cid), Ok(bytes)) => {
let size = bytes.len() as u64;
let held = if size > MAX_UPLOAD_BYTES { None } else { hold_upload(size) };
let Some(held) = held else {
let message = if size > MAX_UPLOAD_BYTES {
format!("Upload refused: {path} is larger than {} KiB", MAX_UPLOAD_BYTES >> 10)
} else {
UPLOADS_BUSY.into()
};
emit(&Event::TransferError { message, cid, path: path.to_string() });
continue;
};
match con.upload_file(ChannelId(cid), path, None, size, true, false) {
Ok(handle) => {
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes));
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes, held));
}
Err(e) => emit(&Event::TransferError {
message: format!("Upload failed: {e}"),
@@ -2290,9 +2380,13 @@ async fn run(args: Args) -> Result<()> {
} else if let Some(rest) = l.strip_prefix("ftuploadchunk ") {
match take_upload_chunk(&mut partial_uploads, rest) {
Ok(Some((cid, path, bytes))) => {
let Some(held) = hold_upload(bytes.len() as u64) else {
emit(&Event::TransferError { message: UPLOADS_BUSY.into(), cid, path });
continue;
};
match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) {
Ok(handle) => {
pending_uploads.insert(handle.0, (cid, path, bytes));
pending_uploads.insert(handle.0, (cid, path, bytes, held));
}
Err(e) => emit(&Event::TransferError { message: format!("Upload failed: {e}"), cid, path }),
}
@@ -2747,6 +2841,14 @@ async fn run(args: Args) -> Result<()> {
} else {
emit(&Event::Error { message: format!("{label} failed: {e}") });
}
} else if label == "Ban client" {
// A rejected ban must be visible: the UI only knows it sent one.
emit(&Event::Error { message: ban_failure_message(&e) });
if e.missing_permission.is_some() {
emit(&Event::ServerLog {
entry: ServerLogEntry::PermissionError { action: label },
});
}
} else if e.missing_permission.is_some() {
emit(&Event::ServerLog {
entry: ServerLogEntry::PermissionError { action: label },
@@ -3177,10 +3279,11 @@ async fn run(args: Args) -> Result<()> {
}
}
Some(Ok(StreamItem::FileUpload(handle, result))) => {
if let Some((cid, path, data)) = pending_uploads.remove(&handle.0) {
if let Some((cid, path, data, held)) = pending_uploads.remove(&handle.0) {
let seek = result.seek_position as usize;
let mut stream = result.stream;
tokio::spawn(async move {
let _held = held;
let slice = if seek < data.len() { &data[seek..] } else { &[][..] };
for piece in slice.chunks(TRANSFER_CHUNK_BYTES) {
let started = std::time::Instant::now();
@@ -3197,7 +3300,7 @@ async fn run(args: Args) -> Result<()> {
Some(Ok(StreamItem::FiletransferFailed(handle, e))) => {
let failed = pending_downloads
.remove(&handle.0)
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, _)| (cid, path)));
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, ..)| (cid, path)));
if let Some((cid, path)) = failed {
emit(&Event::TransferError { message: format!("File transfer failed: {e}"), cid, path });
}
@@ -3264,6 +3367,17 @@ async fn run(args: Args) -> Result<()> {
mod tests {
use super::*;
#[test]
fn held_uploads_are_capped_and_released() {
let a = hold_upload(MAX_UPLOAD_BYTES).unwrap();
let b = hold_upload(MAX_UPLOAD_BYTES).unwrap();
assert!(hold_upload(1).is_none());
drop(a);
assert!(hold_upload(MAX_UPLOAD_BYTES).is_some());
drop(b);
assert_eq!(UPLOADS_HELD.load(Ordering::Relaxed), 0);
}
fn chunk(offset: u64, total: u64, data: &[u8]) -> String {
format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data))
}
@@ -3281,6 +3395,15 @@ mod tests {
);
}
#[test]
fn hardware_id_is_stable_and_per_identity() {
let a = hardware_id_for(&[1u8; 20]);
assert_eq!(a, hardware_id_for(&[1u8; 20]));
assert_ne!(a, hardware_id_for(&[2u8; 20]));
let (left, right) = a.split_once(',').unwrap();
assert_eq!((left.len(), right.len()), (32, 32));
}
#[test]
fn upload_chunks_assemble_in_order_and_reject_gaps() {
let mut partials = HashMap::new();
+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);
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 421 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

+1 -2
View File
@@ -1,4 +1,4 @@
# TeaSpeak / GreenTeaSpeak support (WebSpeak3)
# 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`.
@@ -12,7 +12,6 @@ TeaSpeak / GreenTeaSpeak servers need an extra identity handshake before `client
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`
- Design theme **GreenTeaSpeak** (third UI style)
Verified against `ts.greenteaspeak.de` (Official GreenTeaSpeak Public Server).
+7
View File
@@ -8,6 +8,7 @@
"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",
+3 -1
View File
@@ -7,9 +7,11 @@
"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": {
+1 -2
View File
@@ -51,7 +51,6 @@ export async function logFeedback(entry: FeedbackEntry): Promise<void> {
// and other instances shouldn't get connection logging just because it's in
// 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 const LOG_CONNECTIONS = process.env.LOG_CONNECTIONS === "1";
export interface ConnectionEvent {
type: "connected" | "disconnected";
@@ -60,7 +59,7 @@ export interface ConnectionEvent {
}
export function logConnectionEvent(event: ConnectionEvent): void {
if (!LOG_CONNECTIONS) return;
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 {
+688
View File
@@ -0,0 +1,688 @@
// Admin panel at /admin: change the live settings from config.ts in the
// browser. Off unless both ADMIN_USER and ADMIN_PASSWORD are set (404
// otherwise). Optional ADMIN_TOTP_SECRET (base32) adds a 6-digit
// authenticator code to the login.
//
// The panel can also change the password and switch 2FA on or off. Those
// land in ADMIN_AUTH_FILE (next to the settings file) and override .env;
// every such change asks for the current password again, so a stolen session
// alone can't lock the operator out. Deleting that file goes back to .env.
import type { IncomingMessage, ServerResponse } from "node:http";
import type { TLSSocket } from "node:tls";
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { readFileSync } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import qrcode from "qrcode-generator";
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
import { describeSettings, updateSettings, validate } from "./config.js";
const ADMIN_USER = process.env.ADMIN_USER ?? "";
const ENV_PASSWORD = process.env.ADMIN_PASSWORD ?? "";
const ENV_TOTP = (process.env.ADMIN_TOTP_SECRET ?? "").replace(/[\s=]/g, "").toUpperCase();
export const ADMIN_ENABLED = ADMIN_USER !== "" && ENV_PASSWORD !== "";
const AUTH_FILE = process.env.ADMIN_AUTH_FILE
?? path.join(path.dirname(process.env.ADMIN_CONFIG_FILE ?? path.resolve(process.cwd(), "admin-config.json")), "admin-auth.json");
// Set from the panel. totpSecret "" = 2FA switched off there (wins over .env).
let auth: { passwordHash?: string; totpSecret?: string } = {};
try {
const raw = JSON.parse(readFileSync(AUTH_FILE, "utf8"));
if (typeof raw?.passwordHash === "string") auth.passwordHash = raw.passwordHash;
if (typeof raw?.totpSecret === "string") auth.totpSecret = raw.totpSecret;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`[admin] Ignoring unreadable ${AUTH_FILE}:`, err);
}
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
async function saveAuth(next: typeof auth) {
await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
auth = next;
}
const scryptAsync = promisify(scrypt) as (pw: string, salt: Buffer, len: number) => Promise<Buffer>;
async function hashPassword(pw: string): Promise<string> {
const salt = randomBytes(16);
return `scrypt$${salt.toString("base64url")}$${(await scryptAsync(pw, salt, 32)).toString("base64url")}`;
}
async function passwordOk(pw: string): Promise<boolean> {
if (!auth.passwordHash) return sameString(pw, ENV_PASSWORD);
const [, salt = "", hash = ""] = auth.passwordHash.split("$");
const want = Buffer.from(hash, "base64url");
const got = await scryptAsync(pw, Buffer.from(salt, "base64url"), 32);
return want.length === got.length && timingSafeEqual(want, got);
}
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
const COOKIE = "webspeak3_admin";
const sessions = new Map<string, number>(); // token -> expiry
// Every attempt counts, so a right guess can't be hidden between wrong ones.
const tooManyFromIp = createRateLimiter(5, 15 * 60_000);
const tooManyOverall = createRateLimiter(30, 15 * 60_000);
const tooManyReauth = createRateLimiter(10, 15 * 60_000);
let lastTotpCounter = -1; // a code works once, even within its window
const sha256 = (s: string) => createHash("sha256").update(s).digest();
const sameString = (a: string, b: string) => timingSafeEqual(sha256(a), sha256(b));
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
function base32Decode(s: string): Buffer {
let bits = 0, value = 0;
const out: number[] = [];
for (const c of s) {
const i = B32.indexOf(c);
if (i === -1) throw new Error("invalid base32");
value = (value << 5) | i;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 0xff);
bits -= 8;
}
}
return Buffer.from(out);
}
function base32Encode(buf: Buffer): string {
let bits = 0, value = 0, out = "";
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += B32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
return bits > 0 ? out + B32[(value << (5 - bits)) & 31] : out;
}
/** RFC 6238 code (SHA-1, 6 digits, 30 s) for a given time step. */
export function totp(secret: Buffer, counter: number): string {
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(counter));
const h = createHmac("sha1", secret).update(msg).digest();
const o = h[h.length - 1] & 0xf;
return String((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).padStart(6, "0");
}
/** Accepts the current code and one step either side (clock drift). */
/** Time step the code matches (±1 step of clock drift, only steps after `after`), or -1. */
function matchTotp(secretB32: string, code: unknown, after = -1): number {
if (typeof code !== "string" || !/^\d{6}$/.test(code)) return -1;
const secret = base32Decode(secretB32);
const now = Math.floor(Date.now() / 30_000);
for (const c of [now - 1, now, now + 1]) {
if (c > after && sameString(totp(secret, c), code)) return c;
}
return -1;
}
function checkTotp(code: unknown): boolean {
const c = matchTotp(totpSecret(), code, lastTotpCounter);
if (c < 0) return false;
lastTotpCounter = c;
return true;
}
if (ADMIN_ENABLED && totpSecret()) {
try {
if (base32Decode(totpSecret()).length < 10) throw new Error("too short");
} catch (err) {
// Fail closed: a typo here must not silently drop the second factor.
console.error(`[admin] ADMIN_TOTP_SECRET is not valid base32 (${(err as Error).message}); login disabled`);
}
}
function json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}) {
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers });
res.end(JSON.stringify(body));
}
async function readJson(req: IncomingMessage): Promise<Record<string, unknown> | undefined> {
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return undefined;
let size = 0;
const chunks: Buffer[] = [];
for await (const chunk of req) {
size += (chunk as Buffer).length;
if (size > 64 * 1024) return undefined;
chunks.push(chunk as Buffer);
}
try {
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
return v && typeof v === "object" && !Array.isArray(v) ? v : undefined;
} catch {
return undefined;
}
}
function sessionOf(req: IncomingMessage): string | undefined {
const m = new RegExp(`(?:^|;\\s*)${COOKIE}=([A-Za-z0-9_-]+)`).exec(req.headers.cookie ?? "");
if (!m) return undefined;
const expires = sessions.get(m[1]);
if (!expires || expires < Date.now()) {
sessions.delete(m[1]);
return undefined;
}
return m[1];
}
function cookie(req: IncomingMessage, value: string, maxAgeS: number): string {
// Secure only where the browser actually talks HTTPS, else a plain-HTTP
// LAN setup could never log in.
const https = (req.socket as TLSSocket).encrypted || req.headers["x-forwarded-proto"] === "https";
return `${COOKIE}=${value}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeS}${https ? "; Secure" : ""}`;
}
async function handleLogin(req: IncomingMessage, res: ServerResponse) {
const ip = clientIp(req);
if (tooManyFromIp(ip) || tooManyOverall("all")) {
console.warn("[admin] login rate-limited");
return json(res, 429, { error: "rate_limited" });
}
const body = await readJson(req);
const userOk = sameString(String(body?.user ?? ""), ADMIN_USER);
const passOk = await passwordOk(String(body?.password ?? ""));
// The code is only used up by a fully successful login, so a password typo
// doesn't burn it.
let step = -1;
if (totpSecret()) {
try {
step = matchTotp(totpSecret(), body?.code, lastTotpCounter);
} catch {
step = -1;
}
}
if (!(userOk && passOk && (step >= 0 || !totpSecret()))) {
console.warn("[admin] failed login");
return json(res, 401, { error: "invalid_login" });
}
if (step >= 0) lastTotpCounter = step;
const token = randomBytes(32).toString("base64url");
sessions.set(token, Date.now() + SESSION_TTL_MS);
for (const [t, exp] of sessions) if (exp < Date.now()) sessions.delete(t);
console.log("[admin] login");
json(res, 200, { ok: true }, { "Set-Cookie": cookie(req, token, SESSION_TTL_MS / 1000) });
}
let countConnections = () => 0;
/** index.ts hands in its WebSocket server's client count (shown before a restart). */
export function setConnectionCounter(fn: () => number) {
countConnections = fn;
}
const state = () => ({
settings: describeSettings(),
totp: totpSecret() ? (auth.totpSecret ? "panel" : "env") : "",
passwordFromPanel: Boolean(auth.passwordHash),
connections: countConnections(),
version: process.env.WEBSPEAK3_VERSION || "",
uptime: Math.round(process.uptime()),
});
// Credential changes re-check the current password (own limiter, so a few
// panel actions don't eat the login budget).
async function reauth(req: IncomingMessage, res: ServerResponse, body: Record<string, unknown> | undefined): Promise<boolean> {
if (tooManyReauth(clientIp(req))) return json(res, 429, { error: "rate_limited" }), false;
if (!(await passwordOk(String(body?.password ?? "")))) {
console.warn("[admin] wrong password on credential change");
return json(res, 403, { error: "wrong_password" }), false;
}
return true;
}
export async function handleAdmin(req: IncomingMessage, res: ServerResponse, pathname: string) {
if (!ADMIN_ENABLED) return json(res, 404, { error: "not_found" });
if (pathname === "/admin" || pathname === "/admin/") {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
"X-Frame-Options": "DENY",
});
return res.end(PAGE);
}
if (pathname === "/admin/admin.js") {
res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store" });
return res.end(SCRIPT);
}
if (req.method !== "GET" && req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
// Cross-site requests can't set this header without a CORS preflight,
// which this endpoint never grants: CSRF protection on top of SameSite.
if (req.method === "POST" && req.headers["x-webspeak3-admin"] !== "1") return json(res, 403, { error: "forbidden" });
if (pathname === "/admin/api/login" && req.method === "POST") return handleLogin(req, res);
const session = sessionOf(req);
if (!session) return json(res, 401, { error: "unauthorized" });
if (pathname === "/admin/api/logout" && req.method === "POST") {
sessions.delete(session);
return json(res, 200, { ok: true }, { "Set-Cookie": cookie(req, "", 0) });
}
if (pathname === "/admin/api/config" && req.method === "GET") return json(res, 200, state());
if (pathname === "/admin/api/restart" && req.method === "POST") {
console.log(`[admin] restart requested (${countConnections()} connected)`);
json(res, 200, { ok: true });
// Same graceful path as `docker stop`: users get the restart notice, TS
// sessions are closed. Coming back up is the supervisor's job (Docker's
// restart policy, systemd Restart=always).
setTimeout(() => process.kill(process.pid, "SIGTERM"), 300);
return;
}
if (pathname === "/admin/api/config" && req.method === "POST") {
const body = await readJson(req);
const changes = body?.changes;
if (!changes || typeof changes !== "object" || Array.isArray(changes)) return json(res, 400, { error: "bad_request" });
const clean: Record<string, string | null> = {};
for (const [key, value] of Object.entries(changes)) {
if (value !== null && typeof value !== "string") return json(res, 400, { error: "bad_request", key });
// null = reset to .env; then only the key itself has to be known.
const err = value === null ? (validate(key, "") === "unknown setting" ? "unknown setting" : undefined) : validate(key, value.trim());
if (err) return json(res, 400, { error: err, key });
clean[key] = value === null ? null : value.trim();
}
await updateSettings(clean);
console.log(`[admin] settings changed: ${Object.keys(clean).join(", ")}`);
return json(res, 200, state());
}
if (pathname === "/admin/api/totp-secret" && req.method === "GET") {
const secret = base32Encode(randomBytes(20));
const label = encodeURIComponent(`WebSpeak3:${ADMIN_USER}`);
const uri = `otpauth://totp/${label}?secret=${secret}&issuer=WebSpeak3`;
const qr = qrcode(0, "M");
qr.addData(uri);
qr.make();
return json(res, 200, { secret, uri, qr: qr.createDataURL(5, 4) });
}
// Setup check: does the authenticator app produce codes for the secret
// just generated? Only then the panel shows the .env line.
if (pathname === "/admin/api/totp-verify" && req.method === "POST") {
const body = await readJson(req);
const secret = String(body?.secret ?? "");
if (!/^[A-Z2-7]{16,64}$/.test(secret)) return json(res, 400, { error: "bad_request" });
return json(res, 200, { ok: matchTotp(secret, String(body?.code ?? "").trim()) >= 0 });
}
if (pathname === "/admin/api/totp-enable" && req.method === "POST") {
const body = await readJson(req);
const secret = String(body?.secret ?? "");
if (!/^[A-Z2-7]{16,64}$/.test(secret)) return json(res, 400, { error: "bad_request" });
if (!(await reauth(req, res, body))) return;
const c = matchTotp(secret, String(body?.code ?? "").trim());
if (c < 0) return json(res, 400, { error: "code_wrong" });
await saveAuth({ ...auth, totpSecret: secret });
lastTotpCounter = c; // the code just typed can't be replayed at login
console.log("[admin] 2FA switched on in the panel");
return json(res, 200, state());
}
if (pathname === "/admin/api/totp-disable" && req.method === "POST") {
const body = await readJson(req);
if (!(await reauth(req, res, body))) return;
if (!checkTotp(String(body?.code ?? "").trim())) return json(res, 400, { error: "code_wrong" });
await saveAuth({ ...auth, totpSecret: "" });
console.log("[admin] 2FA switched off in the panel");
return json(res, 200, state());
}
if (pathname === "/admin/api/password" && req.method === "POST") {
const body = await readJson(req);
const next = String(body?.newPassword ?? "");
if (next.length < 10 || next.length > 200) return json(res, 400, { error: "weak_password" });
if (!(await reauth(req, res, body))) return;
await saveAuth({ ...auth, passwordHash: await hashPassword(next) });
for (const t of sessions.keys()) if (t !== session) sessions.delete(t); // other logins end
console.log("[admin] password changed in the panel");
return json(res, 200, state());
}
json(res, 404, { error: "not_found" });
}
const PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
<title>WebSpeak3 Admin</title><style>
:root{color-scheme:light;--bg:#f4f6f8;--card:#fff;--fg:#1b1f24;--muted:#5f6b7a;--line:#dde2e8;--field:#f7f9fb;--accent:#2f6fde;--on-accent:#fff;--bad:#c0392b;--warn:#a86200;--ok:#1e7f43}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){color-scheme:dark;--bg:#131619;--card:#1c2025;--fg:#e6e9ed;--muted:#97a1ad;--line:#2f363e;--field:#15191d;--accent:#6a9cff;--on-accent:#0b1426;--bad:#ff6b5b;--warn:#f0b35a;--ok:#5cc98a}}
:root[data-theme="dark"]{color-scheme:dark;--bg:#131619;--card:#1c2025;--fg:#e6e9ed;--muted:#97a1ad;--line:#2f363e;--field:#15191d;--accent:#6a9cff;--on-accent:#0b1426;--bad:#ff6b5b;--warn:#f0b35a;--ok:#5cc98a}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.45 system-ui,sans-serif}
main{max-width:1320px;margin:0 auto;padding:20px 16px 0}
header{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;margin-bottom:18px}
h1{font-size:22px;margin:0}#stat{margin:2px 0 0}.tools{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--card)}
.seg button{background:transparent;color:var(--fg);border:0;border-radius:0;padding:6px 10px;font-size:13px}
.seg button[aria-pressed="true"]{background:var(--accent);color:var(--on-accent)}
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px}
.layout{display:grid;grid-template-columns:230px minmax(0,1fr);gap:20px;align-items:start}
.side{position:sticky;top:12px;display:flex;flex-direction:column;gap:10px}
#nav{display:flex;flex-direction:column;gap:2px}
#nav button{display:flex;justify-content:space-between;align-items:center;gap:8px;background:transparent;color:var(--fg);text-align:left;padding:8px 10px;border:1px solid transparent;border-radius:8px}
#nav button:hover{background:var(--card)}
#nav button[aria-current="true"]{background:var(--card);border-color:var(--line);font-weight:600;box-shadow:inset 3px 0 0 var(--accent)}
#nav button.muted{color:var(--muted)}#nav hr{width:100%;border:0;border-top:1px solid var(--line);margin:6px 0}
.cnt{font-size:12px;line-height:18px;min-width:18px;text-align:center;border-radius:9px;padding:0 6px;background:var(--accent);color:var(--on-accent);font-weight:600}.cnt.warnc{background:var(--warn)}
#content>#groups>.card,#extras>.card{margin-bottom:16px}
.rows{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,340px),1fr));column-gap:32px}
.rows .row{border-top:0;border-bottom:1px solid var(--line)}
.lab{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:6px}.lab label{margin:0}
.badge{font-size:11px;padding:1px 8px;border-radius:9px;border:1px solid var(--line);color:var(--muted)}.badge.panel{border-color:var(--accent);color:var(--accent)}
.lab .reset{margin-left:auto;font-size:13px}.help{margin-top:4px}
@media (max-width:760px){.layout{grid-template-columns:minmax(0,1fr)}.side{position:static}#nav{flex-direction:row;overflow-x:auto;padding-bottom:4px}#nav button{flex:none;white-space:nowrap}#nav hr{display:none}}
h2{font-size:15px;margin:0 0 4px;padding-bottom:8px;border-bottom:2px solid var(--accent)}
label{display:block;font-weight:600;font-size:13px;margin-bottom:4px;font-family:ui-monospace,monospace}
input,select{width:100%;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--field);color:var(--fg);font:inherit}
input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}
button{padding:8px 14px;border:0;border-radius:6px;background:var(--accent);color:var(--on-accent);font:inherit;cursor:pointer}
button.plain{background:transparent;color:var(--accent);padding:2px 0}
.row{padding:12px 0;border-top:1px solid var(--line)}h2+.row{border-top:0}
.help,.meta{color:var(--muted);font-size:13px}.err{color:var(--bad);min-height:1.4em;margin:0}
.changed input,.changed select{border-color:var(--accent)}
.inactive input,.inactive select{opacity:.5}button.second{background:transparent;color:var(--accent);border:1px solid var(--accent)}button.second.due{background:var(--warn);border-color:var(--warn);color:var(--on-accent)}.warn{color:var(--warn);font-size:13px}
.foot{display:flex;justify-content:space-between;align-items:center;gap:8px}
.savebar{position:sticky;bottom:0;margin:16px -16px 0;padding:12px 16px;background:var(--bg);border-top:1px solid var(--line);display:flex;gap:12px;align-items:center;flex-wrap:wrap}
#pwCard input{max-width:420px}.step{font-weight:600;font-size:14px;margin:16px 0 8px}.okbox{display:flex;width:fit-content;align-items:center;gap:8px;color:var(--ok);font-weight:600;margin:4px 0 0;padding:8px 12px;border-radius:8px;background:color-mix(in srgb,var(--ok) 12%,transparent)}#login{max-width:380px;margin:40px auto}#login p{margin:0 0 12px}
code{word-break:break-all}[hidden]{display:none!important}
</style></head><body><main>
<header><div><h1>WebSpeak3 Admin</h1><p class="meta" id="stat" hidden></p></div><div class="tools">
<span class="seg" id="langSeg"><button type="button" data-lang="de">DE</button><button type="button" data-lang="en">EN</button></span>
<span class="seg" id="themeSeg"><button type="button" data-theme-btn="auto" data-i18n="auto"></button><button type="button" data-theme-btn="light" data-i18n="light"></button><button type="button" data-theme-btn="dark" data-i18n="dark"></button></span>
<button id="logout" class="plain" type="button" data-i18n="logout" hidden></button></div></header>
<form id="login" class="card" hidden>
<p><label for="u" data-i18n="user"></label><input id="u" autocomplete="username" required></p>
<p><label for="p" data-i18n="pass"></label><input id="p" type="password" autocomplete="current-password" required></p>
<p><label for="c"><span data-i18n="code"></span> <span class="meta" data-i18n="codeHint"></span></label><input id="c" inputmode="numeric" autocomplete="one-time-code" maxlength="6"></p>
<p class="err" id="loginErr"></p><button data-i18n="login"></button></form>
<form id="panel" hidden><div class="layout"><div class="side"><input id="search" type="search" autocomplete="off"><nav id="nav"></nav></div>
<div id="content"><div id="groups"></div><p class="meta" id="noHits" hidden></p>
<div id="extras"><div class="card" id="totpCard"><h2 data-i18n="totpTitle"></h2><p class="help" id="totpState"></p>
<div id="totpOffBox" hidden><p class="help" data-i18n="offHint"></p>
<p style="display:flex;gap:8px;flex-wrap:wrap"><input id="offCode" inputmode="numeric" autocomplete="off" maxlength="6" style="max-width:9em"><input id="offPw" type="password" autocomplete="current-password" style="max-width:16em"><button type="button" id="offBtn" class="second" data-i18n="turnOff"></button></p>
<p class="err" id="offErr"></p></div>
<button class="plain" id="genTotp" type="button" data-i18n="gen"></button><div id="totpOut" hidden>
<p class="step" data-i18n="step1"></p>
<p><img id="totpQr" alt="QR" style="image-rendering:pixelated;background:#fff;padding:4px;border-radius:6px;max-width:100%"></p>
<p class="help"><span data-i18n="cantScan"></span> <code id="totpSecret"></code></p>
<p class="step" data-i18n="step2"></p>
<p style="display:flex;gap:8px"><input id="totpCheck" inputmode="numeric" autocomplete="off" maxlength="6" style="max-width:9em"><button type="button" id="totpCheckBtn" class="second" data-i18n="check"></button></p>
<p class="err" id="totpCheckErr"></p>
<div id="totpDone" hidden><p class="okbox" data-i18n="codeOk"></p><p class="step" data-i18n="step3"></p>
<p style="display:flex;gap:8px;flex-wrap:wrap"><input id="onPw" type="password" autocomplete="current-password" style="max-width:16em"><button type="button" id="onBtn" data-i18n="turnOn"></button></p>
<p class="err" id="onErr"></p>
<p class="help"><span data-i18n="envAlt"></span> <code id="totpEnv"></code></p></div></div></div>
<div class="card" id="pwCard"><h2 data-i18n="pwTitle"></h2><p class="help" id="pwState"></p>
<p><label for="pwOld" data-i18n="pwOld"></label><input id="pwOld" type="password" autocomplete="current-password"></p>
<p><label for="pwNew" data-i18n="pwNew"></label><input id="pwNew" type="password" autocomplete="new-password" minlength="10"></p>
<p><label for="pwNew2" data-i18n="pwNew2"></label><input id="pwNew2" type="password" autocomplete="new-password"></p>
<p class="err" id="pwErr"></p><button type="button" id="pwBtn" data-i18n="pwBtn"></button></div>
<div class="card" id="aboutCard"><h2 data-i18n="aboutTitle"></h2><p class="help" data-i18n="about"></p></div></div>
</div></div>
<div class="savebar"><button id="save" data-i18n="save"></button><button id="restart" type="button" class="second"></button><span class="meta" id="status"></span><p class="err" id="saveErr"></p></div>
</form></main><script src="/admin/admin.js"></script></body></html>`;
const SCRIPT = `"use strict";
const T = {
en: {
user: "Username", pass: "Password", code: "Authenticator code", codeHint: "(if 2FA is on)", login: "Log in", logout: "Log out",
auto: "Auto", light: "Light", dark: "Dark", save: "Save", saved: "Saved, active now.", unsaved: (n) => n + " unsaved change" + (n === 1 ? "" : "s"),
fromPanel: "set in panel", fromEnv: "from .env", notSet: "not set (built-in default)", reset: "Reset", on: "On", off: "Off", def: "default: ",
secretSet: "set - type to replace", secretUnset: "not set", tooMany: "Too many attempts, try again in 15 minutes.", loginFailed: "Login failed.", saveFailed: "Save failed",
inactive: "No effect here: WEB_STATIC=0, the web UI is hosted separately (set it in that build instead).",
totpTitle: "Two-factor login", totpOn: "On (set in .env).", totpOnPanel: "On (switched on here).", totpOff: "Off. Generate a secret below to require a code at login.",
offHint: "Switch off: current code from the app and your password.", turnOff: "Switch 2FA off", turnOn: "Switch 2FA on",
envAlt: "Or put this line in .env instead:", codePh: "Code", pwPh: "Password",
pwTitle: "Password", pwEnv: "Currently the password from .env (ADMIN_PASSWORD).", pwPanel: "Changed here; ADMIN_PASSWORD in .env is no longer used.",
pwOld: "Current password", pwNew: "New password (at least 10 characters)", pwNew2: "Repeat new password", pwBtn: "Change password",
pwMismatch: "The new passwords differ.", pwDone: "Password changed. Other logins were signed out.", totpDoneOn: "2FA is on now. Next login asks for the code.",
statConn: (n) => n + " connected", statUp: "up ", statVer: "version ",
gen: "Generate a new secret", step1: "1. Scan this code with your authenticator app (Google Authenticator, Aegis, 2FAS, ...):", cantScan: "Can't scan? Enter the secret manually:",
step2: "2. Enter the 6-digit code the app now shows for WebSpeak3:", check: "Check", codeWrong: "Code doesn\\u2019t match. Wait for the next code, check the phone\\u2019s clock, or scan again.",
codeOk: "\\u2713 Code is correct", step3: "3. Confirm with your password to switch 2FA on:",
credErr: { wrong_password: "Wrong password.", code_wrong: "Wrong code.", weak_password: "At least 10 characters.", rate_limited: "Too many attempts, try again in 15 minutes." },
aboutTitle: "How this works", about: "Changes apply immediately, except in \\u201cRestart required\\u201d. They override .env and are stored in admin-config.json (ADMIN_CONFIG_FILE). \\u201cReset\\u201d returns a setting to its .env value. Password and 2FA changes go to admin-auth.json; deleting that file goes back to .env (e.g. if you are locked out).",
search: "Search settings\\u2026", noHits: "No matching settings.", std: "default",
restartBtn: "Restart gateway", restartDue: (n) => "Restart gateway (" + n + " pending)", pendingRestart: "Saved \\u2013 applies after the next restart.",
restartConfirm: (n) => (n ? n + " connection(s) are open right now; they get a restart notice and are dropped. " : "Nobody is connected. ") + "Restart now? This only works if Docker's restart policy or systemd brings the gateway back up.",
restarting: "Restarting\\u2026 the page reloads when the gateway is back.", restartFailed: "Restart failed",
errors: {}, groups: {}, help: {},
},
de: {
user: "Benutzername", pass: "Passwort", code: "Authenticator-Code", codeHint: "(falls 2FA an ist)", login: "Anmelden", logout: "Abmelden",
auto: "Auto", light: "Hell", dark: "Dunkel", save: "Speichern", saved: "Gespeichert, sofort aktiv.", unsaved: (n) => n + " ungespeicherte \\u00c4nderung" + (n === 1 ? "" : "en"),
fromPanel: "im Panel gesetzt", fromEnv: "aus .env", notSet: "nicht gesetzt (Standardwert)", reset: "Zur\\u00fccksetzen", on: "An", off: "Aus", def: "Standard: ",
secretSet: "gesetzt \\u2013 zum Ersetzen tippen", secretUnset: "nicht gesetzt", tooMany: "Zu viele Versuche, bitte in 15 Minuten erneut versuchen.", loginFailed: "Anmeldung fehlgeschlagen.", saveFailed: "Speichern fehlgeschlagen",
inactive: "Hier ohne Wirkung: WEB_STATIC=0, die Web-Oberfl\\u00e4che wird separat gehostet (dort beim Build setzen).",
totpTitle: "Zwei-Faktor-Anmeldung", totpOn: "Aktiv (in der .env gesetzt).", totpOnPanel: "Aktiv (hier eingeschaltet).", totpOff: "Aus. Unten ein Secret erzeugen, um beim Login einen Code zu verlangen.",
offHint: "Abschalten: aktueller Code aus der App und dein Passwort.", turnOff: "2FA abschalten", turnOn: "2FA einschalten",
envAlt: "Oder stattdessen diese Zeile in die .env:", codePh: "Code", pwPh: "Passwort",
pwTitle: "Passwort", pwEnv: "Aktuell gilt das Passwort aus der .env (ADMIN_PASSWORD).", pwPanel: "Hier ge\\u00e4ndert; ADMIN_PASSWORD in der .env wird nicht mehr verwendet.",
pwOld: "Aktuelles Passwort", pwNew: "Neues Passwort (mindestens 10 Zeichen)", pwNew2: "Neues Passwort wiederholen", pwBtn: "Passwort \\u00e4ndern",
pwMismatch: "Die neuen Passw\\u00f6rter stimmen nicht \\u00fcberein.", pwDone: "Passwort ge\\u00e4ndert. Andere Anmeldungen wurden abgemeldet.", totpDoneOn: "2FA ist jetzt aktiv. Der n\\u00e4chste Login fragt nach dem Code.",
statConn: (n) => n + " verbunden", statUp: "l\\u00e4uft seit ", statVer: "Version ",
gen: "Neues Secret erzeugen", step1: "1. Diesen Code mit der Authenticator-App scannen (Google Authenticator, Aegis, 2FAS, ...):", cantScan: "Scannen klappt nicht? Secret von Hand eingeben:",
step2: "2. Den 6-stelligen Code eingeben, den die App jetzt f\\u00fcr WebSpeak3 anzeigt:", check: "Pr\\u00fcfen", codeWrong: "Code passt nicht. Auf den n\\u00e4chsten Code warten, die Uhrzeit am Handy pr\\u00fcfen oder neu scannen.",
codeOk: "\\u2713 Code stimmt", step3: "3. Mit deinem Passwort best\\u00e4tigen, um 2FA einzuschalten:",
credErr: { wrong_password: "Falsches Passwort.", code_wrong: "Falscher Code.", weak_password: "Mindestens 10 Zeichen.", rate_limited: "Zu viele Versuche, in 15 Minuten erneut probieren." },
aboutTitle: "So funktioniert's", about: "\\u00c4nderungen gelten sofort, au\\u00dfer unter \\u201eNeustart n\\u00f6tig\\u201c. Sie \\u00fcberschreiben die .env und liegen in admin-config.json (ADMIN_CONFIG_FILE). \\u201eZur\\u00fccksetzen\\u201c stellt den Wert aus der .env wieder her. Passwort und 2FA aus dem Panel liegen in admin-auth.json; wer die Datei l\\u00f6scht, ist wieder bei der .env (z. B. wenn man sich ausgesperrt hat).",
search: "Einstellungen suchen\\u2026", noHits: "Keine passende Einstellung.", std: "Standardwert",
restartBtn: "Gateway neu starten", restartDue: (n) => "Gateway neu starten (" + n + " ausstehend)", pendingRestart: "Gespeichert \\u2013 gilt ab dem n\\u00e4chsten Neustart.",
restartConfirm: (n) => (n ? "Gerade sind " + n + " Verbindung(en) offen; sie bekommen einen Neustart-Hinweis und werden getrennt. " : "Niemand ist verbunden. ") + "Jetzt neu starten? Das klappt nur, wenn Dockers Restart-Policy oder systemd das Gateway wieder hochf\\u00e4hrt.",
restarting: "Startet neu\\u2026 die Seite l\\u00e4dt neu, sobald das Gateway wieder da ist.", restartFailed: "Neustart fehlgeschlagen",
errors: { "must be a port (1-65535)": "muss ein Port sein (1\\u201365535)", "must be a whole number": "muss eine ganze Zahl sein", "must be 0 or 1": "muss 0 oder 1 sein", "invalid characters or too long": "ung\\u00fcltige Zeichen oder zu lang", "unknown setting": "unbekannte Einstellung" },
groups: { "Connections & limits": "Verbindungen & Limits", "Access": "Zugriff", "Connect dialog": "Verbindungsdialog", "Features": "Funktionen", "News ticker": "News-Ticker", "Bot check (Cloudflare Turnstile)": "Bot-Check (Cloudflare Turnstile)", "Screen sharing & webcam (TURN)": "Bildschirmfreigabe & Webcam (TURN)", "Feedback & GitHub": "Feedback & GitHub", "Design Store": "Design Store", "Restart required": "Neustart n\\u00f6tig" },
help: {
MAX_CONNECTIONS: "Offene WebSocket-Verbindungen insgesamt (0 = unbegrenzt).", MAX_CONNECTIONS_PER_IP: "Offene Verbindungen pro Client-IP (0 = unbegrenzt).",
CONNECT_RATE_LIMIT: "Verbindungsversuche pro IP und Minute (0 = unbegrenzt).",
ALLOWED_SERVERS: "Kommagetrennte TeamSpeak-Server, mit denen sich dieses Gateway verbinden darf (*.example.com erlaubt). Leer = alle.",
ALLOWED_ORIGINS: "Kommagetrennte Web-Origins, die dieses Gateway nutzen d\\u00fcrfen (https://client.example.com). Leer = alle.",
SERVER_PICKER: "ALLOWED_SERVERS im Verbindungsdialog als Auswahlliste anbieten.", DEFAULT_SERVER: "Im Verbindungsdialog vorausgef\\u00fcllte Serveradresse.", DEFAULT_CHANNEL: "Im Verbindungsdialog vorausgef\\u00fcllter Kanal.",
FEEDBACK_ENABLED: "Feedback aus der App annehmen (/api/feedback).", STORE_ENABLED: "Design Store betreiben (Theme-Einreichungen und Downloads).", LOG_CONNECTIONS: "Verbindungen protokollieren (gehashte Client-Kennungen, keine Klartext-IPs).",
NEWS_TICKER: "News-Ticker anzeigen.", NEWS_TICKER_CENTRAL: "Offizielle WebSpeak3-News im Ticker mit anzeigen.", NEWS_TICKER_MESSAGES: "Eigene Ticker-Meldungen, getrennt durch |.",
TURNSTILE_SITE_KEY: "Cloudflare-Turnstile-Site-Key (Bot-Check, braucht auch das Secret).", TURNSTILE_SECRET: "Cloudflare-Turnstile-Secret-Key.",
TURN_URLS: "Kommagetrennte TURN-Server-URLs f\\u00fcr Bildschirmfreigabe/Webcam.", TURN_SECRET: "coturn use-auth-secret (Zugangsdaten pro Nutzer).",
TURN_USERNAME: "Fester TURN-Benutzername (ohne TURN_SECRET).", TURN_CREDENTIAL: "Festes TURN-Passwort (ohne TURN_SECRET).",
ENABLE_TS2: "TeamSpeak-2-Server erlauben (experimentell).", TELEMETRY: "Anonymer t\\u00e4glicher Nutzungs-Ping (nur zuf\\u00e4llige Instanz-ID + Version).",
FEEDBACK_ALLOWED_ORIGIN: "Web-Origin, die Feedback senden darf (CORS). * = alle.", GITHUB_TOKEN: "GitHub-Token (Issues: write), um aus Feedback Issues zu machen.",
GITHUB_REPO: "Repository f\\u00fcr Feedback-Issues und die Release-News.", STORE_ALLOWED_ORIGIN: "Web-Origin, die den Store nutzen darf (CORS). * = alle.",
STORE_RESERVED_AUTHORS: "Kommagetrennte Autorennamen, unter denen nur der Store-Admin ver\\u00f6ffentlichen darf.", STORE_ADMIN_TOKEN: "Token zum Freigeben von Store-Einreichungen.",
TRUST_PROXY: "Hinter einem Proxy: \\"cloudflare\\" (CF-Connecting-IP) oder \\"1\\" (letzter X-Forwarded-For). Nur wenn das Gateway ausschlie\\u00dflich dar\\u00fcber erreichbar ist. Leer = aus.",
SYNC_URL: "Eigener Konto-Sync-Server (sync-server.js). Leer = der offizielle.",
PORT: "Port, auf dem das Gateway lauscht. Vorsicht: Bei Docker muss das Port-Mapping passen, sonst ist dieses Panel nicht mehr erreichbar (Abhilfe: PORT aus admin-config.json entfernen).",
TLS_CERT: "Pfad zum TLS-Zertifikat (mit TLS_KEY: HTTPS direkt ausliefern). Ein falscher Pfad verhindert den Start.", TLS_KEY: "Pfad zum privaten TLS-Schl\\u00fcssel.",
WEB_STATIC: "Web-Oberfl\\u00e4che von diesem Gateway ausliefern. Aus, wenn sie woanders gehostet wird.", WEB_DIST: "Ordner mit der gebauten Web-Oberfl\\u00e4che (web/dist).",
STORE_DATA_FILE: "Datendatei des Design Stores.", NEWS_DATA_FILE: "Datei f\\u00fcr News aus dem Stats-Panel.",
FEEDBACK_LOG_FILE: "Privates Feedback-Log (enth\\u00e4lt Kontakt-E-Mails).", TELEMETRY_ID_FILE: "Datei mit der zuf\\u00e4lligen Instanz-ID des Nutzungs-Pings.",
BROADCAST_TOKEN: "Bearer-Token f\\u00fcr /api/broadcast (Hinweise an alle Nutzer). Leer = Endpunkt aus.",
},
},
};
const $ = (id) => document.getElementById(id);
const store = { get(k) { try { return localStorage.getItem(k); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch {} } };
let lang = store.get("wsAdminLang") || (navigator.language.toLowerCase().startsWith("de") ? "de" : "en");
let theme = store.get("wsAdminTheme") || "auto";
let data = null, pending = {};
let current = store.get("wsAdminTab") || "";
// Non-setting pages in the sidebar: [tab key, card id, title string].
const EXTRA = [["__totp", "totpCard", "totpTitle"], ["__pw", "pwCard", "pwTitle"], ["__about", "aboutCard", "aboutTitle"]];
const gname = (g) => t("groups")[g] || g;
const t = (k) => T[lang][k];
const api = (path, body) => fetch("/admin/api/" + path, body === undefined ? {} : {
method: "POST", headers: { "Content-Type": "application/json", "X-WebSpeak3-Admin": "1" }, body: JSON.stringify(body),
}).then(async (r) => ({ status: r.status, data: await r.json().catch(() => ({})) }));
function el(tag, props, ...kids) { const e = Object.assign(document.createElement(tag), props); e.append(...kids); return e; }
function applyChrome() {
document.documentElement.lang = lang;
if (theme === "auto") document.documentElement.removeAttribute("data-theme"); else document.documentElement.dataset.theme = theme;
for (const b of document.querySelectorAll("[data-lang]")) b.setAttribute("aria-pressed", String(b.dataset.lang === lang));
for (const b of document.querySelectorAll("[data-theme-btn]")) b.setAttribute("aria-pressed", String(b.dataset.themeBtn === theme));
for (const e of document.querySelectorAll("[data-i18n]")) e.textContent = t(e.dataset.i18n);
$("search").placeholder = t("search"); $("noHits").textContent = t("noHits");
$("offCode").placeholder = $("totpCheck").placeholder = t("codePh"); $("offPw").placeholder = $("onPw").placeholder = t("pwPh");
}
function updateStatus() {
const n = Object.keys(pending).length;
$("status").textContent = n ? t("unsaved")(n) : "";
}
function render() {
applyChrome();
if (!data) return;
$("login").hidden = true; $("panel").hidden = false; $("logout").hidden = false;
$("totpState").textContent = data.totp === "panel" ? t("totpOnPanel") : data.totp ? t("totpOn") : t("totpOff");
$("totpOffBox").hidden = !data.totp;
$("pwState").textContent = data.passwordFromPanel ? t("pwPanel") : t("pwEnv");
renderStat();
const groups = $("groups"); groups.replaceChildren();
const cards = {};
for (const s of data.settings) {
let card = cards[s.group];
if (!card) {
card = cards[s.group] = el("section", { className: "card" }, el("h2", { textContent: gname(s.group) }), el("div", { className: "rows" }));
card.dataset.group = s.group; groups.append(card);
}
const id = "s_" + s.key;
const help = t("help")[s.key] || s.help;
let input;
if (s.kind === "bool") {
input = el("select", { id }, el("option", { value: "1", textContent: t("on") }), el("option", { value: "0", textContent: t("off") }));
input.value = s.value || s.fallback || "0";
} else {
input = el("input", { id, type: s.kind === "secret" ? "password" : s.kind === "number" ? "number" : "text", autocomplete: "off" });
if (s.kind === "number") input.min = "0";
if (s.kind === "secret") input.placeholder = s.isSet ? t("secretSet") : t("secretUnset");
else { input.value = s.value; if (s.fallback) input.placeholder = t("def") + s.fallback; }
}
if (s.key in pending) input.value = pending[s.key];
const reset = el("button", { type: "button", className: "plain reset", textContent: t("reset"), hidden: !s.overridden });
reset.addEventListener("click", () => save({ [s.key]: null }));
const badge = el("span", { className: "badge" + (s.overridden ? " panel" : ""), textContent: s.overridden ? t("fromPanel") : s.fromEnv ? t("fromEnv") : t("std") });
const row = el("div", { className: "row" + (s.inactive ? " inactive" : "") + (s.key in pending ? " changed" : "") },
el("div", { className: "lab" }, el("label", { htmlFor: id, textContent: s.key }), badge, reset), input, el("div", { className: "help", textContent: help }));
row.dataset.find = (s.key + " " + help + " " + gname(s.group)).toLowerCase();
const mark = () => { pending[s.key] = input.value; row.classList.add("changed"); updateStatus(); renderNav(); };
input.addEventListener("input", mark); input.addEventListener("change", mark);
if (s.inactive) row.append(el("div", { className: "warn", textContent: t("inactive") }));
if (s.pendingRestart) row.append(el("div", { className: "warn", textContent: t("pendingRestart") }));
card.lastChild.append(row);
}
if (!cards[current] && !EXTRA.some(([k]) => k === current)) current = data.settings[0].group;
const due = data.settings.filter((s) => s.pendingRestart).length;
$("restart").textContent = due ? t("restartDue")(due) : t("restartBtn");
$("restart").classList.toggle("due", due > 0);
updateStatus(); renderNav(); applyView();
}
function renderNav() {
const nav = $("nav"); nav.replaceChildren();
const item = (key, label, badge) => {
const b = el("button", { type: "button" }, el("span", { textContent: label }), ...(badge ? [badge] : []));
b.dataset.tab = key;
b.addEventListener("click", () => { current = key; store.set("wsAdminTab", key); $("search").value = ""; applyView(); });
nav.append(b); return b;
};
for (const g of [...new Set(data.settings.map((s) => s.group))]) {
const ss = data.settings.filter((s) => s.group === g);
const unsaved = ss.filter((s) => s.key in pending).length;
const badge = unsaved ? el("span", { className: "cnt", textContent: String(unsaved), title: t("unsaved")(unsaved) })
: ss.some((s) => s.pendingRestart) ? el("span", { className: "cnt warnc", textContent: "!", title: t("pendingRestart") }) : null;
const b = item(g, gname(g), badge);
if (ss.every((s) => s.inactive)) { b.classList.add("muted"); b.title = t("inactive"); }
}
nav.append(el("hr"));
for (const [k, , label] of EXTRA) item(k, t(label));
markCurrent();
}
function markCurrent() {
const q = $("search").value.trim();
for (const b of $("nav").children) if (b.dataset.tab) b.setAttribute("aria-current", String(!q && b.dataset.tab === current));
}
// One page at a time; a search shows matches from every category instead.
function applyView() {
const q = $("search").value.trim().toLowerCase();
let hits = 0;
for (const card of $("groups").children) {
let any = false;
for (const row of card.lastChild.children) { const m = !q || row.dataset.find.includes(q); row.hidden = !m; if (m) { any = true; hits++; } }
card.hidden = q ? !any : card.dataset.group !== current;
}
for (const [k, id] of EXTRA) $(id).hidden = Boolean(q) || current !== k;
$("noHits").hidden = !q || hits > 0;
markCurrent();
}
function renderStat() {
const up = data.uptime, d = Math.floor(up / 86400), h = Math.floor(up / 3600) % 24, m = Math.floor(up / 60) % 60;
const parts = [t("statConn")(data.connections), t("statUp") + (d ? d + " d " : "") + (d || h ? h + " h " : "") + m + " min"];
if (data.version) parts.unshift(t("statVer") + data.version);
$("stat").textContent = parts.join(" \\u00b7 "); $("stat").hidden = false;
}
// Keeps the status line fresh without re-rendering half-typed fields.
setInterval(async () => {
if (!data || document.hidden) return;
const r = await api("config");
if (r.status === 200) { data.connections = r.data.connections; data.uptime = r.data.uptime; renderStat(); }
}, 30000);
// Credential actions: show the server's error next to the form, else take the new state.
async function cred(path, body, errId) {
$(errId).textContent = "";
const r = await api(path, body);
if (r.status === 401) { load(); return false; }
if (r.status !== 200) { $(errId).textContent = t("credErr")[r.data.error] || r.data.error || t("saveFailed"); return false; }
data = r.data; render(); return true;
}
async function load() {
const r = await api("config");
if (r.status === 200) { data = r.data; pending = {}; return render(); }
data = null; applyChrome();
$("panel").hidden = true; $("logout").hidden = true; $("stat").hidden = true; $("login").hidden = false;
}
async function save(changes) {
$("saveErr").textContent = "";
const r = await api("config", { changes });
if (r.status === 401) return load();
if (r.status !== 200) { $("saveErr").textContent = (r.data.key ? r.data.key + ": " : "") + (t("errors")[r.data.error] || r.data.error || t("saveFailed")); return; }
data = r.data; for (const k of Object.keys(changes)) delete pending[k];
render(); $("status").textContent = t("saved");
}
document.querySelectorAll("[data-lang]").forEach((b) => b.addEventListener("click", () => { lang = b.dataset.lang; store.set("wsAdminLang", lang); render(); }));
document.querySelectorAll("[data-theme-btn]").forEach((b) => b.addEventListener("click", () => { theme = b.dataset.themeBtn; store.set("wsAdminTheme", theme); applyChrome(); }));
$("login").addEventListener("submit", async (e) => {
e.preventDefault(); $("loginErr").textContent = "";
const r = await api("login", { user: $("u").value, password: $("p").value, code: $("c").value });
if (r.status === 200) { $("p").value = ""; $("c").value = ""; return load(); }
$("loginErr").textContent = r.status === 429 ? t("tooMany") : t("loginFailed");
});
$("panel").addEventListener("submit", (e) => { e.preventDefault(); if (Object.keys(pending).length) save({ ...pending }); });
$("search").addEventListener("input", applyView);
$("restart").addEventListener("click", async () => {
const fresh = await api("config"); if (fresh.status !== 200) return load();
if (!confirm(t("restartConfirm")(fresh.data.connections))) return;
const r = await api("restart", {});
if (r.status !== 200) { $("saveErr").textContent = t("restartFailed"); return; }
$("restart").disabled = $("save").disabled = true; $("status").textContent = t("restarting");
// Wait for the old process to go away, then until /admin answers again.
await new Promise((ok) => setTimeout(ok, 2000));
for (let i = 0; i < 90; i++) {
try { if ((await fetch("/admin/admin.js", { cache: "no-store" })).ok) return location.reload(); } catch {}
await new Promise((ok) => setTimeout(ok, 2000));
}
$("saveErr").textContent = t("restartFailed");
});
$("logout").addEventListener("click", async () => { await api("logout", {}); load(); });
$("genTotp").addEventListener("click", async () => {
const r = await api("totp-secret"); if (r.status !== 200) return load();
$("totpQr").src = r.data.qr; $("totpSecret").textContent = r.data.secret; $("totpEnv").textContent = "ADMIN_TOTP_SECRET=" + r.data.secret; $("totpOut").hidden = false; $("totpDone").hidden = true; $("totpCheck").value = ""; $("totpCheckErr").textContent = "";
});
$("totpCheckBtn").addEventListener("click", async () => {
$("totpCheckErr").textContent = "";
const r = await api("totp-verify", { secret: $("totpSecret").textContent, code: $("totpCheck").value });
if (r.status === 401) return load();
if (r.status === 200 && r.data.ok) { $("totpDone").hidden = false; return; }
$("totpDone").hidden = true; $("totpCheckErr").textContent = t("codeWrong");
});
$("onBtn").addEventListener("click", async () => {
if (await cred("totp-enable", { secret: $("totpSecret").textContent, code: $("totpCheck").value, password: $("onPw").value }, "onErr")) {
$("onPw").value = ""; $("totpOut").hidden = true; $("totpState").textContent = t("totpDoneOn");
}
});
$("offBtn").addEventListener("click", async () => {
if (await cred("totp-disable", { code: $("offCode").value, password: $("offPw").value }, "offErr")) { $("offCode").value = $("offPw").value = ""; }
});
$("pwBtn").addEventListener("click", async () => {
$("pwErr").textContent = "";
if ($("pwNew").value !== $("pwNew2").value) { $("pwErr").textContent = t("pwMismatch"); return; }
if (await cred("password", { password: $("pwOld").value, newPassword: $("pwNew").value }, "pwErr")) {
$("pwOld").value = $("pwNew").value = $("pwNew2").value = ""; $("pwState").textContent = t("pwDone");
}
});
applyChrome();
load();
`;
+140
View File
@@ -0,0 +1,140 @@
// Settings the admin panel (admin.ts) may change at runtime. Values saved
// there live in ADMIN_CONFIG_FILE and are written onto process.env, both at
// startup and on every save, so code that reads process.env at use time picks
// them up without a restart. Must be imported before any module that reads
// these variables at load time (first import in index.ts).
//
// Settings marked `restart` are only written onto process.env at startup:
// they are read once at load time, so the panel saves them and asks for a
// restart instead of pretending they are live.
//
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
// operator's LAN), and the admin credentials themselves.
import { readFileSync } from "node:fs";
import { writeFileAtomic } from "./net.js";
import path from "node:path";
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
export interface Setting {
key: string;
kind: SettingKind;
/** Value used when neither .env nor the panel sets one (shown as hint). */
fallback?: string;
help: string;
group: string;
/** Only ends up in the UI this gateway serves itself (meta tags). */
staticOnly?: boolean;
/** Read once at startup; changes take effect after a restart. */
restart?: boolean;
}
export const SETTINGS: Setting[] = [
{ group: "Connections & limits", key: "MAX_CONNECTIONS", kind: "number", fallback: "60", help: "Open WebSocket connections in total (0 = unlimited)." },
{ group: "Connections & limits", key: "MAX_CONNECTIONS_PER_IP", kind: "number", fallback: "10", help: "Open connections per client IP (0 = unlimited)." },
{ group: "Connections & limits", key: "CONNECT_RATE_LIMIT", kind: "number", fallback: "30", help: "Connect attempts per IP per minute (0 = unlimited)." },
{ group: "Access", key: "ALLOWED_SERVERS", kind: "list", help: "Comma-separated TeamSpeak servers this gateway may connect to (*.example.com allowed). Empty = any." },
{ group: "Access", key: "ALLOWED_ORIGINS", kind: "list", help: "Comma-separated web origins allowed to use this gateway (https://client.example.com). Empty = any." },
{ group: "Access", key: "TRUST_PROXY", kind: "text", help: "Behind a proxy: \"cloudflare\" (CF-Connecting-IP) or \"1\" (last X-Forwarded-For). Only if the gateway is reachable solely through it. Empty = off." },
{ group: "Connect dialog", staticOnly: true, key: "SERVER_PICKER", kind: "bool", fallback: "1", help: "Offer ALLOWED_SERVERS as a dropdown in the connect dialog." },
{ group: "Connect dialog", staticOnly: true, key: "DEFAULT_SERVER", kind: "text", help: "Server address prefilled in the connect dialog." },
{ group: "Connect dialog", staticOnly: true, key: "DEFAULT_CHANNEL", kind: "text", help: "Channel prefilled in the connect dialog." },
{ group: "Connect dialog", staticOnly: true, key: "SYNC_URL", kind: "text", help: "Own account-sync server (sync-server.js). Empty = the official one." },
{ group: "Features", key: "FEEDBACK_ENABLED", kind: "bool", fallback: "0", help: "Accept in-app feedback (/api/feedback)." },
{ group: "Features", key: "STORE_ENABLED", kind: "bool", fallback: "0", help: "Run the Design Store (theme submissions and downloads)." },
{ group: "Features", key: "LOG_CONNECTIONS", kind: "bool", fallback: "0", help: "Log connects/disconnects (hashed client tags, no plain IPs)." },
{ group: "Features", key: "ENABLE_TS2", kind: "bool", fallback: "0", help: "Allow TeamSpeak 2 servers (experimental)." },
{ group: "Features", key: "TELEMETRY", kind: "bool", fallback: "1", help: "Anonymous daily usage ping (random instance id + version only)." },
{ group: "Feedback & GitHub", key: "FEEDBACK_ALLOWED_ORIGIN", kind: "text", fallback: "*", help: "Web origin allowed to send feedback (CORS). * = any." },
{ group: "Feedback & GitHub", key: "GITHUB_TOKEN", kind: "secret", help: "GitHub token (Issues: write) to turn feedback into issues." },
{ group: "Feedback & GitHub", key: "GITHUB_REPO", kind: "text", fallback: "WebSpeak3/webspeak3", help: "Repository for feedback issues and the release news." },
{ group: "Design Store", key: "STORE_ALLOWED_ORIGIN", kind: "text", fallback: "*", help: "Web origin allowed to use the store (CORS). * = any." },
{ group: "Design Store", key: "STORE_RESERVED_AUTHORS", kind: "list", fallback: "Möpchi,Moepchi", help: "Comma-separated author names only the store admin may publish under." },
{ group: "Design Store", key: "STORE_ADMIN_TOKEN", kind: "secret", help: "Token for approving store submissions." },
{ group: "Access", key: "BROADCAST_TOKEN", kind: "secret", help: "Bearer token for /api/broadcast (notices to all users). Empty = endpoint off." },
{ group: "News ticker", key: "NEWS_TICKER", kind: "bool", fallback: "1", help: "Show the news ticker." },
{ group: "News ticker", key: "NEWS_TICKER_CENTRAL", kind: "bool", fallback: "1", help: "Include the official WebSpeak3 news in the ticker." },
{ group: "News ticker", key: "NEWS_TICKER_MESSAGES", kind: "text", help: "Own ticker messages, separated by |." },
{ group: "Bot check (Cloudflare Turnstile)", key: "TURNSTILE_SITE_KEY", kind: "text", help: "Cloudflare Turnstile site key (bot check, needs the secret too)." },
{ group: "Bot check (Cloudflare Turnstile)", key: "TURNSTILE_SECRET", kind: "secret", help: "Cloudflare Turnstile secret key." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_URLS", kind: "list", help: "Comma-separated TURN server URLs for screen sharing/webcam." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_SECRET", kind: "secret", help: "coturn use-auth-secret (per-user credentials)." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_USERNAME", kind: "text", help: "Static TURN username (if no TURN_SECRET)." },
{ group: "Screen sharing & webcam (TURN)", key: "TURN_CREDENTIAL", kind: "secret", help: "Static TURN password (if no TURN_SECRET)." },
{ group: "Restart required", restart: true, key: "PORT", kind: "number", fallback: "8080", help: "Port the gateway listens on. Careful: with Docker the port mapping must match, or this panel becomes unreachable (fix: remove PORT from admin-config.json)." },
{ group: "Restart required", restart: true, key: "TLS_CERT", kind: "text", help: "Path to the TLS certificate (with TLS_KEY: serve HTTPS directly). A wrong path stops the gateway from starting." },
{ group: "Restart required", restart: true, key: "TLS_KEY", kind: "text", help: "Path to the TLS private key." },
{ group: "Restart required", restart: true, key: "WEB_STATIC", kind: "bool", fallback: "1", help: "Serve the web UI from this gateway. Off when the UI is hosted elsewhere." },
{ group: "Restart required", restart: true, key: "WEB_DIST", kind: "text", help: "Folder with the built web UI (web/dist)." },
{ group: "Restart required", restart: true, key: "STORE_DATA_FILE", kind: "text", fallback: "./store-themes.json", help: "Design Store data file." },
{ group: "Restart required", restart: true, key: "NEWS_DATA_FILE", kind: "text", help: "File for news managed in the stats panel." },
{ group: "Restart required", restart: true, key: "FEEDBACK_LOG_FILE", kind: "text", fallback: "./feedback.log", help: "Private feedback log (includes contact e-mails)." },
{ group: "Restart required", restart: true, key: "TELEMETRY_ID_FILE", kind: "text", fallback: "./instance-id", help: "File holding the random instance id of the usage ping." },
];
const BY_KEY = new Map(SETTINGS.map((s) => [s.key, s]));
const CONFIG_FILE = process.env.ADMIN_CONFIG_FILE ?? path.resolve(process.cwd(), "admin-config.json");
// What .env said before any override, so "reset" can go back to it.
const ENV_DEFAULTS = new Map(SETTINGS.map((s) => [s.key, process.env[s.key]]));
let overrides: Record<string, string> = {};
const configured = (key: string) => (key in overrides ? overrides[key] : ENV_DEFAULTS.get(key));
function apply(startup = false): void {
for (const { key, restart } of SETTINGS) {
if (restart && !startup) continue;
const value = configured(key);
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
try {
const raw = JSON.parse(readFileSync(CONFIG_FILE, "utf8")) as Record<string, unknown>;
for (const [key, value] of Object.entries(raw)) {
if (BY_KEY.has(key) && typeof value === "string") overrides[key] = value;
}
apply(true);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`[admin] Ignoring unreadable ${CONFIG_FILE}:`, err);
}
/** Returns an error message, or undefined when the value is acceptable. */
export function validate(key: string, value: string): string | undefined {
const setting = BY_KEY.get(key);
if (!setting) return "unknown setting";
if (value.length > 4000 || /[\p{Cc}]/u.test(value)) return "invalid characters or too long";
if (setting.kind === "number" && !/^\d{1,6}$/.test(value)) return "must be a whole number";
if (setting.kind === "bool" && value !== "0" && value !== "1") return "must be 0 or 1";
if (key === "PORT" && value !== "" && (Number(value) < 1 || Number(value) > 65535)) return "must be a port (1-65535)";
return undefined;
}
/** Applies and persists changes. `null` removes the override (back to .env). */
export async function updateSettings(changes: Record<string, string | null>): Promise<void> {
const next = { ...overrides };
for (const [key, value] of Object.entries(changes)) {
if (value === null) delete next[key];
else next[key] = value;
}
await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
overrides = next;
apply();
}
/** Panel view: secrets only say whether they are set. */
export function describeSettings() {
return SETTINGS.map((s) => {
// Restart settings show what is saved, not what the process still runs with.
const value = s.restart ? configured(s.key) : process.env[s.key];
return {
...s,
overridden: s.key in overrides,
fromEnv: ENV_DEFAULTS.get(s.key) !== undefined,
value: s.kind === "secret" ? undefined : (value ?? ""),
isSet: Boolean(value),
// With WEB_STATIC=0 the UI comes from elsewhere and never sees these.
inactive: Boolean(s.staticOnly && process.env.WEB_STATIC === "0"),
pendingRestart: Boolean(s.restart && (value ?? "") !== (process.env[s.key] ?? "")),
};
});
}
+124 -56
View File
@@ -1,3 +1,4 @@
import "./config.js"; // first: applies admin-panel overrides to process.env
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createServer as createSecureServer } from "node:https";
import { readFileSync } from "node:fs";
@@ -9,14 +10,18 @@ import { WebSocketServer, type WebSocket } from "ws";
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
import { handleStore } from "./store.js";
import { handleNewsConfig } from "./news.js";
import { handleAdmin, setConnectionCounter } from "./admin.js";
import { logFeedback, logConnectionEvent } from "./activity-log.js";
import { clientIp, createRateLimiter } from "./net.js";
import { turnstileEnabled, turnstileSiteKey, isValidPass, issuePass, verifyToken } from "./turnstile.js";
import "./telemetry.js";
const SERVER_TYPES = new Set<ServerType>(["teamspeak", "teaspeak", "auto"]);
// TeamSpeak 2 support is experimental and opt-in (ENABLE_TS2=1).
const ts2Enabled = () => process.env.ENABLE_TS2 === "1";
const serverTypes = () => new Set<ServerType>(["teamspeak", "teaspeak", "auto", ...(ts2Enabled() ? (["ts2"] as const) : [])]);
function parseServerType(value: unknown): ServerType | undefined {
return typeof value === "string" && SERVER_TYPES.has(value as ServerType)
return typeof value === "string" && serverTypes().has(value as ServerType)
? (value as ServerType)
: undefined;
}
@@ -31,10 +36,13 @@ function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): st
// Self-hosting admins may want to lock their instance to specific server(s)
// instead of leaving it as a general-purpose "connect anywhere" client.
// Unset (the default) means unrestricted, unchanged from before this existed.
const ALLOWED_SERVERS = (process.env.ALLOWED_SERVERS ?? "")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
// Live settings below are functions, not constants: the admin panel
// (config.ts/admin.ts) can change process.env while the gateway runs.
const allowedServers = () =>
(process.env.ALLOWED_SERVERS ?? "")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
// Strips a trailing ":port" so "ts.example.com:9987" and "ts.example.com"
// both match a plain "ts.example.com" allowlist entry. IPv6 literals come
@@ -42,14 +50,17 @@ const ALLOWED_SERVERS = (process.env.ALLOWED_SERVERS ?? "")
// as-is. Deliberately not full URL parsing - `host` here is never a URL.
function stripPort(host: string): string {
if (host.startsWith("[")) {
const end = host.indexOf("]");
return end === -1 ? host : host.slice(1, end);
// Only "[v6]" or "[v6]:port"; anything after "]" would otherwise be
// ignored here but still reach the connector ("[allowed]evil.tld").
const m = /^\[([^\]]*)\](?::\d+)?$/.exec(host);
return m ? m[1] : host;
}
const i = host.lastIndexOf(":");
return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host;
}
function isServerAllowed(host: unknown): boolean {
const ALLOWED_SERVERS = allowedServers();
if (ALLOWED_SERVERS.length === 0) return true;
if (typeof host !== "string") return false;
const target = stripPort(host).trim().toLowerCase();
@@ -85,22 +96,25 @@ function isValidNickname(nickname: unknown): nickname is string {
// Unset keeps the old "any origin" behavior for self-hosters; entries are
// full origins ("https://client.example.com"). Non-browser clients send no
// Origin header at all - they could fake one anyway, so they aren't blocked.
const ALLOWED_ORIGINS = (process.env.ALLOWED_ORIGINS ?? "")
.split(",")
.map((s) => s.trim().replace(/\/+$/, "").toLowerCase())
.filter(Boolean);
const allowedOrigins = () =>
(process.env.ALLOWED_ORIGINS ?? "")
.split(",")
.map((s) => s.trim().replace(/\/+$/, "").toLowerCase())
.filter(Boolean);
// Each /ws socket can spawn a connector process holding a live TeamSpeak
// session, so both need a ceiling. 0 disables the respective limit.
const MAX_CONNECTIONS_PER_IP = Number(process.env.MAX_CONNECTIONS_PER_IP ?? 10);
const MAX_CONNECTIONS = Number(process.env.MAX_CONNECTIONS ?? 300);
const maxConnectionsPerIp = () => Number(process.env.MAX_CONNECTIONS_PER_IP ?? 10);
// Measured 2026-10-25: ~8-9 % of a core per client listening to constant audio
// (connector + node + cloudflared), ~10-15 MB RAM. 60 suits a 2-core VPS.
const maxConnections = () => Number(process.env.MAX_CONNECTIONS ?? 60);
const connectionsPerIp = new Map<string, number>();
// Every "connect" spawns a fresh connector, and a socket can send any number
// of them - without this, 10 sockets were enough to join-flood a TS server
// through this gateway at several joins per second. Real clients (reconnect
// backoff, restoring a handful of tabs) stay far below it.
const CONNECT_RATE_LIMIT = Number(process.env.CONNECT_RATE_LIMIT ?? 30);
const isConnectRateLimited = createRateLimiter(CONNECT_RATE_LIMIT, 60_000);
const connectRateLimit = () => Number(process.env.CONNECT_RATE_LIMIT ?? 30);
const isConnectRateLimited = createRateLimiter(connectRateLimit, 60_000);
// Largest single WS message. Uploads now arrive in small "uploadFileChunk"
// pieces; this size only stays for browsers still running a client from
@@ -122,15 +136,16 @@ const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
// Sent to every browser in the "hello" message on socket open; see there.
const GATEWAY_FEATURES = ["clientVolume", "keepalive", "chunkedUpload", "whisperPolicy", "transferLimit"];
const gatewayFeatures = () => ["clientVolume", "keepalive", "chunkedUpload", "whisperPolicy", "transferLimit", ...(ts2Enabled() ? ["ts2"] : [])];
// Optional TURN relay for screen streams, also handed out in "hello". With
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
// valid for a day; TURN_USERNAME/TURN_CREDENTIAL are static and so readable by
// every visitor. ponytail: a socket open longer than a day hands an expired
// credential to a stream started after that; reconnecting fixes it.
const TURN_URLS = (process.env.TURN_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean);
function turnServers() {
const TURN_URLS = (process.env.TURN_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean);
if (!TURN_URLS.length) return undefined;
const secret = process.env.TURN_SECRET;
if (!secret) {
@@ -147,11 +162,14 @@ function turnServers() {
// The allowlist goes along so the client can offer it as a dropdown (or a
// locked field for a single entry) instead of a free-text address; not with
// wildcards, which can't be listed, nor with SERVER_PICKER=0.
const SERVER_PICKER =
process.env.SERVER_PICKER !== "0" && !ALLOWED_SERVERS.some((e) => e.startsWith("*."))
? ALLOWED_SERVERS.join(",")
: undefined;
const RUNTIME_CONFIG_META = Object.entries({
// Built per request, since the admin panel can change these at runtime.
const runtimeConfigMeta = () => {
const ALLOWED_SERVERS = allowedServers();
const SERVER_PICKER =
process.env.SERVER_PICKER !== "0" && !ALLOWED_SERVERS.some((e) => e.startsWith("*."))
? ALLOWED_SERVERS.join(",")
: undefined;
return Object.entries({
"webspeak3-default-server": process.env.DEFAULT_SERVER,
"webspeak3-default-channel": process.env.DEFAULT_CHANNEL,
"webspeak3-allowed-servers": SERVER_PICKER,
@@ -162,6 +180,7 @@ const RUNTIME_CONFIG_META = Object.entries({
value ? [`<meta name="${name}" content="${value.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}">`] : [],
)
.join("");
};
const MIME_TYPES: Record<string, string> = {
".html": "text/html",
@@ -185,16 +204,15 @@ const MIME_TYPES: Record<string, string> = {
// (see IS_OWN_HOSTED_INSTANCE in web/src/App.tsx), but this endpoint
// enforces its own opt-in independently since it's reachable directly over
// HTTP by anyone who finds the gateway's address, not just from that UI.
const FEEDBACK_ENABLED = process.env.FEEDBACK_ENABLED === "1";
// The web app is commonly hosted on a different origin than the gateway
// (see mem:deployment / GATEWAY_URL in web/), so this needs its own CORS
// allowance; default "*" since the endpoint is opt-in, rate-limited, and
// only ever accepts a feedback submission, nothing that reads data back.
const FEEDBACK_ALLOWED_ORIGIN = process.env.FEEDBACK_ALLOWED_ORIGIN ?? "*";
const feedbackAllowedOrigin = () => process.env.FEEDBACK_ALLOWED_ORIGIN || "*";
// A token with "Issues: write" access on the target repo. Without it,
// feedback is still accepted and logged, just never turned into an issue.
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_REPO = process.env.GITHUB_REPO ?? "WebSpeak3/webspeak3";
const githubRepo = () => process.env.GITHUB_REPO || "WebSpeak3/webspeak3";
const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]);
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
@@ -205,18 +223,18 @@ const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
// tab (reuses the same {type:"notice"} message the SIGTERM handler already
// sends, which the frontend renders even without a messageKey). Unset
// BROADCAST_TOKEN and the endpoint 404s, same as feedback when disabled.
const BROADCAST_TOKEN = process.env.BROADCAST_TOKEN;
const BROADCAST_MESSAGE_MAX_LENGTH = 500;
function isValidBroadcastToken(provided: string): boolean {
if (!BROADCAST_TOKEN) return false;
const token = process.env.BROADCAST_TOKEN;
if (!token) return false;
const a = Buffer.from(provided);
const b = Buffer.from(BROADCAST_TOKEN);
const b = Buffer.from(token);
return a.length === b.length && timingSafeEqual(a, b);
}
async function handleBroadcast(req: IncomingMessage, res: ServerResponse) {
if (!BROADCAST_TOKEN) {
if (!process.env.BROADCAST_TOKEN) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
@@ -295,7 +313,8 @@ function neutralizeMentions(text: string): string {
// The contact e-mail is deliberately *not* part of this: it's only kept in
// the private feedback log (logFeedback), never in the public issue.
async function createGithubIssue(payload: { category: string; message: string }): Promise<string | undefined> {
if (!GITHUB_TOKEN) return undefined;
const githubToken = process.env.GITHUB_TOKEN;
if (!githubToken) return undefined;
const title = neutralizeMentions(
`[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`,
);
@@ -311,10 +330,10 @@ async function createGithubIssue(payload: { category: string; message: string })
"_Submitted via the in-client feedback form._",
].join("\n");
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/issues`, {
const res = await fetch(`https://api.github.com/repos/${githubRepo()}/issues`, {
method: "POST",
headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`,
Authorization: `Bearer ${githubToken}`,
Accept: "application/vnd.github+json",
"Content-Type": "application/json",
"User-Agent": "webspeak3-gateway",
@@ -332,7 +351,7 @@ async function createGithubIssue(payload: { category: string; message: string })
}
async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", FEEDBACK_ALLOWED_ORIGIN);
res.setHeader("Access-Control-Allow-Origin", feedbackAllowedOrigin());
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
@@ -341,7 +360,7 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.end();
return;
}
if (!FEEDBACK_ENABLED) {
if (process.env.FEEDBACK_ENABLED !== "1") {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
@@ -482,10 +501,21 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
await handleFeedback(req, res);
return;
}
if (requestUrl.pathname === "/api/features") {
// Same list as the "hello" message, readable before any connect
// (the connect dialog offers TeamSpeak 2 only when it is enabled).
res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=300" });
res.end(JSON.stringify({ features: gatewayFeatures(), ...(turnstileEnabled() ? { turnstileSiteKey: turnstileSiteKey() } : {}) }));
return;
}
if (requestUrl.pathname === "/api/news") {
handleNewsConfig(res);
return;
}
if (requestUrl.pathname === "/admin" || requestUrl.pathname.startsWith("/admin/")) {
await handleAdmin(req, res, requestUrl.pathname);
return;
}
if (requestUrl.pathname === "/api/broadcast") {
await handleBroadcast(req, res);
return;
@@ -539,9 +569,10 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
filePath = path.join(WEB_DIST, "index.html");
body = await readFile(filePath);
}
if (RUNTIME_CONFIG_META && filePath === path.join(WEB_DIST, "index.html")) {
const meta = filePath === path.join(WEB_DIST, "index.html") ? runtimeConfigMeta() : "";
if (meta) {
// Function replacer: a string one would expand "$&" etc. in the values.
body = Buffer.from(body.toString("utf8").replace("</head>", () => `${RUNTIME_CONFIG_META}</head>`));
body = Buffer.from(body.toString("utf8").replace("</head>", () => `${meta}</head>`));
}
const ext = path.extname(filePath);
res.writeHead(200, {
@@ -567,19 +598,20 @@ const wss = new WebSocketServer({
path: "/ws",
maxPayload: WS_MAX_PAYLOAD,
verifyClient: ({ origin, req }, done) => {
const ALLOWED_ORIGINS = allowedOrigins();
if (ALLOWED_ORIGINS.length > 0 && origin && !ALLOWED_ORIGINS.includes(origin.toLowerCase())) {
return done(false, 403, "Origin not allowed");
}
if (MAX_CONNECTIONS > 0 && wss.clients.size >= MAX_CONNECTIONS) {
return done(false, 503, "Gateway is full");
}
const ip = clientIp(req);
const MAX_CONNECTIONS_PER_IP = maxConnectionsPerIp();
if (MAX_CONNECTIONS_PER_IP > 0 && (connectionsPerIp.get(ip) ?? 0) >= MAX_CONNECTIONS_PER_IP) {
console.warn(`[ratelimit] too many open connections from one IP (limit ${MAX_CONNECTIONS_PER_IP})`);
return done(false, 429, "Too many connections");
}
done(true);
},
});
setConnectionCounter(() => wss.clients.size);
// Heartbeat: a browser tab that loses its network mid-session (mobile
// handover, Wi-Fi drop, backgrounded/frozen tab) often never sends a proper
@@ -678,6 +710,18 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
// One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens
// multiple /ws connections in parallel (one per server tab).
let connection: Ts3Connection | undefined;
// Message handlers are async and run concurrently, so a connect can still be
// awaiting when a newer connect or the close arrives. Only the newest
// connect on an open socket may spawn a connector, else one leaks.
let closed = false;
let connectGen = 0;
// Full: accept and say so, since a browser can't read why an upgrade was refused.
if (maxConnections() > 0 && wss.clients.size > maxConnections()) {
socket.send(JSON.stringify({ type: "error", code: "gateway_full", message: "This gateway is full right now. Please try again in a few minutes." }));
socket.close(1013, "Gateway is full");
return;
}
const ip = clientIp(req);
connectionsPerIp.set(ip, (connectionsPerIp.get(ip) ?? 0) + 1);
@@ -686,7 +730,7 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
// pulled, so the browser must not assume a feature exists just because it
// knows about it. A gateway without "hello" (before v0.15) supports the
// v0.14 feature set, streaming included; anything newer gets a name here.
socket.send(JSON.stringify({ type: "hello", features: GATEWAY_FEATURES, iceServers: turnServers() }));
socket.send(JSON.stringify({ type: "hello", features: gatewayFeatures(), iceServers: turnServers() }));
heartbeats.set(socket, { isAlive: true });
socket.on("pong", () => {
@@ -732,24 +776,38 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
);
break;
}
if (CONNECT_RATE_LIMIT > 0 && isConnectRateLimited(ip)) {
if (connectRateLimit() > 0 && isConnectRateLimited(ip)) {
console.warn(`[ratelimit] too many connects from one IP, target host=${msg.host}`);
socket.send(
JSON.stringify({ type: "error", message: "Too many connection attempts. Please wait a minute." }),
);
break;
}
// Replacing a connection on the same socket: tear down the previous
// connector so we don't leak processes.
if (connection) {
try {
await connection.disconnect();
} catch {
/* ignore */
if (turnstileEnabled() && !isValidPass(msg.turnstilePass, ip)) {
// No (valid) pass yet: ask the browser to solve the check, it
// resends this connect with the token.
if (msg.turnstileToken === undefined) {
socket.send(JSON.stringify({ type: "turnstileRequired" }));
break;
}
liveConnections.delete(connection);
connection = undefined;
if (!(await verifyToken(msg.turnstileToken, ip))) {
socket.send(
JSON.stringify({ type: "error", code: "turnstile_failed", message: "Bot check failed. Please try again." }),
);
break;
}
socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) }));
}
// Replacing a connection on the same socket: take the previous one
// out before awaiting its teardown, so no other handler sees it.
const gen = ++connectGen;
const prev = connection;
connection = undefined;
if (prev) {
liveConnections.delete(prev);
await prev.disconnect().catch(() => {});
}
if (closed || gen !== connectGen) break;
const options: Ts3ConnectOptions = {
host: msg.host,
nickname: msg.nickname,
@@ -759,6 +817,8 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
identity: msg.identity,
serverType: parseServerType(msg.serverType),
privilegeKey: parsePrivilegeKey(msg),
loginName: typeof msg.loginName === "string" ? msg.loginName.trim() || undefined : undefined,
loginPassword: typeof msg.loginPassword === "string" ? msg.loginPassword || undefined : undefined,
};
connection = new Ts3Connection(options);
liveConnections.add(connection);
@@ -1041,9 +1101,13 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
break;
}
case "disconnect": {
await connection?.disconnect(msg.message ?? "");
if (connection) liveConnections.delete(connection);
// Same as above: detach first, a connect may arrive while this awaits.
const current = connection;
connection = undefined;
if (current) {
liveConnections.delete(current);
await current.disconnect(msg.message ?? "");
}
break;
}
default:
@@ -1059,7 +1123,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
if (remaining > 0) connectionsPerIp.set(ip, remaining);
else connectionsPerIp.delete(ip);
heartbeats.delete(socket);
if (connection) liveConnections.delete(connection);
connection?.disconnect();
closed = true;
if (connection) {
liveConnections.delete(connection);
void connection.disconnect().catch(() => {});
connection = undefined;
}
});
});
+23 -4
View File
@@ -1,4 +1,5 @@
import type { IncomingMessage } from "node:http";
import { rename, writeFile } from "node:fs/promises";
// 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
@@ -6,9 +7,9 @@ import type { IncomingMessage } from "node:http";
// - "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.
const TRUST_PROXY = process.env.TRUST_PROXY;
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();
@@ -22,7 +23,7 @@ export function clientIp(req: IncomingMessage): string {
/** 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, windowMs: number): (key: string) => boolean {
export function createRateLimiter(limit: number | (() => number), windowMs: number): (key: string) => boolean {
const hits = new Map<string, number[]>();
setInterval(() => {
const now = Date.now();
@@ -35,6 +36,24 @@ export function createRateLimiter(limit: number, windowMs: number): (key: string
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
recent.push(now);
hits.set(key, recent);
return recent.length > limit;
return recent.length > (typeof limit === "function" ? limit() : limit);
};
}
/** Write-then-rename, one write at a time per file. Concurrent requests used
* to share one `.tmp` path: one rename won, the others failed with ENOENT,
* and overlapping writes could leave a mangled file. Queued, the last caller's
* data always lands last. */
const writeQueues = new Map<string, Promise<void>>();
export function writeFileAtomic(file: string, data: string, mode?: number): Promise<void> {
const run = async () => {
const tmp = `${file}.tmp`;
await writeFile(tmp, data, { encoding: "utf-8", mode });
await rename(tmp, file);
};
const done = (writeQueues.get(file) ?? Promise.resolve()).then(run);
const tail = done.catch(() => {});
writeQueues.set(file, tail);
void tail.then(() => { if (writeQueues.get(file) === tail) writeQueues.delete(file); });
return done;
}
+18 -14
View File
@@ -13,7 +13,8 @@
//
// Like store.ts, this file has zero private modifications.
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises";
import { readFile } from "node:fs/promises";
import { writeFileAtomic } from "./net.js";
import { randomUUID } from "node:crypto";
import { isAdminRequest, latestPublicTheme } from "./store.js";
@@ -24,7 +25,6 @@ type NewsItem =
type TextItem = Extract<NewsItem, { kind: "text" }>;
const NEWS_DATA_FILE = process.env.NEWS_DATA_FILE;
const GITHUB_REPO = process.env.GITHUB_REPO ?? "WebSpeak3/webspeak3";
const MAX_ITEMS = 20;
const MAX_TEXT = 300;
const AUTO_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
@@ -44,9 +44,7 @@ async function load(): Promise<TextItem[]> {
}
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!);
await writeFileAtomic(NEWS_DATA_FILE!, JSON.stringify(items));
cache = items;
}
@@ -57,7 +55,7 @@ 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/${GITHUB_REPO}/releases?per_page=1`, {
const res = await fetch(`https://api.github.com/repos/${process.env.GITHUB_REPO || "WebSpeak3/webspeak3"}/releases?per_page=1`, {
headers: { Accept: "application/vnd.github+json", "User-Agent": "webspeak3-store" },
});
if (!res.ok) return release.item;
@@ -135,16 +133,22 @@ export async function handleNewsFeed(req: IncomingMessage, res: ServerResponse,
json(res, 400, { error: "bad_request" });
}
const NEWS_TICKER = process.env.NEWS_TICKER !== "0";
const NEWS_TICKER_CENTRAL = process.env.NEWS_TICKER_CENTRAL !== "0";
const LOCAL_ITEMS: 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: "" }));
// 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, NEWS_TICKER ? { enabled: true, central: NEWS_TICKER_CENTRAL, items: LOCAL_ITEMS } : { enabled: false });
json(
res,
200,
process.env.NEWS_TICKER !== "0"
? { enabled: true, central: process.env.NEWS_TICKER_CENTRAL !== "0", items: localItems() }
: { enabled: false },
);
}
+3 -5
View File
@@ -4,8 +4,8 @@
// row per instance id: version, first and last seen. No IP addresses, no
// 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 { readFile } from "node:fs/promises";
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
import { isAdminRequest } from "./store.js";
const PING_DATA_FILE = process.env.PING_DATA_FILE;
@@ -36,9 +36,7 @@ async function save(instances: Record<string, Instance>) {
// Instances silent for 90 days are gone for good.
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!);
await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
}
function json(res: ServerResponse, status: number, body: unknown) {
+23 -22
View File
@@ -11,13 +11,12 @@
// 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 { readFile } from "node:fs/promises";
import { timingSafeEqual, randomUUID } from "node:crypto";
import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js";
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
const STORE_ENABLED = process.env.STORE_ENABLED === "1";
const STORE_ALLOWED_ORIGIN = process.env.STORE_ALLOWED_ORIGIN ?? "*";
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
@@ -36,24 +35,24 @@ const STORE_SCREENSHOT_RE = /^data:image\/(png|jpe?g|webp);base64,[A-Za-z0-9+/]+
// 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", "greenteaspeak", "pulse", "ide"]);
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 STORE_RESERVED_AUTHORS = new Set(
const storeReservedAuthors = () => new Set(
(process.env.STORE_RESERVED_AUTHORS ?? "Möpchi,Moepchi")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
);
const STORE_ADMIN_TOKEN = process.env.STORE_ADMIN_TOKEN;
function isValidStoreAdminToken(provided: string): boolean {
if (!STORE_ADMIN_TOKEN) return false;
const token = process.env.STORE_ADMIN_TOKEN;
if (!token) return false;
const a = Buffer.from(provided);
const b = Buffer.from(STORE_ADMIN_TOKEN);
const b = Buffer.from(token);
return a.length === b.length && timingSafeEqual(a, b);
}
@@ -76,9 +75,10 @@ interface StoreTheme {
// Undo what a plain pattern check would miss: comments splitting a keyword
// (u/**/rl), CSS escapes (\75 rl( is url(), and case.
function normalizeCss(css: string): string {
return css
.replace(/\/\*[\s\S]*?\*\//g, "")
// 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";
@@ -95,7 +95,7 @@ const FORBIDDEN_CSS = [
/@import/,
/@font-face/,
/@namespace/,
/(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
/(?:^|[^a-z])(?:-[a-z]+-)?(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
/-moz-binding/,
/behavior\s*:/,
/javascript:/,
@@ -103,7 +103,10 @@ const FORBIDDEN_CSS = [
];
export function isSafeThemeCss(css: string): boolean {
const normalized = normalizeCss(css);
return isSafeNormalized(normalizeCss(css, true)) && isSafeNormalized(normalizeCss(css, false));
}
function isSafeNormalized(normalized: string): boolean {
if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false;
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;
@@ -131,9 +134,7 @@ 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);
await writeFileAtomic(STORE_DATA_FILE, JSON.stringify(themes));
}
export function isAdminRequest(req: IncomingMessage): boolean {
@@ -165,7 +166,7 @@ const isStoreRateLimited = createRateLimiter(STORE_RATE_LIMIT, STORE_RATE_WINDOW
const storeRatingsSeen = new Set<string>();
function setStoreCors(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", STORE_ALLOWED_ORIGIN);
res.setHeader("Access-Control-Allow-Origin", storeAllowedOrigin());
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
@@ -346,7 +347,7 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
}
const isAdmin = isAdminRequest(req);
if (STORE_RESERVED_AUTHORS.has(author.toLowerCase())) {
if (storeReservedAuthors().has(author.toLowerCase())) {
if (!isAdmin) {
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "author_reserved" }));
@@ -373,8 +374,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
const themes = await loadStoreThemes();
// Re-uploading an installed store theme unchanged would just duplicate it.
const cssKey = normalizeCss(css).replace(/\s+/g, "");
if (themes.some((t) => normalizeCss(t.css).replace(/\s+/g, "") === cssKey)) {
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;
@@ -506,7 +507,7 @@ export async function handleStore(req: IncomingMessage, res: ServerResponse, pat
res.end();
return;
}
if (!STORE_ENABLED) {
if (process.env.STORE_ENABLED !== "1") {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
+3 -5
View File
@@ -8,9 +8,9 @@
// 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 { mkdir, readdir, readFile, rm } from "node:fs/promises";
import path from "node:path";
import { clientIp, createRateLimiter } from "./net.js";
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
@@ -76,9 +76,7 @@ async function load(id: string): Promise<Account | null> {
}
async function save(id: string, account: Account) {
const tmp = `${file(id)}.tmp`;
await writeFile(tmp, JSON.stringify(account), "utf-8");
await rename(tmp, file(id));
await writeFileAtomic(file(id), JSON.stringify(account));
}
// Writes to one account run one after another, so the version check can't race.
+9 -6
View File
@@ -33,12 +33,17 @@ async function instanceId(): Promise<string> {
return id;
}
async function ping(id: string) {
let id: Promise<string> | undefined;
async function ping() {
// Checked on every ping: the admin panel can switch it on/off live.
if (process.env.TELEMETRY === "0") return;
id ??= instanceId();
try {
await fetch(TELEMETRY_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, version: VERSION }),
body: JSON.stringify({ id: await id, version: VERSION }),
signal: AbortSignal.timeout(10_000),
});
} catch {
@@ -50,8 +55,6 @@ 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 instanceId().then((id) => {
void ping(id);
setInterval(() => void ping(id), DAY_MS).unref();
});
}
void ping();
setInterval(() => void ping(), DAY_MS).unref();
+6 -1
View File
@@ -213,7 +213,7 @@ export type Ts3ConnectionEvent =
/** TS6 Stream/Call signaling, forwarded verbatim; `args` is already unescaped. */
| { type: "streamEvent"; name: string; args: Record<string, string> };
export type ServerType = "teamspeak" | "teaspeak" | "auto";
export type ServerType = "teamspeak" | "teaspeak" | "auto" | "ts2";
export interface Ts3ConnectOptions {
host: string;
@@ -228,6 +228,9 @@ export interface Ts3ConnectOptions {
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));
@@ -280,6 +283,8 @@ export class Ts3Connection {
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
+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 });
}
});
+20
View File
@@ -0,0 +1,20 @@
// Concurrent saves to one file used to share a .tmp path: all but one rename
// failed with ENOENT (seen live from a parallel /api/ping probe).
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { writeFileAtomic } from "../dist/net.js";
test("parallel writes to one file all succeed, last one wins", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-atomic-"));
try {
const file = path.join(dir, "data.json");
await Promise.all(Array.from({ length: 50 }, (_, i) => writeFileAtomic(file, JSON.stringify({ i, pad: "x".repeat(i * 500) }))));
assert.equal(JSON.parse(readFileSync(file, "utf-8")).i, 49);
assert.deepEqual(readdirSync(dir), ["data.json"]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+21
View File
@@ -0,0 +1,21 @@
// Theme CSS from the Design Store must never load anything external.
import { test } from "node:test";
import assert from "node:assert/strict";
import { isSafeThemeCss } from "../dist/store.js";
test("theme CSS filter", () => {
const evil = "url(https://attacker.example/t.png)";
for (const css of [
`body{background:${evil}}`,
`body{background:\\75rl(https://attacker.example/t.png)}`,
`body{background:image-set("https://attacker.example/t.png" 1x)}`,
`a{content:"/*"}body{background:${evil}}b{content:"*/"}`,
`a{--x:\\/*}body{background:${evil}}b{--y:*/}`,
`body{background:-webkit-image-set("https://attacker.example/t.png" 1x)}`,
]) assert.equal(isSafeThemeCss(css), false, css);
for (const css of [
":root{--bg:#123}body{color:red}a:hover{opacity:.5}",
"body{background:url(data:image/png;base64,AAAA)}",
"/* a comment */ body{color:red}",
]) assert.equal(isSafeThemeCss(css), true, css);
});
+96
View File
@@ -0,0 +1,96 @@
// Connect/close races on one WebSocket must not leave connector processes
// behind. Uses a fake connector that records its PID and lives until its
// stdin closes (like the real one), against the built gateway.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
const INDEX = path.resolve(import.meta.dirname, "../dist/index.js");
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
const freePort = () => new Promise((ok) => {
const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); });
});
test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-orphans-"));
const pids = path.join(dir, "pids");
const fake = path.join(dir, "fake-connector.sh");
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\nsleep 1\n`);
chmodSync(fake, 0o755);
const port = await freePort();
const gw = spawn(process.execPath, [INDEX], {
cwd: dir,
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake },
stdio: "ignore",
});
const recorded = () => (existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).map(Number) : []);
try {
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
const connect = JSON.stringify({ type: "connect", host: "example.invalid", nickname: "dummy" });
const open = async () => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
return ws;
};
// connect, connect while the first connector shuts down, close
let ws = await open();
ws.send(connect); await wait(300);
ws.send(connect); await wait(100);
ws.close();
// connect, then two connects back to back, close later
ws = await open();
ws.send(connect); await wait(300);
ws.send(connect); ws.send(connect);
await wait(4000);
ws.close();
await wait(4000);
assert.ok(recorded().length >= 2, "fake connector was spawned");
assert.deepEqual(recorded().filter(alive), [], "connector processes left behind");
} finally {
for (const pid of recorded()) if (alive(pid)) process.kill(pid, "SIGKILL");
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
rmSync(dir, { recursive: true, force: true });
}
});
test("ALLOWED_SERVERS can't be bypassed with a bracketed prefix", { timeout: 30_000 }, async () => {
const dir = mkdtempSync(path.join(tmpdir(), "ws3-allow-"));
const pids = path.join(dir, "pids");
const fake = path.join(dir, "fake-connector.sh");
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\n`);
chmodSync(fake, 0o755);
const port = await freePort();
const gw = spawn(process.execPath, [INDEX], {
cwd: dir,
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake, ALLOWED_SERVERS: "ts.example.com" },
stdio: "ignore",
});
try {
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
const reply = async (host) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
const msgs = [];
ws.onmessage = (e) => msgs.push(JSON.parse(e.data));
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
ws.send(JSON.stringify({ type: "connect", host, nickname: "dummy" }));
await wait(500);
ws.close();
return msgs.find((m) => m.type === "error")?.message ?? "";
};
for (const host of ["[ts.example.com]evil.tld", "[ts.example.com]evil.tld:9987", "evil.tld"]) {
assert.match(await reply(host), /not allowed/, host);
}
assert.doesNotMatch(await reply("ts.example.com:9987"), /not allowed/);
assert.equal(existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).length : 0, 1, "only the allowed host spawned a connector");
} finally {
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
rmSync(dir, { recursive: true, force: true });
}
});
+1048 -13
View File
File diff suppressed because it is too large. Load diff
+521 -111
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>
);
}
Binary file not shown.
+6 -3
View File
@@ -5,8 +5,9 @@ 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";
export type Lang = "de" | "en" | "zh-CN" | "fa" | "cs-CZ" | "ru";
const RTL_LANGS = new Set<Lang>(["fa"]);
export type LangPref = "auto" | Lang;
@@ -16,7 +17,7 @@ const LANGUAGE_KEY = "webspeak3:language";
// 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 like Weblate can read/write these files
// TS objects) so translation tools can read/write these files
// directly.
const translations: Record<Lang, Record<string, string>> = {
de,
@@ -24,6 +25,7 @@ const translations: Record<Lang, Record<string, string>> = {
"zh-CN": zhCN,
fa,
"cs-CZ": csCZ,
ru,
};
function detectSystemLang(): Lang {
@@ -32,6 +34,7 @@ function detectSystemLang(): Lang {
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";
}
@@ -41,7 +44,7 @@ export function resolveLang(pref: LangPref): Lang {
export function loadLangPref(): LangPref {
const raw = localStorage.getItem(LANGUAGE_KEY);
return raw === "de" || raw === "en" || raw === "zh-CN" || raw === "fa" || raw === "cs-CZ" || raw === "auto" ? raw : "auto";
return raw === "de" || raw === "en" || raw === "zh-CN" || raw === "fa" || raw === "cs-CZ" || raw === "ru" || raw === "auto" ? raw : "auto";
}
export function saveLangPref(pref: LangPref) {
+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;
}
}
+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;
}
+26 -8
View File
@@ -19,7 +19,7 @@
"menu.help.about": "O WebSpeak3",
"menu.help.github": "GitHub",
"menu.help.changelog": "Seznam změn",
"menu.help.translate": "Pomozte s překladem (Weblate)",
"menu.help.translate": "Pomozte s překladem (GitHub)",
"menu.extras.identities": "Identity",
"menu.extras.contacts": "Kontakty",
"menu.extras.collectedUrls": "Shromážděné URL",
@@ -70,7 +70,7 @@
"restartNotice.ack": "Rozumím",
"menu.extras.tos": "Podmínky používání",
"tos.title": "Podmínky používání pro client.webspeak3.de",
"tos.rule1": "This client is for private, non-commercial use of TeamSpeak/TeaSpeak/GreenTeaSpeak servers via browser.",
"tos.rule1": "This client is for private, non-commercial use of TeamSpeak/TeaSpeak/VoySpeak servers via browser.",
"tos.rule2": "Prohibited in particular: any criminal activity, harassment and hate speech, spam and flooding, disrupting service, and circumventing bans.",
"tos.rule3": "Violations may result in access being blocked without warning; serious cases may be reported to relevant authorities.",
"tos.rule4Pre": "For operational security and abuse detection, connections are logged (server address, server name, timestamp) and automatically deleted after 90 days – see",
@@ -112,6 +112,7 @@
"connect.title": "Připojit",
"connect.novaSubtitle": "WebSpeak3 běží celý v prohlížeči — není potřeba nic stahovat",
"connect.serverAddress": "Přezdívka nebo adresa serveru:",
"connect.hostPlaceholder": "např. ts.example.com:9987",
"connect.serverPassword": "Heslo serveru:",
"connect.nickname": "Přezdívka:",
"connect.phoneticNickname": "Fonetická přezdívka:",
@@ -125,6 +126,9 @@
"connect.serverType.auto": "Automaticky",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.serverType.ts2": "TeamSpeak 2 (experimentální)",
"connect.ts2LoginName": "Název účtu TS2 (prázdné = anonymně):",
"connect.ts2LoginPassword": "Heslo účtu TS2:",
"connect.hotkeyProfile": "Profil klávesových zkratek:",
"connect.soundPack": "Balíček zvuků:",
"connect.more": "Více",
@@ -298,8 +302,6 @@
"design.theme.standard.desc": "Původní vzhled WebSpeak3.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "Modernější tmavý vzhled se zaoblenými prvky.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "Klasické rozvržení klienta GreenTeaSpeak s tmavými panely a zlatou lištou nabídky.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "Rozvržení založené na kartách s navigační lištou a barevným zvýrazněním.",
"design.theme.ide": "Command Center",
@@ -409,7 +411,8 @@
"app.language.zh-CN": "简体中文",
"app.language.fa": "فارسی (بتا)",
"app.language.cs-CZ": "Čeština",
"app.language.helpTranslate": "Missing your language or spotted wrong translation? Help out on Weblate →",
"app.language.ru": "Русский (бета)",
"app.language.helpTranslate": "Chybí váš jazyk nebo jste našli chybu v překladu? Takto můžete pomoct →",
"app.serverBanner": "Zobrazovat bannery serveru",
"app.serverBanner.hint": "Banner se načítá přímo z adresy nastavené administrátorem serveru a tento hostitel vidí vaši IP adresu.",
"app.chatImages": "Načítat obrázky v chatu",
@@ -474,6 +477,8 @@
"tree.search": "Hledat kanály a uživatele",
"tree.label": "Kanály",
"tree.notConnected": "Nepřipojeno",
"tree.connectingTo": "Připojování k {host}…",
"tree.tryDemo": "Nemáte server? Vyzkoušejte demo",
"tree.clickToSelect": "Kliknutím vyberete, dvojklikem se připojíte",
"tree.clickToJoin": "Dvojklikem se připojíte",
"tree.joinNotConnected": "Nepřipojeno — nelze přepnout kanál",
@@ -491,10 +496,13 @@
"publish.alphaTitle": "Alfa – nestabilní, může se kdykoli změnit nebo přestat fungovat",
"publish.demoUnavailable": "Streamování není v demu dostupné – vyžaduje skutečný server TeamSpeak 6.",
"publish.alphaNote": "Streamování je ve fázi alfa. Používá nezdokumentovaný protokol Stream/Call služby TeamSpeak 6, takže připojení, kvalita obrazu i práce s diváky mohou selhat nebo se bez upozornění změnit. Není určeno pro produkční použití.",
"publish.start": "Sdílet obrazovku",
"publish.start": "Sdílet obrazovku nebo kameru",
"publish.stop": "Zastavit sdílení",
"publish.title": "Vaše vysílání",
"publish.screen": "Obrazovka",
"publish.camera": "Kamera",
"publish.kind": "Sdílet",
"publish.kind.display": "Obrazovka / okno",
"publish.starting": "Spouštění…",
"publish.viewers": "Sleduje {count} diváků",
"publish.request.allow": "Povolit",
@@ -509,6 +517,7 @@
"publish.preset": "Předvolba",
"publish.preset.presentation": "Prezentace",
"publish.audio": "Snímat zvuk",
"publish.audio.cameraHint": "U kamery jde tvůj zvuk jako obvykle přes mikrofon.",
"publish.privacy": "Soukromí",
"publish.privacy.public": "Veřejné",
"publish.privacy.contacts": "Kontakty",
@@ -711,6 +720,8 @@
"serverContext.addFavorite": "Přidat do oblíbených",
"serverContext.disconnect": "Odpojit",
"connectError.dismiss": "Zavřít",
"connectError.gatewayFull": "Brána je právě plná. Zkus to za pár minut znovu – nebo si WebSpeak3 hostuj sám: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Kontrola proti botům selhala. Obnov stránku a zkus to znovu. Blokátory reklam nebo skriptů mohou kontrole bránit.",
"dialog.close": "Zavřít",
"sounds.title": "Zvuky",
"sounds.subtitle": "Nastavit zvuková upozornění na události",
@@ -931,7 +942,7 @@
"securitySettings.masterNew": "Nové hlavní heslo",
"securitySettings.masterRepeat": "Zopakovat",
"securitySettings.masterMismatch": "Hesla se neshodují.",
"securitySettings.masterNote": "Dobře si ho zapamatujte: bez něj přijdete o identity a uložená hesla.",
"securitySettings.masterNote": "Budete ho muset zadat znovu v každé nové relaci (po obnovení stránky nebo v nové kartě). Dobře si ho zapamatujte: bez něj přijdete o identity a uložená hesla.",
"sync.subtitle": "Tvá data na všech zařízeních",
"sync.intro": "Účet je jen náhodné číslo, volitelně s heslem. Žádný e-mail, žádné jméno. Vše se před nahráním zašifruje na tvém zařízení. Server vidí jen nečitelná data.",
"sync.create.title": "Nový účet",
@@ -995,5 +1006,12 @@
"sync.error.pow_required": "Bezpečnostní kontrola selhala, zkus to znovu.",
"sync.error.conflict": "Jiné zařízení mezitím něco změnilo.",
"sync.error.payload_too_large": "Příliš mnoho dat pro synchronizaci (max. 1 MB).",
"sync.error.generic": "Synchronizace selhala."
"sync.error.generic": "Synchronizace selhala.",
"mobile.tab.channels": "Kanály",
"mobile.tab.chat": "Chat",
"mobile.tab.info": "Info",
"mobile.mic": "Mikrofon",
"mobile.sound": "Zvuk",
"mobile.leave": "Odpojit",
"mobile.talk": "Mluvit"
}
+26 -8
View File
@@ -19,7 +19,7 @@
"menu.help.about": "Über WebSpeak3",
"menu.help.github": "GitHub",
"menu.help.changelog": "Changelog",
"menu.help.translate": "Mitübersetzen (Weblate)",
"menu.help.translate": "Mitübersetzen (GitHub)",
"menu.extras.identities": "Identitäten",
"menu.extras.contacts": "Kontakte",
"menu.extras.collectedUrls": "Gesammelte URLs",
@@ -71,7 +71,7 @@
"restartNotice.ack": "Verstanden",
"menu.extras.tos": "Nutzungsbedingungen",
"tos.title": "Nutzungsbedingungen für client.webspeak3.de",
"tos.rule1": "Dieser Client dient der privaten, nicht-kommerziellen Nutzung von TeamSpeak-/TeaSpeak-/GreenTeaSpeak-Servern über den Browser.",
"tos.rule1": "Dieser Client dient der privaten, nicht-kommerziellen Nutzung von TeamSpeak-/TeaSpeak-/VoySpeak-Servern über den Browser.",
"tos.rule2": "Verboten sind insbesondere: Straftaten jeder Art, Belästigung und Hassrede, Spam und Flooding, Störung des Dienstes sowie die Umgehung von Sperren.",
"tos.rule3": "Bei Verstößen kann der Zugang ohne Vorwarnung gesperrt werden; schwerwiegende Fälle werden ggf. an die zuständigen Behörden gemeldet.",
"tos.rule4Pre": "Zur Betriebssicherheit und Missbrauchserkennung werden Verbindungen protokolliert (Serveradresse, Servername, Zeitpunkt) und nach 90 Tagen automatisch gelöscht – siehe ",
@@ -112,6 +112,7 @@
"connect.title": "Verbinden",
"connect.novaSubtitle": "WebSpeak3 läuft komplett im Browser — kein Download nötig",
"connect.serverAddress": "Server Nickname oder Adresse:",
"connect.hostPlaceholder": "z. B. ts.beispiel.de:9987",
"connect.serverPassword": "Server Passwort:",
"connect.nickname": "Nickname:",
"connect.phoneticNickname": "Phonetischer Nickname:",
@@ -125,6 +126,9 @@
"connect.serverType.auto": "Auto",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.serverType.ts2": "TeamSpeak 2 (experimentell)",
"connect.ts2LoginName": "TS2-Kontoname (leer = anonym):",
"connect.ts2LoginPassword": "TS2-Kontopasswort:",
"connect.hotkeyProfile": "Hotkeyprofil:",
"connect.soundPack": "Sound Pack:",
"connect.more": "Mehr",
@@ -298,8 +302,6 @@
"design.theme.standard.desc": "Das originale WebSpeak3-Design.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "Moderneres, dunkles Design mit abgerundeten Elementen.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "Klassisches GreenTeaSpeak-Client-Layout mit dunklen Panels und goldener Menüleiste.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "Karten-Layout mit Breadcrumb-Leiste und farbigem Akzent.",
"design.theme.ide": "Command Center",
@@ -409,7 +411,8 @@
"app.language.zh-CN": "简体中文",
"app.language.fa": "فارسی (بتا)",
"app.language.cs-CZ": "Čeština",
"app.language.helpTranslate": "Fehlt deine Sprache oder eine Übersetzung ist ungenau? Hilf mit auf Weblate →",
"app.language.ru": "Русский (бета)",
"app.language.helpTranslate": "Fehlt deine Sprache oder eine Übersetzung ist ungenau? So hilfst du mit →",
"app.serverBanner": "Server-Banner anzeigen",
"app.serverBanner.hint": "Das Banner lädt direkt von der Adresse, die der Serverbetreiber eingetragen hat. Dieser Host sieht dabei deine IP-Adresse.",
"app.chatImages": "Bilder im Chat laden",
@@ -474,6 +477,8 @@
"tree.search": "Kanäle und Nutzer suchen",
"tree.label": "Kanäle",
"tree.notConnected": "Nicht verbunden",
"tree.connectingTo": "Verbinde mit {host}…",
"tree.tryDemo": "Kein Server? Probier die Demo",
"tree.clickToSelect": "Klicken zum Auswählen, Doppelklick zum Beitreten",
"tree.clickToJoin": "Doppelklick zum Beitreten",
"tree.joinNotConnected": "Nicht verbunden — Channel-Wechsel nicht möglich",
@@ -491,10 +496,13 @@
"publish.alphaTitle": "Alpha – instabil, kann sich jederzeit ändern oder brechen",
"publish.demoUnavailable": "Übertragen ist in der Demo nicht verfügbar – dafür braucht es einen echten TeamSpeak-6-Server.",
"publish.alphaNote": "Streaming ist Alpha. Es spricht TeamSpeak 6s Stream/Call-Protokoll, das nicht dokumentiert ist – Verbindungsaufbau, Bildqualität und Zuschauerverwaltung können fehlschlagen oder sich ohne Vorankündigung ändern. Nicht für produktive Nutzung gedacht.",
"publish.start": "Bildschirm übertragen",
"publish.start": "Bildschirm oder Kamera übertragen",
"publish.stop": "Übertragung beenden",
"publish.title": "Deine Übertragung",
"publish.screen": "Bildschirm",
"publish.camera": "Kamera",
"publish.kind": "Übertragen",
"publish.kind.display": "Bildschirm / Fenster",
"publish.starting": "Wird gestartet…",
"publish.viewers": "{count} Zuschauer",
"publish.request.allow": "Zulassen",
@@ -509,6 +517,7 @@
"publish.preset": "Voreinstellung",
"publish.preset.presentation": "Präsentation",
"publish.audio": "Audio aufnehmen",
"publish.audio.cameraHint": "Bei der Kamera läuft dein Ton wie gewohnt übers Mikrofon.",
"publish.privacy": "Privatsphäre",
"publish.privacy.public": "Öffentlich",
"publish.privacy.contacts": "Kontakte",
@@ -711,6 +720,8 @@
"serverContext.addFavorite": "Zu Favoriten hinzufügen",
"serverContext.disconnect": "Verbindung trennen",
"connectError.dismiss": "Schließen",
"connectError.gatewayFull": "Das Gateway ist gerade voll. Versuch es in ein paar Minuten nochmal – oder hoste WebSpeak3 selbst: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Bot-Prüfung fehlgeschlagen. Bitte lade die Seite neu und versuch es noch mal. Werbe- oder Skriptblocker können die Prüfung stören.",
"dialog.close": "Schließen",
"sounds.title": "Sounds",
"sounds.subtitle": "Sound-Benachrichtigungen für Ereignisse festlegen",
@@ -931,7 +942,7 @@
"securitySettings.masterNew": "Neues Master Passwort",
"securitySettings.masterRepeat": "Wiederholen",
"securitySettings.masterMismatch": "Die Passwörter stimmen nicht überein.",
"securitySettings.masterNote": "Merk es dir gut: Ohne das Passwort sind Identitäten und gespeicherte Passwörter weg.",
"securitySettings.masterNote": "Du musst es bei jeder neuen Sitzung (Neuladen oder neuer Tab) wieder eingeben. Merk es dir gut: Ohne das Passwort sind Identitäten und gespeicherte Passwörter weg.",
"sync.subtitle": "Deine Daten auf allen Geräten",
"sync.intro": "Ein Konto besteht nur aus einer zufälligen Nummer, optional mit Passwort. Keine Mail, kein Name. Alles wird auf deinem Gerät verschlüsselt, bevor es hochgeladen wird. Der Server sieht nur unlesbare Daten.",
"sync.create.title": "Neues Konto",
@@ -995,5 +1006,12 @@
"sync.error.pow_required": "Sicherheitsprüfung fehlgeschlagen, bitte nochmal versuchen.",
"sync.error.conflict": "Ein anderes Gerät hat inzwischen etwas geändert.",
"sync.error.payload_too_large": "Zu viele Daten für die Synchronisierung (max. 1 MB).",
"sync.error.generic": "Synchronisierung fehlgeschlagen."
"sync.error.generic": "Synchronisierung fehlgeschlagen.",
"mobile.tab.channels": "Kanäle",
"mobile.tab.chat": "Chat",
"mobile.tab.info": "Info",
"mobile.mic": "Mikro",
"mobile.sound": "Ton",
"mobile.leave": "Trennen",
"mobile.talk": "Sprechen"
}
+26 -8
View File
@@ -19,7 +19,7 @@
"menu.help.about": "About WebSpeak3",
"menu.help.github": "GitHub",
"menu.help.changelog": "Changelog",
"menu.help.translate": "Help translate (Weblate)",
"menu.help.translate": "Help translate (GitHub)",
"menu.extras.identities": "Identities",
"menu.extras.contacts": "Contacts",
"menu.extras.collectedUrls": "Collected URLs",
@@ -70,7 +70,7 @@
"restartNotice.ack": "Got it",
"menu.extras.tos": "Terms of use",
"tos.title": "Terms of use for client.webspeak3.de",
"tos.rule1": "This client is for private, non-commercial use of TeamSpeak/TeaSpeak/GreenTeaSpeak servers via the browser.",
"tos.rule1": "This client is for private, non-commercial use of TeamSpeak/TeaSpeak/VoySpeak servers via the browser.",
"tos.rule2": "Prohibited in particular: any criminal activity, harassment and hate speech, spam and flooding, disrupting the service, and circumventing bans.",
"tos.rule3": "Violations may result in access being blocked without warning; serious cases may be reported to the relevant authorities.",
"tos.rule4Pre": "For operational security and abuse detection, connections are logged (server address, server name, timestamp) and automatically deleted after 90 days – see the ",
@@ -112,6 +112,7 @@
"connect.title": "Connect",
"connect.novaSubtitle": "WebSpeak3 runs entirely in the browser — no download needed",
"connect.serverAddress": "Server nickname or address:",
"connect.hostPlaceholder": "e.g. ts.example.com:9987",
"connect.serverPassword": "Server password:",
"connect.nickname": "Nickname:",
"connect.phoneticNickname": "Phonetic nickname:",
@@ -125,6 +126,9 @@
"connect.serverType.auto": "Auto",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.serverType.ts2": "TeamSpeak 2 (experimental)",
"connect.ts2LoginName": "TS2 account name (empty = anonymous):",
"connect.ts2LoginPassword": "TS2 account password:",
"connect.hotkeyProfile": "Hotkey profile:",
"connect.soundPack": "Sound pack:",
"connect.more": "More",
@@ -298,8 +302,6 @@
"design.theme.standard.desc": "The original WebSpeak3 design.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "A more modern, dark design with rounded elements.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "Classic GreenTeaSpeak client layout with dark panels and a gold menu bar.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "Card-based layout with a breadcrumb bar and a color accent.",
"design.theme.ide": "Command Center",
@@ -409,7 +411,8 @@
"app.language.zh-CN": "简体中文",
"app.language.fa": "فارسی (بتا)",
"app.language.cs-CZ": "Čeština",
"app.language.helpTranslate": "Missing your language or spotted a wrong translation? Help out on Weblate →",
"app.language.ru": "Русский (бета)",
"app.language.helpTranslate": "Missing your language or spotted a wrong translation? Here's how to help →",
"app.serverBanner": "Show server banners",
"app.serverBanner.hint": "The banner loads straight from the address the server admin set, and that host sees your IP address.",
"app.chatImages": "Load images in chat",
@@ -474,6 +477,8 @@
"tree.search": "Search channels and users",
"tree.label": "Channels",
"tree.notConnected": "Not connected",
"tree.connectingTo": "Connecting to {host}…",
"tree.tryDemo": "No server? Try the demo",
"tree.clickToSelect": "Click to select, double-click to join",
"tree.clickToJoin": "Double-click to join",
"tree.joinNotConnected": "Not connected — cannot switch channel",
@@ -491,10 +496,13 @@
"publish.alphaTitle": "Alpha - unstable, may change or break at any time",
"publish.demoUnavailable": "Streaming is not available in the demo - it needs a real TeamSpeak 6 server.",
"publish.alphaNote": "Streaming is alpha. It speaks TeamSpeak 6's undocumented Stream/Call protocol, so connecting, picture quality and viewer handling can fail or change without notice. Not meant for production use.",
"publish.start": "Share your screen",
"publish.start": "Share your screen or camera",
"publish.stop": "Stop sharing",
"publish.title": "Your broadcast",
"publish.screen": "Screen",
"publish.camera": "Camera",
"publish.kind": "Share",
"publish.kind.display": "Screen / window",
"publish.starting": "Starting…",
"publish.viewers": "{count} watching",
"publish.request.allow": "Allow",
@@ -509,6 +517,7 @@
"publish.preset": "Preset",
"publish.preset.presentation": "Presentation",
"publish.audio": "Capture audio",
"publish.audio.cameraHint": "With the camera, your sound goes out through your microphone as usual.",
"publish.privacy": "Privacy",
"publish.privacy.public": "Public",
"publish.privacy.contacts": "Contacts",
@@ -711,6 +720,8 @@
"serverContext.addFavorite": "Add to favorites",
"serverContext.disconnect": "Disconnect",
"connectError.dismiss": "Dismiss",
"connectError.gatewayFull": "The gateway is full right now. Try again in a few minutes – or host WebSpeak3 yourself: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Bot check failed. Please reload the page and try again. Ad or script blockers can get in the way of the check.",
"dialog.close": "Close",
"sounds.title": "Sounds",
"sounds.subtitle": "Configure sound notifications for events",
@@ -931,7 +942,7 @@
"securitySettings.masterNew": "New master password",
"securitySettings.masterRepeat": "Repeat",
"securitySettings.masterMismatch": "The passwords don't match.",
"securitySettings.masterNote": "Remember it well: without it, identities and saved passwords are lost.",
"securitySettings.masterNote": "You'll have to enter it again in every new session (reload or new tab). Remember it well: without it, identities and saved passwords are lost.",
"sync.subtitle": "Your data on all your devices",
"sync.intro": "An account is just a random number, optionally with a password. No email, no name. Everything is encrypted on your device before it is uploaded. The server only sees unreadable data.",
"sync.create.title": "New account",
@@ -995,5 +1006,12 @@
"sync.error.pow_required": "Security check failed, please try again.",
"sync.error.conflict": "Another device changed something in the meantime.",
"sync.error.payload_too_large": "Too much data to sync (max. 1 MB).",
"sync.error.generic": "Sync failed."
"sync.error.generic": "Sync failed.",
"mobile.tab.channels": "Channels",
"mobile.tab.chat": "Chat",
"mobile.tab.info": "Info",
"mobile.mic": "Mic",
"mobile.sound": "Sound",
"mobile.leave": "Leave",
"mobile.talk": "Talk"
}
+26 -8
View File
@@ -19,7 +19,7 @@
"menu.help.about": "درباره WebSpeak3",
"menu.help.github": "گیت‌هاب",
"menu.help.changelog": "تاریخچه تغییرات",
"menu.help.translate": "کمک به ترجمه (Weblate)",
"menu.help.translate": "کمک به ترجمه (GitHub)",
"menu.extras.identities": "هویت‌ها",
"menu.extras.contacts": "مخاطبین",
"menu.extras.collectedUrls": "لینک‌های جمع‌آوری‌شده",
@@ -70,7 +70,7 @@
"restartNotice.ack": "متوجه شدم",
"menu.extras.tos": "شرایط استفاده",
"tos.title": "شرایط استفاده از client.webspeak3.de",
"tos.rule1": "این کلاینت برای استفاده خصوصی و غیرتجاری از سرورهای TeamSpeak/TeaSpeak/GreenTeaSpeak از طریق مرورگر است.",
"tos.rule1": "این کلاینت برای استفاده خصوصی و غیرتجاری از سرورهای TeamSpeak/TeaSpeak/VoySpeak از طریق مرورگر است.",
"tos.rule2": "به‌طور خاص ممنوع است: هرگونه فعالیت مجرمانه، آزار و سخنان نفرت‌پراکنانه، اسپم و سیل پیام، ایجاد اختلال در سرویس، و دور زدن مسدودیت‌ها.",
"tos.rule3": "تخلفات ممکن است بدون هشدار منجر به مسدود شدن دسترسی شوند؛ در موارد جدی، گزارش به مراجع ذی‌صلاح نیز ممکن است.",
"tos.rule4Pre": "به‌منظور امنیت عملیاتی و شناسایی سوءاستفاده، اطلاعات اتصال (آدرس سرور، نام سرور، زمان اتصال) ثبت می‌شود و پس از ۹۰ روز به‌صورت خودکار حذف می‌شود - برای جزئیات به ",
@@ -112,6 +112,7 @@
"connect.title": "اتصال",
"connect.novaSubtitle": "WebSpeak3 به‌طور کامل در مرورگر اجرا می‌شود — بدون نیاز به دانلود",
"connect.serverAddress": "نام مستعار یا آدرس سرور:",
"connect.hostPlaceholder": "مثلاً ts.example.com:9987",
"connect.serverPassword": "رمز عبور سرور:",
"connect.nickname": "نام مستعار:",
"connect.phoneticNickname": "تلفظ نام مستعار:",
@@ -125,6 +126,9 @@
"connect.serverType.auto": "خودکار",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.serverType.ts2": "TeamSpeak 2 (آزمایشی)",
"connect.ts2LoginName": "نام حساب TS2 (خالی = ناشناس):",
"connect.ts2LoginPassword": "رمز حساب TS2:",
"connect.hotkeyProfile": "پروفایل کلید میانبر:",
"connect.soundPack": "بسته صوتی:",
"connect.more": "بیشتر",
@@ -298,8 +302,6 @@
"design.theme.standard.desc": "طراحی اصلی WebSpeak3.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "طراحی مدرن‌تر و تیره با عناصر گرد.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "چیدمان کلاسیک کلاینت GreenTeaSpeak با پنل‌های تیره و نوار منوی طلایی.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "چیدمان کارتی با نوار مسیر و رنگ تأکیدی.",
"design.theme.ide": "Command Center",
@@ -409,7 +411,8 @@
"app.language.zh-CN": "简体中文",
"app.language.fa": "فارسی (بتا)",
"app.language.cs-CZ": "Čeština",
"app.language.helpTranslate": "زبان شما موجود نیست یا ترجمه‌ای اشتباه دیدید؟ در Weblate کمک کنید →",
"app.language.ru": "Русский (бета)",
"app.language.helpTranslate": "زبان شما موجود نیست یا ترجمه‌ای اشتباه دیدید؟ روش کمک کردن →",
"app.serverBanner": "نمایش بنر سرور",
"app.serverBanner.hint": "بنر مستقیماً از نشانی‌ای بارگیری می‌شود که مدیر سرور تعیین کرده است و آن میزبان نشانی IP شما را می‌بیند.",
"app.chatImages": "بارگیری تصاویر در گفتگو",
@@ -473,6 +476,8 @@
"tree.search": "جستجوی کانال‌ها و کاربران",
"tree.label": "کانال‌ها",
"tree.notConnected": "متصل نیست",
"tree.connectingTo": "در حال اتصال به {host}…",
"tree.tryDemo": "سروری ندارید؟ دمو را امتحان کنید",
"tree.clickToSelect": "برای انتخاب کلیک کن، برای ورود دوبار کلیک کن",
"tree.clickToJoin": "برای ورود دوبار کلیک کن",
"tree.joinNotConnected": "متصل نیست — نمی‌توان کانال را تغییر داد",
@@ -490,10 +495,13 @@
"publish.alphaTitle": "آلفا - ناپایدار، ممکن است هر زمان تغییر کند یا از کار بیفتد",
"publish.demoUnavailable": "پخش زنده در حالت دمو در دسترس نیست - به یک سرور واقعی TeamSpeak 6 نیاز دارد.",
"publish.alphaNote": "پخش زنده در مرحله آلفا است. این ویژگی از پروتکل مستندنشده Stream/Call در TeamSpeak 6 استفاده می‌کند، بنابراین اتصال، کیفیت تصویر و مدیریت بینندگان ممکن است بدون اطلاع قبلی دچار خطا شوند یا تغییر کنند. برای استفاده تولیدی مناسب نیست.",
"publish.start": "اشتراک‌گذاری صفحه",
"publish.start": "اشتراک‌گذاری صفحه یا دوربین",
"publish.stop": "توقف اشتراک‌گذاری",
"publish.title": "پخش زنده تو",
"publish.screen": "صفحه نمایش",
"publish.camera": "دوربین",
"publish.kind": "اشتراک‌گذاری",
"publish.kind.display": "صفحه / پنجره",
"publish.starting": "در حال شروع…",
"publish.viewers": "{count} بیننده",
"publish.request.allow": "اجازه دادن",
@@ -508,6 +516,7 @@
"publish.preset": "پیش‌تنظیم",
"publish.preset.presentation": "ارائه",
"publish.audio": "ضبط صدا",
"publish.audio.cameraHint": "با دوربین، صدای شما مثل همیشه از طریق میکروفون ارسال می‌شود.",
"publish.privacy": "حریم خصوصی",
"publish.privacy.public": "عمومی",
"publish.privacy.contacts": "مخاطبین",
@@ -710,6 +719,8 @@
"serverContext.addFavorite": "افزودن به نشانک‌ها",
"serverContext.disconnect": "قطع اتصال",
"connectError.dismiss": "رد کردن",
"connectError.gatewayFull": "گیت‌وی در حال حاضر پر است. چند دقیقه دیگر دوباره امتحان کنید – یا WebSpeak3 را خودتان میزبانی کنید: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "بررسی ضد ربات ناموفق بود. لطفاً صفحه را دوباره بارگذاری کنید و دوباره امتحان کنید. مسدودکننده‌های تبلیغات یا اسکریپت ممکن است مانع بررسی شوند.",
"dialog.close": "بستن",
"sounds.title": "صداها",
"sounds.subtitle": "پیکربندی اعلان‌های صوتی برای رویدادها",
@@ -930,7 +941,7 @@
"securitySettings.masterNew": "رمز اصلی جدید",
"securitySettings.masterRepeat": "تکرار",
"securitySettings.masterMismatch": "رمزها یکسان نیستند.",
"securitySettings.masterNote": "آن را به خاطر بسپارید: بدون آن، هویت‌ها و رمزهای ذخیره‌شده از دست می‌روند.",
"securitySettings.masterNote": "باید آن را در هر جلسهٔ جدید (بارگذاری دوباره یا زبانهٔ جدید) دوباره وارد کنید. آن را به خاطر بسپارید: بدون آن، هویت‌ها و رمزهای ذخیره‌شده از دست می‌روند.",
"sync.subtitle": "داده‌های تو روی همه دستگاه‌ها",
"sync.intro": "حساب فقط یک شماره تصادفی است، در صورت تمایل با رمز عبور. بدون ایمیل، بدون نام. همه چیز پیش از بارگذاری روی دستگاه تو رمزگذاری می‌شود. سرور فقط داده‌های ناخوانا می‌بیند.",
"sync.create.title": "حساب جدید",
@@ -994,5 +1005,12 @@
"sync.error.pow_required": "بررسی امنیتی ناموفق بود، دوباره امتحان کن.",
"sync.error.conflict": "دستگاه دیگری در این فاصله چیزی را تغییر داده است.",
"sync.error.payload_too_large": "داده برای همگام‌سازی بیش از حد است (حداکثر ۱ مگابایت).",
"sync.error.generic": "همگام‌سازی ناموفق بود."
"sync.error.generic": "همگام‌سازی ناموفق بود.",
"mobile.tab.channels": "کانال‌ها",
"mobile.tab.chat": "گفتگو",
"mobile.tab.info": "اطلاعات",
"mobile.mic": "میکروفون",
"mobile.sound": "صدا",
"mobile.leave": "خروج",
"mobile.talk": "صحبت"
}
File diff suppressed because it is too large. Load diff
+26 -8
View File
@@ -56,6 +56,7 @@
"away.setGlobalStatus": "设置全局离开状态",
"connect.title": "连接",
"connect.serverAddress": "服务器昵称或地址:",
"connect.hostPlaceholder": "例如 ts.example.com:9987",
"connect.serverPassword": "服务器密码:",
"connect.nickname": "昵称:",
"connect.phoneticNickname": "昵称读音:",
@@ -69,6 +70,9 @@
"connect.serverType.auto": "自动",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.serverType.ts2": "TeamSpeak 2(实验性)",
"connect.ts2LoginName": "TS2 账户名(留空 = 匿名):",
"connect.ts2LoginPassword": "TS2 账户密码:",
"connect.hotkeyProfile": "快捷键配置:",
"connect.soundPack": "声音包:",
"connect.more": "更多",
@@ -237,8 +241,6 @@
"design.theme.standard.desc": "原始 WebSpeak3 设计。",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "更现代的深色设计,带圆角元素。",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "经典 GreenTeaSpeak 客户端布局:深色面板与金色菜单栏。",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "卡片式布局,带面包屑栏和彩色强调。",
"design.theme.ide": "Command Center",
@@ -303,7 +305,8 @@
"app.language.zh-CN": "简体中文",
"app.language.fa": "فارسی (بتا)",
"app.language.cs-CZ": "Čeština",
"app.language.helpTranslate": "没有你的语言,或发现翻译有误?欢迎到 Weblate 参与改进 →",
"app.language.ru": "Русский (бета)",
"app.language.helpTranslate": "没有你的语言,或发现翻译有误?了解如何参与 →",
"app.serverBanner": "显示服务器横幅",
"app.serverBanner.hint": "横幅直接从服务器管理员设置的地址加载,该主机会看到你的 IP 地址。",
"app.chatImages": "在聊天中加载图片",
@@ -366,6 +369,8 @@
"tree.search": "搜索频道和用户",
"tree.label": "频道",
"tree.notConnected": "未连接",
"tree.connectingTo": "正在连接到 {host}…",
"tree.tryDemo": "没有服务器?试试演示版",
"tree.clickToSelect": "单击选择,双击加入",
"tree.clickToJoin": "双击加入",
"tree.joinNotConnected": "未连接 — 无法切换频道",
@@ -556,6 +561,8 @@
"serverContext.addFavorite": "添加到收藏夹",
"serverContext.disconnect": "断开连接",
"connectError.dismiss": "关闭",
"connectError.gatewayFull": "网关当前已满。请几分钟后再试,或自行部署 WebSpeak3:github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "人机验证失败。请刷新页面后重试。广告或脚本拦截器可能会干扰验证。",
"dialog.close": "关闭",
"sounds.title": "声音",
"sounds.subtitle": "配置事件提示音",
@@ -593,7 +600,7 @@
"menu.help.about": "关于 WebSpeak3",
"menu.help.github": "GitHub",
"menu.help.changelog": "更新日志",
"menu.help.translate": "参与翻译(Weblate)",
"menu.help.translate": "参与翻译(GitHub)",
"menu.extras.feedback": "发送反馈",
"feedback.fab.nudge": "你觉得 WebSpeak3 怎么样?欢迎反馈!",
"donate.label": "捐助",
@@ -633,7 +640,7 @@
"restartNotice.ack": "知道了",
"menu.extras.tos": "使用条款",
"tos.title": "client.webspeak3.de 使用条款",
"tos.rule1": "本客户端仅供通过浏览器私人、非商业使用 TeamSpeak / TeaSpeak / GreenTeaSpeak 服务器。",
"tos.rule1": "本客户端仅供通过浏览器私人、非商业使用 TeamSpeak / TeaSpeak / VoySpeak 服务器。",
"tos.rule2": "尤其禁止:任何违法行为、骚扰与仇恨言论、垃圾信息与刷屏、干扰服务运行,以及规避封禁。",
"tos.rule3": "违规可能导致访问权限被无预警封禁;严重情况可能会上报相关部门。",
"tos.rule4Pre": "出于运行安全和滥用检测的目的,连接信息(服务器地址、服务器名称、连接时间)会被记录,并在 90 天后自动删除 —— 详见",
@@ -702,10 +709,13 @@
"publish.alphaTitle": "内测阶段 —— 不稳定,可能随时变更或失效",
"publish.demoUnavailable": "演示模式下无法使用直播功能 —— 需要真实的 TeamSpeak 6 服务器。",
"publish.alphaNote": "直播功能处于内测阶段,使用的是 TeamSpeak 6 未公开文档的 Stream/Call 协议,因此连接、画质和观众处理可能会出错或在无预警的情况下发生变化,不建议用于正式场合。",
"publish.start": "共享屏幕",
"publish.start": "共享屏幕或摄像头",
"publish.stop": "停止共享",
"publish.title": "你的直播",
"publish.screen": "屏幕",
"publish.camera": "摄像头",
"publish.kind": "共享内容",
"publish.kind.display": "屏幕 / 窗口",
"publish.starting": "启动中…",
"publish.viewers": "{count} 人观看",
"publish.request.allow": "允许",
@@ -720,6 +730,7 @@
"publish.preset": "预设",
"publish.preset.presentation": "演示",
"publish.audio": "采集音频",
"publish.audio.cameraHint": "使用摄像头时,你的声音照常通过麦克风发送。",
"publish.privacy": "可见范围",
"publish.privacy.public": "公开",
"publish.privacy.contacts": "联系人",
@@ -930,7 +941,7 @@
"securitySettings.masterNew": "新主密码",
"securitySettings.masterRepeat": "重复",
"securitySettings.masterMismatch": "两次密码不一致。",
"securitySettings.masterNote": "请牢记:没有它,身份和已保存的密码将丢失。",
"securitySettings.masterNote": "每次新会话(重新加载或新标签页)都需要重新输入。请牢记:没有它,身份和已保存的密码将丢失。",
"sync.subtitle": "在所有设备上使用你的数据",
"sync.intro": "账户只是一个随机号码,可选附加密码。无需邮箱,无需姓名。所有数据在上传前都会在你的设备上加密,服务器只能看到无法读取的数据。",
"sync.create.title": "新账户",
@@ -994,5 +1005,12 @@
"sync.error.pow_required": "安全检查失败,请重试。",
"sync.error.conflict": "另一台设备在此期间做了更改。",
"sync.error.payload_too_large": "同步数据过多(最多 1 MB)。",
"sync.error.generic": "同步失败。"
"sync.error.generic": "同步失败。",
"mobile.tab.channels": "频道",
"mobile.tab.chat": "聊天",
"mobile.tab.info": "信息",
"mobile.mic": "麦克风",
"mobile.sound": "声音",
"mobile.leave": "断开",
"mobile.talk": "说话"
}
-1
View File
@@ -2,7 +2,6 @@ import './storageFallback'
import { StrictMode, useState, type FormEvent, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './styles/greenteaspeak.css'
import './App.css'
import { LanguageProvider, useT } from './i18n'
import { discardVault, hasVault, unlockVault } from './vault'
+15 -9
View File
@@ -46,6 +46,8 @@ export const StreamMode = {
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. */
@@ -112,15 +114,16 @@ export class StreamPublisher {
}
/**
* Captures a screen and announces the stream.
* Captures a screen or the webcam and announces the stream.
*
* `getDisplayMedia` is secure-context-only, so this throws on a plain-http
* 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;
if (!navigator.mediaDevices?.getDisplayMedia) {
this.fail("Screen sharing requires HTTPS (or localhost) - the site is not a secure context.");
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;
}
@@ -132,13 +135,15 @@ export class StreamPublisher {
if (options.fps > 0) video.frameRate = { ideal: options.fps };
try {
this.media = await navigator.mediaDevices.getDisplayMedia({
video: Object.keys(video).length > 0 ? video : true,
audio: options.audio,
});
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 screen: ${describe(err)}`);
this.fail(`Could not capture the ${camera ? "camera" : "screen"}: ${describe(err)}`);
return;
}
@@ -423,6 +428,7 @@ export class StreamPublisher {
* 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;
}
File diff suppressed because it is too large. Load diff
@@ -1,98 +0,0 @@
import type { ReactNode } from "react";
import { useT } from "../../i18n";
export type ConnectionTabItem = {
id: string;
label: string;
connected?: boolean;
connecting?: boolean;
};
export type GreenteaSpeakChromeProps = {
/** @deprecated Prefer `tabs` + `activeTabId` for multi-join. */
connected?: boolean;
/** @deprecated Prefer `tabs`. */
serverName?: string;
tabs?: ConnectionTabItem[];
activeTabId?: string | null;
onSelectTab?: (id: string) => void;
onCloseTab?: (id: string) => void;
children?: ReactNode;
};
/**
* GTS branding chrome: connection-tab strip (multi-join) + brand label when empty.
* Renders children unchanged — WebSpeak keeps its own React state/handlers.
*/
export function GreenteaSpeakChrome({
connected,
serverName,
tabs,
activeTabId,
onSelectTab,
onCloseTab,
children,
}: GreenteaSpeakChromeProps) {
const resolvedTabs: ConnectionTabItem[] =
tabs ??
(connected
? [{ id: "legacy", label: (serverName ?? "").trim() || "GreenTeaSpeak", connected: true }]
: []);
const hasTabs = resolvedTabs.length > 0;
const t = useT();
return (
<>
{hasTabs ? (
<div className="gts-connection-tabs" role="tablist" aria-label={t("tabs.connections")}>
{resolvedTabs.map((tab) => {
const isActive = tab.id === (activeTabId ?? resolvedTabs[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>
) : (
<div className="gts-connection-tabs gts-brand-strip">
<span className="gts-brand-label">GreenTeaSpeak</span>
</div>
)}
{children}
</>
);
}
@@ -1,56 +0,0 @@
/**
* Maps WebSpeak gateway WebSocket payloads to the shape the GreenTeaSpeak
* shell expects. The browser UI still uses App.tsx state; this module is the
* contract layer so GTS chrome never talks to Electron IPC.
*/
export type GatewayServerType = "auto" | "teamspeak" | "teaspeak";
export type GatewayConnectPayload = {
type: "connect";
host: string;
nickname: string;
serverPassword?: string;
channelPassword?: string;
defaultChannel?: string;
identity?: string;
privilegeKey?: string;
serverType?: GatewayServerType;
};
export type GatewayOutboundAction =
| GatewayConnectPayload
| { type: "disconnect" }
| { type: "switchChannel"; channelId: number }
| { type: "sendChat"; message: string; target?: "channel" | "server" | number }
| { type: string; [key: string]: unknown };
/** Build the connect message sent on the WebSpeak gateway socket. */
export function buildGatewayConnect(input: {
host: string;
nickname: string;
serverPassword?: string;
channelPassword?: string;
defaultChannel?: string;
identity?: string;
privilegeKey?: string;
serverType?: GatewayServerType;
}): GatewayConnectPayload {
return {
type: "connect",
host: input.host.trim(),
nickname: input.nickname.trim(),
serverPassword: input.serverPassword?.trim() || undefined,
channelPassword: input.channelPassword?.trim() || undefined,
defaultChannel: input.defaultChannel?.trim() || undefined,
identity: input.identity || undefined,
privilegeKey: input.privilegeKey?.trim() || undefined,
serverType: input.serverType || "auto",
};
}
export function sendGatewayAction(ws: WebSocket | null, action: GatewayOutboundAction): boolean {
if (!ws || ws.readyState !== WebSocket.OPEN) return false;
ws.send(JSON.stringify(action));
return true;
}
-19
View File
@@ -1,19 +0,0 @@
export const GREENTEASPEAK_THEME_ID = "greenteaspeak" as const;
export function isGreenteaSpeakTheme(theme: string): boolean {
return theme === GREENTEASPEAK_THEME_ID;
}
export {
GreenteaSpeakChrome,
type GreenteaSpeakChromeProps,
type ConnectionTabItem,
} from "./GreenteaSpeakChrome";
export {
buildGatewayConnect,
sendGatewayAction,
type GatewayConnectPayload,
type GatewayOutboundAction,
type GatewayServerType,
} from "./gatewayAdapter";