diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index c7c9dfc..fdb236a 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -56,6 +56,7 @@ jobs: context: . push: true tags: ${{ steps.tags.outputs.tags }} + build-args: WEBSPEAK3_VERSION=${{ github.event.release.tag_name || 'latest' }} platforms: linux/amd64,linux/arm64 cache-from: type=gha cache-to: type=gha,mode=max diff --git a/Dockerfile b/Dockerfile index 5a9bd50..2fa92fd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -90,6 +90,10 @@ COPY --from=connector-builder /src/connector/target/*/release/ts-connector /app/ COPY --from=web-builder /src/web/dist /app/web/dist ENV PORT=8080 +# Release tag, set by .github/workflows/docker-publish.yml. Only used for the +# anonymous usage ping (gateway/src/telemetry.ts). +ARG WEBSPEAK3_VERSION=unknown +ENV WEBSPEAK3_VERSION=$WEBSPEAK3_VERSION ENV WEB_DIST=/app/web/dist ENV CONNECTOR_BIN=/app/connector-bin/ts-connector EXPOSE 8080 diff --git a/README.md b/README.md index 02dcece..d7e8aa8 100644 --- a/README.md +++ b/README.md @@ -209,6 +209,9 @@ All optional; add them under `environment:` in your compose override next to `PO | `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. | | `CONNECT_RATE_LIMIT` | `30` | Server connects per client IP per minute. Each one starts a new TeamSpeak session, so this stops anyone from flooding a server through your gateway. `0` disables it. | | `TRUST_PROXY` | off | Only when the gateway is reachable **solely** through a proxy/tunnel, so per-IP limits see the real client instead of the proxy: `cloudflare` (Cloudflare Tunnel or proxy) uses `CF-Connecting-IP`; `1` (your own nginx/Caddy/Traefik) uses the last `X-Forwarded-For` entry, the one your proxy appended. Don't set it on a directly exposed gateway - clients could then fake their IP. | +| `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). | + +> **Anonymous usage ping:** when the gateway starts and then once a day, it sends a random instance ID (made up on first start, stored in `instance-id` in the working directory, used for nothing else) and its version number to `gateway.webspeak3.de`. That's the only way to tell whether anyone self-hosts WebSpeak3 at all, and how many instances still run an old version, e.g. after a security fix. Nothing else is sent: no hostnames, no TeamSpeak servers, no users, no settings. The receiving side doesn't store IP addresses. The startup log says when it's on. Turn it off with `TELEMETRY=0`. > **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. diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 59e97e1..0261f8f 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -10,6 +10,7 @@ import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/co import { handleStore } from "./store.js"; import { logFeedback, logConnectionEvent } from "./activity-log.js"; import { clientIp, createRateLimiter } from "./net.js"; +import "./telemetry.js"; const SERVER_TYPES = new Set(["teamspeak", "teaspeak", "auto"]); diff --git a/gateway/src/ping.ts b/gateway/src/ping.ts new file mode 100644 index 0000000..805449f --- /dev/null +++ b/gateway/src/ping.ts @@ -0,0 +1,94 @@ +// --- Receiving end of telemetry.ts --------------------------------------------- +// +// Only served by store-server.ts, and only with PING_DATA_FILE set. Keeps one +// row per instance id: version, first and last seen. No IP addresses, no +// request log. The admin view returns counts only. +import type { IncomingMessage, ServerResponse } from "node:http"; +import { readFile, rename, writeFile } from "node:fs/promises"; +import { clientIp, createRateLimiter } from "./net.js"; +import { isAdminRequest } from "./store.js"; + +const PING_DATA_FILE = process.env.PING_DATA_FILE; +const MAX_INSTANCES = 20_000; +const DAY_MS = 24 * 60 * 60 * 1000; +const isRateLimited = createRateLimiter(20, 60 * 60 * 1000); + +interface Instance { + version: string; + firstSeen: string; + lastSeen: string; +} + +let cache: Record | null = null; + +async function load(): Promise> { + if (cache) return cache; + try { + cache = JSON.parse(await readFile(PING_DATA_FILE!, "utf-8")) as Record; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; + cache = {}; + } + return cache; +} + +async function save(instances: Record) { + // Instances silent for 90 days are gone for good. + const cutoff = Date.now() - 90 * DAY_MS; + for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id]; + const tmp = `${PING_DATA_FILE}.tmp`; + await writeFile(tmp, JSON.stringify(instances), "utf-8"); + await rename(tmp, PING_DATA_FILE!); +} + +function json(res: ServerResponse, status: number, body: unknown) { + res.writeHead(status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); +} + +export async function handlePing(req: IncomingMessage, res: ServerResponse, pathname: string) { + if (!PING_DATA_FILE) return json(res, 404, { error: "not_found" }); + + if (pathname === "/api/ping/stats" && req.method === "GET") { + if (!isAdminRequest(req)) return json(res, 401, { error: "unauthorized" }); + const now = Date.now(); + const instances = Object.values(await load()); + const activeSince = (days: number) => instances.filter((i) => now - Date.parse(i.lastSeen) < days * DAY_MS); + const versions: Record = {}; + for (const i of activeSince(30)) versions[i.version] = (versions[i.version] ?? 0) + 1; + return json(res, 200, { + active2d: activeSince(2).length, + active7d: activeSince(7).length, + active30d: activeSince(30).length, + newLast7d: instances.filter((i) => now - Date.parse(i.firstSeen) < 7 * DAY_MS).length, + versions, + }); + } + + if (pathname !== "/api/ping" || req.method !== "POST") return json(res, 405, { error: "method_not_allowed" }); + if (isRateLimited(clientIp(req))) return json(res, 429, { error: "rate_limited" }); + + let raw = ""; + for await (const chunk of req) { + raw += chunk; + if (raw.length > 500) return json(res, 413, { error: "payload_too_large" }); + } + let body: { id?: unknown; version?: unknown }; + try { + body = JSON.parse(raw || "{}"); + } catch { + return json(res, 400, { error: "invalid_json" }); + } + const { id, version } = body; + if (typeof id !== "string" || !/^[0-9a-f-]{36}$/.test(id) || typeof version !== "string" || !/^[\w.+-]{1,40}$/.test(version)) { + return json(res, 400, { error: "invalid_ping" }); + } + + const instances = await load(); + const now = new Date().toISOString(); + const known = instances[id]; + if (!known && Object.keys(instances).length >= MAX_INSTANCES) return json(res, 507, { error: "full" }); + instances[id] = { version, firstSeen: known?.firstSeen ?? now, lastSeen: now }; + await save(instances); + json(res, 200, { ok: true }); +} diff --git a/gateway/src/store-server.ts b/gateway/src/store-server.ts index 0e8c43f..debe1bf 100644 --- a/gateway/src/store-server.ts +++ b/gateway/src/store-server.ts @@ -6,6 +6,7 @@ // and the reverse proxy routes /api/store/* here. import { createServer } from "node:http"; import { handleStore } from "./store.js"; +import { handlePing } from "./ping.js"; const PORT = Number(process.env.PORT ?? 8080); @@ -27,6 +28,16 @@ createServer((req, res) => { }); return; } + if (pathname === "/api/ping" || pathname === "/api/ping/stats") { + handlePing(req, res, pathname).catch((err) => { + console.error("[ping] Request failed:", err); + if (!res.headersSent) { + res.writeHead(500, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "internal" })); + } + }); + return; + } res.writeHead(404, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "not_found" })); }).listen(PORT, () => console.log(`WebSpeak3 store listening on http://localhost:${PORT}`)); diff --git a/gateway/src/store.ts b/gateway/src/store.ts index 73124b2..538f588 100644 --- a/gateway/src/store.ts +++ b/gateway/src/store.ts @@ -136,7 +136,7 @@ async function saveStoreThemes(themes: StoreTheme[]): Promise { await rename(tmp, STORE_DATA_FILE); } -function isAdminRequest(req: IncomingMessage): boolean { +export function isAdminRequest(req: IncomingMessage): boolean { const authHeader = req.headers.authorization ?? ""; return authHeader.startsWith("Bearer ") && isValidStoreAdminToken(authHeader.slice("Bearer ".length)); } diff --git a/gateway/src/telemetry.ts b/gateway/src/telemetry.ts new file mode 100644 index 0000000..d4753bd --- /dev/null +++ b/gateway/src/telemetry.ts @@ -0,0 +1,57 @@ +// --- Anonymous usage ping ---------------------------------------------------- +// +// Once at startup and then once a day, the gateway tells webspeak3.de that an +// instance is running. That's the only way to know whether anyone self-hosts +// at all, and which versions are still out there (e.g. before dropping +// support for something or after a security fix). +// +// Sent: a random instance id (generated here, used for nothing else) and the +// version. Not sent: hostnames, TeamSpeak servers, user counts, settings. +// The receiving side stores no IP addresses (see ping.ts). +// +// On by default, off with TELEMETRY=0. Said so in the startup log, too. +import { readFile, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import path from "node:path"; + +const TELEMETRY_URL = process.env.TELEMETRY_URL || "https://gateway.webspeak3.de/api/ping"; +const VERSION = process.env.WEBSPEAK3_VERSION || "unknown"; +// ponytail: without a volume over the working directory a container recreate +// makes a new id, so an update counts twice for a day or so. +const ID_FILE = process.env.TELEMETRY_ID_FILE ?? path.resolve(process.cwd(), "instance-id"); +const DAY_MS = 24 * 60 * 60 * 1000; + +async function instanceId(): Promise { + try { + const id = (await readFile(ID_FILE, "utf-8")).trim(); + if (/^[0-9a-f-]{36}$/.test(id)) return id; + } catch { + // first start - fall through + } + const id = randomUUID(); + await writeFile(ID_FILE, id + "\n").catch(() => {}); + return id; +} + +async function ping(id: string) { + try { + await fetch(TELEMETRY_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id, version: VERSION }), + signal: AbortSignal.timeout(10_000), + }); + } catch { + // Offline or blocked - not worth a log line every day. + } +} + +if (process.env.TELEMETRY !== "0") { + console.log( + `Sending an anonymous usage ping (random instance id + version ${VERSION}) to ${new URL(TELEMETRY_URL).host} at startup and once a day. Disable with TELEMETRY=0.` + ); + void instanceId().then((id) => { + void ping(id); + setInterval(() => void ping(id), DAY_MS).unref(); + }); +}