Merge branch 'codex/myteamspeak-account': myTeamSpeak account sign-in

Conflicts with the channel banners on main, both kept:
- crates/proto/UPSTREAM.md: myTeamSpeak's local patch is number 14, after
  the channel banners' 13.
- voelin-core/src/voice.rs: both test modules.
- ui/app.slint: the mobile shell hides behind the account prompt and keeps
  the channel chat's banner.
- ui/shells/common.slint: the user card counts a signed-in account as named
  and shows our avatar, the person icon only without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEpqsPES27Eacue91u3d2Q
This commit is contained in:
Claude committed 2026-10-04 17:55:31 +00:00
commit 64fa161cd6
185 files changed
+52751 -217

No files matched your search

+12 -2
View File
@@ -63,6 +63,7 @@ pub mod settings;
pub mod stream;
#[cfg(feature = "media")]
pub mod studio;
pub mod versions;
mod voice;
mod web;
@@ -70,7 +71,7 @@ use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
use tokio::sync::{broadcast, mpsc, watch};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{
@@ -101,6 +102,8 @@ pub type SessionId = u64;
/// What the UI asks for.
#[derive(Clone, Debug)]
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -812,6 +815,7 @@ async fn run(
// Before any command: a contact set meanwhile would be lost.
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
@@ -856,6 +860,10 @@ async fn run(
},
};
let id = match command {
Command::SetMytsIdentity(identity) => {
myts_identity.send_replace(identity);
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -931,6 +939,7 @@ async fn run(
frames.clone(),
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1008,7 +1017,8 @@ fn command_session(command: &Command) -> SessionId {
| Command::DeleteOfflineMessage { session, .. }
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetAudioSettings(_)
Command::SetMytsIdentity(_)
| Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
+10 -2
View File
@@ -86,9 +86,12 @@ impl SessionHandle {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames, audio_settings, shared).run(rx));
tokio::spawn(
Session::new(id, events, frames, audio_settings, shared, myts_identity).run(rx),
);
Self { tx }
}
@@ -171,6 +174,7 @@ struct OwnStream {
}
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -244,11 +248,13 @@ impl Session {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
myts_identity,
cache,
contacts,
contacts_rx,
@@ -381,6 +387,7 @@ impl Session {
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
let link = VoiceLink {
myts_identity: self.myts_identity.clone(),
session: self.id,
events: self.events.clone(),
settings: self.settings.clone(),
@@ -691,7 +698,8 @@ impl Session {
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
}
// Engine-wide.
Command::CloseSession { .. }
Command::SetMytsIdentity(_)
| Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
+175
View File
@@ -0,0 +1,175 @@
//! Known signed client versions.
//!
//! `clientinit` must carry a `client_version_sign` produced by TeamSpeak's
//! private key, so a client can only claim versions from this list of captured
//! signatures (the `Versions.csv` declaration file).
use anyhow::{Context, Result, bail};
use base64::prelude::*;
use tsclientlib::Version;
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KnownVersion {
pub version: String,
pub platform: String,
pub signature: String,
}
impl KnownVersion {
pub fn to_version(&self) -> Result<Version> {
let signature = BASE64_STANDARD
.decode(&self.signature)
.with_context(|| format!("invalid signature for {}@{}", self.platform, self.version))?;
Ok(Version::Custom {
platform: self.platform.clone(),
version: self.version.clone(),
signature,
})
}
}
pub fn known_versions() -> Vec<KnownVersion> {
VERSIONS_CSV
.lines()
.skip(1)
.filter(|l| !l.trim().is_empty())
.filter_map(|l| {
// The version string contains no commas, the signature is base64.
let mut parts = l.splitn(3, ',');
Some(KnownVersion {
version: parts.next()?.to_string(),
platform: parts.next()?.to_string(),
signature: parts.next()?.trim().to_string(),
})
})
.collect()
}
/// Resolve a `--client-version` argument.
///
/// Accepts `default` (the core native-platform default), an index into [`known_versions`],
/// or `<platform>@<version>` with the exact strings from `voelinctl versions`.
pub fn resolve(spec: &str) -> Result<Option<Version>> {
if spec == "default" {
return Ok(None);
}
let versions = known_versions();
if let Ok(i) = spec.parse::<usize>() {
let Some(v) = versions.get(i) else {
bail!("version index {i} out of range (0..{})", versions.len());
};
return v.to_version().map(Some);
}
let Some((platform, version)) = spec.split_once('@') else {
bail!("expected `default`, an index or `<platform>@<version>`, got {spec:?}");
};
match versions.iter().find(|v| v.platform == platform && v.version == version) {
Some(v) => v.to_version().map(Some),
None => bail!("unknown client version {spec:?}, see `voelinctl versions`"),
}
}
/// The signed compatibility tuple for the native operating system.
///
/// The generic version retains the library's minimum-version compatibility.
/// Its version, platform and signature must stay together: the signature does
/// not authorize renaming the client or changing its platform.
///
/// Unsupported operating systems return an error rather than claiming another
/// platform. Product identity belongs in [`client_metadata`], not this tuple.
pub fn native_version() -> Result<Version> {
compatibility_version(std::env::consts::OS)
}
fn compatibility_version(os: &str) -> Result<Version> {
let platform = match os {
"linux" => "Linux",
"windows" => "Windows",
"macos" => "OS X",
"android" => "Android",
"ios" => "iOS",
_ => bail!("no signed compatibility version for operating system {os:?}"),
};
known_versions()
.into_iter()
.find(|version| version.platform == platform && version.version.contains("3.6"))
.with_context(|| format!("missing signed compatibility version for {platform}"))?
.to_version()
}
/// Truthful product identity, separate from the signed compatibility tuple.
pub fn client_metadata() -> String {
serde_json::json!({
"name": "Voelin",
"version": env!("CARGO_PKG_VERSION"),
"platform": std::env::consts::OS,
})
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_platform_preserves_complete_signed_tuple() {
for (os, platform) in [
("linux", "Linux"),
("windows", "Windows"),
("macos", "OS X"),
("android", "Android"),
("ios", "iOS"),
] {
let version = compatibility_version(os).unwrap();
assert_eq!(version.get_platform(), platform);
assert_eq!(version.get_version_string(), "3.?.? [Build: 5680278000]");
assert_eq!(version.get_signature().len(), 64);
let known = known_versions()
.into_iter()
.find(|known| {
known.platform == platform && known.version == version.get_version_string()
})
.unwrap();
assert_eq!(version, known.to_version().unwrap());
}
assert!(compatibility_version("freebsd").is_err());
assert!(compatibility_version("unknown").is_err());
match compatibility_version(std::env::consts::OS) {
Ok(expected) => assert_eq!(native_version().unwrap(), expected),
Err(_) => assert!(native_version().is_err()),
}
}
#[test]
fn metadata_identifies_voelin_without_changing_signed_version() {
let metadata: serde_json::Value = serde_json::from_str(&client_metadata()).unwrap();
assert_eq!(metadata["name"], "Voelin");
assert_eq!(metadata["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(metadata["platform"], std::env::consts::OS);
}
#[test]
fn parses_all_rows() {
let versions = known_versions();
assert!(versions.len() > 50);
for v in &versions {
let signature = BASE64_STANDARD.decode(&v.signature).unwrap();
assert_eq!(signature.len(), 64, "{v:?}");
}
}
#[test]
fn resolves_specs() {
assert!(resolve("default").unwrap().is_none());
let by_index = resolve("0").unwrap().unwrap();
let first = &known_versions()[0];
let by_name = resolve(&format!("{}@{}", first.platform, first.version)).unwrap().unwrap();
assert_eq!(by_index, by_name);
assert_eq!(by_name.get_platform(), first.platform);
assert!(resolve("Nope@1.0").is_err());
assert!(resolve("100000").is_err());
assert!(resolve("garbage").is_err());
}
}
+210 -33
View File
@@ -8,11 +8,12 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use futures::prelude::*;
use tokio::sync::{broadcast, mpsc};
use tokio::sync::{broadcast, mpsc, watch};
use tokio::task::AbortHandle;
use tokio::time::{Instant, timeout};
use tracing::{debug, info, warn};
@@ -39,7 +40,7 @@ pub struct VoiceOptions {
pub address: String,
pub nickname: String,
pub identity: Option<Identity>,
/// Signed client version; `None` for the library default.
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`.
@@ -68,6 +69,7 @@ impl VoiceOptions {
/// Where a voice connection reports answers the session does not need to see.
#[derive(Clone)]
pub(crate) struct VoiceLink {
pub myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
pub session: SessionId,
pub events: broadcast::Sender<Event>,
pub settings: SharedSettings,
@@ -224,6 +226,8 @@ fn now_ms() -> i64 {
}
enum Input {
MytsIdentityChanged,
AccountSourceClosed,
Item(Option<Result<StreamItem, tsclientlib::Error>>),
Cmd(Option<VoiceCmd>),
Tick,
@@ -231,6 +235,7 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
Stream(Request),
FileList {
request: RequestId,
@@ -343,35 +348,55 @@ async fn run_inner(
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
events: &mpsc::UnboundedSender<VoiceEvent>,
) -> anyhow::Result<()> {
let mut builder = Connection::build(options.address.clone()).name(options.nickname.clone());
let version = match &options.client_version {
Some(version) => version.clone(),
None => crate::versions::native_version()?,
};
let mut builder = Connection::build(options.address.clone())
.name(options.nickname.clone())
.version(version)
.metadata(crate::versions::client_metadata());
if let Some(identity) = &options.identity {
builder = builder.identity(identity.clone());
}
if let Some(version) = &options.client_version {
builder = builder.version(version.clone());
}
if let Some(pw) = &options.server_password {
builder = builder.password(pw.clone());
}
if let Some(channel) = &options.channel {
builder = builder.channel(channel.clone());
}
let mut con = builder.connect()?;
// Wait for the initial state.
let connected = timeout(Duration::from_secs(30), async {
con.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await
let mut identity = link.myts_identity.clone();
// A changed account invalidates an in-flight handshake. Drop that connection
// and take a fresh snapshot before publishing any connected state.
let mut con = timeout(Duration::from_secs(30), async {
loop {
let snapshot = identity.borrow_and_update().as_deref().cloned();
let mut con = builder.clone().myts_identity(snapshot).connect()?;
let connected = tokio::select! {
biased;
changed = identity.changed() => {
changed.map_err(|_| anyhow::anyhow!("account source closed"))?;
continue;
}
connected = async {
con.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next().await
} => connected,
};
match connected {
Some(Ok(_)) => {}
Some(Err(e)) => return Err(anyhow::Error::from(e)),
None => anyhow::bail!("connection closed"),
}
if identity.has_changed().unwrap_or(true) {
continue;
}
return Ok(con);
}
})
.await
.map_err(|_| anyhow::anyhow!("timed out while connecting"))?;
match connected {
Some(Ok(_)) => {}
Some(Err(e)) => return Err(e.into()),
None => anyhow::bail!("connection closed"),
}
.map_err(|_| anyhow::anyhow!("timed out while connecting"))??;
let server_uid = {
let state = con.get_state()?;
let flavor = ServerFlavor::from_version_string(&state.server.version);
@@ -409,15 +434,25 @@ async fn run_inner(
let mut tick = tokio::time::interval(Duration::from_millis(250));
let result = loop {
let input = {
let mut stream = voice.con.events();
tokio::select! {
item = stream.next() => Input::Item(item),
cmd = commands.recv() => Input::Cmd(cmd),
_ = tick.tick() => Input::Tick,
}
};
// Check on every turn so busy command/audio queues cannot delay expiry.
if voice.pending.values().any(|pending| {
matches!(pending, Pending::MytsIdentity(started)
if started.elapsed() >= Duration::from_secs(10))
}) {
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
}
let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await;
match input {
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
Input::MytsIdentityChanged => {
let snapshot = identity.borrow_and_update().as_deref().cloned();
match voice.con.update_myts_identity(snapshot) {
Ok(handle) => {
voice.pending.insert(handle, Pending::MytsIdentity(Instant::now()));
}
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
}
}
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
Input::Item(Some(Err(e))) => break Err(e.into()),
Input::Item(Some(Ok(item))) => {
@@ -438,10 +473,52 @@ async fn run_inner(
for (_, job) in voice.jobs.drain() {
job.report()(TransferState::Failed("disconnected".into()));
}
let disconnect = shutdown_connection(voice.con).await;
result?;
voice.con.disconnect(DisconnectOptions::new())?;
let _ =
timeout(Duration::from_secs(3), voice.con.events().for_each(|_| future::ready(()))).await;
disconnect?;
Ok(())
}
async fn next_input(
stream: &mut (impl Stream<Item = Result<StreamItem, tsclientlib::Error>> + Unpin),
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
tick: &mut tokio::time::Interval,
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
) -> Input {
tokio::select! {
biased;
changed = identity.changed() => if changed.is_ok() {
Input::MytsIdentityChanged
} else {
Input::AccountSourceClosed
},
input = async {
// Keep account changes first without starving network or timers when
// the audio command queue remains ready.
tokio::select! {
cmd = commands.recv() => Input::Cmd(cmd),
_ = tick.tick() => Input::Tick,
item = stream.next() => Input::Item(item),
}
} => input,
}
}
async fn shutdown_connection(mut con: Connection) -> Result<(), tsclientlib::Error> {
// disconnect() also returns Ok while Connecting. Never poll that stale
// handshake: dropping it is the cancellation boundary for logout.
if con.get_state().is_err() {
return Ok(());
}
con.disconnect(DisconnectOptions::new())?;
let _ = timeout(Duration::from_secs(3), async {
while con.get_state().is_ok() {
if con.events().next().await.is_none() {
break;
}
}
})
.await;
Ok(())
}
@@ -496,7 +573,13 @@ impl Voice {
StreamItem::MessageEvent(msg) => self.message_event(&msg),
StreamItem::MessageResult(handle, result) => {
if let Some(pending) = self.pending.remove(&handle) {
self.answered(pending, result.map_err(|e| e.error));
if matches!(pending, Pending::MytsIdentity(_)) {
result.map_err(|e| {
anyhow::anyhow!("myTeamSpeak account update: {}", e.error)
})?;
} else {
self.answered(pending, result.map_err(|e| e.error));
}
}
}
StreamItem::FileDownload(handle, download) => {
@@ -714,7 +797,7 @@ impl Voice {
};
self.link.emit(Event::OfflineMessage { session, request, result });
}
Pending::Quiet => {}
Pending::Quiet | Pending::MytsIdentity(_) => {}
Pending::Report(what) => {
if let Err(e) = result {
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
@@ -1021,3 +1104,97 @@ mod image_download_tests {
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
}
}
#[cfg(test)]
mod account_tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn account_priority_preserves_ready_network_and_timer_progress() {
let (account, mut identity) = watch::channel(None);
let (commands, mut receiver) = mpsc::unbounded_channel();
for _ in 0..512 {
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
}
let mut stream = futures::stream::poll_fn(|_| {
std::task::Poll::Ready(Some(Err(tsclientlib::Error::NotConnected)))
});
let mut tick = tokio::time::interval(Duration::from_millis(1));
account.send_replace(None);
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await,
Input::MytsIdentityChanged
));
identity.borrow_and_update();
let (mut network, mut timers, mut audio) = (0, 0, 0);
for _ in 0..512 {
tokio::time::advance(Duration::from_millis(1)).await;
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await {
Input::Item(_) => network += 1,
Input::Tick => timers += 1,
Input::Cmd(_) => audio += 1,
_ => panic!("unexpected account change"),
}
}
assert!(network > 0 && timers > 0 && audio > 0);
}
#[tokio::test]
async fn shutdown_never_polls_a_connecting_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut con =
Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap();
assert!(matches!(con.update_myts_identity(None), Err(tsclientlib::Error::NotConnected)));
// tsclientlib returns Ok here despite retaining its Connecting future.
assert!(con.disconnect(DisconnectOptions::new()).is_ok());
timeout(Duration::from_millis(100), shutdown_connection(con)).await.unwrap().unwrap();
let mut packet = [0; 2048];
assert!(matches!(server.try_recv_from(&mut packet), Err(error)
if error.kind() == std::io::ErrorKind::WouldBlock));
}
#[tokio::test]
async fn account_change_cancels_pending_handshake() {
// A silent UDP peer keeps the handshake in flight without an external server.
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let (account, identity) = watch::channel(None);
let (events, _) = broadcast::channel(8);
let link = VoiceLink {
session: 1,
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: identity,
};
let (_commands, commands) = mpsc::unbounded_channel();
let (events, mut received) = mpsc::unbounded_channel();
let task = tokio::spawn(run(
VoiceOptions::new(server.local_addr().unwrap().to_string(), "account-test"),
link,
commands,
events,
));
let mut packet = [0; 2048];
let (_, first) =
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
// A logout/clear notification must cancel the old socket and restart.
account.send_replace(None);
let second = timeout(Duration::from_secs(5), async {
loop {
let (_, peer) = server.recv_from(&mut packet).await.unwrap();
if peer != first {
break peer;
}
}
})
.await
.unwrap();
assert_ne!(first, second);
// Losing the account authority fails closed immediately, not after connect timeout.
drop(account);
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
assert!(
matches!(received.recv().await, Some(VoiceEvent::Disconnected(Some(reason))) if reason == "account source closed")
);
assert!(received.try_recv().is_err());
}
}