mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 08:52:51 +08:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0778c8adb | ||
|
|
8e934c6646 | ||
|
|
a9f0586b88 | ||
|
|
ddc7ce5dec | ||
|
|
a79f2aa4a7 | ||
|
|
2b668a7f73 | ||
|
|
eba1e1af92 | ||
|
|
034be9cc77 | ||
|
|
92479d8a38 | ||
|
|
37a84e4cee | ||
|
|
e89d83c4bb | ||
|
|
57447fdd11 | ||
|
|
b87eb0f4b7 | ||
|
|
4124071371 | ||
|
|
295af1781e | ||
|
|
914afd19bd | ||
|
|
032969d16a | ||
|
|
0428f80af8 | ||
|
|
3c58650c1c |
No files matched your search
@@ -20,33 +20,42 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Determine image tags
|
||||
id: tags
|
||||
# Passed via env, never spliced into the script: a tag name is
|
||||
# user-controlled text and would otherwise run as shell code.
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
run: |
|
||||
TAGS="moepchi/webspeak3:latest"
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
TAGS="$TAGS,moepchi/webspeak3:${{ github.event.release.tag_name }}"
|
||||
if [ "$EVENT_NAME" = "release" ]; then
|
||||
TAGS="$TAGS,moepchi/webspeak3:$RELEASE_TAG"
|
||||
fi
|
||||
echo "tags=$TAGS" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -28,10 +28,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v5
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
|
||||
- name: Upload Safari screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v5
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5
|
||||
with:
|
||||
name: safari-client-screenshots
|
||||
path: test-results/safari-client-*.png
|
||||
|
||||
+38
-10
@@ -1,26 +1,37 @@
|
||||
# --- Rust connector -----------------------------------------------------
|
||||
FROM rust:1-bookworm AS connector-builder
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake && rm -rf /var/lib/apt/lists/*
|
||||
# Cross-compiled on the build machine for the target platform via xx, so an
|
||||
# arm64 image doesn't have to run rustc under QEMU. xx is copied into the
|
||||
# builder's root, hence pinned by digest rather than a movable tag.
|
||||
FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.9.0@sha256:c64defb9ed5a91eacb37f96ccc3d4cd72521c4bd18d5442905b95e2226b0e707 AS xx
|
||||
FROM --platform=$BUILDPLATFORM rust:1-bookworm AS connector-builder
|
||||
COPY --from=xx / /
|
||||
ARG TARGETPLATFORM
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake clang && rm -rf /var/lib/apt/lists/*
|
||||
RUN xx-apt-get update && xx-apt-get install -y libc6-dev gcc g++ && rm -rf /var/lib/apt/lists/*
|
||||
RUN rustup target add $(xx-cargo --print-target-triple)
|
||||
WORKDIR /src
|
||||
COPY tsclientlib/ tsclientlib/
|
||||
COPY connector/ connector/
|
||||
WORKDIR /src/connector
|
||||
ENV CMAKE_POLICY_VERSION_MINIMUM=3.5
|
||||
RUN cargo build --release
|
||||
RUN xx-cargo build --release
|
||||
|
||||
# --- Web frontend ---------------------------------------------------------
|
||||
FROM node:22-bookworm-slim AS web-builder
|
||||
# The bundle is plain JS/CSS, identical for every target platform - build it
|
||||
# natively on the build machine instead of under emulation.
|
||||
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS web-builder
|
||||
WORKDIR /src/web
|
||||
COPY web/package*.json ./
|
||||
RUN npm ci
|
||||
# Vite 8 pulls in Rolldown, which ships its bundler as a platform-specific
|
||||
# optional dependency (@rolldown/binding-linux-x64-gnu here). `npm ci`
|
||||
# intermittently fails to install it due to a long-standing npm bug
|
||||
# optional dependency (@rolldown/binding-linux-<arch>-gnu, <arch> being
|
||||
# Node's process.arch). `npm ci` intermittently fails to install it due to a
|
||||
# long-standing npm bug
|
||||
# (https://github.com/npm/cli/issues/4828) without raising a non-zero exit
|
||||
# code, so `vite build` only fails later with a confusing MODULE_NOT_FOUND.
|
||||
# Verify the binding actually loaded and self-heal via the workaround from
|
||||
# npm's own error message before wasting a full build on a broken install.
|
||||
RUN node -e "require('@rolldown/binding-linux-x64-gnu')" \
|
||||
RUN node -e "require('@rolldown/binding-linux-' + process.arch + '-gnu')" \
|
||||
|| (rm -rf node_modules package-lock.json && npm install)
|
||||
COPY web/ ./
|
||||
# The UI carries a small Ko-fi donation button (see web/src/App.tsx).
|
||||
@@ -35,13 +46,19 @@ ARG DONATE_URL=keep
|
||||
# sentinel needed.
|
||||
ARG DEFAULT_SERVER=
|
||||
ARG DEFAULT_CHANNEL=
|
||||
# Design Store catalog to use - unset means "use the maintainer's shared
|
||||
# one" (App.tsx's own default), same unset-means-no-override convention as
|
||||
# DEFAULT_SERVER above.
|
||||
ARG STORE_URL=
|
||||
# tsc -b currently fails on pre-existing type errors unrelated to this build;
|
||||
# vite build alone is enough to produce the production bundle.
|
||||
RUN if [ "$DONATE_URL" = "keep" ]; then DONATE_URL_ENV=; else DONATE_URL_ENV="VITE_DONATE_URL=$DONATE_URL"; fi; \
|
||||
env $DONATE_URL_ENV VITE_DEFAULT_SERVER="$DEFAULT_SERVER" VITE_DEFAULT_CHANNEL="$DEFAULT_CHANNEL" npx vite build
|
||||
env $DONATE_URL_ENV VITE_DEFAULT_SERVER="$DEFAULT_SERVER" VITE_DEFAULT_CHANNEL="$DEFAULT_CHANNEL" VITE_STORE_URL="$STORE_URL" npx vite build
|
||||
|
||||
# --- Gateway ----------------------------------------------------------------
|
||||
FROM node:22-bookworm-slim AS gateway-builder
|
||||
# tsc output is platform-independent too; only the runtime stage below
|
||||
# installs the (pure-JS) production deps for the target platform.
|
||||
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS gateway-builder
|
||||
WORKDIR /src/gateway
|
||||
COPY gateway/package*.json ./
|
||||
RUN npm ci
|
||||
@@ -53,6 +70,11 @@ FROM node:22-bookworm-slim AS runtime
|
||||
LABEL org.opencontainers.image.title="WebSpeak3"
|
||||
LABEL org.opencontainers.image.description="Self-hosted web client for TeamSpeak 3 servers"
|
||||
WORKDIR /app
|
||||
# ts-connector (Rust, native-tls) needs the OS CA bundle for its HTTPS calls
|
||||
# (e.g. TeamSpeak nickname lookup) - Node bundles its own certs and works
|
||||
# without this, but native-tls doesn't, so it's not optional here.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY gateway/package*.json ./
|
||||
# npm/npx are only needed to install the gateway's runtime deps; the
|
||||
# container never runs either afterwards, so strip them (plus npm's own
|
||||
@@ -64,7 +86,7 @@ RUN npm ci --omit=dev \
|
||||
&& rm -rf /root/.npm /usr/local/lib/node_modules/npm \
|
||||
&& rm -f /usr/local/bin/npm /usr/local/bin/npx
|
||||
COPY --from=gateway-builder /src/gateway/dist ./dist
|
||||
COPY --from=connector-builder /src/connector/target/release/ts-connector /app/connector-bin/ts-connector
|
||||
COPY --from=connector-builder /src/connector/target/*/release/ts-connector /app/connector-bin/ts-connector
|
||||
COPY --from=web-builder /src/web/dist /app/web/dist
|
||||
|
||||
ENV PORT=8080
|
||||
@@ -72,6 +94,12 @@ ENV WEB_DIST=/app/web/dist
|
||||
ENV CONNECTOR_BIN=/app/connector-bin/ts-connector
|
||||
EXPOSE 8080
|
||||
|
||||
# Run unprivileged. /app itself is the default spot for feedback.log and
|
||||
# store-themes.json, so it has to be writable by that user; a volume mounted
|
||||
# there from an older (root) image may need a one-off `chown 1000:1000`.
|
||||
RUN chown node:node /app
|
||||
USER node
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD ["node", "-e", "fetch('http://127.0.0.1:8080/healthz').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"]
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ services:
|
||||
|
||||
Then `docker compose up -d` and open `http://localhost:8080` (or whatever host port you chose).
|
||||
|
||||
Prefer to skip the build entirely? A prebuilt image is published on [Docker Hub](https://hub.docker.com/r/moepchi/webspeak3):
|
||||
Prefer to skip the build entirely? A prebuilt image for `linux/amd64` and `linux/arm64` (e.g. a Raspberry Pi 4/5 on a 64-bit OS) is published on [Docker Hub](https://hub.docker.com/r/moepchi/webspeak3):
|
||||
|
||||
```bash
|
||||
docker run -d -p 8080:8080 --name webspeak3 moepchi/webspeak3:latest
|
||||
@@ -180,6 +180,8 @@ docker run -d -p 8080:8080 --name webspeak3 moepchi/webspeak3:latest
|
||||
|
||||
The UI shows a small **Ko-fi donation button** in the bottom right corner. Building it yourself and would rather not carry someone else's donation link? `docker compose build --build-arg DONATE_URL=` removes it (any other value points it somewhere else). Outside Docker the same thing is a build-time variable: `VITE_DONATE_URL= npm run build` in `web/`.
|
||||
|
||||
The **Design Store** (browse/upload community themes) points at the maintainer's shared catalog by default, same as the official client — no setup needed. Want to run your own store instead, backed by your own gateway (`STORE_ENABLED=1`, see below)? `docker compose build --build-arg STORE_URL=https://your-gateway.example.com/api/store/themes`. Outside Docker: `VITE_STORE_URL=https://your-gateway.example.com/api/store/themes npm run build` in `web/`.
|
||||
|
||||
#### Environment variables
|
||||
|
||||
All optional; add them under `environment:` in your compose override next to `PORT`.
|
||||
@@ -189,8 +191,20 @@ All optional; add them under `environment:` in your compose override next to `PO
|
||||
| `PORT` | `8080` | Port the gateway listens on. |
|
||||
| `WEB_STATIC` | on | Set to `0` to disable serving the built UI (`web/dist`) entirely — the gateway then only answers `/ws`, `/api/feedback` and `/healthz`. Use this when the UI is hosted elsewhere (e.g. a CDN/static host) and the gateway is purely a backend. |
|
||||
| `WEB_DIST` | `web/dist` next to the gateway | Overrides the directory served when `WEB_STATIC` is on. Only needed for non-standard layouts. |
|
||||
| `DEFAULT_SERVER` / `DEFAULT_CHANNEL` | unset | Server (and optionally channel) every visitor auto-connects to — see [Bake in a default server](#2-bake-in-a-default-server). |
|
||||
| `BROADCAST_TOKEN` | unset | Bearer token required to call `/api/broadcast` (send an in-app notice to all connected clients before a maintenance restart). Endpoint 404s while unset. |
|
||||
| `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. |
|
||||
| `STORE_DATA_FILE` | `store-themes.json` in the container's working dir | Where submitted themes (including screenshots) are stored. Mount a volume over this path if they should survive a container recreate. |
|
||||
| `STORE_ALLOWED_ORIGIN` | `*` | CORS origin allowed to call the store endpoint, if you want to restrict it to your own frontend's origin. |
|
||||
| `STORE_ADMIN_TOKEN` | unset | Bearer token for moderation. New submissions wait as "pending" until approved on the review page at `/api/store/admin` (enter the token there); the token holder's own submissions and the reserved author name(s) skip the queue. Without it, nothing ever gets published. Submitted CSS is also checked server-side: no `@import`/`@font-face`, no external `url()` — only inline `data:` images. |
|
||||
| `ALLOWED_SERVERS` | unset (any server) | Comma-separated list of server addresses this gateway is allowed to connect to (e.g. `ts.example.com,*.example.net`). A port is matched separately from the host, so listing `ts.example.com` allows any port on it. An entry starting with `*.` matches any subdomain (`*.example.com` allows `ts.example.com`, not `example.com` itself - list that separately too if it should also be reachable). Locks a self-hosted instance down to specific server(s) instead of acting as a general "connect anywhere" client; a rejected `connect` gets an error back before any connector process is even spawned. |
|
||||
| `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`.** |
|
||||
| `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. |
|
||||
| `TRUST_PROXY` | off | Set to `1` when the gateway is **only** reachable through a reverse proxy/tunnel (e.g. cloudflared): per-IP limits then use `CF-Connecting-IP` / `X-Forwarded-For` instead of the proxy's own address. Don't set it on a directly exposed gateway - clients could then spoof their IP. |
|
||||
|
||||
> **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.
|
||||
|
||||
<details>
|
||||
<summary><b>🛠️ Manual installation (without Docker)</b></summary>
|
||||
@@ -280,7 +294,7 @@ Skip the connect dialog entirely and drop visitors straight into a TeamSpeak ser
|
||||
Add a `connect` parameter to your instance's URL and send that link out — in a Discord post, a landing page button, a QR code, wherever:
|
||||
|
||||
```
|
||||
https://your-instance/?connect=voice.example.com&nickname=Guest&channel=Lobby&token=abc123
|
||||
https://your-instance/?connect=voice.example.com&nickname=Guest&channel=Lobby#token=abc123
|
||||
```
|
||||
|
||||
| Parameter | Required | What it does |
|
||||
@@ -288,19 +302,23 @@ https://your-instance/?connect=voice.example.com&nickname=Guest&channel=Lobby&to
|
||||
| `connect` | yes | Server address to join, `host` or `host:port` |
|
||||
| `nickname` | no | Nickname to connect with — omit it and the visitor gets an auto-generated `Guest-XXXX` |
|
||||
| `channel` | no | Default channel to join |
|
||||
| `token` | no | Server/channel privilege key, if the target requires one |
|
||||
| `token` | no | Server/channel privilege key, if the target requires one. Put it after `#` (as above) so it never reaches server logs or `Referer` headers; `?token=` still works too |
|
||||
|
||||
This works on **any** deployment — no rebuild, no configuration. WebSpeak3 connects as soon as the page loads and immediately strips these parameters from the address bar, so refreshing the tab (or someone screenshotting/forwarding the URL later) won't silently reconnect off a stale link.
|
||||
|
||||
### 2. Bake in a default server
|
||||
|
||||
Running a dedicated instance for one community or event? Set a default at build time so **every** visitor auto-connects with zero parameters, no link needed:
|
||||
Running a dedicated instance for one community or event? Set a default server so **every** visitor auto-connects with zero parameters, no link needed. With the Docker image that's just two environment variables, no rebuild:
|
||||
|
||||
```bash
|
||||
docker compose build --build-arg DEFAULT_SERVER=voice.example.com --build-arg DEFAULT_CHANNEL=Lobby
|
||||
```yaml
|
||||
environment:
|
||||
- DEFAULT_SERVER=voice.example.com
|
||||
- DEFAULT_CHANNEL=Lobby
|
||||
```
|
||||
|
||||
Outside Docker, the same thing is a build-time variable:
|
||||
The gateway hands them to the UI it serves itself, so this needs `WEB_STATIC` left on. Returning visitors' browsers keep the cached app (including its default) until the next image update, so a later change of these values reaches them only then — new visitors get it right away.
|
||||
|
||||
Building it yourself, you can bake the default in instead: `docker compose build --build-arg DEFAULT_SERVER=voice.example.com --build-arg DEFAULT_CHANNEL=Lobby` (the environment variables above win over these if both are set). Outside Docker, the same thing is a build-time variable:
|
||||
|
||||
```bash
|
||||
VITE_DEFAULT_SERVER=voice.example.com VITE_DEFAULT_CHANNEL=Lobby npm run build
|
||||
|
||||
@@ -14,6 +14,8 @@ This roadmap is intentionally outcome-focused. It does not promise fixed dates.
|
||||
- Server, channel, and private text chat
|
||||
- Favorites, identities, contacts, pokes, away state, and reconnect
|
||||
- File transfers, local session recording, sound packs, and administration tools
|
||||
- Design Store: browse, upload, rate, and download community-made themes
|
||||
- Opt-in WASM AEC3 echo cancellation for speaker+mic setups
|
||||
- Responsive desktop and mobile interfaces in German and English
|
||||
- Docker image and Compose-based self-hosting
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "io-st
|
||||
futures = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
anyhow = "1"
|
||||
num-traits = "0.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
+34
-7
@@ -35,6 +35,9 @@ use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio,
|
||||
|
||||
/// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects.
|
||||
const FRAME_SAMPLES: usize = 960;
|
||||
/// Upper bound for a file download relayed to the browser (see its use).
|
||||
const MAX_DOWNLOAD_BYTES: u64 = 25 << 20;
|
||||
const MAX_ICON_BYTES: u64 = 512 << 10;
|
||||
const OUT_CHANNELS: usize = 2;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
@@ -46,11 +49,13 @@ struct Args {
|
||||
/// Nickname to use on the server
|
||||
#[arg(short, long, default_value = "Browser User")]
|
||||
nickname: String,
|
||||
/// Server password, if the server requires one
|
||||
#[arg(long)]
|
||||
/// Server password, if the server requires one. The secrets below are
|
||||
/// normally passed via their env vars (as the gateway does) rather than
|
||||
/// as flags, since argv is visible to every process on the host.
|
||||
#[arg(long, env = "TS_SERVER_PASSWORD", hide_env_values = true)]
|
||||
server_password: Option<String>,
|
||||
/// Password for the default channel to join, if it's password-protected
|
||||
#[arg(long)]
|
||||
#[arg(long, env = "TS_CHANNEL_PASSWORD", hide_env_values = true)]
|
||||
channel_password: Option<String>,
|
||||
/// Channel (name or path, e.g. "Default Channel/Nested") to join on connect,
|
||||
/// instead of the server's actual default channel
|
||||
@@ -60,14 +65,14 @@ struct Args {
|
||||
/// `identity` field) to reconnect with, so the server sees the same
|
||||
/// client UID across sessions. A fresh identity is generated - and
|
||||
/// reported back the same way - when omitted or unparseable.
|
||||
#[arg(long)]
|
||||
#[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"])]
|
||||
server_type: String,
|
||||
/// Privilege key / token (`client_default_token` in clientinit).
|
||||
#[arg(long, alias = "token")]
|
||||
#[arg(long, alias = "token", env = "TS_PRIVILEGE_KEY", hide_env_values = true)]
|
||||
privilege_key: Option<String>,
|
||||
}
|
||||
|
||||
@@ -835,6 +840,12 @@ GreenTeaSpeak public servers often only allow the official GreenTeaSpeak desktop
|
||||
Try a self-hosted TeaSpeak with TeamSpeak-compat enabled, or use GreenTeaSpeak 2 for ts.greenteaspeak.de."
|
||||
);
|
||||
}
|
||||
if raw.contains("BlockedTarget") {
|
||||
return anyhow::anyhow!(
|
||||
"Could not connect to \"{address}\": 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.)"
|
||||
);
|
||||
}
|
||||
match &e {
|
||||
tsclientlib::Error::ConnectTs(inner) => {
|
||||
anyhow::anyhow!("The server rejected the connection: {inner}")
|
||||
@@ -2905,10 +2916,26 @@ async fn run(args: Args) -> Result<()> {
|
||||
// file does not stall channel switches, chat, etc. while in flight;
|
||||
// emit() is just a println! under the hood, so it is safe to call
|
||||
// from a spawned task even while the main loop is emitting too.
|
||||
let mut stream = result.stream;
|
||||
// Everything is buffered and then sent as one base64 JSON line,
|
||||
// so cap it - a server could otherwise announce (or just send)
|
||||
// gigabytes and take the whole gateway host's memory with it.
|
||||
let stream = result.stream;
|
||||
let announced_size = result.size;
|
||||
// Group/server icons are fetched automatically, without the user
|
||||
// asking, so they get a far smaller budget than explicit downloads.
|
||||
let limit = if cid == 0 && path.starts_with("/icon_") { MAX_ICON_BYTES } else { MAX_DOWNLOAD_BYTES };
|
||||
tokio::spawn(async move {
|
||||
if announced_size > limit {
|
||||
emit(&Event::Error {
|
||||
message: format!("Download refused: {path} is larger than {} KiB", limit >> 10),
|
||||
});
|
||||
return;
|
||||
}
|
||||
let mut buf = Vec::new();
|
||||
match stream.read_to_end(&mut buf).await {
|
||||
match stream.take(limit + 1).read_to_end(&mut buf).await {
|
||||
Ok(_) if buf.len() as u64 > limit => emit(&Event::Error {
|
||||
message: format!("Download aborted: {path} is larger than {} KiB", limit >> 10),
|
||||
}),
|
||||
Ok(_) => {
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(&buf);
|
||||
emit(&Event::FileDownloadData { cid, path, data });
|
||||
|
||||
@@ -6,6 +6,15 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PORT=8080
|
||||
# This file publishes no port - the gateway is only reachable through
|
||||
# the cloudflared tunnel below, so the client IP it forwards can be
|
||||
# trusted (per-IP limits would otherwise see every user as the tunnel).
|
||||
# Remove this if you publish a port directly instead.
|
||||
- TRUST_PROXY=1
|
||||
# Nothing in here needs Linux capabilities (unprivileged port, plain
|
||||
# TCP/UDP sockets), so drop them all.
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
# Port publishing is deployment-specific and left out of this file on
|
||||
# purpose - Compose concatenates `ports:` lists across an override file
|
||||
# instead of replacing them, so adding one here would double-publish
|
||||
|
||||
+185
-26
@@ -9,6 +9,7 @@ import { WebSocketServer, type WebSocket } from "ws";
|
||||
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
|
||||
import { handleStore } from "./store.js";
|
||||
import { logFeedback, logConnectionEvent } from "./activity-log.js";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
|
||||
const SERVER_TYPES = new Set<ServerType>(["teamspeak", "teaspeak", "auto"]);
|
||||
|
||||
@@ -25,6 +26,79 @@ function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): st
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
// 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
|
||||
// wrapped in brackets ("[::1]:9987"); nicknames have neither and pass through
|
||||
// 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);
|
||||
}
|
||||
const i = host.lastIndexOf(":");
|
||||
return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host;
|
||||
}
|
||||
|
||||
function isServerAllowed(host: unknown): boolean {
|
||||
if (ALLOWED_SERVERS.length === 0) return true;
|
||||
if (typeof host !== "string") return false;
|
||||
const target = stripPort(host).trim().toLowerCase();
|
||||
return ALLOWED_SERVERS.some((entry) => {
|
||||
// "*.example.com" matches any subdomain (TLS-wildcard-style: not the
|
||||
// bare apex itself - list that separately if it should be allowed too).
|
||||
if (entry.startsWith("*.")) return target.endsWith(entry.slice(1));
|
||||
return target === entry;
|
||||
});
|
||||
}
|
||||
|
||||
// Everything a "connect" message hands to the connector as a CLI argument.
|
||||
// The connector's own resolver does the real parsing; this only rejects input
|
||||
// no legitimate address or nickname has (control chars, absurd lengths), and
|
||||
// anything starting with "-" so it can never be read as a flag.
|
||||
const HOST_PATTERN = /^[\p{L}\p{N}._\-:[\]]{1,253}$/u;
|
||||
|
||||
function isValidHost(host: unknown): host is string {
|
||||
return typeof host === "string" && HOST_PATTERN.test(host) && !host.startsWith("-");
|
||||
}
|
||||
|
||||
function isValidNickname(nickname: unknown): nickname is string {
|
||||
return (
|
||||
typeof nickname === "string" &&
|
||||
nickname.trim().length > 0 &&
|
||||
nickname.length <= 100 &&
|
||||
!/[\p{Cc}]/u.test(nickname)
|
||||
);
|
||||
}
|
||||
|
||||
// Which web pages may open /ws. Without this any website can embed a hidden
|
||||
// WebSocket to this gateway and use it as a free relay into TeamSpeak land.
|
||||
// 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);
|
||||
|
||||
// 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 connectionsPerIp = new Map<string, number>();
|
||||
|
||||
// Largest single WS message: file uploads travel base64-encoded inside one,
|
||||
// so this is ~4/3 of the biggest uploadable file (see MAX_UPLOAD_BYTES in
|
||||
// web/src/App.tsx). ws's own default is 100 MiB.
|
||||
const WS_MAX_PAYLOAD = 34 * 1024 * 1024;
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 8080);
|
||||
|
||||
// In production (Docker), the built web app lives alongside the gateway and
|
||||
@@ -37,6 +111,19 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist");
|
||||
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
|
||||
|
||||
// Runtime counterpart of the web build's VITE_DEFAULT_SERVER/_CHANNEL (GitHub
|
||||
// issue #12): set on the container, these end up in the served index.html as
|
||||
// <meta> tags the client reads at startup, so changing them needs no rebuild.
|
||||
// Meta tags rather than an inline script, which CONTENT_SECURITY_POLICY forbids.
|
||||
const RUNTIME_CONFIG_META = Object.entries({
|
||||
"webspeak3-default-server": process.env.DEFAULT_SERVER,
|
||||
"webspeak3-default-channel": process.env.DEFAULT_CHANNEL,
|
||||
})
|
||||
.flatMap(([name, value]) =>
|
||||
value ? [`<meta name="${name}" content="${value.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}">`] : [],
|
||||
)
|
||||
.join("");
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html",
|
||||
".js": "text/javascript",
|
||||
@@ -156,33 +243,34 @@ async function handleBroadcast(req: IncomingMessage, res: ServerResponse) {
|
||||
// fine here - it only needs to survive as long as the process does.
|
||||
const FEEDBACK_RATE_LIMIT = 5;
|
||||
const FEEDBACK_RATE_WINDOW_MS = 60 * 60 * 1000;
|
||||
const feedbackSubmissionTimes = new Map<string, number[]>();
|
||||
const isFeedbackRateLimited = createRateLimiter(FEEDBACK_RATE_LIMIT, FEEDBACK_RATE_WINDOW_MS);
|
||||
|
||||
function isFeedbackRateLimited(ip: string): boolean {
|
||||
const now = Date.now();
|
||||
const recent = (feedbackSubmissionTimes.get(ip) ?? []).filter((t) => now - t < FEEDBACK_RATE_WINDOW_MS);
|
||||
recent.push(now);
|
||||
feedbackSubmissionTimes.set(ip, recent);
|
||||
return recent.length > FEEDBACK_RATE_LIMIT;
|
||||
// The issue is public, and its text is whatever an anonymous visitor typed:
|
||||
// a zero-width space after "@" stops @mentions from pinging real users, and
|
||||
// the body goes into a fenced code block (longer than any backtick run in the
|
||||
// message) so links, images and markup render as inert text.
|
||||
function neutralizeMentions(text: string): string {
|
||||
return text.replace(/@/g, "@\u200b");
|
||||
}
|
||||
|
||||
async function createGithubIssue(payload: {
|
||||
category: string;
|
||||
message: string;
|
||||
email?: string;
|
||||
}): Promise<string | undefined> {
|
||||
// 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 title = `[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`;
|
||||
const title = neutralizeMentions(
|
||||
`[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`,
|
||||
);
|
||||
const longestTicks = Math.max(0, ...(payload.message.match(/`+/g) ?? []).map((m) => m.length));
|
||||
const fence = "`".repeat(Math.max(3, longestTicks + 1));
|
||||
const body = [
|
||||
payload.message,
|
||||
`${fence}text`,
|
||||
neutralizeMentions(payload.message),
|
||||
fence,
|
||||
"",
|
||||
"---",
|
||||
`Category: ${payload.category}`,
|
||||
payload.email ? `Contact: ${payload.email}` : undefined,
|
||||
"_Submitted via the in-client feedback form._",
|
||||
]
|
||||
.filter((line): line is string => Boolean(line))
|
||||
.join("\n");
|
||||
].join("\n");
|
||||
|
||||
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/issues`, {
|
||||
method: "POST",
|
||||
@@ -225,8 +313,7 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ip = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
||||
if (isFeedbackRateLimited(ip)) {
|
||||
if (isFeedbackRateLimited(clientIp(req))) {
|
||||
res.writeHead(429, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "rate_limited" }));
|
||||
return;
|
||||
@@ -278,7 +365,7 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
|
||||
let githubIssueUrl: string | undefined;
|
||||
if (publishAsIssue) {
|
||||
try {
|
||||
githubIssueUrl = await createGithubIssue({ category, message, email });
|
||||
githubIssueUrl = await createGithubIssue({ category, message });
|
||||
} catch (err) {
|
||||
console.error("[feedback] Failed to create GitHub issue:", err);
|
||||
}
|
||||
@@ -319,7 +406,28 @@ const tlsOptions =
|
||||
? { cert: readFileSync(TLS_CERT), key: readFileSync(TLS_KEY) }
|
||||
: null;
|
||||
|
||||
// Only for the UI this process serves itself; a separately hosted frontend
|
||||
// (GitHub/Cloudflare Pages) needs its own. Theme CSS from the Design Store is
|
||||
// the main thing this contains: it can't load scripts, frame the app, or
|
||||
// pull in fonts/styles from arbitrary hosts.
|
||||
const CONTENT_SECURITY_POLICY = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'wasm-unsafe-eval'",
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||
"font-src 'self' data: https://fonts.gstatic.com",
|
||||
"img-src 'self' data: blob: https:",
|
||||
"media-src 'self' data: blob:",
|
||||
"connect-src 'self' https: wss: ws:",
|
||||
"worker-src 'self' blob:",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"frame-ancestors 'self'",
|
||||
].join("; ");
|
||||
|
||||
const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
res.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||
void (async () => {
|
||||
try {
|
||||
const requestUrl = new URL(req.url ?? "/", "http://localhost");
|
||||
@@ -331,8 +439,18 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
|
||||
await handleBroadcast(req, res);
|
||||
return;
|
||||
}
|
||||
if (requestUrl.pathname === "/api/store/themes" || requestUrl.pathname.startsWith("/api/store/themes/")) {
|
||||
await handleStore(req, res, requestUrl.pathname);
|
||||
if (
|
||||
requestUrl.pathname === "/api/store/admin" ||
|
||||
requestUrl.pathname === "/api/store/themes" ||
|
||||
requestUrl.pathname.startsWith("/api/store/themes/")
|
||||
) {
|
||||
await handleStore(req, res, requestUrl.pathname).catch((err) => {
|
||||
console.error("[store] Request failed:", err);
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "internal" }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -370,7 +488,15 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
|
||||
filePath = path.join(WEB_DIST, "index.html");
|
||||
body = await readFile(filePath);
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": MIME_TYPES[path.extname(filePath)] ?? "application/octet-stream" });
|
||||
if (RUNTIME_CONFIG_META && filePath === path.join(WEB_DIST, "index.html")) {
|
||||
// Function replacer: a string one would expand "$&" etc. in the values.
|
||||
body = Buffer.from(body.toString("utf8").replace("</head>", () => `${RUNTIME_CONFIG_META}</head>`));
|
||||
}
|
||||
const ext = path.extname(filePath);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": MIME_TYPES[ext] ?? "application/octet-stream",
|
||||
...(ext === ".html" ? { "Content-Security-Policy": CONTENT_SECURITY_POLICY } : {}),
|
||||
});
|
||||
res.end(body);
|
||||
} catch {
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
@@ -385,7 +511,24 @@ const server = tlsOptions
|
||||
? createSecureServer(tlsOptions, requestHandler)
|
||||
: createServer(requestHandler);
|
||||
|
||||
const wss = new WebSocketServer({ server, path: "/ws" });
|
||||
const wss = new WebSocketServer({
|
||||
server,
|
||||
path: "/ws",
|
||||
maxPayload: WS_MAX_PAYLOAD,
|
||||
verifyClient: ({ origin, req }, done) => {
|
||||
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);
|
||||
if (MAX_CONNECTIONS_PER_IP > 0 && (connectionsPerIp.get(ip) ?? 0) >= MAX_CONNECTIONS_PER_IP) {
|
||||
return done(false, 429, "Too many connections");
|
||||
}
|
||||
done(true);
|
||||
},
|
||||
});
|
||||
|
||||
// Heartbeat: a browser tab that loses its network mid-session (mobile
|
||||
// handover, Wi-Fi drop, backgrounded/frozen tab) often never sends a proper
|
||||
@@ -477,11 +620,14 @@ server.listen(PORT, () => {
|
||||
}
|
||||
});
|
||||
|
||||
wss.on("connection", (socket: WebSocket) => {
|
||||
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;
|
||||
|
||||
const ip = clientIp(req);
|
||||
connectionsPerIp.set(ip, (connectionsPerIp.get(ip) ?? 0) + 1);
|
||||
|
||||
heartbeats.set(socket, { isAlive: true });
|
||||
socket.on("pong", () => {
|
||||
const state = heartbeats.get(socket);
|
||||
@@ -516,6 +662,16 @@ wss.on("connection", (socket: WebSocket) => {
|
||||
async function handleMessage(msg: any): Promise<void> {
|
||||
switch (msg.type) {
|
||||
case "connect": {
|
||||
if (!isValidHost(msg.host) || !isValidNickname(msg.nickname)) {
|
||||
socket.send(JSON.stringify({ type: "error", message: "Invalid server address or nickname." }));
|
||||
break;
|
||||
}
|
||||
if (!isServerAllowed(msg.host)) {
|
||||
socket.send(
|
||||
JSON.stringify({ type: "error", message: "This server is not allowed by this gateway's admin." }),
|
||||
);
|
||||
break;
|
||||
}
|
||||
// Replacing a connection on the same socket: tear down the previous
|
||||
// connector so we don't leak processes.
|
||||
if (connection) {
|
||||
@@ -816,6 +972,9 @@ wss.on("connection", (socket: WebSocket) => {
|
||||
});
|
||||
|
||||
socket.on("close", () => {
|
||||
const remaining = (connectionsPerIp.get(ip) ?? 1) - 1;
|
||||
if (remaining > 0) connectionsPerIp.set(ip, remaining);
|
||||
else connectionsPerIp.delete(ip);
|
||||
heartbeats.delete(socket);
|
||||
if (connection) liveConnections.delete(connection);
|
||||
connection?.disconnect();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
// Behind a reverse proxy / tunnel (e.g. cloudflared) every request arrives
|
||||
// from the proxy's own address, so per-IP limits would lump all users into
|
||||
// one bucket. TRUST_PROXY=1 makes us read the client IP the proxy reports
|
||||
// instead - only set it when the gateway is reachable *solely* through that
|
||||
// proxy, otherwise anyone can send the header and pick their own "IP".
|
||||
const TRUST_PROXY = process.env.TRUST_PROXY === "1";
|
||||
|
||||
export function clientIp(req: IncomingMessage): string {
|
||||
if (TRUST_PROXY) {
|
||||
const cf = req.headers["cf-connecting-ip"];
|
||||
if (typeof cf === "string" && cf) return cf.trim();
|
||||
const xff = req.headers["x-forwarded-for"];
|
||||
const first = (Array.isArray(xff) ? xff[0] : xff)?.split(",")[0]?.trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
||||
}
|
||||
|
||||
/** Sliding-window "N per window per key" limiter. Expired keys are swept
|
||||
* periodically so the map can't grow without bound under a stream of
|
||||
* one-shot IPs. */
|
||||
export function createRateLimiter(limit: number, windowMs: number): (key: string) => boolean {
|
||||
const hits = new Map<string, number[]>();
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, times] of hits) {
|
||||
if (times.every((t) => now - t >= windowMs)) hits.delete(key);
|
||||
}
|
||||
}, windowMs).unref();
|
||||
return (key) => {
|
||||
const now = Date.now();
|
||||
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
|
||||
recent.push(now);
|
||||
hits.set(key, recent);
|
||||
return recent.length > limit;
|
||||
};
|
||||
}
|
||||
+177
-42
@@ -11,9 +11,10 @@
|
||||
// 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, writeFile } from "node:fs/promises";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { timingSafeEqual, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
|
||||
const STORE_ENABLED = process.env.STORE_ENABLED === "1";
|
||||
const STORE_ALLOWED_ORIGIN = process.env.STORE_ALLOWED_ORIGIN ?? "*";
|
||||
@@ -67,22 +68,47 @@ interface StoreTheme {
|
||||
ratingSum: number;
|
||||
ratingCount: number;
|
||||
createdAt: string;
|
||||
// ponytail: no moderation queue/admin UI yet - everything publishes as
|
||||
// "approved" immediately. The field exists so a bad submission can be
|
||||
// hidden by hand-editing STORE_DATA_FILE (status: "rejected") without a
|
||||
// schema change, once there's an actual admin surface to do that from.
|
||||
status: "approved" | "rejected";
|
||||
// New submissions start "pending" and only become public once someone
|
||||
// holding STORE_ADMIN_TOKEN approves them (GET /api/store/admin); rejected
|
||||
// ones are deleted outright. "rejected" only survives in old data files.
|
||||
status: "approved" | "pending" | "rejected";
|
||||
}
|
||||
|
||||
// Rendered CSS reaches other users' browsers, so block the two ways a
|
||||
// stylesheet can reach outside itself. Everything else (colors, selectors,
|
||||
// animations, pseudo-elements) is harmless - it only ever applies inside the
|
||||
// app's own theme wrapper class.
|
||||
const CSS_IMPORT_RE = /@import/i;
|
||||
const CSS_REMOTE_URL_RE = /url\s*\(\s*["']?\s*(?:https?:)?\/\//i;
|
||||
// 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, "")
|
||||
.replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => {
|
||||
const cp = parseInt(hex, 16);
|
||||
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd";
|
||||
})
|
||||
.replace(/\\(.)/gs, "$1")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function sanitizeThemeCss(css: string): string | null {
|
||||
return CSS_IMPORT_RE.test(css) || CSS_REMOTE_URL_RE.test(css) ? null : css;
|
||||
// Theme CSS runs in every installer's browser, so it may style the app but
|
||||
// never load anything: no imports/fonts, no functions that fetch a resource,
|
||||
// and url() only for inline data: images. Everything else (colors,
|
||||
// selectors, animations) can at worst look bad - which moderation catches.
|
||||
const FORBIDDEN_CSS = [
|
||||
/@import/,
|
||||
/@font-face/,
|
||||
/@namespace/,
|
||||
/(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
|
||||
/-moz-binding/,
|
||||
/behavior\s*:/,
|
||||
/javascript:/,
|
||||
/<\/?style/,
|
||||
];
|
||||
|
||||
export function isSafeThemeCss(css: string): boolean {
|
||||
const normalized = normalizeCss(css);
|
||||
if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false;
|
||||
for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) {
|
||||
if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
let storeCache: StoreTheme[] | null = null;
|
||||
@@ -91,7 +117,11 @@ async function loadStoreThemes(): Promise<StoreTheme[]> {
|
||||
if (storeCache) return storeCache;
|
||||
try {
|
||||
storeCache = JSON.parse(await readFile(STORE_DATA_FILE, "utf-8")) as StoreTheme[];
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// Only a missing file means "no themes yet". Anything else (unreadable,
|
||||
// corrupt) must fail loudly - treating it as empty would let the next
|
||||
// submission overwrite every stored theme.
|
||||
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
||||
storeCache = [];
|
||||
}
|
||||
return storeCache;
|
||||
@@ -99,22 +129,29 @@ async function loadStoreThemes(): Promise<StoreTheme[]> {
|
||||
|
||||
async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
|
||||
storeCache = themes;
|
||||
await writeFile(STORE_DATA_FILE, JSON.stringify(themes), "utf-8");
|
||||
// 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);
|
||||
}
|
||||
|
||||
function isAdminRequest(req: IncomingMessage): boolean {
|
||||
const authHeader = req.headers.authorization ?? "";
|
||||
return authHeader.startsWith("Bearer ") && isValidStoreAdminToken(authHeader.slice("Bearer ".length));
|
||||
}
|
||||
|
||||
// Approved, and still passing today's CSS check - themes published before
|
||||
// that check got stricter are hidden instead of served.
|
||||
function isPublic(theme: StoreTheme): boolean {
|
||||
return theme.status === "approved" && isSafeThemeCss(theme.css);
|
||||
}
|
||||
|
||||
// Same in-memory-per-IP approach as FEEDBACK_RATE_LIMIT in index.ts; kept as a
|
||||
// separate map since the two endpoints are independent.
|
||||
const STORE_RATE_LIMIT = 5;
|
||||
const STORE_RATE_WINDOW_MS = 60 * 60 * 1000;
|
||||
const storeSubmissionTimes = new Map<string, number[]>();
|
||||
|
||||
function isStoreRateLimited(ip: string): boolean {
|
||||
const now = Date.now();
|
||||
const recent = (storeSubmissionTimes.get(ip) ?? []).filter((t) => now - t < STORE_RATE_WINDOW_MS);
|
||||
recent.push(now);
|
||||
storeSubmissionTimes.set(ip, recent);
|
||||
return recent.length > STORE_RATE_LIMIT;
|
||||
}
|
||||
const isStoreRateLimited = createRateLimiter(STORE_RATE_LIMIT, STORE_RATE_WINDOW_MS);
|
||||
|
||||
// One rating per IP per theme - not robust against a determined multi-IP
|
||||
// spammer, but it stops the trivial "click again" case with no accounts to
|
||||
@@ -137,7 +174,7 @@ function storeRating(theme: StoreTheme): { average: number; count: number } {
|
||||
async function handleStoreList(res: ServerResponse) {
|
||||
const themes = await loadStoreThemes();
|
||||
const listing = themes
|
||||
.filter((t) => t.status === "approved")
|
||||
.filter(isPublic)
|
||||
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
||||
.map((t) => ({
|
||||
id: t.id,
|
||||
@@ -153,9 +190,9 @@ async function handleStoreList(res: ServerResponse) {
|
||||
res.end(JSON.stringify(listing));
|
||||
}
|
||||
|
||||
async function handleStoreDownload(res: ServerResponse, id: string) {
|
||||
async function handleStoreDownload(req: IncomingMessage, res: ServerResponse, id: string) {
|
||||
const themes = await loadStoreThemes();
|
||||
const theme = themes.find((t) => t.id === id && t.status === "approved");
|
||||
const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req)));
|
||||
if (!theme) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "not_found" }));
|
||||
@@ -167,9 +204,9 @@ async function handleStoreDownload(res: ServerResponse, id: string) {
|
||||
res.end(JSON.stringify({ name: theme.name, baseTheme: theme.baseTheme, css: theme.css }));
|
||||
}
|
||||
|
||||
async function handleStoreScreenshot(res: ServerResponse, id: string) {
|
||||
async function handleStoreScreenshot(req: IncomingMessage, res: ServerResponse, id: string) {
|
||||
const themes = await loadStoreThemes();
|
||||
const theme = themes.find((t) => t.id === id && t.status === "approved");
|
||||
const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req)));
|
||||
if (!theme?.screenshot) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "not_found" }));
|
||||
@@ -186,7 +223,7 @@ async function handleStoreScreenshot(res: ServerResponse, id: string) {
|
||||
}
|
||||
|
||||
async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: string) {
|
||||
const ip = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
||||
const ip = clientIp(req);
|
||||
const seenKey = `${ip}:${id}`;
|
||||
if (storeRatingsSeen.has(seenKey)) {
|
||||
res.writeHead(409, { "Content-Type": "application/json" });
|
||||
@@ -221,7 +258,7 @@ async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: st
|
||||
}
|
||||
|
||||
const themes = await loadStoreThemes();
|
||||
const theme = themes.find((t) => t.id === id && t.status === "approved");
|
||||
const theme = themes.find((t) => t.id === id && isPublic(t));
|
||||
if (!theme) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "not_found" }));
|
||||
@@ -238,6 +275,9 @@ async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: st
|
||||
res.end(JSON.stringify({ error: "save_failed" }));
|
||||
return;
|
||||
}
|
||||
// ponytail: wholesale reset instead of per-entry expiry; only bounds memory,
|
||||
// at worst it lets old voters vote once more, same as a redeploy does.
|
||||
if (storeRatingsSeen.size > 100_000) storeRatingsSeen.clear();
|
||||
storeRatingsSeen.add(seenKey);
|
||||
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
@@ -245,7 +285,7 @@ async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: st
|
||||
}
|
||||
|
||||
async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
|
||||
const ip = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
||||
const ip = clientIp(req);
|
||||
if (isStoreRateLimited(ip)) {
|
||||
res.writeHead(429, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "rate_limited" }));
|
||||
@@ -300,18 +340,17 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isAdmin = isAdminRequest(req);
|
||||
if (STORE_RESERVED_AUTHORS.has(author.toLowerCase())) {
|
||||
const authHeader = req.headers.authorization ?? "";
|
||||
const token = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length) : "";
|
||||
if (!isValidStoreAdminToken(token)) {
|
||||
if (!isAdmin) {
|
||||
res.writeHead(403, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "author_reserved" }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const css = sanitizeThemeCss(rawCss);
|
||||
if (css === null) {
|
||||
const css = rawCss;
|
||||
if (!isSafeThemeCss(css)) {
|
||||
res.writeHead(400, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "css_rejected" }));
|
||||
return;
|
||||
@@ -345,7 +384,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
|
||||
ratingSum: 0,
|
||||
ratingCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: "approved",
|
||||
// The admin's own submissions skip the queue - they'd approve them anyway.
|
||||
status: isAdmin ? "approved" : "pending",
|
||||
};
|
||||
themes.push(theme);
|
||||
try {
|
||||
@@ -358,9 +398,95 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
|
||||
}
|
||||
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, id: theme.id }));
|
||||
res.end(JSON.stringify({ ok: true, id: theme.id, status: theme.status }));
|
||||
if (theme.status === "pending") console.log(`[store] New theme awaiting review: "${theme.name}" (${theme.id})`);
|
||||
}
|
||||
|
||||
async function handleStorePending(req: IncomingMessage, res: ServerResponse) {
|
||||
if (!isAdminRequest(req)) {
|
||||
res.writeHead(401, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "unauthorized" }));
|
||||
return;
|
||||
}
|
||||
const themes = await loadStoreThemes();
|
||||
const pending = themes
|
||||
.filter((t) => t.status === "pending")
|
||||
.map(({ screenshot, ratingSum: _s, ratingCount: _c, ...t }) => ({ ...t, hasScreenshot: Boolean(screenshot) }));
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(pending));
|
||||
}
|
||||
|
||||
async function handleStoreModerate(req: IncomingMessage, res: ServerResponse, id: string, action: string) {
|
||||
if (!isAdminRequest(req)) {
|
||||
res.writeHead(401, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "unauthorized" }));
|
||||
return;
|
||||
}
|
||||
const themes = await loadStoreThemes();
|
||||
const index = themes.findIndex((t) => t.id === id);
|
||||
if (index === -1) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "not_found" }));
|
||||
return;
|
||||
}
|
||||
// Reject and delete are the same thing: drop it, freeing its slot.
|
||||
if (action === "approve") themes[index].status = "approved";
|
||||
else themes.splice(index, 1);
|
||||
try {
|
||||
await saveStoreThemes(themes);
|
||||
} catch (err) {
|
||||
console.error("[store] Failed to save moderation result:", err);
|
||||
res.writeHead(500, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "save_failed" }));
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
}
|
||||
|
||||
// Minimal moderation page. The theme CSS is shown as text only (textContent),
|
||||
// never applied, so reviewing a hostile submission is harmless.
|
||||
const ADMIN_PAGE = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Store moderation</title><style>
|
||||
body{font:14px system-ui;margin:0 auto;padding:1rem;max-width:60rem;background:#111;color:#eee}
|
||||
input,button{font:inherit;padding:.4rem .7rem}article{border:1px solid #444;border-radius:8px;padding:1rem;margin:1rem 0}
|
||||
pre{max-height:20rem;overflow:auto;background:#000;padding:.5rem;white-space:pre-wrap}img{max-width:100%}
|
||||
.ok{background:#2a6}.no{background:#a33}button{color:#fff;border:0;border-radius:4px;cursor:pointer}
|
||||
</style></head><body><h1>Design Store – pending themes</h1>
|
||||
<p><input id="token" type="password" placeholder="STORE_ADMIN_TOKEN" size="40"> <button class="ok" id="load">Load</button></p>
|
||||
<div id="list"></div><script>
|
||||
const base = location.pathname.replace(/\/admin$/, "/themes");
|
||||
const auth = () => ({ Authorization: "Bearer " + document.getElementById("token").value });
|
||||
async function load() {
|
||||
const list = document.getElementById("list");
|
||||
list.textContent = "Loading…";
|
||||
const res = await fetch(base + "/pending", { headers: auth() });
|
||||
if (!res.ok) { list.textContent = "Error " + res.status; return; }
|
||||
const themes = await res.json();
|
||||
list.textContent = themes.length ? "" : "Nothing to review.";
|
||||
for (const t of themes) {
|
||||
const el = document.createElement("article");
|
||||
const h = document.createElement("h2"); h.textContent = t.name + " – " + t.author + " (" + t.baseTheme + ")"; el.append(h);
|
||||
const d = document.createElement("p"); d.textContent = t.description + " · " + t.createdAt; el.append(d);
|
||||
if (t.hasScreenshot) {
|
||||
const img = document.createElement("img"); el.append(img);
|
||||
fetch(base + "/" + t.id + "/screenshot", { headers: auth() }).then(r => r.blob()).then(b => img.src = URL.createObjectURL(b));
|
||||
}
|
||||
const pre = document.createElement("pre"); pre.textContent = t.css; el.append(pre);
|
||||
for (const [action, label, cls] of [["approve", "Approve", "ok"], ["reject", "Reject (delete)", "no"]]) {
|
||||
const b = document.createElement("button"); b.textContent = label; b.className = cls; b.style.marginRight = ".5rem";
|
||||
b.onclick = async () => {
|
||||
const r = await fetch(base + "/" + t.id + "/" + action, { method: "POST", headers: auth() });
|
||||
if (r.ok) el.remove(); else alert("Error " + r.status);
|
||||
};
|
||||
el.append(b);
|
||||
}
|
||||
list.append(el);
|
||||
}
|
||||
}
|
||||
document.getElementById("load").onclick = load;
|
||||
</script></body></html>`;
|
||||
|
||||
export async function handleStore(req: IncomingMessage, res: ServerResponse, pathname: string) {
|
||||
setStoreCors(res);
|
||||
if (req.method === "OPTIONS") {
|
||||
@@ -374,13 +500,22 @@ export async function handleStore(req: IncomingMessage, res: ServerResponse, pat
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/store/admin") {
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
||||
res.end(ADMIN_PAGE);
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/store/themes") {
|
||||
if (req.method === "GET") return handleStoreList(res);
|
||||
if (req.method === "POST") return handleStoreSubmit(req, res);
|
||||
} else {
|
||||
const [id, sub] = pathname.slice("/api/store/themes/".length).split("/");
|
||||
if (id && !sub && req.method === "GET") return handleStoreDownload(res, id);
|
||||
if (id && sub === "screenshot" && req.method === "GET") return handleStoreScreenshot(res, id);
|
||||
if (id === "pending" && !sub && req.method === "GET") return handleStorePending(req, res);
|
||||
if (id && !sub && req.method === "GET") return handleStoreDownload(req, res, id);
|
||||
if (id && sub === "screenshot" && req.method === "GET") return handleStoreScreenshot(req, res, id);
|
||||
if (id && (sub === "approve" || sub === "reject") && req.method === "POST") {
|
||||
return handleStoreModerate(req, res, id, sub);
|
||||
}
|
||||
if (id && sub === "rate" && req.method === "POST") return handleStoreRate(req, res, id);
|
||||
}
|
||||
|
||||
|
||||
@@ -237,6 +237,11 @@ const CONNECTOR_BIN =
|
||||
export class Ts3Connection {
|
||||
private listeners = new Set<(event: Ts3ConnectionEvent) => void>();
|
||||
private child?: ChildProcessWithoutNullStreams;
|
||||
// Set once the child is confirmed gone - either it exited, or it never
|
||||
// managed to spawn at all. disconnect() uses this to skip waiting on an
|
||||
// "exit" event that already fired (and so will never fire again) before
|
||||
// disconnect() got a chance to listen for it.
|
||||
private childGone = false;
|
||||
|
||||
constructor(private options: Ts3ConnectOptions) {}
|
||||
|
||||
@@ -259,14 +264,39 @@ export class Ts3Connection {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
const args = ["--address", this.options.host, "--nickname", this.options.nickname];
|
||||
if (this.options.serverPassword) args.push("--server-password", this.options.serverPassword);
|
||||
if (this.options.channelPassword) args.push("--channel-password", this.options.channelPassword);
|
||||
if (this.options.defaultChannel) args.push("--default-channel", this.options.defaultChannel);
|
||||
if (this.options.identity) args.push("--identity", this.options.identity);
|
||||
if (this.options.serverType) args.push("--server-type", this.options.serverType);
|
||||
if (this.options.privilegeKey) args.push("--privilege-key", this.options.privilegeKey);
|
||||
this.child = spawn(CONNECTOR_BIN, args);
|
||||
// "--flag=value" so a value starting with "-" can never be parsed as a
|
||||
// flag of its own. Secrets go through the environment instead of argv,
|
||||
// which any process on the host can read via `ps`.
|
||||
const args = [`--address=${this.options.host}`, `--nickname=${this.options.nickname}`];
|
||||
if (this.options.defaultChannel) args.push(`--default-channel=${this.options.defaultChannel}`);
|
||||
if (this.options.serverType) args.push(`--server-type=${this.options.serverType}`);
|
||||
const env: NodeJS.ProcessEnv = { ...process.env };
|
||||
if (this.options.serverPassword) env.TS_SERVER_PASSWORD = this.options.serverPassword;
|
||||
if (this.options.channelPassword) env.TS_CHANNEL_PASSWORD = this.options.channelPassword;
|
||||
if (this.options.identity) env.TS_IDENTITY = this.options.identity;
|
||||
if (this.options.privilegeKey) env.TS_PRIVILEGE_KEY = this.options.privilegeKey;
|
||||
this.child = spawn(CONNECTOR_BIN, args, { env });
|
||||
|
||||
// The connector can exit on its own (e.g. the TS3 server drops it) and close
|
||||
// its stdin pipe before writeLine()'s `this.child.killed` guard has any way
|
||||
// to know - killed only reflects Node-side .kill() calls. A write to that
|
||||
// closed pipe emits an unhandled 'error' (EPIPE) on the stream, which Node
|
||||
// treats as fatal and crashes the whole gateway process, killing every
|
||||
// other client's session too. Listening here turns it into a normal,
|
||||
// isolated write failure instead of a process-wide crash.
|
||||
this.child.stdin.on("error", () => {});
|
||||
|
||||
// spawn() itself can fail asynchronously - wrong CONNECTOR_BIN path, no
|
||||
// exec permission, or (under load, with many connections already open)
|
||||
// EMFILE/ENFILE from running out of file descriptors. That failure surfaces
|
||||
// as an unhandled 'error' event on the child process object, which is just
|
||||
// as fatal to the whole gateway process as the stdin case above - and far
|
||||
// more likely to hit at the worst possible time, since a file-descriptor
|
||||
// limit is reached exactly when the most other connections are active.
|
||||
this.child.on("error", (err) => {
|
||||
this.childGone = true;
|
||||
this.emit({ type: "error", message: `Connector failed to start: ${err.message}` });
|
||||
});
|
||||
|
||||
createInterface({ input: this.child.stdout }).on("line", (line) => {
|
||||
try {
|
||||
@@ -574,6 +604,7 @@ export class Ts3Connection {
|
||||
});
|
||||
|
||||
this.child.on("exit", (code) => {
|
||||
this.childGone = true;
|
||||
if (code !== 0) {
|
||||
this.emit({ type: "error", message: `Connector exited with code ${code}` });
|
||||
}
|
||||
@@ -918,7 +949,11 @@ export class Ts3Connection {
|
||||
}
|
||||
|
||||
async disconnect(message = ""): Promise<void> {
|
||||
if (this.child && !this.child.killed) {
|
||||
// childGone means the "exit" event already fired - which happens exactly
|
||||
// once, so a .once("exit", ...) listener attached only now (below) would
|
||||
// never see it, and this would always fall through to the 3s hard-kill
|
||||
// timeout for a process that's already gone. Skip straight past it.
|
||||
if (this.child && !this.child.killed && !this.childGone) {
|
||||
const child = this.child;
|
||||
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
|
||||
child.stdin.write(`disconnect ${sanitized}\n`);
|
||||
|
||||
+1
-1
Submodule tsclientlib updated: 7361a8d71d...2e7794928f.
+274
-111
@@ -137,27 +137,39 @@ const IS_OWN_HOSTED_INSTANCE = !DEMO_MODE && OWN_HOSTED_HOSTNAMES.has(window.loc
|
||||
// reconnect off a stale link sitting in the address bar or browser history.
|
||||
const AUTO_CONNECT_FROM_URL = (() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
// The token may also sit in the fragment (#token=...), which - unlike the
|
||||
// query - never reaches server logs or Referer headers.
|
||||
const hashParams = new URLSearchParams(window.location.hash.slice(1));
|
||||
const connectHost = params.get("connect");
|
||||
if (!connectHost) return null;
|
||||
const target = {
|
||||
host: connectHost,
|
||||
nickname: params.get("nickname") || undefined,
|
||||
defaultChannel: params.get("channel") || undefined,
|
||||
privilegeKey: params.get("token") || undefined,
|
||||
privilegeKey: hashParams.get("token") || params.get("token") || undefined,
|
||||
};
|
||||
for (const key of ["connect", "nickname", "channel", "token"]) params.delete(key);
|
||||
let hash = window.location.hash;
|
||||
if (hashParams.has("token")) {
|
||||
hashParams.delete("token");
|
||||
hash = hashParams.size ? `#${hashParams}` : "";
|
||||
}
|
||||
const rest = params.toString();
|
||||
window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : "") + window.location.hash);
|
||||
window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : "") + hash);
|
||||
return target;
|
||||
})();
|
||||
|
||||
// A self-hosted build can also bake in a default server so the page
|
||||
// auto-connects with zero URL params at all - set via `docker compose build
|
||||
// --build-arg DEFAULT_SERVER=...` (see Dockerfile/README) or plain
|
||||
// VITE_DEFAULT_SERVER= at build time. AUTO_CONNECT_FROM_URL above always wins
|
||||
// when a share link is present.
|
||||
const DEFAULT_SERVER = import.meta.env.VITE_DEFAULT_SERVER || null;
|
||||
const DEFAULT_CHANNEL = import.meta.env.VITE_DEFAULT_CHANNEL || "";
|
||||
// VITE_DEFAULT_SERVER= at build time. The Docker image can set the same thing
|
||||
// at runtime instead (DEFAULT_SERVER/DEFAULT_CHANNEL env vars, issue #12): the
|
||||
// gateway passes them in as <meta> tags, which take precedence over the build
|
||||
// values. AUTO_CONNECT_FROM_URL above always wins when a share link is present.
|
||||
const runtimeConfig = (name: string) =>
|
||||
document.querySelector<HTMLMetaElement>(`meta[name="webspeak3-${name}"]`)?.content;
|
||||
const DEFAULT_SERVER = runtimeConfig("default-server") || import.meta.env.VITE_DEFAULT_SERVER || null;
|
||||
const DEFAULT_CHANNEL = runtimeConfig("default-channel") || import.meta.env.VITE_DEFAULT_CHANNEL || "";
|
||||
|
||||
// Terms of use, own-hosted instance only (see TODO.md #2/#7.1). Versioned so
|
||||
// a rule change can re-surface the modal: bump TOS_VERSION and everyone who
|
||||
@@ -184,7 +196,9 @@ function hasAcceptedToS(): boolean {
|
||||
|
||||
const LAST_HOST_KEY = "webspeak3:last-host";
|
||||
const LAST_NICKNAME_KEY = "webspeak3:last-nickname";
|
||||
const LAST_PRIVILEGE_KEY = "webspeak3:last-privilege-key";
|
||||
// Privilege keys are one-shot grants, so they're no longer remembered across
|
||||
// reloads; drop what older versions stored in plain text.
|
||||
localStorage.removeItem("webspeak3:last-privilege-key");
|
||||
const LAST_SERVER_TYPE_KEY = "webspeak3:last-server-type";
|
||||
|
||||
type ServerType = "teamspeak" | "teaspeak" | "auto";
|
||||
@@ -715,15 +729,19 @@ function triggerBrowserDownload(filename: string, base64Data: string): void {
|
||||
const binary = atob(base64Data);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
const blob = new Blob([bytes]);
|
||||
downloadBlob(new Blob([bytes]), filename);
|
||||
}
|
||||
|
||||
function downloadBlob(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
a.remove();
|
||||
// Revoking right after click() can cancel the download in some browsers.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
function formatDurationSecs(totalSeconds: number): string {
|
||||
@@ -874,7 +892,6 @@ function ChannelTree({
|
||||
onSelectItem,
|
||||
onSwitchChannel,
|
||||
onOpenPrivateChat,
|
||||
onPokeClient,
|
||||
onMoveClient,
|
||||
onClientContextMenu,
|
||||
onChannelContextMenu,
|
||||
@@ -893,7 +910,6 @@ function ChannelTree({
|
||||
onSelectItem: (item: SelectedItem) => void;
|
||||
onSwitchChannel: (channelId: number) => void;
|
||||
onOpenPrivateChat: (clientId: number, clientName: string) => void;
|
||||
onPokeClient: (clientId: number, clientName: string) => void;
|
||||
onMoveClient: (clientId: number, channelId: number) => void;
|
||||
onClientContextMenu: (e: React.MouseEvent, clientId: number, clientName: string, isSelf: boolean) => void;
|
||||
onChannelContextMenu: (e: React.MouseEvent, channelId: number, channelName: string) => void;
|
||||
@@ -989,7 +1005,7 @@ function ChannelTree({
|
||||
className={`ts-tree-expander${hasChildren ? "" : " ts-tree-expander-empty"}${
|
||||
isCollapsed ? " ts-tree-expander-collapsed" : ""
|
||||
}`}
|
||||
aria-label={isCollapsed ? "aufklappen" : "zuklappen"}
|
||||
aria-label={isCollapsed ? t("tree.expand") : t("tree.collapse")}
|
||||
tabIndex={-1}
|
||||
onMouseDown={(e) => {
|
||||
// Keep focus on the row so a nearby double-click still joins.
|
||||
@@ -1131,7 +1147,6 @@ function ChannelTree({
|
||||
onSelectItem={onSelectItem}
|
||||
onSwitchChannel={onSwitchChannel}
|
||||
onOpenPrivateChat={onOpenPrivateChat}
|
||||
onPokeClient={onPokeClient}
|
||||
onMoveClient={onMoveClient}
|
||||
onClientContextMenu={onClientContextMenu}
|
||||
onChannelContextMenu={onChannelContextMenu}
|
||||
@@ -1498,7 +1513,7 @@ function ConnectDialog({
|
||||
<div className="ts-dialog-grid">
|
||||
<label className="ts-dialog-field">
|
||||
{t("connect.phoneticNickname")}
|
||||
<input disabled title="Not supported yet" />
|
||||
<input disabled title={t("clientContext.notSupported")} />
|
||||
</label>
|
||||
<label className="ts-dialog-field">
|
||||
{t("connect.identity")}
|
||||
@@ -2557,7 +2572,7 @@ function FavoritesDialog({
|
||||
</label>
|
||||
<label className="ts-dialog-field">
|
||||
{t("connect.phoneticNickname")}
|
||||
<input disabled title="Not supported yet" />
|
||||
<input disabled title={t("clientContext.notSupported")} />
|
||||
</label>
|
||||
<label className="ts-dialog-field">
|
||||
{t("connect.serverAddress")}
|
||||
@@ -2636,7 +2651,7 @@ function FavoritesDialog({
|
||||
{t("favorites.showServerQueryClients")}
|
||||
</label>
|
||||
<label className="ts-dialog-checkbox">
|
||||
<input type="checkbox" disabled title="Not supported yet" />
|
||||
<input type="checkbox" disabled title={t("clientContext.notSupported")} />
|
||||
{t("favorites.connectOnStartup")}
|
||||
</label>
|
||||
</div>
|
||||
@@ -2748,6 +2763,7 @@ function InviteFriendDialog({
|
||||
const t = useT();
|
||||
const [includeChannel, setIncludeChannel] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const linkInputRef = useRef<HTMLInputElement>(null);
|
||||
const backdrop = useBackdropDismiss(onClose);
|
||||
|
||||
const link = `ts3server://${host}${includeChannel && channelId !== null ? `?channel=${channelId}` : ""}`;
|
||||
@@ -2781,7 +2797,7 @@ function InviteFriendDialog({
|
||||
</div>
|
||||
<label className="ts-dialog-field">
|
||||
{t("inviteFriend.link")}
|
||||
<input readOnly value={link} onFocus={(e) => e.target.select()} />
|
||||
<input ref={linkInputRef} readOnly value={link} onFocus={(e) => e.target.select()} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="ts-dialog-buttons">
|
||||
@@ -2791,9 +2807,15 @@ function InviteFriendDialog({
|
||||
<div className="ts-dialog-buttons-right">
|
||||
<button
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(link);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
// No clipboard API on plain-http origins - select the link
|
||||
// instead so it can be copied by hand.
|
||||
(navigator.clipboard?.writeText(link) ?? Promise.reject()).then(
|
||||
() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
},
|
||||
() => linkInputRef.current?.select()
|
||||
);
|
||||
}}
|
||||
>
|
||||
{copied ? t("inviteFriend.copied") : t("inviteFriend.copyToClipboard")}
|
||||
@@ -3573,6 +3595,8 @@ function iconDataUrl(base64: string): string {
|
||||
// colored-letter badge instead; only real custom uploads (id >= threshold)
|
||||
// are fetched as actual images.
|
||||
const CUSTOM_ICON_ID_THRESHOLD = 1000;
|
||||
// Keep in sync with WS_MAX_PAYLOAD in gateway/src/index.ts (base64 adds ~4/3).
|
||||
const MAX_UPLOAD_BYTES = 24 * 1024 * 1024;
|
||||
|
||||
/** Deterministic color for a group's letter badge - same icon id always
|
||||
* produces the same hue, so a group looks consistent across the tree
|
||||
@@ -3742,7 +3766,7 @@ function PermissionsEditorDialog({
|
||||
serverGroups,
|
||||
channels,
|
||||
clients,
|
||||
entries,
|
||||
entries: loadedEntries,
|
||||
catalog,
|
||||
onSelectTarget,
|
||||
onLoadCatalog,
|
||||
@@ -3810,6 +3834,17 @@ function PermissionsEditorDialog({
|
||||
}
|
||||
})();
|
||||
|
||||
// Entries only count while they belong to the target on screen - after a
|
||||
// tab switch they'd otherwise show (and let you delete/add against) the
|
||||
// previous tab's target, e.g. server group 6 edited as channel group 6.
|
||||
const targetKey = target ? `${scope}:${target.id1}:${target.id2 ?? ""}` : null;
|
||||
const [loadedKey, setLoadedKey] = useState<string | null>(null);
|
||||
const entries = loadedKey !== null && loadedKey === targetKey ? loadedEntries : null;
|
||||
const select = (s: PermScope, id1: number, id2?: number) => {
|
||||
setLoadedKey(`${s}:${id1}:${id2 ?? ""}`);
|
||||
onSelectTarget(s, id1, id2);
|
||||
};
|
||||
|
||||
const load = (next: { scope: PermScope; groupId?: number | null; channelId?: number | null; clientDbId?: number }) => {
|
||||
// The catalog doubles as the name->id lookup the delete button needs, so
|
||||
// fetch it alongside the first load rather than only when "+ Hinzufügen"
|
||||
@@ -3820,13 +3855,13 @@ function PermissionsEditorDialog({
|
||||
const cid = next.channelId !== undefined ? next.channelId : channelId;
|
||||
const cldbid = next.clientDbId !== undefined ? next.clientDbId : parseInt(clientDbIdInput, 10);
|
||||
if ((s === "server" || s === "channelgroup") && gid !== null && gid !== undefined) {
|
||||
onSelectTarget(s, gid);
|
||||
select(s, gid);
|
||||
} else if (s === "channel" && cid !== null && cid !== undefined) {
|
||||
onSelectTarget(s, cid);
|
||||
select(s, cid);
|
||||
} else if (s === "client" && !Number.isNaN(cldbid)) {
|
||||
onSelectTarget(s, cldbid);
|
||||
select(s, cldbid);
|
||||
} else if (s === "channelclient" && cid !== null && cid !== undefined && !Number.isNaN(cldbid)) {
|
||||
onSelectTarget(s, cid, cldbid);
|
||||
select(s, cid, cldbid);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3853,8 +3888,13 @@ function PermissionsEditorDialog({
|
||||
key={tab.scope}
|
||||
className={`ts-perms-editor-tab${scope === tab.scope ? " ts-perms-editor-tab-active" : ""}`}
|
||||
onClick={() => {
|
||||
// Server and channel group ids overlap, so a picked group
|
||||
// never carries over between those two tabs.
|
||||
const switchesGroupKind = isGroupScope && tab.scope !== scope;
|
||||
if (switchesGroupKind) setGroupId(null);
|
||||
setScope(tab.scope);
|
||||
setShowAddForm(false);
|
||||
load({ scope: tab.scope, groupId: switchesGroupKind ? null : undefined });
|
||||
}}
|
||||
>
|
||||
{t(tab.labelKey)}
|
||||
@@ -5281,12 +5321,7 @@ function DesignPanel({
|
||||
[JSON.stringify({ name: theme.name, baseTheme: theme.baseTheme, css: theme.css }, null, 2)],
|
||||
{ type: "application/json" }
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${theme.name.replace(/[^a-z0-9-_]+/gi, "_") || "theme"}.webspeak3theme.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
downloadBlob(blob, `${theme.name.replace(/[^a-z0-9-_]+/gi, "_") || "theme"}.webspeak3theme.json`);
|
||||
};
|
||||
|
||||
const handleImportSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -5485,7 +5520,7 @@ function DesignStorePanel({
|
||||
() => localStorage.getItem(STORE_ADMIN_TOKEN_KEY) ?? ""
|
||||
);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [publishResult, setPublishResult] = useState<"ok" | "error" | null>(null);
|
||||
const [publishResult, setPublishResult] = useState<"ok" | "pending" | "error" | null>(null);
|
||||
const [ratedIds, setRatedIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const refreshThemes = () =>
|
||||
@@ -5565,7 +5600,8 @@ function DesignStorePanel({
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
setPublishResult("ok");
|
||||
const body = (await res.json().catch(() => ({}))) as { status?: string };
|
||||
setPublishResult(body.status === "pending" ? "pending" : "ok");
|
||||
setPublishAuthor("");
|
||||
setPublishDescription("");
|
||||
setPublishScreenshot(null);
|
||||
@@ -5713,6 +5749,7 @@ function DesignStorePanel({
|
||||
{t("design.store.publish.submit")}
|
||||
</button>
|
||||
{publishResult === "ok" && <p className="ts-options-subtitle">{t("design.store.publish.success")}</p>}
|
||||
{publishResult === "pending" && <p className="ts-options-subtitle">{t("design.store.publish.pending")}</p>}
|
||||
{publishResult === "error" && <p className="ts-options-subtitle">{t("design.store.publish.error")}</p>}
|
||||
</>
|
||||
)}
|
||||
@@ -5737,6 +5774,7 @@ function SoundsPanel() {
|
||||
matchedCount: number;
|
||||
unmatchedFiles: string[];
|
||||
} | null>(null);
|
||||
const [soundpackFailed, setSoundpackFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -5801,7 +5839,15 @@ function SoundsPanel() {
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
setSoundpackResult(null);
|
||||
const { matched, unmatchedFiles } = await parseSoundpack(file);
|
||||
setSoundpackFailed(false);
|
||||
let parsed: Awaited<ReturnType<typeof parseSoundpack>>;
|
||||
try {
|
||||
parsed = await parseSoundpack(file);
|
||||
} catch {
|
||||
setSoundpackFailed(true);
|
||||
return;
|
||||
}
|
||||
const { matched, unmatchedFiles } = parsed;
|
||||
for (const [event, sound] of Object.entries(matched) as [SoundEventId, { name: string; blob: Blob }][]) {
|
||||
await saveCustomSound(event, new File([sound.blob], sound.name, { type: sound.blob.type }));
|
||||
}
|
||||
@@ -5838,6 +5884,7 @@ function SoundsPanel() {
|
||||
<div className="ts-options-field-row">
|
||||
<button onClick={handleImportSoundpackClick}>{t("sounds.importSoundpack")}</button>
|
||||
</div>
|
||||
{soundpackFailed && <p className="ts-options-subtitle">{t("sounds.importFailed")}</p>}
|
||||
{soundpackResult && (
|
||||
<p className="ts-options-subtitle">
|
||||
{t("sounds.importResult", {
|
||||
@@ -6317,9 +6364,7 @@ function AppInner() {
|
||||
const [serverPassword, setServerPassword] = useState("");
|
||||
const [channelPassword, setChannelPassword] = useState("");
|
||||
const [defaultChannel, setDefaultChannel] = useState("");
|
||||
const [privilegeKey, setPrivilegeKey] = useState(
|
||||
() => localStorage.getItem(LAST_PRIVILEGE_KEY) ?? ""
|
||||
);
|
||||
const [privilegeKey, setPrivilegeKey] = useState("");
|
||||
const [serverType, setServerType] = useState<ServerType>(loadServerType);
|
||||
// Prompt shown when switching into a password-protected channel mid-session
|
||||
// (the initial-connect "default channel" password above is a separate field).
|
||||
@@ -6479,8 +6524,12 @@ function AppInner() {
|
||||
const handleDesignSelectionChange = (next: string) => {
|
||||
setDesignSelection(next);
|
||||
localStorage.setItem(DESIGN_SELECTION_KEY, next);
|
||||
localStorage.setItem(DESIGN_THEME_KEY, resolveDesignThemeBase(next, customThemes));
|
||||
};
|
||||
// Persisted from the resolved value, not in the handler: a theme selected
|
||||
// right after being created/installed isn't in the handler's customThemes yet.
|
||||
useEffect(() => {
|
||||
localStorage.setItem(DESIGN_THEME_KEY, designTheme);
|
||||
}, [designTheme]);
|
||||
const handleSaveCustomTheme = (nextTheme: CustomTheme) => {
|
||||
setCustomThemes((prev) => {
|
||||
const idx = prev.findIndex((th) => th.id === nextTheme.id);
|
||||
@@ -6535,6 +6584,9 @@ function AppInner() {
|
||||
const [aec3Enabled, setAec3Enabled] = useState(() => loadBoolPref(AEC3_ENABLED_KEY, false));
|
||||
const [aec3Loading, setAec3Loading] = useState(false);
|
||||
const aec3Ref = useRef<Aec3Instance | null>(null);
|
||||
// Mirrors aec3Enabled but updates immediately, for startMic() calls made in
|
||||
// the same tick as a toggle (restartMic right after setAec3Enabled).
|
||||
const aec3EnabledRef = useRef(aec3Enabled);
|
||||
const [micTestOn, setMicTestOn] = useState(false);
|
||||
const [connectionsMenuOpen, setConnectionsMenuOpen] = useState(false);
|
||||
// Nova-theme-only: collapses the classic menu items behind a hamburger button.
|
||||
@@ -6624,6 +6676,10 @@ function AppInner() {
|
||||
const recordChunksRef = useRef<{ left: Float32Array[]; right: Float32Array[] }>({ left: [], right: [] });
|
||||
const activeTabRef = useRef<ActiveTab>("channel");
|
||||
const hasConnectedRef = useRef(false);
|
||||
// Sessions that reached "connected" at least once. hasConnectedRef (and
|
||||
// parked.hasConnected) reset for every reconnect attempt; this doesn't, so
|
||||
// a failed reconnect keeps retrying instead of closing the tab outright.
|
||||
const everConnectedRef = useRef(new Set<string>());
|
||||
// Set when a "disconnected" event is received, so the socket's onclose
|
||||
// handler (which fires shortly after, on its own close handshake) can tell
|
||||
// a clean disconnect apart from the socket dying before ever connecting.
|
||||
@@ -6682,11 +6738,18 @@ function AppInner() {
|
||||
});
|
||||
};
|
||||
|
||||
// Same lookup as `ownClient` below: by server-reported id first, since a
|
||||
// nickname match breaks as soon as we're renamed (by us or the server).
|
||||
const ownNameRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
const own = clients.find((c) => c.name === nickname) ?? null;
|
||||
const own =
|
||||
(ownClientId != null ? clients.find((c) => c.id === ownClientId) : null) ??
|
||||
clients.find((c) => c.name === nickname) ??
|
||||
null;
|
||||
inputMutedRef.current = own?.inputMuted ?? false;
|
||||
outputMutedRef.current = own?.outputMuted ?? false;
|
||||
}, [clients, nickname]);
|
||||
ownNameRef.current = own?.name ?? null;
|
||||
}, [clients, nickname, ownClientId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (micCaptureRef.current) micCaptureRef.current.threshold = vadThreshold;
|
||||
@@ -6765,15 +6828,16 @@ function AppInner() {
|
||||
}, [activeSessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
const sessions = sessionsRef.current;
|
||||
return () => {
|
||||
for (const rec of sessionsRef.current.values()) {
|
||||
for (const rec of sessions.values()) {
|
||||
try {
|
||||
rec.socket?.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
sessionsRef.current.clear();
|
||||
sessions.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -6809,7 +6873,13 @@ function AppInner() {
|
||||
window.addEventListener("mouseup", onUp);
|
||||
};
|
||||
|
||||
// Bumped by every start/stop: a startMic() still awaiting getUserMedia
|
||||
// compares against it afterwards and discards its mic if it was superseded,
|
||||
// instead of installing it after a stopMic() that already "ran".
|
||||
const micGenerationRef = useRef(0);
|
||||
|
||||
const stopMic = () => {
|
||||
micGenerationRef.current++;
|
||||
micCaptureRef.current?.stop();
|
||||
micCaptureRef.current = null;
|
||||
setMicOn(false);
|
||||
@@ -6823,11 +6893,38 @@ function AppInner() {
|
||||
if (!audioContextRef.current) {
|
||||
const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
|
||||
audioContextRef.current = audioContext;
|
||||
audioPlayerRef.current = new AudioPlayer(audioContext);
|
||||
const player = new AudioPlayer(audioContext);
|
||||
audioPlayerRef.current = player;
|
||||
// The volume effect and the device picker only ever touch the player
|
||||
// that existed at the time - a fresh one (first use, or after
|
||||
// disposeAudioIfIdle) has to be brought up to the current settings.
|
||||
player.setVolume(playbackVolume);
|
||||
if (outputDeviceId) {
|
||||
player.setOutputDevice(outputDeviceId).catch((error: Error) =>
|
||||
appendLog({ text: `Output device error: ${error.message}`, kind: "error" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
return audioContextRef.current;
|
||||
};
|
||||
|
||||
// Browsers keep an AudioContext created without a user gesture (auto-mic
|
||||
// on page load, a reconnect) "suspended" - silent - until one happens. The
|
||||
// mic permission prompt used to be the only thing resuming it, so with the
|
||||
// mic denied or absent you'd never hear anyone. Any click/keypress does it.
|
||||
useEffect(() => {
|
||||
const resume = () => {
|
||||
const ctx = audioContextRef.current;
|
||||
if (ctx?.state === "suspended") ctx.resume().catch(() => {});
|
||||
};
|
||||
window.addEventListener("pointerdown", resume, true);
|
||||
window.addEventListener("keydown", resume, true);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", resume, true);
|
||||
window.removeEventListener("keydown", resume, true);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const snapshotActiveToParked = (): ParkedSessionState =>
|
||||
emptyParkedState({
|
||||
host,
|
||||
@@ -6966,6 +7063,9 @@ function AppInner() {
|
||||
if (sessionsRef.current.size > 0) return;
|
||||
stopMic();
|
||||
stopRecording();
|
||||
// AEC3 is bound to this context's render tap - keep the preference, but
|
||||
// drop the instance so startMic() builds a fresh one on the next context.
|
||||
teardownAec3();
|
||||
audioPlayerRef.current?.dispose();
|
||||
audioPlayerRef.current = null;
|
||||
void audioContextRef.current?.close();
|
||||
@@ -6985,6 +7085,12 @@ function AppInner() {
|
||||
});
|
||||
stopMic();
|
||||
stopRecording();
|
||||
// Stream state is global, not per tab: left running, its signaling would
|
||||
// go out on the next tab's socket and its clids would name other people.
|
||||
handleStopWatchingStream();
|
||||
handleStopPublishing();
|
||||
setStreamInfos({});
|
||||
requestedStreamInfoRef.current.clear();
|
||||
};
|
||||
|
||||
const switchToSession = (id: string) => {
|
||||
@@ -7011,6 +7117,7 @@ function AppInner() {
|
||||
};
|
||||
|
||||
const removeSession = (id: string, opts?: { skipSocketClose?: boolean }) => {
|
||||
everConnectedRef.current.delete(id);
|
||||
const rec = sessionsRef.current.get(id);
|
||||
if (rec && !opts?.skipSocketClose) {
|
||||
try {
|
||||
@@ -7026,7 +7133,7 @@ function AppInner() {
|
||||
}
|
||||
if (rec) {
|
||||
try {
|
||||
rec.socket && ((rec.socket as WebSocket).onmessage = null);
|
||||
if (rec.socket) (rec.socket as WebSocket).onmessage = null;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@@ -7067,7 +7174,10 @@ function AppInner() {
|
||||
// session — active or parked in the background — getting a fresh socket
|
||||
// after an unexpected drop), so a reconnect behaves identically to the
|
||||
// original connect from the gateway/UI's point of view.
|
||||
const wireSocket = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
|
||||
// Rebuilt every render and only ever called through socketHandlersRef, so
|
||||
// a long-lived socket always sees current state (clients, contacts, t,
|
||||
// mic settings, ...) instead of whatever existed when it connected.
|
||||
const socketHandlers = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
|
||||
const connectHost = params.host;
|
||||
const connectNickname = params.nickname;
|
||||
const connectServerPassword = params.serverPassword;
|
||||
@@ -7079,7 +7189,7 @@ function AppInner() {
|
||||
const connectFavoriteId = params.favoriteId;
|
||||
const connectIdentityBlob = identities.find((i) => i.id === connectIdentityId)?.blob ?? undefined;
|
||||
|
||||
socket.onopen = () => {
|
||||
const onopen = () => {
|
||||
logClient("info", "Connection", `Connecting to ${connectHost}…`);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
@@ -7096,7 +7206,7 @@ function AppInner() {
|
||||
);
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
const onmessage = (event: MessageEvent) => {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
// Broadcast, not tied to any one session - show it regardless of which
|
||||
@@ -7151,6 +7261,7 @@ function AppInner() {
|
||||
logClient("info", "Connection", `Connected to ${data.serverName}`);
|
||||
reconnectAttemptsRef.current.delete(sessionId);
|
||||
hasConnectedRef.current = true;
|
||||
everConnectedRef.current.add(sessionId);
|
||||
setConnecting(false);
|
||||
setConnectError(null);
|
||||
setConnected(true);
|
||||
@@ -7161,7 +7272,6 @@ function AppInner() {
|
||||
});
|
||||
localStorage.setItem(LAST_HOST_KEY, connectHost);
|
||||
localStorage.setItem(LAST_NICKNAME_KEY, connectNickname);
|
||||
localStorage.setItem(LAST_PRIVILEGE_KEY, connectPrivilegeKey);
|
||||
localStorage.setItem(LAST_SERVER_TYPE_KEY, connectServerType);
|
||||
if (connectIdentityId) {
|
||||
setIdentities((prev) =>
|
||||
@@ -7224,13 +7334,13 @@ function AppInner() {
|
||||
if (isSenderIgnored(data.from)) break;
|
||||
setChat((prev) => [...prev, { from: data.from, message: data.message }]);
|
||||
recordUrlsFromMessage(data.message, data.from);
|
||||
if (data.from !== connectNickname) void playSound("message");
|
||||
if (data.from !== connectNickname && data.from !== ownNameRef.current) void playSound("message");
|
||||
break;
|
||||
case "serverMessage":
|
||||
if (isSenderIgnored(data.from)) break;
|
||||
setServerChat((prev) => [...prev, { from: data.from, message: data.message }]);
|
||||
recordUrlsFromMessage(data.message, data.from);
|
||||
if (data.from !== connectNickname) void playSound("message");
|
||||
if (data.from !== connectNickname && data.from !== ownNameRef.current) void playSound("message");
|
||||
break;
|
||||
case "privateMessage":
|
||||
if (!data.fromSelf && isSenderIgnored(data.partnerName)) break;
|
||||
@@ -7356,8 +7466,6 @@ function AppInner() {
|
||||
channelPasswordCacheRef.current.delete(data.channelId);
|
||||
setChannelPasswordPrompt((prev) => ({
|
||||
channelId: data.channelId,
|
||||
// `channels` here can be stale (this handler's closure is fixed at
|
||||
// connect time) - the dialog falls back to showing just the id.
|
||||
channelName: channels.find((c) => c.id === data.channelId)?.name ?? "",
|
||||
wrongPassword: prev?.channelId === data.channelId,
|
||||
}));
|
||||
@@ -7471,7 +7579,7 @@ function AppInner() {
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = () => {
|
||||
const onerror = () => {
|
||||
logClient("error", "WebSocket", "WebSocket error (is the gateway running?)");
|
||||
if (sessionId !== activeSessionIdRef.current) {
|
||||
const rec = sessionsRef.current.get(sessionId);
|
||||
@@ -7493,13 +7601,13 @@ function AppInner() {
|
||||
appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" });
|
||||
}
|
||||
};
|
||||
socket.onclose = () => {
|
||||
const onclose = () => {
|
||||
if (sessionId !== activeSessionIdRef.current) {
|
||||
const rec = sessionsRef.current.get(sessionId);
|
||||
// Missing already means a deliberate disconnect (the "disconnected"
|
||||
// message handler above already removed it) — nothing to do.
|
||||
if (!rec) return;
|
||||
if (rec.parked?.hasConnected) {
|
||||
if (rec.parked?.hasConnected || everConnectedRef.current.has(sessionId)) {
|
||||
// Unexpected drop of a background tab (network blip, or the OS
|
||||
// suspended the backgrounded/screen-off page) — keep the tab
|
||||
// instead of dropping it, same as a real TS3 client keeps other
|
||||
@@ -7507,7 +7615,7 @@ function AppInner() {
|
||||
// one. It comes back on its own (immediately if we're still in
|
||||
// the foreground, otherwise the visibilitychange handler retries
|
||||
// it once the page is visible again), mic still off throughout.
|
||||
rec.parked = { ...rec.parked, connecting: false, connected: false };
|
||||
if (rec.parked) rec.parked = { ...rec.parked, connecting: false, connected: false };
|
||||
updateTabMeta(sessionId, { connecting: false, connected: false });
|
||||
if (document.visibilityState === "visible") scheduleReconnectRef.current(sessionId);
|
||||
return;
|
||||
@@ -7517,6 +7625,15 @@ function AppInner() {
|
||||
setSessionTabs((prev) => prev.filter((t) => t.id !== sessionId));
|
||||
return;
|
||||
}
|
||||
if (!hasConnectedRef.current && !cleanDisconnectRef.current && everConnectedRef.current.has(sessionId)) {
|
||||
// A reconnect attempt of a session that was connected before failed
|
||||
// - same as a drop: keep the tab and let the backoff try again.
|
||||
setConnecting(false);
|
||||
setConnected(false);
|
||||
updateTabMeta(sessionId, { connecting: false, connected: false });
|
||||
if (document.visibilityState === "visible") scheduleReconnectRef.current(sessionId);
|
||||
return;
|
||||
}
|
||||
if (!hasConnectedRef.current && !cleanDisconnectRef.current) {
|
||||
setConnecting(false);
|
||||
setConnectError((prev) => prev ?? "Connection closed before the server responded");
|
||||
@@ -7543,6 +7660,17 @@ function AppInner() {
|
||||
removeSession(sessionId, { skipSocketClose: true });
|
||||
}
|
||||
};
|
||||
return { onopen, onmessage, onerror, onclose };
|
||||
};
|
||||
const socketHandlersRef = useRef(socketHandlers);
|
||||
socketHandlersRef.current = socketHandlers;
|
||||
|
||||
const wireSocket = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
|
||||
const current = () => socketHandlersRef.current(sessionId, socket, params);
|
||||
socket.onopen = () => current().onopen();
|
||||
socket.onmessage = (event) => current().onmessage(event);
|
||||
socket.onerror = () => current().onerror();
|
||||
socket.onclose = () => current().onclose();
|
||||
};
|
||||
|
||||
const handleConnect = (overrides?: {
|
||||
@@ -7988,6 +8116,11 @@ function AppInner() {
|
||||
// cid 0 always lands in serverIconImages, regardless of who asked) - fetch
|
||||
// any group icon referenced by a currently visible client that isn't
|
||||
// cached yet.
|
||||
const requestedIconPathsRef = useRef(new Set<string>());
|
||||
useEffect(() => {
|
||||
if (!connected) requestedIconPathsRef.current.clear();
|
||||
}, [connected]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverGroups) return;
|
||||
const iconById = new Map(serverGroups.map((g) => [g.id, g.iconId]));
|
||||
@@ -7998,7 +8131,10 @@ function AppInner() {
|
||||
);
|
||||
for (const iconId of wantedIconIds) {
|
||||
const path = `/icon_${iconId}`;
|
||||
if (!(path in serverIconImages)) {
|
||||
// Once per path and connection: without this, every client-list update
|
||||
// re-requested icons still in flight (or ones that failed for good).
|
||||
if (!(path in serverIconImages) && !requestedIconPathsRef.current.has(path)) {
|
||||
requestedIconPathsRef.current.add(path);
|
||||
socketRef.current?.send(JSON.stringify({ type: "downloadFile", channelId: 0, path }));
|
||||
}
|
||||
}
|
||||
@@ -8052,6 +8188,9 @@ function AppInner() {
|
||||
...prevLog,
|
||||
{ id: ++whisperLogIdRef.current, timestamp: Date.now(), description },
|
||||
]);
|
||||
// Only a change of whisper targets should log; channels/clients/t are
|
||||
// read for the description but must not re-trigger it (renames, joins).
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [whisperChannelIds, whisperClientIds, connected]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -8134,23 +8273,30 @@ function AppInner() {
|
||||
};
|
||||
}, [rightsMenuOpen]);
|
||||
|
||||
// Rebuilt each render and read through the ref, so the listener below is
|
||||
// registered once yet always sees current state.
|
||||
const shortcutHandlerRef = useRef<(e: KeyboardEvent) => void>(() => {});
|
||||
shortcutHandlerRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey) return;
|
||||
// Typing in a field (chat, dialogs) must never trigger e.g. Ctrl+D.
|
||||
const el = e.target as HTMLElement | null;
|
||||
if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return;
|
||||
if (e.key.toLowerCase() === "s" && !connecting) {
|
||||
e.preventDefault();
|
||||
setConnectDialogOpen(true);
|
||||
} else if (e.key.toLowerCase() === "d" && (connected || sessionTabs.length > 0)) {
|
||||
e.preventDefault();
|
||||
handleDisconnect();
|
||||
} else if (e.key.toLowerCase() === "b") {
|
||||
e.preventDefault();
|
||||
openAddFavorite();
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey) return;
|
||||
if (e.key.toLowerCase() === "s" && !connecting) {
|
||||
e.preventDefault();
|
||||
setConnectDialogOpen(true);
|
||||
} else if (e.key.toLowerCase() === "d" && (connected || sessionTabs.length > 0)) {
|
||||
e.preventDefault();
|
||||
handleDisconnect();
|
||||
} else if (e.key.toLowerCase() === "b") {
|
||||
e.preventDefault();
|
||||
openAddFavorite();
|
||||
}
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent) => shortcutHandlerRef.current(e);
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [connected, connecting, sessionTabs.length, host, nickname, serverPassword, defaultChannel, channelPassword]);
|
||||
}, []);
|
||||
|
||||
// Nova-theme-only: the connect dialog IS the app until a connection exists -
|
||||
// it's forced open on load and after every disconnect, and closes itself the
|
||||
@@ -8168,10 +8314,34 @@ function AppInner() {
|
||||
autoGainControl?: boolean;
|
||||
}) => {
|
||||
const audioContext = ensureAudioContext();
|
||||
const generation = ++micGenerationRef.current;
|
||||
// AEC3 enabled (persisted pref, or left over from a disposed context) but
|
||||
// not instantiated for this context yet: build it now, before the mic
|
||||
// below decides whether to turn the native canceller off.
|
||||
if (aec3EnabledRef.current && !aec3Ref.current) {
|
||||
try {
|
||||
const aec3 = await createAec3(audioContext.sampleRate, 2, 1);
|
||||
if (aec3Ref.current || audioContextRef.current !== audioContext) {
|
||||
aec3.free();
|
||||
} else {
|
||||
aec3Ref.current = aec3;
|
||||
audioPlayerRef.current?.attachAecRenderTap(aec3);
|
||||
}
|
||||
} catch (error) {
|
||||
appendLog({ text: `Advanced echo cancellation failed to load: ${(error as Error).message}`, kind: "error" });
|
||||
aec3EnabledRef.current = false;
|
||||
setAec3Enabled(false);
|
||||
}
|
||||
if (generation !== micGenerationRef.current) return;
|
||||
}
|
||||
let mic: MicCapture | null = null;
|
||||
try {
|
||||
const mic = new MicCapture(audioContext, {
|
||||
mic = new MicCapture(audioContext, {
|
||||
onFrame: (pcm) => {
|
||||
if (!inputMutedRef.current) socketRef.current?.send(JSON.stringify({ type: "sendAudio", pcm }));
|
||||
// A reconnecting socket is still CONNECTING, where send() throws.
|
||||
if (!inputMutedRef.current && socketRef.current?.readyState === WebSocket.OPEN) {
|
||||
socketRef.current.send(JSON.stringify({ type: "sendAudio", pcm }));
|
||||
}
|
||||
},
|
||||
onActivity: (active) => setSelfActive(active),
|
||||
onLevel: (rms) => {
|
||||
@@ -8188,12 +8358,19 @@ function AppInner() {
|
||||
aec3: aec3Ref.current ?? undefined,
|
||||
});
|
||||
await mic.start();
|
||||
if (generation !== micGenerationRef.current) {
|
||||
mic.stop();
|
||||
return;
|
||||
}
|
||||
micCaptureRef.current?.stop();
|
||||
micCaptureRef.current = mic;
|
||||
setMicOn(true);
|
||||
refreshOutputDevices();
|
||||
refreshInputDevices();
|
||||
connectMicToRecorder();
|
||||
} catch (error) {
|
||||
mic?.stop();
|
||||
if (generation !== micGenerationRef.current) return;
|
||||
appendLog({ text: `Microphone error: ${(error as Error).message}`, kind: "error" });
|
||||
}
|
||||
};
|
||||
@@ -8258,6 +8435,7 @@ function AppInner() {
|
||||
|
||||
const handleToggleAec3 = async () => {
|
||||
if (aec3Enabled) {
|
||||
aec3EnabledRef.current = false;
|
||||
setAec3Enabled(false);
|
||||
teardownAec3();
|
||||
if (micCaptureRef.current) void restartMic({});
|
||||
@@ -8276,11 +8454,13 @@ function AppInner() {
|
||||
const aec3 = await createAec3(audioContext.sampleRate, 2, 1);
|
||||
aec3Ref.current = aec3;
|
||||
audioPlayerRef.current?.attachAecRenderTap(aec3);
|
||||
aec3EnabledRef.current = true;
|
||||
setAec3Enabled(true);
|
||||
if (micCaptureRef.current) await restartMic({});
|
||||
} catch (error) {
|
||||
appendLog({ text: `Advanced echo cancellation failed to load: ${(error as Error).message}`, kind: "error" });
|
||||
teardownAec3();
|
||||
aec3EnabledRef.current = false;
|
||||
setAec3Enabled(false);
|
||||
} finally {
|
||||
setAec3Loading(false);
|
||||
@@ -8361,14 +8541,7 @@ function AppInner() {
|
||||
const blob = encodeWavStereo(mergedLeft, mergedRight, audioContextRef.current?.sampleRate ?? SAMPLE_RATE);
|
||||
const safeServerName = (serverName || "session").replace(/[\\/:*?"<>|]+/g, "_").trim() || "session";
|
||||
const filename = `webspeak3-${safeServerName}-${new Date().toISOString().replace(/[:.]/g, "-")}.wav`;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
downloadBlob(blob, filename);
|
||||
logClient("info", "Recording", `Saved recording as ${filename}`);
|
||||
};
|
||||
|
||||
@@ -8564,14 +8737,7 @@ function AppInner() {
|
||||
const identity = identities.find((i) => i.id === id);
|
||||
if (!identity?.blob) return;
|
||||
const blob = new Blob([identity.blob], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${identity.name.replace(/[^a-z0-9_-]+/gi, "_") || "identity"}.ts3identity.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
downloadBlob(blob, `${identity.name.replace(/[^a-z0-9_-]+/gi, "_") || "identity"}.ts3identity.json`);
|
||||
};
|
||||
|
||||
/** Parses the native client's identity .ini format:
|
||||
@@ -8661,7 +8827,7 @@ function AppInner() {
|
||||
try {
|
||||
JSON.parse(text);
|
||||
} catch {
|
||||
logClient("error", "Identitäten", `"${file.name}" ist keine gültige Identitätsdatei.`);
|
||||
logClient("error", "Identities", t("identity.importInvalid", { file: file.name }));
|
||||
return;
|
||||
}
|
||||
const name = file.name.replace(/\.(ts3identity\.)?json$/i, "") || t("identities.newName");
|
||||
@@ -9103,8 +9269,17 @@ function AppInner() {
|
||||
);
|
||||
};
|
||||
|
||||
// Uploads travel base64-encoded in a single WebSocket message; anything
|
||||
// above the gateway's maxPayload would make it drop the whole connection.
|
||||
const rejectOversizedUpload = (file: File): boolean => {
|
||||
if (file.size <= MAX_UPLOAD_BYTES) return false;
|
||||
appendLog({ text: t("fileBrowser.tooLarge", { mb: String(MAX_UPLOAD_BYTES >> 20) }), kind: "error" });
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleFileBrowserUpload = (file: File) => {
|
||||
if (!fileBrowserTarget) return;
|
||||
if (rejectOversizedUpload(file)) return;
|
||||
const channelId = fileBrowserTarget.channelId;
|
||||
const targetPath = ftJoinPath(fileBrowserPath, file.name);
|
||||
const reader = new FileReader();
|
||||
@@ -9131,6 +9306,7 @@ function AppInner() {
|
||||
};
|
||||
|
||||
const handleServerIconUpload = (iconId: number, file: File) => {
|
||||
if (rejectOversizedUpload(file)) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const result = reader.result as string;
|
||||
@@ -9283,7 +9459,7 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🟢</span>
|
||||
<span className="ts-menu-item-label">{t("menu.connections.connect")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+S</span>
|
||||
<span className="ts-menu-item-shortcut">{t("shortcut.ctrl")}+S</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9295,7 +9471,7 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🔴</span>
|
||||
<span className="ts-menu-item-label">{t("menu.connections.disconnectCurrent")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+D</span>
|
||||
<span className="ts-menu-item-shortcut">{t("shortcut.ctrl")}+D</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9323,7 +9499,7 @@ function AppInner() {
|
||||
<button className="ts-menu-item" onClick={openAddFavorite}>
|
||||
<span className="ts-menu-item-icon">⭐</span>
|
||||
<span className="ts-menu-item-label">{t("menu.favorites.add")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+B</span>
|
||||
<span className="ts-menu-item-shortcut">{t("shortcut.ctrl")}+B</span>
|
||||
</button>
|
||||
<button className="ts-menu-item" onClick={openManageFavorites}>
|
||||
<span className="ts-menu-item-icon">🗂️</span>
|
||||
@@ -9537,7 +9713,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🪪</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.identities")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+I</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9548,7 +9723,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">📇</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.contacts")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+O</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9559,7 +9733,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🔗</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.collectedUrls")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+U</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9582,7 +9755,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🗒️</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.whisperLists")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+W</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9593,7 +9765,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🕓</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.whisperHistory")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+H</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9604,7 +9775,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">📜</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.clientLog")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+L</span>
|
||||
</button>
|
||||
<div className="ts-menu-separator" />
|
||||
<button
|
||||
@@ -9616,7 +9786,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🚫</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.banList")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+B</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9627,7 +9796,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">⚠️</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.complaintList")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+C</span>
|
||||
</button>
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
@@ -9660,7 +9828,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">📄</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.serverLog")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+L</span>
|
||||
</button>
|
||||
<div className="ts-menu-separator" />
|
||||
<button
|
||||
@@ -9673,7 +9840,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">🔴</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.startRecording")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+R</span>
|
||||
</button>
|
||||
<button className="ts-menu-item" disabled>
|
||||
<span className="ts-menu-item-icon">🔴</span>
|
||||
@@ -9689,7 +9855,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">⏹️</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.stopRecording")}</span>
|
||||
<span className="ts-menu-item-shortcut">Strg+Umschalt+T</span>
|
||||
</button>
|
||||
<div className="ts-menu-separator" />
|
||||
<button
|
||||
@@ -9701,7 +9866,6 @@ function AppInner() {
|
||||
>
|
||||
<span className="ts-menu-item-icon">⚙️</span>
|
||||
<span className="ts-menu-item-label">{t("menu.extras.options")}</span>
|
||||
<span className="ts-menu-item-shortcut">Alt+P</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -10045,8 +10209,8 @@ function AppInner() {
|
||||
onServerTypeChange={setServerType}
|
||||
onActiveIdentityChange={handleActiveIdentityChange}
|
||||
onToggleExpanded={() => setConnectDialogExpanded((v) => !v)}
|
||||
onConnect={handleConnect}
|
||||
onConnectNewTab={handleConnect}
|
||||
onConnect={() => handleConnect()}
|
||||
onConnectNewTab={() => handleConnect()}
|
||||
canOpenNewTab={sessionTabs.length > 0 || connected}
|
||||
onCancel={novaSplash ? () => {} : () => setConnectDialogOpen(false)}
|
||||
nova={designTheme === "nova"}
|
||||
@@ -10930,7 +11094,6 @@ function AppInner() {
|
||||
onSelectItem={handleSelectItem}
|
||||
onSwitchChannel={handleSwitchChannel}
|
||||
onOpenPrivateChat={handleOpenPrivateChat}
|
||||
onPokeClient={handlePokeClient}
|
||||
onMoveClient={handleMoveClient}
|
||||
onClientContextMenu={handleClientContextMenu}
|
||||
onChannelContextMenu={handleChannelContextMenu}
|
||||
@@ -11083,9 +11246,9 @@ function AppInner() {
|
||||
{log.slice(-50).map((entry, i) => {
|
||||
let text = entry.text;
|
||||
if (/os[- ]?error\s*10049/i.test(text) || /angeforderte Adresse ist in diesem Kontext ungültig/i.test(text)) {
|
||||
text = "File-Transfer fehlgeschlagen (ungültige Adresse)";
|
||||
text = t("log.fileTransferInvalidAddress");
|
||||
} else {
|
||||
text = text.replace(/^(file transfer failed:\s*)+/i, "File-Transfer fehlgeschlagen: ");
|
||||
text = text.replace(/^(file transfer failed:\s*)+/i, `${t("log.fileTransferFailed")} `);
|
||||
}
|
||||
return (
|
||||
<div key={i} className={entry.kind === "error" ? "ts-log-error" : "ts-log-info"}>
|
||||
|
||||
+11
-4
@@ -37,10 +37,17 @@ function loadScript(src: string): Promise<void> {
|
||||
|
||||
function loadModule(): Promise<Aec3Module> {
|
||||
if (!modulePromise) {
|
||||
modulePromise = loadScript("/vendor/webrtcaec3.js").then(() => {
|
||||
if (!window.WebRtcAec3) throw new Error("AEC3 script loaded but did not register window.WebRtcAec3");
|
||||
return window.WebRtcAec3();
|
||||
});
|
||||
// BASE_URL keeps sub-path deployments (VITE_BASE_PATH) working; a failed
|
||||
// load is forgotten so the next attempt retries instead of reusing it.
|
||||
modulePromise = loadScript(`${import.meta.env.BASE_URL}vendor/webrtcaec3.js`)
|
||||
.then(() => {
|
||||
if (!window.WebRtcAec3) throw new Error("AEC3 script loaded but did not register window.WebRtcAec3");
|
||||
return window.WebRtcAec3();
|
||||
})
|
||||
.catch((err) => {
|
||||
modulePromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return modulePromise;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable react/only-export-components -- provider and its hooks belong together; only costs fast refresh */
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
import de from "./locales/de.json";
|
||||
import en from "./locales/en.json";
|
||||
|
||||
@@ -15,7 +15,7 @@ export type ParsedChannelName = {
|
||||
};
|
||||
|
||||
/** Pure line fillers that look better as a CSS rule than raw `---` / `***`. */
|
||||
const LINE_FILLER_RE = /^[\-\u2013\u2014\u2500\u2501\u2550=\*\.·_\s]+$/;
|
||||
const LINE_FILLER_RE = /^[-\u2013\u2014\u2500\u2501\u2550=*.·_\s]+$/;
|
||||
|
||||
/** Corners / verticals of box-frame spacers (not pure horizontal fills). */
|
||||
const BOX_FRAME_RE = /[╔╗╚╝╒╓╕╖╘╙╛╜┌┐└┘├┤┬┴┼║│╟╢╤╧╪╫╬╒╓╕╖╘╙╛╜]/;
|
||||
|
||||
+14
-2
@@ -52,7 +52,7 @@
|
||||
"feedback.dialog.reportHint": "Meldungen bleiben privat und werden nie als GitHub-Issue veröffentlicht. Gib bei Bedarf den betroffenen Server mit an.",
|
||||
"feedback.dialog.message": "Nachricht",
|
||||
"feedback.dialog.messagePlaceholder": "Was ist passiert, oder was schlägst du vor?",
|
||||
"feedback.dialog.email": "E-Mail (optional, für Rückfragen)",
|
||||
"feedback.dialog.email": "E-Mail (optional, für Rückfragen – bleibt privat, wird nie veröffentlicht)",
|
||||
"feedback.dialog.publishAsIssue": "Als öffentliches GitHub-Issue veröffentlichen",
|
||||
"feedback.dialog.publishAsIssueHint": "Ohne Haken bleibt dein Feedback privat und geht nur an den Betreiber.",
|
||||
"feedback.dialog.publishAsIssueHintBug": "Fehlermeldungen werden immer als öffentliches GitHub-Issue veröffentlicht.",
|
||||
@@ -315,6 +315,7 @@
|
||||
"design.store.publish.adminTokenPlaceholder": "Leer lassen, außer du weißt, was das ist",
|
||||
"design.store.publish.submit": "Im Store veröffentlichen",
|
||||
"design.store.publish.success": "Design wurde veröffentlicht!",
|
||||
"design.store.publish.pending": "Danke! Dein Design wurde eingereicht und erscheint im Store, sobald es geprüft wurde.",
|
||||
"design.store.publish.error": "Veröffentlichen fehlgeschlagen.",
|
||||
"options.section.erweiterungen": "Erweiterungen",
|
||||
"options.section.hotkeys": "Hotkeys",
|
||||
@@ -575,6 +576,7 @@
|
||||
"channelContext.files": "Dateien...",
|
||||
"fileBrowser.title": "Dateitransfers",
|
||||
"fileBrowser.up": "Nach oben",
|
||||
"fileBrowser.tooLarge": "Datei zu groß – höchstens {mb} MiB pro Upload.",
|
||||
"fileBrowser.refresh": "Aktualisieren",
|
||||
"fileBrowser.newFolder": "Neuer Ordner",
|
||||
"fileBrowser.upload": "Hochladen",
|
||||
@@ -646,5 +648,15 @@
|
||||
"nachrichten.templateName": "Vorlagenname",
|
||||
"nachrichten.message": "Nachricht",
|
||||
"nachrichten.add": "Hinzufügen",
|
||||
"nachrichten.delete": "Löschen"
|
||||
"nachrichten.delete": "Löschen",
|
||||
"tree.expand": "Aufklappen",
|
||||
"tree.collapse": "Zuklappen",
|
||||
"tabs.disconnect": "Verbindung trennen",
|
||||
"tabs.closeTab": "Tab schließen: {label}",
|
||||
"identity.importInvalid": "„{file}“ ist keine gültige Identitätsdatei.",
|
||||
"log.fileTransferFailed": "Dateiübertragung fehlgeschlagen:",
|
||||
"log.fileTransferInvalidAddress": "Dateiübertragung fehlgeschlagen (ungültige Adresse)",
|
||||
"sounds.importFailed": "Das Soundpack konnte nicht gelesen werden – ist es eine gültige .ts3soundpack-/ZIP-Datei?",
|
||||
"tabs.connections": "Server-Verbindungen",
|
||||
"shortcut.ctrl": "Strg"
|
||||
}
|
||||
+14
-2
@@ -52,7 +52,7 @@
|
||||
"feedback.dialog.reportHint": "Reports stay private and are never published as a GitHub issue. Feel free to name the affected server.",
|
||||
"feedback.dialog.message": "Message",
|
||||
"feedback.dialog.messagePlaceholder": "What happened, or what are you suggesting?",
|
||||
"feedback.dialog.email": "Email (optional, for follow-up)",
|
||||
"feedback.dialog.email": "Email (optional, for follow-up – stays private, never published)",
|
||||
"feedback.dialog.publishAsIssue": "Publish as a public GitHub issue",
|
||||
"feedback.dialog.publishAsIssueHint": "Leave unchecked to keep your feedback private, visible only to the maintainer.",
|
||||
"feedback.dialog.publishAsIssueHintBug": "Bug reports are always published as a public GitHub issue.",
|
||||
@@ -315,6 +315,7 @@
|
||||
"design.store.publish.adminTokenPlaceholder": "Leave empty unless you know what this is",
|
||||
"design.store.publish.submit": "Publish to the store",
|
||||
"design.store.publish.success": "Design published!",
|
||||
"design.store.publish.pending": "Thanks! Your design was submitted and will appear in the store once it has been reviewed.",
|
||||
"design.store.publish.error": "Publishing failed.",
|
||||
"options.section.erweiterungen": "Addons",
|
||||
"options.section.hotkeys": "Hotkeys",
|
||||
@@ -575,6 +576,7 @@
|
||||
"channelContext.files": "Files...",
|
||||
"fileBrowser.title": "File Transfers",
|
||||
"fileBrowser.up": "Up",
|
||||
"fileBrowser.tooLarge": "File too large – uploads are limited to {mb} MiB.",
|
||||
"fileBrowser.refresh": "Refresh",
|
||||
"fileBrowser.newFolder": "New Folder",
|
||||
"fileBrowser.upload": "Upload",
|
||||
@@ -646,5 +648,15 @@
|
||||
"nachrichten.templateName": "Template name",
|
||||
"nachrichten.message": "Message",
|
||||
"nachrichten.add": "Add",
|
||||
"nachrichten.delete": "Delete"
|
||||
"nachrichten.delete": "Delete",
|
||||
"tree.expand": "Expand",
|
||||
"tree.collapse": "Collapse",
|
||||
"tabs.disconnect": "Disconnect",
|
||||
"tabs.closeTab": "Close tab: {label}",
|
||||
"identity.importInvalid": "\"{file}\" is not a valid identity file.",
|
||||
"log.fileTransferFailed": "File transfer failed:",
|
||||
"log.fileTransferInvalidAddress": "File transfer failed (invalid address)",
|
||||
"sounds.importFailed": "Could not read this soundpack - is it a valid .ts3soundpack/ZIP file?",
|
||||
"tabs.connections": "Server connections",
|
||||
"shortcut.ctrl": "Ctrl"
|
||||
}
|
||||
+14
-2
@@ -52,7 +52,7 @@
|
||||
"feedback.dialog.reportHint": "گزارشها همیشه خصوصی میمانند و هرگز بهصورت Issue عمومی در گیتهاب منتشر نمیشوند. در صورت نیاز میتوانی نام سرور مربوطه را ذکر کنی.",
|
||||
"feedback.dialog.message": "پیام",
|
||||
"feedback.dialog.messagePlaceholder": "چه اتفاقی افتاد، یا چه پیشنهادی داری؟",
|
||||
"feedback.dialog.email": "ایمیل (اختیاری، برای پیگیری)",
|
||||
"feedback.dialog.email": "ایمیل (اختیاری، برای پیگیری – خصوصی میماند و هرگز منتشر نمیشود)",
|
||||
"feedback.dialog.publishAsIssue": "بهصورت Issue عمومی در گیتهاب منتشر شود",
|
||||
"feedback.dialog.publishAsIssueHint": "اگر تیک نزنی، بازخوردت خصوصی میماند و فقط برای مدیر پروژه قابل مشاهده است.",
|
||||
"feedback.dialog.publishAsIssueHintBug": "گزارش اشکالها همیشه بهصورت Issue عمومی در گیتهاب منتشر میشوند.",
|
||||
@@ -315,6 +315,7 @@
|
||||
"design.store.publish.adminTokenPlaceholder": "اگر نمیدانی این چیست، خالی بگذار",
|
||||
"design.store.publish.submit": "انتشار در فروشگاه",
|
||||
"design.store.publish.success": "طراحی منتشر شد!",
|
||||
"design.store.publish.pending": "ممنون! طراحی تو ارسال شد و پس از بررسی در فروشگاه نمایش داده میشود.",
|
||||
"design.store.publish.error": "انتشار ناموفق بود.",
|
||||
"options.section.erweiterungen": "افزونهها",
|
||||
"options.section.hotkeys": "کلیدهای میانبر",
|
||||
@@ -574,6 +575,7 @@
|
||||
"channelContext.files": "فایلها...",
|
||||
"fileBrowser.title": "انتقال فایل",
|
||||
"fileBrowser.up": "بالا",
|
||||
"fileBrowser.tooLarge": "فایل خیلی بزرگ است – حداکثر {mb} مگابایت برای هر آپلود.",
|
||||
"fileBrowser.refresh": "بارگذاری مجدد",
|
||||
"fileBrowser.newFolder": "پوشه جدید",
|
||||
"fileBrowser.upload": "بارگذاری",
|
||||
@@ -645,5 +647,15 @@
|
||||
"nachrichten.templateName": "نام الگو",
|
||||
"nachrichten.message": "پیام",
|
||||
"nachrichten.add": "افزودن",
|
||||
"nachrichten.delete": "حذف"
|
||||
"nachrichten.delete": "حذف",
|
||||
"tree.expand": "باز کردن",
|
||||
"tree.collapse": "بستن",
|
||||
"tabs.disconnect": "قطع اتصال",
|
||||
"tabs.closeTab": "بستن زبانه: {label}",
|
||||
"identity.importInvalid": "«{file}» یک فایل هویت معتبر نیست.",
|
||||
"log.fileTransferFailed": "انتقال فایل ناموفق بود:",
|
||||
"log.fileTransferInvalidAddress": "انتقال فایل ناموفق بود (نشانی نامعتبر)",
|
||||
"sounds.importFailed": "این بسته صدا خوانده نشد - آیا یک فایل .ts3soundpack/ZIP معتبر است؟",
|
||||
"tabs.connections": "اتصالهای سرور",
|
||||
"shortcut.ctrl": "Ctrl"
|
||||
}
|
||||
@@ -431,6 +431,7 @@
|
||||
"channelContext.files": "文件...",
|
||||
"fileBrowser.title": "文件传输",
|
||||
"fileBrowser.up": "上一级",
|
||||
"fileBrowser.tooLarge": "文件过大——每次上传最多 {mb} MiB。",
|
||||
"fileBrowser.refresh": "刷新",
|
||||
"fileBrowser.newFolder": "新建文件夹",
|
||||
"fileBrowser.upload": "上传",
|
||||
@@ -522,7 +523,7 @@
|
||||
"feedback.dialog.reportHint": "举报内容保持私密,不会作为 GitHub Issue 公开。如有需要可注明相关服务器。",
|
||||
"feedback.dialog.message": "消息",
|
||||
"feedback.dialog.messagePlaceholder": "发生了什么,或者你有什么建议?",
|
||||
"feedback.dialog.email": "邮箱(可选,用于回复)",
|
||||
"feedback.dialog.email": "邮箱(可选,用于回复——仅私下保存,绝不公开)",
|
||||
"feedback.dialog.publishAsIssue": "作为公开的 GitHub Issue 发布",
|
||||
"feedback.dialog.publishAsIssueHint": "不勾选则反馈保持私密,仅维护者可见。",
|
||||
"feedback.dialog.publishAsIssueHintBug": "错误报告将始终作为公开的 GitHub Issue 发布。",
|
||||
@@ -597,6 +598,7 @@
|
||||
"design.store.publish.adminTokenPlaceholder": "不确定的话请留空",
|
||||
"design.store.publish.submit": "发布到商店",
|
||||
"design.store.publish.success": "设计已发布!",
|
||||
"design.store.publish.pending": "谢谢!你的设计已提交,审核通过后将显示在商店中。",
|
||||
"design.store.publish.error": "发布失败。",
|
||||
"recording.autoGainControl": "自动增益控制",
|
||||
"tree.streaming": "正在直播",
|
||||
@@ -645,5 +647,15 @@
|
||||
"stream.state.disconnected": "连接中断",
|
||||
"stream.state.failed": "连接失败",
|
||||
"stream.state.closed": "已结束",
|
||||
"clientContext.watchStream": "观看直播"
|
||||
"clientContext.watchStream": "观看直播",
|
||||
"tree.expand": "展开",
|
||||
"tree.collapse": "折叠",
|
||||
"tabs.disconnect": "断开连接",
|
||||
"tabs.closeTab": "关闭标签页:{label}",
|
||||
"identity.importInvalid": "“{file}”不是有效的身份文件。",
|
||||
"log.fileTransferFailed": "文件传输失败:",
|
||||
"log.fileTransferInvalidAddress": "文件传输失败(地址无效)",
|
||||
"sounds.importFailed": "无法读取此音效包——它是有效的 .ts3soundpack/ZIP 文件吗?",
|
||||
"tabs.connections": "服务器连接",
|
||||
"shortcut.ctrl": "Ctrl"
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import './storageFallback'
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// With storage blocked (privacy settings, some embedded webviews) merely
|
||||
// touching `localStorage` throws, and dozens of module-level reads would
|
||||
// leave a blank page. Swap in an in-memory stand-in so the app runs; settings
|
||||
// just don't survive a reload then. Imported first thing in main.tsx.
|
||||
try {
|
||||
const probe = "__webspeak3_probe__";
|
||||
localStorage.setItem(probe, probe);
|
||||
localStorage.removeItem(probe);
|
||||
} catch {
|
||||
const data = new Map<string, string>();
|
||||
const memory: Storage = {
|
||||
get length() {
|
||||
return data.size;
|
||||
},
|
||||
key: (i) => [...data.keys()][i] ?? null,
|
||||
getItem: (k) => data.get(k) ?? null,
|
||||
setItem: (k, v) => void data.set(k, String(v)),
|
||||
removeItem: (k) => void data.delete(k),
|
||||
clear: () => data.clear(),
|
||||
};
|
||||
Object.defineProperty(window, "localStorage", { value: memory, configurable: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useT } from "../../i18n";
|
||||
|
||||
export type ConnectionTabItem = {
|
||||
id: string;
|
||||
@@ -39,11 +40,12 @@ export function GreenteaSpeakChrome({
|
||||
: []);
|
||||
|
||||
const hasTabs = resolvedTabs.length > 0;
|
||||
const t = useT();
|
||||
|
||||
return (
|
||||
<>
|
||||
{hasTabs ? (
|
||||
<div className="gts-connection-tabs" role="tablist" aria-label="Server-Verbindungen">
|
||||
<div className="gts-connection-tabs" role="tablist" aria-label={t("tabs.connections")}>
|
||||
{resolvedTabs.map((tab) => {
|
||||
const isActive = tab.id === (activeTabId ?? resolvedTabs[0]?.id);
|
||||
return (
|
||||
@@ -62,8 +64,8 @@ export function GreenteaSpeakChrome({
|
||||
<button
|
||||
type="button"
|
||||
className="gts-connection-tab-close"
|
||||
title="Verbindung trennen"
|
||||
aria-label={`Tab schließen: ${tab.label}`}
|
||||
title={t("tabs.disconnect")}
|
||||
aria-label={t("tabs.closeTab", { label: tab.label })}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCloseTab(tab.id);
|
||||
|
||||
@@ -95,6 +95,11 @@ export default defineConfig({
|
||||
// ignores non-GET and non-http(s) requests (ws:// isn't touched), so
|
||||
// no extra runtimeCaching exclusions are needed here.
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
|
||||
// The SPA fallback answers every navigation with index.html — except
|
||||
// the gateway's own pages under /api/ (e.g. /api/store/admin), which
|
||||
// would otherwise open the client instead when UI and gateway share
|
||||
// an origin.
|
||||
navigateFallbackDenylist: [/^\/api\//],
|
||||
},
|
||||
}),
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user