From 120d3dfc8242a77348b480a415bdbda85f3aadea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 14:30:44 +0000 Subject: [PATCH] M4: tsgw gateway and tsc-gateway-proto - tsc-gateway-proto: versioned JSON envelope (tsgw.v1+json), client and server messages, identity-challenge auth (ECDSA P-256 over a signed challenge), unique ids for TS3 (SHA-1) and TS6 (SHA-256, verified on 6.0.0-beta13.1), hash-cash level. - tsc-gateway (tsgw): axum WebSocket server; hub with one observer, a relay pool and a lookup query session; login by signature or token; permission mirroring via permoverview (server group/client/channel group/channel-client levels, skip and negate); per-user filtered presence (snapshot + diff deltas); channel/server chat relay with server-known nicknames, rate limit, idle relay teardown, pinned channels; SQLite tokens, history and audit; Dockerfile; admin guide. - tsctl gateway client; smoke test covers gateway presence, chat both ways and refusal of unknown identities on TS3 and TS6. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 263 ++++++++++++- Cargo.toml | 4 + README.md | 15 +- crates/tsc-gateway-proto/Cargo.toml | 25 ++ crates/tsc-gateway-proto/src/auth.rs | 160 ++++++++ crates/tsc-gateway-proto/src/lib.rs | 26 ++ crates/tsc-gateway-proto/src/messages.rs | 185 +++++++++ crates/tsc-gateway/Cargo.toml | 40 ++ crates/tsc-gateway/Dockerfile | 14 + crates/tsc-gateway/src/config.rs | 245 ++++++++++++ crates/tsc-gateway/src/db.rs | 193 ++++++++++ crates/tsc-gateway/src/hub.rs | 462 +++++++++++++++++++++++ crates/tsc-gateway/src/main.rs | 65 ++++ crates/tsc-gateway/src/perms.rs | 234 ++++++++++++ crates/tsc-gateway/src/session.rs | 242 ++++++++++++ crates/tsc-gateway/tsgw.example.toml | 43 +++ dev/tsgw-ts3.toml | 22 ++ dev/tsgw-ts6.toml | 22 ++ docs/gateway-admin.md | 77 ++++ docs/protocol-notes/ts6-streaming.md | 5 + scripts/it-smoke.sh | 50 ++- tools/tsctl/Cargo.toml | 3 + tools/tsctl/src/gateway.rs | 187 +++++++++ tools/tsctl/src/main.rs | 5 + 24 files changed, 2578 insertions(+), 9 deletions(-) create mode 100644 crates/tsc-gateway-proto/Cargo.toml create mode 100644 crates/tsc-gateway-proto/src/auth.rs create mode 100644 crates/tsc-gateway-proto/src/lib.rs create mode 100644 crates/tsc-gateway-proto/src/messages.rs create mode 100644 crates/tsc-gateway/Cargo.toml create mode 100644 crates/tsc-gateway/Dockerfile create mode 100644 crates/tsc-gateway/src/config.rs create mode 100644 crates/tsc-gateway/src/db.rs create mode 100644 crates/tsc-gateway/src/hub.rs create mode 100644 crates/tsc-gateway/src/main.rs create mode 100644 crates/tsc-gateway/src/perms.rs create mode 100644 crates/tsc-gateway/src/session.rs create mode 100644 crates/tsc-gateway/tsgw.example.toml create mode 100644 dev/tsgw-ts3.toml create mode 100644 dev/tsgw-ts6.toml create mode 100644 docs/gateway-admin.md create mode 100644 tools/tsctl/src/gateway.rs diff --git a/Cargo.lock b/Cargo.lock index e67a73f..09de061 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -400,6 +400,61 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "az" version = "1.3.0" @@ -1721,6 +1776,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -1730,7 +1797,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.1", "wasm-bindgen", ] @@ -2031,6 +2098,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -2057,6 +2130,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2529,6 +2603,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "md5" version = "0.8.1" @@ -3477,6 +3557,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -3490,10 +3576,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.3" @@ -3515,6 +3611,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -3524,6 +3630,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" @@ -3851,7 +3966,7 @@ dependencies = [ "salsa20", "scrypt", "sec1 0.8.1", - "sha1", + "sha1 0.11.0", "sha2 0.11.0", "sha3 0.12.0", "signature 3.0.0", @@ -4190,6 +4305,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -4243,6 +4369,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1" version = "0.11.0" @@ -4487,7 +4624,7 @@ dependencies = [ "rand_core 0.10.1", "rsa", "sec1 0.8.1", - "sha1", + "sha1 0.11.0", "sha2 0.11.0", "signature 3.0.0", "ssh-cipher", @@ -4727,6 +4864,7 @@ dependencies = [ "bytes", "libc", "mio", + "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", @@ -4766,6 +4904,30 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -4844,6 +5006,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -4882,6 +5045,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -4990,6 +5154,47 @@ dependencies = [ "tsproto-packets", ] +[[package]] +name = "tsc-gateway" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64 0.22.1", + "clap", + "futures", + "rand 0.10.3", + "rusqlite", + "serde", + "serde_json", + "sha2 0.10.9", + "thiserror 2.0.21", + "tokio", + "tokio-tungstenite 0.30.0", + "toml", + "tracing", + "tracing-subscriber", + "tsc-gateway-proto", + "tsc-model", + "tsc-observer", + "tsc-query", +] + +[[package]] +name = "tsc-gateway-proto" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "serde", + "serde_json", + "sha-1", + "sha2 0.10.9", + "thiserror 2.0.21", + "tsc-model", + "tsproto", + "tsproto-types", +] + [[package]] name = "tsc-model" version = "0.1.0" @@ -5077,11 +5282,14 @@ dependencies = [ "clap", "dirs", "futures", + "futures-util", "serde_json", "tokio", + "tokio-tungstenite 0.30.0", "tracing", "tracing-subscriber", "tsc-audio", + "tsc-gateway-proto", "tsc-model", "tsc-observer", "tsc-query", @@ -5176,6 +5384,38 @@ dependencies = [ "tsproto-structs", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1 0.10.7", + "thiserror 2.0.21", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.3", + "sha1 0.11.0", + "thiserror 2.0.21", +] + [[package]] name = "typenum" version = "1.20.1" @@ -5311,6 +5551,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -5667,6 +5916,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "wnaf" version = "0.14.1" diff --git a/Cargo.toml b/Cargo.toml index fa34fa5..810a2a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,8 @@ members = [ "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", "crates/tsc-audio", + "crates/tsc-gateway", + "crates/tsc-gateway-proto", "crates/tsc-model", "crates/tsc-observer", "crates/tsc-query", @@ -23,6 +25,8 @@ default-members = [ "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", "crates/tsc-audio", + "crates/tsc-gateway", + "crates/tsc-gateway-proto", "crates/tsc-model", "crates/tsc-observer", "crates/tsc-query", diff --git a/README.md b/README.md index 2a33210..fec94a5 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ See [docs/architecture.md](docs/architecture.md) for the design and milestones. ## Status -Done so far (milestones M0–M3 of [the plan](docs/architecture.md#milestones)): +Done so far (milestones M0–M4 of [the plan](docs/architecture.md#milestones)): - `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes; @@ -33,11 +33,14 @@ Done so far (milestones M0–M3 of [the plan](docs/architecture.md#milestones)): - `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets - `crates/tsc-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive) - `crates/tsc-observer`: invisible presence (events or polling) and channel-chat relays over ServerQuery +- `crates/tsc-gateway` (`tsgw`) + `tsc-gateway-proto`: companion gateway for server admins. Users log in + with their TeamSpeak identity and get presence, channel chat and history without joining voice, + limited by their server permissions ([admin guide](docs/gateway-admin.md)) - `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events, - `query`, `observe` (invisible presence) and `relay` (channel chat without joining) + `query`, `observe` (invisible presence), `relay` (channel chat without joining) and `gateway` - `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh` - checks tree, server chat, channel chat, a voice tone round-trip, invisible presence - and relay chat on both + checks tree, server chat, channel chat, a voice tone round-trip, invisible presence, + relay chat and the gateway on both - `fuzz/`: cargo-fuzz targets for packets, commands and the license chain No GUI and no screen sharing yet. @@ -58,6 +61,10 @@ cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav cargo run -p tsctl -- observe ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted cargo run -p tsctl -- relay ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted --channel 1 +# Gateway: users without voice, logging in with their identity +cargo run -p tsc-gateway -- --config dev/tsgw-ts6.toml & +cargo run -p tsctl -- gateway ws://127.0.0.1:7788/v1 --identity --presence --open channel:1 + scripts/it-smoke.sh # all of the above, on both servers ``` diff --git a/crates/tsc-gateway-proto/Cargo.toml b/crates/tsc-gateway-proto/Cargo.toml new file mode 100644 index 0000000..0bad230 --- /dev/null +++ b/crates/tsc-gateway-proto/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "tsc-gateway-proto" +version = "0.1.0" +description = "Wire protocol and identity-challenge authentication of the tsgw gateway." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +base64 = "0.22" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha1 = { package = "sha-1", version = "0.10" } +sha2 = "0.10" +thiserror = "2" +tsc-model = { path = "../tsc-model" } +tsproto-types = { path = "../proto/tsproto-types" } + +[lints] +workspace = true + +[dev-dependencies] +tsproto = { path = "../proto/tsproto" } diff --git a/crates/tsc-gateway-proto/src/auth.rs b/crates/tsc-gateway-proto/src/auth.rs new file mode 100644 index 0000000..c5c61d2 --- /dev/null +++ b/crates/tsc-gateway-proto/src/auth.rs @@ -0,0 +1,160 @@ +//! Identity-challenge authentication. + +use base64::prelude::*; +use sha1::{Digest, Sha1}; +use sha2::Sha256; +use tsproto_types::crypto::{EccKeyPrivP256, EccKeyPubP256}; + +/// Maximum allowed difference between the client's and our clock. +pub const MAX_CLOCK_SKEW_SECS: i64 = 60; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum AuthError { + #[error("invalid public key")] + BadKey, + #[error("invalid signature")] + BadSignature, + #[error("timestamp too far from the gateway's clock")] + ClockSkew, +} + +/// The bytes a client signs. +pub fn challenge(gateway_id: &str, server_uid: &str, nonce: &str, ts: i64) -> Vec { + format!("tsgw-auth-v1\n{gateway_id}\n{server_uid}\n{nonce}\n{ts}").into_bytes() +} + +/// Client side: sign the challenge with the identity key (base64 DER). +pub fn sign_challenge( + key: &EccKeyPrivP256, + gateway_id: &str, + server_uid: &str, + nonce: &str, + ts: i64, +) -> String { + BASE64_STANDARD.encode(key.clone().sign(&challenge(gateway_id, server_uid, nonce, ts))) +} + +/// The unique ids a TeamSpeak identity has on the two server generations. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UniqueIds { + /// TeamSpeak 3: `base64(SHA1(omega))`. + pub ts3: String, + /// TeamSpeak 6: `base64(SHA256(omega))` (verified on 6.0.0-beta13.1). + pub ts6: String, +} + +impl UniqueIds { + pub fn from_omega(omega: &str) -> Self { + Self { + ts3: BASE64_STANDARD.encode(Sha1::digest(omega.as_bytes())), + ts6: BASE64_STANDARD.encode(Sha256::digest(omega.as_bytes())), + } + } + + /// The id the given server knows the identity by. + pub fn for_server(&self, is_ts6: bool) -> &str { + if is_ts6 { &self.ts6 } else { &self.ts3 } + } +} + +/// Gateway side: check the signature and clock, return the identity's ids. +pub fn verify_auth( + omega: &str, + signature: &str, + gateway_id: &str, + server_uid: &str, + nonce: &str, + ts: i64, + now: i64, +) -> Result { + if (now - ts).abs() > MAX_CLOCK_SKEW_SECS { + return Err(AuthError::ClockSkew); + } + let key = EccKeyPubP256::from_ts(omega).map_err(|_| AuthError::BadKey)?; + let signature = BASE64_STANDARD.decode(signature).map_err(|_| AuthError::BadSignature)?; + key.verify(&challenge(gateway_id, server_uid, nonce, ts), &signature) + .map_err(|_| AuthError::BadSignature)?; + Ok(UniqueIds::from_omega(omega)) +} + +/// Hash-cash security level of an identity, as TeamSpeak computes it: +/// leading zero bits of `SHA1(omega + decimal offset)`, bytes from the start, +/// bits from least significant. +pub fn identity_level(omega: &str, key_offset: u64) -> u8 { + let hash = Sha1::digest(format!("{omega}{key_offset}").as_bytes()); + let mut level = 0; + for &byte in hash.as_slice() { + if byte == 0 { + level += 8; + } else { + level += byte.trailing_zeros() as u8; + break; + } + } + level +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sign_and_verify() { + let key = EccKeyPrivP256::create(); + let omega = key.to_pub().to_ts(); + let sig = sign_challenge(&key, "gw", "srv", "nonce", 1000); + let ids = verify_auth(&omega, &sig, "gw", "srv", "nonce", 1000, 1010).unwrap(); + assert_eq!(ids.ts3, key.to_pub().get_uid()); + assert_eq!(ids.ts6.len(), 44); + + // Any change to the challenge breaks the signature. + assert_eq!( + verify_auth(&omega, &sig, "gw", "srv", "other", 1000, 1000), + Err(AuthError::BadSignature) + ); + assert_eq!( + verify_auth(&omega, &sig, "gw2", "srv", "nonce", 1000, 1000), + Err(AuthError::BadSignature) + ); + // Someone else's key. + let other = EccKeyPrivP256::create().to_pub().to_ts(); + assert_eq!( + verify_auth(&other, &sig, "gw", "srv", "nonce", 1000, 1000), + Err(AuthError::BadSignature) + ); + // Stale timestamp. + assert_eq!( + verify_auth(&omega, &sig, "gw", "srv", "nonce", 1000, 2000), + Err(AuthError::ClockSkew) + ); + assert_eq!( + verify_auth("garbage", &sig, "gw", "srv", "nonce", 1000, 1000), + Err(AuthError::BadKey) + ); + } + + #[test] + fn ts6_uid_is_sha256_of_omega() { + // One identity as seen in clientdblist of TeamSpeak 3.13.8 and 6.0.0-beta13.1. + let omega = "MEsDAgcAAgEgAiBCmlKdgFw427AndT7fm2Wx4bgENOi6eQRUzwbT7Dnv9wIgcJETAwMtVjWdsCqZejblVJruSKWe4l845nWNAMYMkpk="; + let ids = UniqueIds::from_omega(omega); + assert_eq!(ids.ts3, "uXDkxSZbv0IoA0z/toW3guGpUbI="); + assert_eq!(ids.ts6, "xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M="); + assert_eq!(ids.for_server(true), ids.ts6); + } + + #[test] + fn level_matches_tsproto() { + // Same algorithm as the vendored client (and the TeamSpeak server). + let identity = tsproto::Identity::create(); + let omega = identity.key().to_pub().to_ts(); + assert!(identity.level() >= 8); + assert_eq!(identity_level(&omega, identity.counter()), identity.level()); + for offset in 0..200 { + assert_eq!( + identity_level(&omega, offset), + tsproto::algorithms::get_hash_cash_level(&omega, offset) + ); + } + } +} diff --git a/crates/tsc-gateway-proto/src/lib.rs b/crates/tsc-gateway-proto/src/lib.rs new file mode 100644 index 0000000..3062125 --- /dev/null +++ b/crates/tsc-gateway-proto/src/lib.rs @@ -0,0 +1,26 @@ +//! Wire protocol of `tsgw`, the companion gateway that gives app users +//! invisible presence and channel chat without joining voice. +//! +//! Transport: WebSocket, subprotocol [`SUBPROTOCOL`], one JSON [`Envelope`] +//! per text frame. Within version 1 changes are additive only: new message +//! types and optional fields. Unknown fields must be ignored. +//! +//! Authentication proves ownership of a TeamSpeak identity: the gateway sends +//! a nonce in [`ServerMsg::Hello`], the client answers with +//! [`ClientMsg::Auth`], an ECDSA P-256 signature over [`challenge`] made with +//! the identity's private key. The unique id is derived from the public key, +//! exactly as the TeamSpeak server does. + +mod auth; +mod messages; + +pub use auth::{ + AuthError, MAX_CLOCK_SKEW_SECS, UniqueIds, challenge, identity_level, sign_challenge, + verify_auth, +}; +pub use messages::*; + +/// WebSocket subprotocol. +pub const SUBPROTOCOL: &str = "tsgw.v1+json"; +/// Protocol version in every envelope. +pub const VERSION: u32 = 1; diff --git a/crates/tsc-gateway-proto/src/messages.rs b/crates/tsc-gateway-proto/src/messages.rs new file mode 100644 index 0000000..017e3bd --- /dev/null +++ b/crates/tsc-gateway-proto/src/messages.rs @@ -0,0 +1,185 @@ +//! Messages in both directions. + +use serde::{Deserialize, Serialize}; +use tsc_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; + +/// Every frame: `{"v":1,"id":7,"type":"send_chat","data":{...}}`. +/// +/// `id` is chosen by the client for requests; the gateway copies it into the +/// answer ([`ServerMsg::Ok`], [`ServerMsg::Error`], [`ServerMsg::History`]). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Envelope { + pub v: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(flatten)] + pub msg: M, +} + +impl Envelope { + pub fn new(msg: M) -> Self { + Self { v: crate::VERSION, id: None, msg } + } + pub fn with_id(id: u64, msg: M) -> Self { + Self { v: crate::VERSION, id: Some(id), msg } + } +} + +/// Client to gateway. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", content = "data", rename_all = "snake_case")] +pub enum ClientMsg { + /// Answer to [`ServerMsg::Hello`]. + Auth { + /// Public key, TeamSpeak "omega" format (base64 libtomcrypt DER). + omega: String, + /// Hash-cash counter (`client_key_offset`) that gives the identity its level. + key_offset: u64, + /// Unix time in seconds, part of the signed challenge. + ts: i64, + /// Base64 DER ECDSA signature over [`crate::challenge`]. + signature: String, + /// Nickname for relayed messages. + nickname: String, + }, + /// Log in again with a token from [`ServerMsg::AuthOk`] instead of a signature. + Resume { + token: String, + nickname: String, + }, + /// Start (or restart) the presence stream: a snapshot, then deltas. + SubscribePresence, + UnsubscribePresence, + /// Start receiving a chat. + OpenChat { + target: ChatTarget, + }, + CloseChat { + target: ChatTarget, + }, + SendChat { + target: ChatTarget, + text: String, + }, + /// Up to `limit` messages before message id `before` (latest when absent). + History { + target: ChatTarget, + #[serde(default, skip_serializing_if = "Option::is_none")] + before: Option, + limit: u32, + }, + Ping, +} + +/// Gateway to client. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", content = "data", rename_all = "snake_case")] +pub enum ServerMsg { + /// First message after connecting. + Hello { + gateway_id: String, + server_uid: String, + server_name: String, + nonce: String, + /// Optional features, e.g. `history`. + #[serde(default)] + capabilities: Vec, + }, + AuthOk { + uid: String, + /// Opaque; send it in [`ClientMsg::Resume`]. + token: String, + /// Unix time in seconds. + token_expires: i64, + }, + /// Presence restricted to what this user may see. `seq` restarts at 0 with + /// each snapshot and increases by one per delta. + PresenceSnapshot { + seq: u64, + snapshot: PresenceSnapshot, + }, + PresenceDelta { + seq: u64, + delta: PresenceDelta, + }, + /// A message in an open chat. `id` orders messages and pages history. + ChatEvent { + id: i64, + message: ChatMessage, + }, + History { + messages: Vec, + }, + /// Request succeeded. + Ok, + Error { + code: ErrorCode, + message: String, + }, + Pong, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct HistoryEntry { + pub id: i64, + pub message: ChatMessage, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + /// Malformed or unexpected message. + BadRequest, + /// Signature, timestamp or token invalid. + AuthFailed, + /// The server's database has no client with this unique id: connect + /// with voice once first. + UnknownIdentity, + /// Identity security level below what the server requires. + LevelTooLow, + /// The user is banned on the server. + Banned, + /// Not allowed by the user's server permissions or the gateway config. + Forbidden, + NotAuthenticated, + /// Temporary problem talking to the TeamSpeak server. + Unavailable, + Internal, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn envelope_json_shape() { + let env = Envelope::with_id( + 7, + ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() }, + ); + let json = serde_json::to_string(&env).unwrap(); + assert_eq!( + json, + r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"# + ); + let back: Envelope = serde_json::from_str(&json).unwrap(); + assert_eq!(back, env); + + let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap(); + assert_eq!(ping, r#"{"v":1,"type":"ping"}"#); + assert_eq!( + serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(), + r#"{"v":1,"type":"ok"}"# + ); + } + + #[test] + fn ignores_unknown_fields() { + let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#; + let env: Envelope = serde_json::from_str(json).unwrap(); + assert_eq!( + env.msg, + ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 } + ); + } +} diff --git a/crates/tsc-gateway/Cargo.toml b/crates/tsc-gateway/Cargo.toml new file mode 100644 index 0000000..38f1160 --- /dev/null +++ b/crates/tsc-gateway/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "tsc-gateway" +version = "0.1.0" +description = "tsgw: companion gateway giving app users invisible presence and channel chat over ServerQuery." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[[bin]] +name = "tsgw" +path = "src/main.rs" + +[dependencies] +anyhow = "1.0.104" +axum = { version = "0.8.9", features = ["ws"] } +base64 = "0.22" +clap = { version = "4.6.7", features = ["derive", "env"] } +futures = "0.3.34" +rand = "0.10.3" +rusqlite = { version = "0.40.2", features = ["bundled"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +sha2 = "0.10" +thiserror = "2.0.21" +tokio = { version = "1.53.1", features = ["full"] } +toml = "1.1.6" +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +tsc-gateway-proto = { path = "../tsc-gateway-proto" } +tsc-model = { path = "../tsc-model" } +tsc-observer = { path = "../tsc-observer" } +tsc-query = { path = "../tsc-query" } + +[lints] +workspace = true + +[dev-dependencies] +tokio-tungstenite = "0.30.0" diff --git a/crates/tsc-gateway/Dockerfile b/crates/tsc-gateway/Dockerfile new file mode 100644 index 0000000..ce58ca0 --- /dev/null +++ b/crates/tsc-gateway/Dockerfile @@ -0,0 +1,14 @@ +# Build: docker build -f crates/tsc-gateway/Dockerfile -t tsgw . +# Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw +FROM rust:1.94-bookworm AS build +WORKDIR /src +RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/* +COPY . . +RUN cargo build --release --locked -p tsc-gateway && cp target/release/tsgw /tsgw + +FROM gcr.io/distroless/cc-debian12:nonroot +COPY --from=build /tsgw /usr/local/bin/tsgw +ENV TSGW_CONFIG=/etc/tsgw/tsgw.toml +WORKDIR /var/lib/tsgw +EXPOSE 7788 +ENTRYPOINT ["/usr/local/bin/tsgw"] diff --git a/crates/tsc-gateway/src/config.rs b/crates/tsc-gateway/src/config.rs new file mode 100644 index 0000000..693e38b --- /dev/null +++ b/crates/tsc-gateway/src/config.rs @@ -0,0 +1,245 @@ +//! `tsgw.toml`. + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde::Deserialize; +use tsc_query::Transport; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + /// Identifies this gateway in signed challenges. Defaults to `public_url` + /// or the query address. + #[serde(default)] + pub gateway_id: Option, + pub server: ServerConfig, + pub query: QueryConfig, + #[serde(default)] + pub listen: ListenConfig, + #[serde(default)] + pub auth: AuthConfig, + #[serde(default)] + pub relay: RelayConfig, + #[serde(default)] + pub history: HistoryConfig, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServerConfig { + /// Voice port of the virtual server to serve. + #[serde(default = "default_voice_port")] + pub voice_port: u16, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct QueryConfig { + /// `raw` (TeamSpeak 3) or `ssh`. HTTP has no events and cannot relay chat. + pub transport: Transport, + /// host:port of the query interface. + pub addr: String, + #[serde(default = "default_user")] + pub user: String, + /// Password; prefer `password_file` or the `TSGW_QUERY_PASSWORD` variable. + #[serde(default)] + pub password: Option, + #[serde(default)] + pub password_file: Option, + /// The gateway's IP is on the server's query allowlist, so the client-side + /// flood limit (10 commands per 3 s) is not needed. + #[serde(default)] + pub allowlisted: bool, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ListenConfig { + #[serde(default = "default_bind")] + pub bind: SocketAddr, + /// URL clients use, e.g. `wss://gw.example.org/v1`. + #[serde(default)] + pub public_url: Option, +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuthConfig { + /// If not empty, users need one of these server groups. + #[serde(default)] + pub require_server_groups: Vec, + /// Unique ids that may never use the gateway. + #[serde(default)] + pub deny_uids: Vec, + /// Minimum identity level, on top of the server's own requirement. + #[serde(default)] + pub min_security_level: u8, + #[serde(default = "default_token_ttl_hours")] + pub token_ttl_hours: u64, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RelayConfig { + #[serde(default = "default_relay_nickname")] + pub nickname: String, + /// How posts appear in the channel; `{nick}` and `{text}` are replaced. + #[serde(default = "default_relay_format")] + pub format: String, + /// Close a relay this long after its last reader left (unless pinned). + #[serde(default = "default_idle_teardown")] + pub idle_teardown_secs: u64, + /// Upper bound on concurrent relays (each is one query connection). + #[serde(default = "default_max_relays")] + pub max_channel_relays: usize, + /// Always relayed, so their history is complete. + #[serde(default)] + pub pinned_channels: Vec, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HistoryConfig { + #[serde(default = "default_true")] + pub enabled: bool, + #[serde(default = "default_db_path")] + pub path: PathBuf, + #[serde(default = "default_retention_days")] + pub retention_days: u64, +} + +fn default_voice_port() -> u16 { + 9987 +} +fn default_user() -> String { + "serveradmin".into() +} +fn default_bind() -> SocketAddr { + "0.0.0.0:7788".parse().unwrap() +} +fn default_token_ttl_hours() -> u64 { + 24 * 30 +} +fn default_relay_nickname() -> String { + "Chat Relay".into() +} +fn default_relay_format() -> String { + "[{nick}] {text}".into() +} +fn default_idle_teardown() -> u64 { + 120 +} +fn default_max_relays() -> usize { + 6 +} +fn default_true() -> bool { + true +} +fn default_db_path() -> PathBuf { + "tsgw.db".into() +} +fn default_retention_days() -> u64 { + 30 +} + +impl Default for ListenConfig { + fn default() -> Self { + Self { bind: default_bind(), public_url: None } + } +} + +impl Default for RelayConfig { + fn default() -> Self { + Self { + nickname: default_relay_nickname(), + format: default_relay_format(), + idle_teardown_secs: default_idle_teardown(), + max_channel_relays: default_max_relays(), + pinned_channels: Vec::new(), + } + } +} + +impl Default for HistoryConfig { + fn default() -> Self { + Self { enabled: true, path: default_db_path(), retention_days: default_retention_days() } + } +} + +impl Config { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .with_context(|| format!("failed to read {}", path.display()))?; + let mut config: Config = + toml::from_str(&text).with_context(|| format!("invalid {}", path.display()))?; + config.resolve_password()?; + if config.query.transport == Transport::Http { + bail!("query.transport = \"http\" has no events; use \"ssh\" or \"raw\""); + } + Ok(config) + } + + fn resolve_password(&mut self) -> Result<()> { + if let Some(file) = &self.query.password_file { + let pw = std::fs::read_to_string(file) + .with_context(|| format!("failed to read {}", file.display()))?; + self.query.password = Some(pw.trim().to_string()); + } else if let Ok(pw) = std::env::var("TSGW_QUERY_PASSWORD") { + self.query.password = Some(pw); + } + Ok(()) + } + + pub fn gateway_id(&self) -> String { + self.gateway_id + .clone() + .or_else(|| self.listen.public_url.clone()) + .unwrap_or_else(|| format!("tsgw@{}", self.query.addr)) + } + + pub fn query_connect(&self) -> tsc_query::Connect { + tsc_query::Connect { + transport: self.query.transport, + addr: self.query.addr.clone(), + user: self.query.user.clone(), + secret: self.query.password.clone(), + server_port: Some(self.server.voice_port), + server_id: None, + line: tsc_query::LineOptions { + rate_limit: if self.query.allowlisted { + None + } else { + tsc_query::LineOptions::default().rate_limit + }, + ..Default::default() + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_example() { + let text = include_str!("../tsgw.example.toml"); + let config: Config = toml::from_str(text).unwrap(); + assert_eq!(config.query.transport, Transport::Ssh); + assert_eq!(config.relay.format, "[{nick}] {text}"); + assert_eq!(config.server.voice_port, 9987); + } + + #[test] + fn minimal_config_uses_defaults() { + let config: Config = + toml::from_str("[server]\n[query]\ntransport = \"raw\"\naddr = \"127.0.0.1:10011\"\n") + .unwrap(); + assert_eq!(config.listen.bind.port(), 7788); + assert_eq!(config.relay.max_channel_relays, 6); + assert!(config.history.enabled); + assert_eq!(config.gateway_id(), "tsgw@127.0.0.1:10011"); + } +} diff --git a/crates/tsc-gateway/src/db.rs b/crates/tsc-gateway/src/db.rs new file mode 100644 index 0000000..b6530fc --- /dev/null +++ b/crates/tsc-gateway/src/db.rs @@ -0,0 +1,193 @@ +//! SQLite: login tokens, chat history, audit log. + +use std::path::Path; +use std::sync::Mutex; + +use rusqlite::{Connection, OptionalExtension, params}; +use tsc_model::{ChatMessage, ChatTarget}; + +pub struct Db(Mutex); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TokenInfo { + pub uid: String, + pub cldbid: u64, + pub expires: i64, +} + +fn target_key(target: &ChatTarget) -> String { + match target { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel/{cid}"), + ChatTarget::Private(uid) => format!("private/{uid}"), + } +} + +impl Db { + pub fn open(path: &Path) -> rusqlite::Result { + Self::init(Connection::open(path)?) + } + + #[cfg(test)] + pub fn in_memory() -> rusqlite::Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(conn: Connection) -> rusqlite::Result { + conn.pragma_update(None, "journal_mode", "WAL")?; + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS tokens ( + hash TEXT PRIMARY KEY, + uid TEXT NOT NULL, + cldbid INTEGER NOT NULL, + expires INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY, + target TEXT NOT NULL, + ts_ms INTEGER NOT NULL, + author_uid TEXT, + author_name TEXT NOT NULL, + text TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS messages_by_target ON messages (target, id); + CREATE TABLE IF NOT EXISTS audit ( + ts INTEGER NOT NULL, + uid TEXT, + action TEXT NOT NULL, + detail TEXT + );", + )?; + Ok(Self(Mutex::new(conn))) + } + + pub fn add_token(&self, hash: &str, info: &TokenInfo) -> rusqlite::Result<()> { + self.0.lock().unwrap().execute( + "INSERT OR REPLACE INTO tokens (hash, uid, cldbid, expires) VALUES (?1, ?2, ?3, ?4)", + params![hash, info.uid, info.cldbid as i64, info.expires], + )?; + Ok(()) + } + + /// A token that has not expired at `now`. + pub fn token(&self, hash: &str, now: i64) -> rusqlite::Result> { + self.0 + .lock() + .unwrap() + .query_row( + "SELECT uid, cldbid, expires FROM tokens WHERE hash = ?1 AND expires > ?2", + params![hash, now], + |r| { + Ok(TokenInfo { + uid: r.get(0)?, + cldbid: r.get::<_, i64>(1)? as u64, + expires: r.get(2)?, + }) + }, + ) + .optional() + } + + /// Store a message; returns its id. + pub fn add_message(&self, msg: &ChatMessage) -> rusqlite::Result { + let conn = self.0.lock().unwrap(); + conn.execute( + "INSERT INTO messages (target, ts_ms, author_uid, author_name, text) VALUES (?1, ?2, ?3, ?4, ?5)", + params![target_key(&msg.target), msg.ts_ms, msg.author_uid, msg.author_name, msg.text], + )?; + Ok(conn.last_insert_rowid()) + } + + /// Up to `limit` messages before id `before`, oldest first. + pub fn history( + &self, + target: &ChatTarget, + before: Option, + limit: u32, + ) -> rusqlite::Result> { + let conn = self.0.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, ts_ms, author_uid, author_name, text FROM messages + WHERE target = ?1 AND id < ?2 ORDER BY id DESC LIMIT ?3", + )?; + let rows = + stmt.query_map(params![target_key(target), before.unwrap_or(i64::MAX), limit], |r| { + Ok(( + r.get::<_, i64>(0)?, + ChatMessage { + target: target.clone(), + ts_ms: r.get(1)?, + author_uid: r.get(2)?, + author_name: r.get(3)?, + author_id: None, + text: r.get(4)?, + via_relay: true, + }, + )) + })?; + let mut out = rows.collect::>>()?; + out.reverse(); + Ok(out) + } + + pub fn prune(&self, now: i64, retention_days: u64) -> rusqlite::Result<()> { + let cutoff_ms = (now - retention_days as i64 * 86_400) * 1000; + let conn = self.0.lock().unwrap(); + conn.execute("DELETE FROM messages WHERE ts_ms < ?1", [cutoff_ms])?; + conn.execute("DELETE FROM tokens WHERE expires < ?1", [now])?; + Ok(()) + } + + pub fn audit(&self, now: i64, uid: Option<&str>, action: &str, detail: &str) { + let result = self.0.lock().unwrap().execute( + "INSERT INTO audit (ts, uid, action, detail) VALUES (?1, ?2, ?3, ?4)", + params![now, uid, action, detail], + ); + if let Err(error) = result { + tracing::warn!(%error, "failed to write audit log"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn msg(target: ChatTarget, text: &str, ts_ms: i64) -> ChatMessage { + ChatMessage { + target, + author_name: "a".into(), + author_uid: Some("u".into()), + author_id: None, + text: text.into(), + ts_ms, + via_relay: true, + } + } + + #[test] + fn tokens_expire() { + let db = Db::in_memory().unwrap(); + let info = TokenInfo { uid: "u".into(), cldbid: 5, expires: 100 }; + db.add_token("h", &info).unwrap(); + assert_eq!(db.token("h", 50).unwrap(), Some(info)); + assert_eq!(db.token("h", 150).unwrap(), None); + assert_eq!(db.token("x", 50).unwrap(), None); + } + + #[test] + fn history_pages_per_target() { + let db = Db::in_memory().unwrap(); + for i in 0..5 { + db.add_message(&msg(ChatTarget::Channel(1), &format!("c{i}"), i)).unwrap(); + db.add_message(&msg(ChatTarget::Server, &format!("s{i}"), i)).unwrap(); + } + let last = db.history(&ChatTarget::Channel(1), None, 2).unwrap(); + assert_eq!(last.iter().map(|(_, m)| m.text.as_str()).collect::>(), ["c3", "c4"]); + let before = db.history(&ChatTarget::Channel(1), Some(last[0].0), 10).unwrap(); + assert_eq!(before.len(), 3); + assert_eq!(db.history(&ChatTarget::Server, None, 10).unwrap().len(), 5); + db.prune(10, 0).unwrap(); + assert!(db.history(&ChatTarget::Server, None, 10).unwrap().is_empty()); + } +} diff --git a/crates/tsc-gateway/src/hub.rs b/crates/tsc-gateway/src/hub.rs new file mode 100644 index 0000000..82cf9f5 --- /dev/null +++ b/crates/tsc-gateway/src/hub.rs @@ -0,0 +1,462 @@ +//! State shared by all sessions: one observer, one relay pool, one query +//! session for lookups, chat storage and fan-out. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use base64::prelude::*; +use rand::RngExt; +use sha2::{Digest, Sha256}; +use tokio::sync::broadcast; +use tracing::{info, warn}; +use tsc_gateway_proto::{ErrorCode, UniqueIds, identity_level, verify_auth}; +use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text}; +use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool}; +use tsc_query::{Command, QueryClient}; + +use crate::config::Config; +use crate::db::{Db, TokenInfo}; +use crate::perms::{ChannelAccess, PermIds, PermResolver, channel_access, effective}; + +pub fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or_default() +} + +fn now_ms() -> i64 { + now_secs() * 1000 +} + +/// A logged-in user. +#[derive(Clone, Debug)] +pub struct User { + pub uid: String, + pub cldbid: u64, + /// Last nickname the server saw; used in relayed posts (not user-chosen, + /// so nobody can post under someone else's name). + pub nickname: String, + /// Effective `i_channel_subscribe_power`, used to filter presence. + pub subscribe_power: i64, +} + +/// An error to send to the client. +#[derive(Debug)] +pub struct Denied(pub ErrorCode, pub String); + +impl Denied { + fn new(code: ErrorCode, msg: impl Into) -> Self { + Self(code, msg.into()) + } +} + +impl From for Denied { + fn from(e: tsc_query::Error) -> Self { + Denied::new(ErrorCode::Unavailable, e.to_string()) + } +} + +pub struct Hub { + pub config: Config, + pub gateway_id: String, + pub server_uid: String, + pub server_name: String, + pub is_ts6: bool, + needed_level: u8, + default_channel: ChannelId, + pub observer: Observer, + relays: RelayPool, + lookup: QueryClient, + perms: PermResolver, + pub db: Option, + chat: broadcast::Sender<(i64, ChatMessage)>, + /// Readers per relayed channel, and when the last one left. + readers: Mutex>, + /// Our own query clients, whose messages are echoes. + own_clients: Mutex>, + next_message_id: Mutex, +} + +impl Hub { + pub async fn start(config: Config) -> Result> { + let connect = config.query_connect(); + let (lookup, _) = + QueryClient::connect(&connect).await.context("query login for lookups failed")?; + let info = lookup.send(&Command::new("serverinfo")).await?; + let info = info.first().context("empty serverinfo")?; + let version = info.get("virtualserver_version").unwrap_or_default(); + let is_ts6 = matches!(ServerFlavor::from_version_string(version), ServerFlavor::Ts6(_)); + let server_uid = + info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(); + let server_name = info.get("virtualserver_name").unwrap_or_default().to_string(); + let needed_level = info.parse("virtualserver_needed_identity_security_level").unwrap_or(8); + let channels = lookup.send(&Command::new("channellist").flag("flags")).await?; + let default_channel = channels + .iter() + .find(|r| r.flag("channel_flag_default") == Some(true)) + .and_then(|r| r.parse("cid")) + .unwrap_or(1); + let perms = PermResolver::new(PermIds::load(&lookup).await?); + let own_id = lookup.own_client_id().await?; + let _ = lookup + .send( + &Command::new("clientupdate") + .arg("client_nickname", format!("{} Gateway", config.relay.nickname)), + ) + .await; + + let db = if config.history.enabled { + let db = Db::open(&config.history.path) + .with_context(|| format!("failed to open {}", config.history.path.display()))?; + db.prune(now_secs(), config.history.retention_days)?; + Some(db) + } else { + None + }; + + let observer = Observer::spawn(ObserverConfig::new(connect.clone())); + let mut relay_config = RelayConfig::new(connect); + relay_config.nickname = config.relay.nickname.clone(); + relay_config.format = config.relay.format.clone(); + let relays = RelayPool::new(relay_config); + + info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server"); + let hub = Arc::new(Self { + gateway_id: config.gateway_id(), + config, + server_uid, + server_name, + is_ts6, + needed_level, + default_channel, + observer, + relays, + lookup, + perms, + db, + chat: broadcast::channel(1024).0, + readers: Default::default(), + own_clients: Mutex::new([own_id].into()), + next_message_id: Mutex::new(0), + }); + tokio::spawn(hub.clone().pump_observer_chat()); + tokio::spawn(hub.clone().pump_relays()); + tokio::spawn(hub.clone().teardown_idle_relays()); + for &cid in &hub.config.relay.pinned_channels { + if let Err(error) = hub.relays.open(cid).await { + warn!(cid, %error, "could not open pinned relay"); + } + } + Ok(hub) + } + + pub fn subscribe_chat(&self) -> broadcast::Receiver<(i64, ChatMessage)> { + self.chat.subscribe() + } + + /// Store (if history is on) and fan out a message. + fn publish(&self, msg: ChatMessage) { + let id = match &self.db { + Some(db) => db.add_message(&msg).unwrap_or_else(|error| { + warn!(%error, "failed to store message"); + -1 + }), + None => { + let mut next = self.next_message_id.lock().unwrap(); + *next += 1; + *next + } + }; + let _ = self.chat.send((id, msg)); + } + + /// Server chat seen by the observer. + async fn pump_observer_chat(self: Arc) { + let mut events = self.observer.subscribe(); + loop { + match events.recv().await { + Ok(ObserverEvent::Chat(msg)) if msg.target == ChatTarget::Server => { + let own = msg + .author_id + .is_some_and(|id| self.own_clients.lock().unwrap().contains(&id)); + if !own { + self.publish(msg); + } + } + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return, + } + } + } + + /// Channel chat seen by relays. + async fn pump_relays(self: Arc) { + let mut events = self.relays.subscribe(); + loop { + match events.recv().await { + Ok(RelayEvent::Message(msg)) => { + let own = msg + .author_id + .is_some_and(|id| self.own_clients.lock().unwrap().contains(&id)); + if !own { + self.publish(msg); + } + } + Ok(RelayEvent::Closed { channel, reason }) => { + warn!(channel, %reason, "relay closed"); + } + Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return, + } + } + } + + async fn teardown_idle_relays(self: Arc) { + let idle = Duration::from_secs(self.config.relay.idle_teardown_secs); + loop { + tokio::time::sleep(Duration::from_secs(15).min(idle)).await; + let idle_channels: Vec = self + .readers + .lock() + .unwrap() + .iter() + .filter(|(cid, (n, since))| { + *n == 0 + && since.elapsed() >= idle + && !self.config.relay.pinned_channels.contains(cid) + }) + .map(|(cid, _)| *cid) + .collect(); + for cid in idle_channels { + self.readers.lock().unwrap().remove(&cid); + self.relays.close(cid).await; + } + } + } + + // Authentication + + /// Verify a signed challenge and look the identity up on the server. + pub async fn authenticate( + &self, + omega: &str, + key_offset: u64, + ts: i64, + signature: &str, + nonce: &str, + ) -> Result<(User, String, i64), Denied> { + let ids: UniqueIds = verify_auth( + omega, + signature, + &self.gateway_id, + &self.server_uid, + nonce, + ts, + now_secs(), + ) + .map_err(|e| Denied::new(ErrorCode::AuthFailed, e.to_string()))?; + let uid = ids.for_server(self.is_ts6).to_string(); + let needed = self.needed_level.max(self.config.auth.min_security_level); + let level = identity_level(omega, key_offset); + if level < needed { + return Err(Denied::new( + ErrorCode::LevelTooLow, + format!("identity level {level}, server needs {needed}"), + )); + } + let user = self.lookup_user(&uid).await?; + let (token, expires) = self.issue_token(&user)?; + self.audit(Some(&user.uid), "login", "signature"); + Ok((user, token, expires)) + } + + /// Log in with a token from an earlier login. + pub async fn resume(&self, token: &str) -> Result<(User, String, i64), Denied> { + let hash = hash_token(token); + let info = self + .db + .as_ref() + .and_then(|db| db.token(&hash, now_secs()).ok().flatten()) + .ok_or_else(|| Denied::new(ErrorCode::AuthFailed, "unknown or expired token"))?; + let user = self.lookup_user(&info.uid).await?; + self.audit(Some(&user.uid), "login", "token"); + Ok((user, token.to_string(), info.expires)) + } + + fn issue_token(&self, user: &User) -> Result<(String, i64), Denied> { + let bytes: [u8; 32] = rand::rng().random(); + let token = BASE64_URL_SAFE_NO_PAD.encode(bytes); + let expires = now_secs() + self.config.auth.token_ttl_hours as i64 * 3600; + if let Some(db) = &self.db { + db.add_token( + &hash_token(&token), + &TokenInfo { uid: user.uid.clone(), cldbid: user.cldbid, expires }, + ) + .map_err(|e| Denied::new(ErrorCode::Internal, e.to_string()))?; + } + Ok((token, expires)) + } + + async fn lookup_user(&self, uid: &str) -> Result { + if self.config.auth.deny_uids.iter().any(|d| d == uid) { + return Err(Denied::new(ErrorCode::Forbidden, "not allowed on this gateway")); + } + let bans = self.lookup.send(&Command::new("banlist")).await.unwrap_or_default(); + if bans.iter().any(|b| b.get("uid") == Some(uid)) { + return Err(Denied::new(ErrorCode::Banned, "banned on this server")); + } + let found = + self.lookup.send(&Command::new("clientdbfind").arg("pattern", uid).flag("uid")).await?; + let cldbid: u64 = found.first().and_then(|r| r.parse("cldbid")).ok_or_else(|| { + Denied::new(ErrorCode::UnknownIdentity, "connect to the server with voice once first") + })?; + let info = self.lookup.send(&Command::new("clientdbinfo").arg("cldbid", cldbid)).await?; + let nickname = + info.first().and_then(|r| r.get("client_nickname")).unwrap_or("unknown").to_string(); + if !self.config.auth.require_server_groups.is_empty() { + let groups = self + .lookup + .send(&Command::new("servergroupsbyclientid").arg("cldbid", cldbid)) + .await?; + let allowed = groups + .iter() + .filter_map(|r| r.parse::("sgid")) + .any(|g| self.config.auth.require_server_groups.contains(&g)); + if !allowed { + return Err(Denied::new(ErrorCode::Forbidden, "missing required server group")); + } + } + let entries = self.perms.entries(&self.lookup, cldbid, self.default_channel).await?; + let subscribe_power = effective(&entries, self.perms.ids.subscribe_power); + Ok(User { uid: uid.to_string(), cldbid, nickname, subscribe_power }) + } + + // Authorization + + pub async fn channel_access( + &self, + user: &User, + cid: ChannelId, + ) -> Result { + let has_password = { + let presence = self.observer.presence(); + let presence = presence.read().unwrap(); + let Some(channel) = presence.channels.get(&cid) else { + return Err(Denied::new(ErrorCode::BadRequest, format!("no channel {cid}"))); + }; + if channel.needed_subscribe_power as i64 > user.subscribe_power { + return Ok(ChannelAccess { read: false, post: false }); + } + channel.has_password + }; + let entries = self.perms.entries(&self.lookup, user.cldbid, cid).await?; + Ok(channel_access(&entries, &self.perms.ids, has_password)) + } + + pub async fn can_post_server_chat(&self, user: &User) -> Result { + let entries = self.perms.entries(&self.lookup, user.cldbid, self.default_channel).await?; + Ok(effective(&entries, self.perms.ids.server_text_send) > 0) + } + + /// Presence as this user may see it: channels within their subscribe + /// power, no query clients. + pub fn filtered_presence(&self, user: &User) -> Presence { + let presence = self.observer.presence(); + let p = presence.read().unwrap(); + let channels: std::collections::BTreeMap<_, _> = p + .channels + .iter() + .filter(|(_, c)| c.needed_subscribe_power as i64 <= user.subscribe_power) + .map(|(id, c)| (*id, c.clone())) + .collect(); + let clients = p + .clients + .iter() + .filter(|(_, c)| !c.is_query && channels.contains_key(&c.channel)) + .map(|(id, c)| (*id, c.clone())) + .collect(); + Presence { server_name: p.server_name.clone(), channels, clients } + } + + // Chat + + /// Start reading a channel for one more session. + pub async fn add_reader(&self, cid: ChannelId) -> Result<(), Denied> { + let open = self.readers.lock().unwrap().len(); + let already = self.readers.lock().unwrap().contains_key(&cid); + if !already && open >= self.config.relay.max_channel_relays { + return Err(Denied::new( + ErrorCode::Unavailable, + "too many relayed channels, try later", + )); + } + self.relays.open(cid).await?; + self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1; + Ok(()) + } + + pub fn remove_reader(&self, cid: ChannelId) { + if let Some(entry) = self.readers.lock().unwrap().get_mut(&cid) { + entry.0 = entry.0.saturating_sub(1); + entry.1 = Instant::now(); + } + } + + /// Post on behalf of `user`; the message is published to readers directly + /// (the relay's echo is dropped). + pub async fn post(&self, user: &User, target: &ChatTarget, text: &str) -> Result<(), Denied> { + match target { + ChatTarget::Server => { + if !self.can_post_server_chat(user).await? { + return Err(Denied::new(ErrorCode::Forbidden, "no permission for server chat")); + } + let msg = relay_text(&self.config.relay.format, &user.nickname, text); + for part in tsc_model::split_message(&msg, 1024) { + self.lookup + .send( + &Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part), + ) + .await?; + } + } + ChatTarget::Channel(cid) => { + if !self.channel_access(user, *cid).await?.post { + return Err(Denied::new(ErrorCode::Forbidden, "no permission to post here")); + } + if !self.readers.lock().unwrap().contains_key(cid) { + // Posting without reading still needs a relay in the channel. + self.add_reader(*cid).await?; + self.remove_reader(*cid); + } + self.relays.send(*cid, &user.nickname, text).await?; + } + ChatTarget::Private(_) => { + return Err(Denied::new(ErrorCode::BadRequest, "private chat is not relayed")); + } + } + self.audit(Some(&user.uid), "post", &format!("{target:?}")); + self.publish(ChatMessage { + target: target.clone(), + author_name: user.nickname.clone(), + author_uid: Some(user.uid.clone()), + author_id: None, + text: text.to_string(), + ts_ms: now_ms(), + via_relay: true, + }); + Ok(()) + } + + pub fn audit(&self, uid: Option<&str>, action: &str, detail: &str) { + if let Some(db) = &self.db { + db.audit(now_secs(), uid, action, detail); + } + } +} + +fn hash_token(token: &str) -> String { + BASE64_STANDARD.encode(Sha256::digest(token.as_bytes())) +} diff --git a/crates/tsc-gateway/src/main.rs b/crates/tsc-gateway/src/main.rs new file mode 100644 index 0000000..053fc84 --- /dev/null +++ b/crates/tsc-gateway/src/main.rs @@ -0,0 +1,65 @@ +//! tsgw: companion gateway for TeamSpeak 3/6 servers. +//! +//! Gives app users invisible presence (who is in which channel) and channel +//! chat without joining voice, through ServerQuery. See +//! docs/gateway-admin.md and the protocol in `tsc-gateway-proto`. + +mod config; +mod db; +mod hub; +mod perms; +mod session; + +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::Result; +use axum::Router; +use axum::extract::{State, WebSocketUpgrade}; +use axum::response::IntoResponse; +use axum::routing::get; +use clap::Parser; +use tracing::info; +use tracing_subscriber::EnvFilter; + +use crate::hub::Hub; + +#[derive(Parser, Debug)] +#[command(version, about)] +struct Args { + /// Configuration file. + #[arg(long, short, default_value = "tsgw.toml", env = "TSGW_CONFIG")] + config: PathBuf, +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), + ) + .init(); + let args = Args::parse(); + let config = config::Config::load(&args.config)?; + let bind = config.listen.bind; + let hub = Hub::start(config).await?; + let app = Router::new() + .route("/v1", get(ws)) + .route("/health", get(|| async { "ok" })) + .with_state(hub); + let listener = tokio::net::TcpListener::bind(bind).await?; + info!(%bind, "listening"); + axum::serve(listener, app).with_graceful_shutdown(shutdown()).await?; + Ok(()) +} + +async fn ws(State(hub): State>, upgrade: WebSocketUpgrade) -> impl IntoResponse { + upgrade + .protocols([tsc_gateway_proto::SUBPROTOCOL]) + .on_upgrade(move |socket| session::run(hub, socket)) +} + +async fn shutdown() { + let _ = tokio::signal::ctrl_c().await; + info!("shutting down"); +} diff --git a/crates/tsc-gateway/src/perms.rs b/crates/tsc-gateway/src/perms.rs new file mode 100644 index 0000000..b529325 --- /dev/null +++ b/crates/tsc-gateway/src/perms.rs @@ -0,0 +1,234 @@ +//! Mirror the server's permission checks for users who are not connected. +//! +//! `permoverview cid= cldbid= permid=0` lists every permission +//! assignment relevant to a user in a channel, one row per level: +//! `t=0` server group, `t=1` client, `t=2` channel, `t=3` channel group, +//! `t=4` channel client; `v` value, `n` negate, `s` skip. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use tsc_query::{Command, QueryClient, Row}; + +const CACHE_TTL: Duration = Duration::from_secs(60); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Entry { + pub level: u8, + pub perm: u32, + pub value: i64, + pub negate: bool, + pub skip: bool, +} + +impl Entry { + fn from_row(row: &Row) -> Option { + Some(Self { + level: row.parse("t")?, + perm: row.parse("p")?, + value: row.parse("v")?, + negate: row.flag("n").unwrap_or(false), + skip: row.flag("s").unwrap_or(false), + }) + } +} + +/// The user's effective value of `perm` (0 if not granted anywhere). +/// +/// Server groups combine to the highest value (lowest among negated ones); +/// a client permission replaces them; channel group and channel-client +/// permissions replace those unless a skip flag was set at the server group +/// or client level. +pub fn effective(entries: &[Entry], perm: u32) -> i64 { + let of = |level: u8| entries.iter().filter(move |e| e.perm == perm && e.level == level); + let groups: Vec<_> = of(0).collect(); + let mut value = if groups.iter().any(|e| e.negate) { + groups.iter().filter(|e| e.negate).map(|e| e.value).min().unwrap_or(0) + } else { + groups.iter().map(|e| e.value).max().unwrap_or(0) + }; + let mut skip = groups.iter().any(|e| e.skip); + if let Some(client) = of(1).next() { + value = client.value; + skip |= client.skip; + } + if !skip { + if let Some(group) = of(3).next() { + value = group.value; + } + if let Some(channel_client) = of(4).next() { + value = channel_client.value; + } + } + value +} + +/// A permission the channel itself sets (level 2), e.g. `i_channel_needed_join_power`. +pub fn channel_value(entries: &[Entry], perm: u32) -> i64 { + entries.iter().find(|e| e.perm == perm && e.level == 2).map(|e| e.value).unwrap_or(0) +} + +/// Permission ids by name; they differ between server versions. +#[derive(Clone, Copy, Debug, Default)] +pub struct PermIds { + pub join_power: u32, + pub needed_join_power: u32, + pub subscribe_power: u32, + pub channel_text_send: u32, + pub server_text_send: u32, + pub ignore_password: u32, +} + +impl PermIds { + pub async fn load(client: &QueryClient) -> tsc_query::Result { + let names = [ + "i_channel_join_power", + "i_channel_needed_join_power", + "i_channel_subscribe_power", + "b_client_channel_textmessage_send", + "b_client_server_textmessage_send", + "b_channel_join_ignore_password", + ]; + let mut ids = [0u32; 6]; + for (i, name) in names.iter().enumerate() { + let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?; + ids[i] = rows + .first() + .and_then(|r| r.parse("permid")) + .ok_or_else(|| tsc_query::Error::Protocol(format!("unknown permission {name}")))?; + } + Ok(Self { + join_power: ids[0], + needed_join_power: ids[1], + subscribe_power: ids[2], + channel_text_send: ids[3], + server_text_send: ids[4], + ignore_password: ids[5], + }) + } +} + +/// What a user may do in a channel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChannelAccess { + /// May join, so may see the channel chat. + pub read: bool, + /// May also write in the channel chat. + pub post: bool, +} + +/// Decide channel access from `permoverview` entries. +pub fn channel_access(entries: &[Entry], ids: &PermIds, has_password: bool) -> ChannelAccess { + let can_join = effective(entries, ids.join_power) + >= channel_value(entries, ids.needed_join_power) + && (!has_password || effective(entries, ids.ignore_password) > 0); + ChannelAccess { + read: can_join, + post: can_join && effective(entries, ids.channel_text_send) > 0, + } +} + +/// `(cldbid, cid)` to the time of the lookup and its entries. +type Cache = HashMap<(u64, u64), (Instant, Vec)>; + +/// Caches `permoverview` per (user, channel). +pub struct PermResolver { + pub ids: PermIds, + cache: Mutex, +} + +impl PermResolver { + pub fn new(ids: PermIds) -> Self { + Self { ids, cache: Default::default() } + } + + pub async fn entries( + &self, + client: &QueryClient, + cldbid: u64, + cid: u64, + ) -> tsc_query::Result> { + if let Some((at, entries)) = self.cache.lock().unwrap().get(&(cldbid, cid)) + && at.elapsed() < CACHE_TTL + { + return Ok(entries.clone()); + } + let rows = client + .send( + &Command::new("permoverview") + .arg("cid", cid) + .arg("cldbid", cldbid) + .arg("permid", 0), + ) + .await?; + let entries: Vec = rows.iter().filter_map(Entry::from_row).collect(); + self.cache.lock().unwrap().insert((cldbid, cid), (Instant::now(), entries.clone())); + Ok(entries) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn e(level: u8, perm: u32, value: i64) -> Entry { + Entry { level, perm, value, negate: false, skip: false } + } + + #[test] + fn server_groups_take_the_highest() { + assert_eq!(effective(&[e(0, 1, 10), e(0, 1, 50), e(0, 2, 99)], 1), 50); + assert_eq!(effective(&[], 1), 0); + } + + #[test] + fn negate_takes_lowest_negated() { + let mut neg = e(0, 1, 5); + neg.negate = true; + assert_eq!(effective(&[e(0, 1, 75), neg], 1), 5); + } + + #[test] + fn levels_override_in_order() { + // client > server groups; channel group and channel client on top. + assert_eq!(effective(&[e(0, 1, 10), e(1, 1, 20)], 1), 20); + assert_eq!(effective(&[e(0, 1, 10), e(1, 1, 20), e(3, 1, 30)], 1), 30); + assert_eq!(effective(&[e(0, 1, 10), e(3, 1, 30), e(4, 1, 40)], 1), 40); + } + + #[test] + fn skip_protects_group_value() { + let mut skip = e(0, 1, 100); + skip.skip = true; + assert_eq!(effective(&[skip, e(3, 1, 0), e(4, 1, 0)], 1), 100); + } + + #[test] + fn channel_access_rules() { + let ids = PermIds { + join_power: 1, + needed_join_power: 2, + subscribe_power: 3, + channel_text_send: 4, + server_text_send: 5, + ignore_password: 6, + }; + // Guest in an open channel: can read and post. + let guest = [e(0, 4, 1)]; + assert_eq!(channel_access(&guest, &ids, false), ChannelAccess { read: true, post: true }); + // Channel needs join power 50. + let locked = [e(0, 4, 1), e(2, 2, 50)]; + assert_eq!( + channel_access(&locked, &ids, false), + ChannelAccess { read: false, post: false } + ); + let strong = [e(0, 4, 1), e(2, 2, 50), e(0, 1, 75)]; + assert!(channel_access(&strong, &ids, false).read); + // Password protected: only with the ignore-password permission. + assert!(!channel_access(&guest, &ids, true).read); + assert!(channel_access(&[e(0, 4, 1), e(0, 6, 1)], &ids, true).read); + // No text permission: read only. + assert_eq!(channel_access(&[], &ids, false), ChannelAccess { read: true, post: false }); + } +} diff --git a/crates/tsc-gateway/src/session.rs b/crates/tsc-gateway/src/session.rs new file mode 100644 index 0000000..c21a1b3 --- /dev/null +++ b/crates/tsc-gateway/src/session.rs @@ -0,0 +1,242 @@ +//! One WebSocket client. + +use std::collections::HashSet; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use axum::extract::ws::{Message, WebSocket}; +use base64::prelude::*; +use rand::RngExt; +use tokio::sync::broadcast::error::RecvError; +use tracing::{debug, info}; +use tsc_gateway_proto::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg}; +use tsc_model::{ChatTarget, Presence}; +use tsc_observer::ObserverEvent; + +use crate::hub::{Denied, Hub, User}; + +/// At most this many posts per window per session. +const POST_LIMIT: (usize, Duration) = (5, Duration::from_secs(5)); + +struct Session { + hub: Arc, + nonce: String, + user: Option, + presence: Option<(Presence, u64)>, + open_chats: HashSet, + posts: Vec, +} + +pub async fn run(hub: Arc, mut socket: WebSocket) { + let nonce_bytes: [u8; 24] = rand::rng().random(); + let mut session = Session { + nonce: BASE64_URL_SAFE_NO_PAD.encode(nonce_bytes), + hub: hub.clone(), + user: None, + presence: None, + open_chats: HashSet::new(), + posts: Vec::new(), + }; + let hello = ServerMsg::Hello { + gateway_id: hub.gateway_id.clone(), + server_uid: hub.server_uid.clone(), + server_name: hub.server_name.clone(), + nonce: session.nonce.clone(), + capabilities: vec!["presence".into(), "relay".into(), "history".into()], + }; + if send(&mut socket, None, hello).await.is_err() { + return; + } + let mut observer = hub.observer.subscribe(); + let mut chat = hub.subscribe_chat(); + + loop { + tokio::select! { + msg = socket.recv() => { + let Some(Ok(msg)) = msg else { break }; + let text = match msg { + Message::Text(t) => t, + Message::Close(_) => break, + _ => continue, + }; + let replies = match serde_json::from_str::>(text.as_str()) { + Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(), + Err(e) => vec![(None, error(ErrorCode::BadRequest, &e.to_string()))], + }; + for (id, reply) in replies { + if send(&mut socket, id, reply).await.is_err() { + break; + } + } + } + event = observer.recv(), if session.presence.is_some() => { + let resync = matches!(event, Err(RecvError::Lagged(_)) | Ok(ObserverEvent::Snapshot(_))); + if let Err(RecvError::Closed) = event { + break; + } + for msg in session.presence_update(resync) { + if send(&mut socket, None, msg).await.is_err() { + break; + } + } + } + event = chat.recv() => { + match event { + Ok((id, message)) if session.open_chats.contains(&message.target) => { + if send(&mut socket, None, ServerMsg::ChatEvent { id, message }).await.is_err() { + break; + } + } + Ok(_) | Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => break, + } + } + } + } + session.close(); +} + +async fn send(socket: &mut WebSocket, id: Option, msg: ServerMsg) -> Result<(), axum::Error> { + let env = Envelope { v: tsc_gateway_proto::VERSION, id, msg }; + let text = serde_json::to_string(&env).expect("messages serialize"); + socket.send(Message::Text(text.into())).await +} + +fn error(code: ErrorCode, message: &str) -> ServerMsg { + ServerMsg::Error { code, message: message.to_string() } +} + +impl Session { + async fn handle(&mut self, msg: ClientMsg) -> Vec { + match self.handle_inner(msg).await { + Ok(msgs) => msgs, + Err(Denied(code, message)) => vec![error(code, &message)], + } + } + + fn user(&self) -> Result<&User, Denied> { + self.user.as_ref().ok_or(Denied(ErrorCode::NotAuthenticated, "log in first".into())) + } + + async fn handle_inner(&mut self, msg: ClientMsg) -> Result, Denied> { + match msg { + ClientMsg::Ping => Ok(vec![ServerMsg::Pong]), + ClientMsg::Auth { omega, key_offset, ts, signature, .. } => { + let (user, token, token_expires) = + self.hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?; + info!(uid = %user.uid, nickname = %user.nickname, "user logged in"); + let uid = user.uid.clone(); + self.user = Some(user); + Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + } + ClientMsg::Resume { token, .. } => { + let (user, token, token_expires) = self.hub.resume(&token).await?; + let uid = user.uid.clone(); + self.user = Some(user); + Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + } + ClientMsg::SubscribePresence => { + self.user()?; + self.presence = None; + self.presence = Some((Presence::default(), 0)); + Ok(self.presence_update(true)) + } + ClientMsg::UnsubscribePresence => { + self.presence = None; + Ok(vec![ServerMsg::Ok]) + } + ClientMsg::OpenChat { target } => { + let user = self.user()?.clone(); + if self.open_chats.contains(&target) { + return Ok(vec![ServerMsg::Ok]); + } + match &target { + ChatTarget::Server => {} + ChatTarget::Channel(cid) => { + if !self.hub.channel_access(&user, *cid).await?.read { + return Err(Denied( + ErrorCode::Forbidden, + "no access to this channel".into(), + )); + } + self.hub.add_reader(*cid).await?; + } + ChatTarget::Private(_) => { + return Err(Denied( + ErrorCode::BadRequest, + "private chat is not relayed".into(), + )); + } + } + debug!(uid = %user.uid, ?target, "chat opened"); + self.open_chats.insert(target); + Ok(vec![ServerMsg::Ok]) + } + ClientMsg::CloseChat { target } => { + if self.open_chats.remove(&target) + && let ChatTarget::Channel(cid) = target + { + self.hub.remove_reader(cid); + } + Ok(vec![ServerMsg::Ok]) + } + ClientMsg::SendChat { target, text } => { + let user = self.user()?.clone(); + self.posts.retain(|t| t.elapsed() < POST_LIMIT.1); + if self.posts.len() >= POST_LIMIT.0 { + return Err(Denied(ErrorCode::Unavailable, "slow down".into())); + } + self.posts.push(Instant::now()); + self.hub.post(&user, &target, &text).await?; + Ok(vec![ServerMsg::Ok]) + } + ClientMsg::History { target, before, limit } => { + let user = self.user()?.clone(); + if let ChatTarget::Channel(cid) = target + && !self.hub.channel_access(&user, cid).await?.read + { + return Err(Denied(ErrorCode::Forbidden, "no access to this channel".into())); + } + let Some(db) = &self.hub.db else { + return Ok(vec![ServerMsg::History { messages: Vec::new() }]); + }; + let messages = db + .history(&target, before, limit.min(200)) + .map_err(|e| Denied(ErrorCode::Internal, e.to_string()))? + .into_iter() + .map(|(id, message)| HistoryEntry { id, message }) + .collect(); + Ok(vec![ServerMsg::History { messages }]) + } + } + } + + /// Send what changed in this user's view of the server (or a snapshot). + fn presence_update(&mut self, snapshot: bool) -> Vec { + let Some(user) = &self.user else { return Vec::new() }; + let Some((last, seq)) = &mut self.presence else { return Vec::new() }; + let current = self.hub.filtered_presence(user); + if snapshot { + *seq = 0; + *last = current.clone(); + return vec![ServerMsg::PresenceSnapshot { seq: 0, snapshot: current.snapshot() }]; + } + let deltas = last.diff(¤t); + *last = current; + deltas + .into_iter() + .map(|delta| { + *seq += 1; + ServerMsg::PresenceDelta { seq: *seq, delta } + }) + .collect() + } + + fn close(&mut self) { + for target in self.open_chats.drain() { + if let ChatTarget::Channel(cid) = target { + self.hub.remove_reader(cid); + } + } + } +} diff --git a/crates/tsc-gateway/tsgw.example.toml b/crates/tsc-gateway/tsgw.example.toml new file mode 100644 index 0000000..31ed2a9 --- /dev/null +++ b/crates/tsc-gateway/tsgw.example.toml @@ -0,0 +1,43 @@ +# tsgw: companion gateway for invisible presence and channel chat. +# Copy to tsgw.toml and adjust. See docs/gateway-admin.md. + +# Signed into every login challenge. Defaults to listen.public_url. +# gateway_id = "wss://gw.example.org/v1" + +[server] +# Voice port of the virtual server this gateway serves. +voice_port = 9987 + +[query] +# "ssh" (TeamSpeak 3 and 6) or "raw" (TeamSpeak 3 only). +transport = "ssh" +addr = "127.0.0.1:10022" +user = "serveradmin" +# Prefer password_file or the TSGW_QUERY_PASSWORD environment variable. +# password_file = "/run/secrets/tsgw_query_password" +# Set to true once the gateway's IP is in the server's query_ip_allowlist. +allowlisted = false + +[listen] +bind = "0.0.0.0:7788" +# public_url = "wss://gw.example.org/v1" + +[auth] +# Only these server groups may use the gateway (empty: everyone known to the server). +require_server_groups = [] +deny_uids = [] +min_security_level = 0 +token_ttl_hours = 720 + +[relay] +nickname = "Chat Relay" +format = "[{nick}] {text}" +idle_teardown_secs = 120 +max_channel_relays = 6 +# Channels relayed all the time, so their history is complete. +pinned_channels = [] + +[history] +enabled = true +path = "tsgw.db" +retention_days = 30 diff --git a/dev/tsgw-ts3.toml b/dev/tsgw-ts3.toml new file mode 100644 index 0000000..a54999f --- /dev/null +++ b/dev/tsgw-ts3.toml @@ -0,0 +1,22 @@ +# Gateway for the ts3 development server (dev/docker-compose.yml). +# cargo run -p tsc-gateway -- --config dev/tsgw-ts3.toml + +[server] +# Inside the container the voice port is always 9987. +voice_port = 9987 + +[query] +transport = "raw" +addr = "127.0.0.1:10011" +user = "serveradmin" +password = "tsc-dev-admin" +allowlisted = true + +[listen] +bind = "127.0.0.1:7787" + +[relay] +idle_teardown_secs = 30 + +[history] +path = "dev/.state/tsgw-ts3.db" diff --git a/dev/tsgw-ts6.toml b/dev/tsgw-ts6.toml new file mode 100644 index 0000000..a2816e3 --- /dev/null +++ b/dev/tsgw-ts6.toml @@ -0,0 +1,22 @@ +# Gateway for the ts6 development server (dev/docker-compose.yml). +# cargo run -p tsc-gateway -- --config dev/tsgw-ts6.toml + +[server] +# Inside the container the voice port is always 9987. +voice_port = 9987 + +[query] +transport = "ssh" +addr = "127.0.0.1:10022" +user = "serveradmin" +password = "tsc-dev-admin" +allowlisted = true + +[listen] +bind = "127.0.0.1:7788" + +[relay] +idle_teardown_secs = 30 + +[history] +path = "dev/.state/tsgw-ts6.db" diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md new file mode 100644 index 0000000..2d51139 --- /dev/null +++ b/docs/gateway-admin.md @@ -0,0 +1,77 @@ +# Running the tsgw gateway + +`tsgw` lets users of this client see who is in which channel and read and +write channel chat **without joining voice**, on a server you administer. It +holds ServerQuery sessions (invisible to normal users of the official clients) +and serves users over a WebSocket (`tsgw.v1+json`, see `crates/tsc-gateway-proto`). + +## What users get + +| Feature | How | +|---|---| +| Presence | One query session watches the server; each user sees the channels their `i_channel_subscribe_power` allows, without query clients | +| Channel chat | A relay query session is moved into each channel someone opened; it forwards what is said and posts users' messages as `[Nick] text` | +| Server chat | Read by the watcher, posted by the gateway's lookup session | +| History | Relayed messages are stored (SQLite) and can be paged | + +The nickname in relayed posts is the one the server has on record for the +user's identity (from `clientdbinfo`), not something the user can choose. + +## Authentication and authorization + +Users log in by signing a challenge with their TeamSpeak identity key. The +gateway derives the unique id (SHA-1 of the public key on TeamSpeak 3, SHA-256 +on TeamSpeak 6) and looks it up with `clientdbfind`, so **an identity must have +connected to the server with voice once** before it can use the gateway. + +Checks, mirroring what the user could do with a real connection +(`permoverview`, cached 60 s): + +- identity security level ≥ `virtualserver_needed_identity_security_level` + (and `auth.min_security_level`); not in `banlist`; not in `auth.deny_uids`; + member of one of `auth.require_server_groups` if set +- read a channel: `i_channel_join_power` ≥ the channel's + `i_channel_needed_join_power`, and no channel password unless the user has + `b_channel_join_ignore_password` +- post in a channel: the above plus `b_client_channel_textmessage_send` +- post in server chat: `b_client_server_textmessage_send` +- see a channel in presence: `i_channel_subscribe_power` (server level) ≥ the + channel's `channel_needed_subscribe_power` + +Posts are limited to 5 per 5 seconds per connection, and every login and post +is written to the audit table. + +## Setup + +1. Enable ServerQuery. TeamSpeak 6 has it off by default: + `TSSERVER_QUERY_SSH_ENABLED=1` (the gateway needs events, so SSH, not HTTP). + TeamSpeak 3: raw (10011) or SSH (10022). +2. Use a query login with enough rights for `clientdbfind`, `clientdbinfo`, + `permoverview`, `banlist`, `clientmove` and `sendtextmessage`, e.g. a + dedicated login in the Server Admin group. +3. Put the gateway's IP into `query_ip_allowlist.txt` and set + `query.allowlisted = true`. Otherwise the server's flood protection + (10 commands / 3 s) applies and bans the gateway under load. +4. Each relayed channel is one more query connection. Keep + `relay.max_channel_relays` below the server's per-IP connection limit. + Relays count toward a channel's max clients unless their group has + `b_channel_join_ignore_maxclients`. +5. Copy `crates/tsc-gateway/tsgw.example.toml` to `tsgw.toml`, set the query + address and credentials (`TSGW_QUERY_PASSWORD` or `password_file`). +6. Run it behind TLS (Caddy, nginx) and give users the `wss://…/v1` URL. + +```sh +cargo run --release -p tsc-gateway -- --config tsgw.toml +# or +docker build -f crates/tsc-gateway/Dockerfile -t tsgw . +docker run -v $PWD/tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw +``` + +## Visibility + +Query clients are not hidden by the server; official clients hide them from +users whose `i_client_serverquery_view_power` is below the query client's +needed view power (100 by default). Server Admins, and third-party clients +that ignore the rule, see the gateway's sessions. Relayed channels show the +relay's posts under its own nickname (`Chat Relay `), so people in the +channel can tell the messages come through the gateway. diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 5e47209..fccd922 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -15,6 +15,11 @@ capture teaches something new. "Unknown argument"): - `initserver`: `virtualserver_address`, `virtualserver_version_sign` - `initserver` / `notifycliententerview`: `client_is_streaming` +- **Confirmed**: unique ids differ. TeamSpeak 3 uses `base64(SHA1(omega))` + (28 characters), TeamSpeak 6 uses `base64(SHA256(omega))` (44 characters), + where omega is the base64 public key string. The same identity therefore has + a different `client_unique_identifier` on each server generation + (`tsc-gateway-proto::UniqueIds`). - **Confirmed**: TS6 has no raw ServerQuery port; SSH query on 10022 and HTTP WebQuery on 10080 (HTTPS 10443). - **Reported**: beta13 made the Init1 puzzle difficulty adaptive to the server's diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 529c98e..1b0eb62 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -9,6 +9,8 @@ # 4. voice: a 1 kHz tone sent by one client is recorded by another # 5. invisible presence: a ServerQuery observer sees a voice client join # 6. relay chat: a query relay reads channel chat and posts into the channel +# 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat +# both ways, refusal of an identity the server does not know # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl) @@ -25,13 +27,15 @@ mkdir -p "$STATE_DIR" trap 'kill $(jobs -p) 2>/dev/null || true' EXIT if [[ -z "${TSCTL:-}" ]]; then - cargo build --quiet -p tsctl + cargo build --quiet -p tsctl -p tsc-gateway TSCTL=target/debug/tsctl fi +TSGW="${TSGW:-target/debug/tsgw}" declare -A PORTS=([ts3]=9987 [ts6]=9988) # ServerQuery transport and address per server (dev/docker-compose.yml). declare -A QUERY=([ts3]="raw 127.0.0.1:10011" [ts6]="ssh 127.0.0.1:10022") +declare -A GATEWAY=([ts3]=7787 [ts6]=7788) QUERY_SECRET=tsc-dev-admin SERVERS=("$@") [[ ${#SERVERS[@]} -eq 0 ]] && SERVERS=(ts3 ts6) @@ -148,6 +152,49 @@ relay_check() { grep "from-relay-$token" "$heard" } +# Users of the gateway: presence, chat both ways, refusal of unknown identities. +gateway_check() { + local svc=$1 addr=$2 port=${GATEWAY[$svc]} out="$STATE_DIR/gateway.log" + local url="ws://127.0.0.1:$port/v1" token="gw-$RANDOM$RANDOM" + "$TSGW" --config "dev/tsgw-$svc.toml" >"$STATE_DIR/tsgw-$svc.log" 2>&1 & + local gateway=$! + for _ in $(seq 1 40); do + grep -q "listening" "$STATE_DIR/tsgw-$svc.log" 2>/dev/null && break + sleep 0.25 + done + + # The gateway only knows identities that connected with voice once. + local user="$STATE_DIR/$svc-gateway-user.json" stranger="$STATE_DIR/stranger.json" + [[ -f "$user" ]] || "$TSCTL" identity new --out "$user" >/dev/null + "$TSCTL" connect "$addr" --identity "$user" --nick gateway-user tree >/dev/null + "$TSCTL" identity new --out "$stranger" --force >/dev/null + if "$TSCTL" gateway "$url" --identity "$stranger" --seconds 3 >/dev/null 2>&1; then + fail "gateway accepted an identity the server does not know" + fi + + "$TSCTL" gateway "$url" --identity "$user" --presence --open channel:1 \ + --expect "to-gateway-$token" --seconds 20 >"$out" 2>&1 & + local reader=$! + "$TSCTL" connect "$addr" --nick gateway-listener listen --expect "from-gateway-$token" \ + --timeout 20 >"$STATE_DIR/gateway-heard.log" 2>&1 & + local listener=$! + sleep 4 + "$TSCTL" connect "$addr" --nick gateway-talker chat channel "to-gateway-$token" + "$TSCTL" gateway "$url" --identity "$user" --send "channel:1=from-gateway-$token" --seconds 3 >/dev/null + if ! wait "$reader"; then + cat "$out" "$STATE_DIR/tsgw-$svc.log" + fail "gateway user did not receive the channel message" + fi + if ! wait "$listener"; then + cat "$STATE_DIR/gateway-heard.log" + fail "voice client did not receive the gateway user's post" + fi + grep -E "presence:|to-gateway-$token" "$out" + grep "from-gateway-$token" "$STATE_DIR/gateway-heard.log" + kill "$gateway" + wait "$gateway" 2>/dev/null || true +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" @@ -165,6 +212,7 @@ for svc in "${SERVERS[@]}"; do voice_roundtrip "$addr" presence_check "$addr" "${QUERY[$svc]}" relay_check "$addr" "${QUERY[$svc]}" + gateway_check "$svc" "$addr" done log "all smoke tests passed" diff --git a/tools/tsctl/Cargo.toml b/tools/tsctl/Cargo.toml index ee1c2c8..24235de 100644 --- a/tools/tsctl/Cargo.toml +++ b/tools/tsctl/Cargo.toml @@ -24,6 +24,9 @@ tsc-model = { path = "../../crates/tsc-model" } tsc-query = { path = "../../crates/tsc-query" } tsc-observer = { path = "../../crates/tsc-observer" } tsc-audio = { path = "../../crates/tsc-audio", default-features = false } +tokio-tungstenite = "0.30" +futures-util = "0.3.34" +tsc-gateway-proto = { path = "../../crates/tsc-gateway-proto" } [lints] workspace = true diff --git a/tools/tsctl/src/gateway.rs b/tools/tsctl/src/gateway.rs new file mode 100644 index 0000000..decfcba --- /dev/null +++ b/tools/tsctl/src/gateway.rs @@ -0,0 +1,187 @@ +//! `tsctl gateway`: talk to a tsgw gateway as a user. + +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow, bail}; +use clap::Args; +use futures_util::{SinkExt, StreamExt}; +use tokio::time::{Instant, timeout_at}; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tsc_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge}; +use tsc_model::{ChatTarget, Presence}; + +#[derive(Args, Debug, Clone)] +pub struct GatewayArgs { + /// Gateway URL, e.g. ws://127.0.0.1:7788/v1. + pub url: String, + /// Identity file (must have connected to the server with voice once). + #[arg(long, env = "TSCTL_IDENTITY")] + pub identity: PathBuf, + /// Receive presence and print the tree. + #[arg(long)] + pub presence: bool, + /// Open a chat: `server` or `channel:`. Repeatable. + #[arg(long = "open")] + pub open: Vec, + /// Send a message: `=`, e.g. `channel:1=hello`. + #[arg(long = "send")] + pub send: Vec, + /// Print stored history of a target. + #[arg(long)] + pub history: Option, + /// Stop after this many seconds. + #[arg(long, default_value_t = 10)] + pub seconds: u64, + /// Exit successfully when a chat message containing this text arrives. + #[arg(long)] + pub expect: Option, + /// Exit successfully when a client with this nickname is present. + #[arg(long)] + pub expect_client: Option, +} + +fn parse_target(s: &str) -> Result { + match s.split_once(':') { + None if s == "server" => Ok(ChatTarget::Server), + Some(("channel", cid)) => Ok(ChatTarget::Channel(cid.parse().context("channel id")?)), + _ => bail!("target must be `server` or `channel:`, got {s:?}"), + } +} + +pub async fn run(args: GatewayArgs) -> Result<()> { + let identity = crate::identity::load(&args.identity)?; + let mut request = args.url.as_str().into_client_request()?; + request.headers_mut().insert("Sec-WebSocket-Protocol", tsc_gateway_proto::SUBPROTOCOL.parse()?); + let (mut ws, _) = tokio_tungstenite::connect_async(request) + .await + .with_context(|| format!("failed to connect to {}", args.url))?; + let deadline = Instant::now() + Duration::from_secs(args.seconds); + + macro_rules! send { + ($id:expr, $msg:expr) => { + ws.send(Message::Text(serde_json::to_string(&Envelope::with_id($id, $msg))?.into())) + .await? + }; + } + + // Hello -> Auth -> AuthOk + let (gateway_id, server_uid, nonce) = match next(&mut ws, deadline).await? { + ServerMsg::Hello { gateway_id, server_uid, nonce, server_name, .. } => { + eprintln!("gateway for {server_name:?}"); + (gateway_id, server_uid, nonce) + } + other => bail!("expected hello, got {other:?}"), + }; + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() as i64; + let key = identity.key(); + send!( + 1, + ClientMsg::Auth { + omega: key.to_pub().to_ts(), + key_offset: identity.counter(), + ts, + signature: sign_challenge(key, &gateway_id, &server_uid, &nonce, ts), + nickname: String::new(), + } + ); + match next(&mut ws, deadline).await? { + ServerMsg::AuthOk { uid, .. } => eprintln!("logged in as {uid}"), + ServerMsg::Error { code, message } => bail!("login refused: {code:?}: {message}"), + other => bail!("unexpected {other:?}"), + } + + let mut id = 1; + if args.presence { + id += 1; + send!(id, ClientMsg::SubscribePresence); + } + for target in &args.open { + id += 1; + send!(id, ClientMsg::OpenChat { target: parse_target(target)? }); + } + for spec in &args.send { + let (target, text) = + spec.split_once('=').ok_or_else(|| anyhow!("--send needs ="))?; + id += 1; + send!(id, ClientMsg::SendChat { target: parse_target(target)?, text: text.to_string() }); + } + if let Some(target) = &args.history { + id += 1; + send!(id, ClientMsg::History { target: parse_target(target)?, before: None, limit: 50 }); + } + + let mut presence = Presence::default(); + loop { + let msg = match next(&mut ws, deadline).await { + Ok(m) => m, + Err(e) if e.to_string() == "timeout" => break, + Err(e) => return Err(e), + }; + match msg { + ServerMsg::PresenceSnapshot { snapshot, .. } => { + presence = Presence::from_snapshot(snapshot); + println!( + "presence: {} channels, {} clients", + presence.channels.len(), + presence.clients.len() + ); + for c in presence.clients.values() { + let channel = + presence.channels.get(&c.channel).map(|c| c.name.as_str()).unwrap_or("?"); + println!(" {} in #{channel}", c.nickname); + } + } + ServerMsg::PresenceDelta { seq, delta } => { + presence.apply(&delta); + println!("delta {seq}: {}", serde_json::to_string(&delta)?); + } + ServerMsg::ChatEvent { id, message } => { + println!( + "chat #{id} {:?} {}: {}", + message.target, message.author_name, message.text + ); + if args.expect.as_ref().is_some_and(|e| message.text.contains(e.as_str())) { + return Ok(()); + } + } + ServerMsg::History { messages } => { + println!("history: {} messages", messages.len()); + for m in messages { + println!(" #{} {}: {}", m.id, m.message.author_name, m.message.text); + } + } + ServerMsg::Error { code, message } => println!("error: {code:?}: {message}"), + ServerMsg::Ok | ServerMsg::Pong => {} + other => println!("{other:?}"), + } + if let Some(nick) = &args.expect_client + && presence.clients.values().any(|c| &c.nickname == nick) + { + return Ok(()); + } + } + if args.expect.is_some() || args.expect_client.is_some() { + bail!("expected event did not arrive"); + } + Ok(()) +} + +async fn next(ws: &mut S, deadline: Instant) -> Result +where + S: StreamExt> + Unpin, +{ + loop { + let msg = timeout_at(deadline, ws.next()).await.map_err(|_| anyhow!("timeout"))?; + match msg { + Some(Ok(Message::Text(text))) => { + let env: Envelope = serde_json::from_str(text.as_str())?; + return Ok(env.msg); + } + Some(Ok(Message::Close(_))) | None => bail!("gateway closed the connection"), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(e.into()), + } + } +} diff --git a/tools/tsctl/src/main.rs b/tools/tsctl/src/main.rs index 081e841..8e5bebc 100644 --- a/tools/tsctl/src/main.rs +++ b/tools/tsctl/src/main.rs @@ -1,5 +1,6 @@ //! `tsctl`: headless TeamSpeak 3/6 client for development and integration tests. +mod gateway; mod identity; mod observe; mod query; @@ -42,6 +43,8 @@ enum Command { Observe(observe::ObserveArgs), /// Read and write a channel's chat through an invisible query relay. Relay(observe::RelayArgs), + /// Use a tsgw gateway as a user: presence, chat, history. + Gateway(gateway::GatewayArgs), } #[derive(Subcommand, Debug)] @@ -201,6 +204,7 @@ fn main() -> Result<()> { Command::Query(args) => tokio::runtime::Runtime::new()?.block_on(query::run(args)), Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)), Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), + Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::run(args)), } } @@ -223,6 +227,7 @@ fn run_identity(command: IdentityCommand) -> Result<()> { let id = identity::load(&path)?; println!("uid: {}", identity::uid(&id)); println!("level: {}", id.level()); + println!("omega: {}", id.key().to_pub().to_ts()); Ok(()) } }