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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
7b5f1ad2bb
commit
120d3dfc82
24 files changed
+2578
-9
No files matched your search
@@ -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" }
|
||||
@@ -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<u8> {
|
||||
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<UniqueIds, AuthError> {
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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<M> {
|
||||
pub v: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<u64>,
|
||||
#[serde(flatten)]
|
||||
pub msg: M,
|
||||
}
|
||||
|
||||
impl<M> Envelope<M> {
|
||||
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<i64>,
|
||||
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<String>,
|
||||
},
|
||||
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<HistoryEntry>,
|
||||
},
|
||||
/// 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<ClientMsg> = 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<ClientMsg> = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(
|
||||
env.msg,
|
||||
ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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"]
|
||||
@@ -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<String>,
|
||||
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<String>,
|
||||
#[serde(default)]
|
||||
pub password_file: Option<PathBuf>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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<u64>,
|
||||
/// Unique ids that may never use the gateway.
|
||||
#[serde(default)]
|
||||
pub deny_uids: Vec<String>,
|
||||
/// 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<u64>,
|
||||
}
|
||||
|
||||
#[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<Self> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<Connection>);
|
||||
|
||||
#[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> {
|
||||
Self::init(Connection::open(path)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn in_memory() -> rusqlite::Result<Self> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> rusqlite::Result<Self> {
|
||||
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<Option<TokenInfo>> {
|
||||
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<i64> {
|
||||
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<i64>,
|
||||
limit: u32,
|
||||
) -> rusqlite::Result<Vec<(i64, ChatMessage)>> {
|
||||
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::<rusqlite::Result<Vec<_>>>()?;
|
||||
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::<Vec<_>>(), ["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());
|
||||
}
|
||||
}
|
||||
@@ -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<String>) -> Self {
|
||||
Self(code, msg.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tsc_query::Error> 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<Db>,
|
||||
chat: broadcast::Sender<(i64, ChatMessage)>,
|
||||
/// Readers per relayed channel, and when the last one left.
|
||||
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
|
||||
/// Our own query clients, whose messages are echoes.
|
||||
own_clients: Mutex<HashSet<u16>>,
|
||||
next_message_id: Mutex<i64>,
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub async fn start(config: Config) -> Result<Arc<Self>> {
|
||||
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<Self>) {
|
||||
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<Self>) {
|
||||
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<Self>) {
|
||||
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<ChannelId> = 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<User, Denied> {
|
||||
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::<u64>("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<ChannelAccess, Denied> {
|
||||
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<bool, Denied> {
|
||||
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()))
|
||||
}
|
||||
@@ -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<Arc<Hub>>, 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");
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Mirror the server's permission checks for users who are not connected.
|
||||
//!
|
||||
//! `permoverview cid=<channel> cldbid=<user> 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<Self> {
|
||||
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<Self> {
|
||||
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<Entry>)>;
|
||||
|
||||
/// Caches `permoverview` per (user, channel).
|
||||
pub struct PermResolver {
|
||||
pub ids: PermIds,
|
||||
cache: Mutex<Cache>,
|
||||
}
|
||||
|
||||
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<Vec<Entry>> {
|
||||
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<Entry> = 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 });
|
||||
}
|
||||
}
|
||||
@@ -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<Hub>,
|
||||
nonce: String,
|
||||
user: Option<User>,
|
||||
presence: Option<(Presence, u64)>,
|
||||
open_chats: HashSet<ChatTarget>,
|
||||
posts: Vec<Instant>,
|
||||
}
|
||||
|
||||
pub async fn run(hub: Arc<Hub>, 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::<Envelope<ClientMsg>>(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<u64>, 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<ServerMsg> {
|
||||
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<Vec<ServerMsg>, 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<ServerMsg> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
Reference in new issue
Block a user