Signed-off-by: Faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-10-04 19:11:37 +03:00
1 parent 9c305f2a4d
commit 21261db8ef
185 files changed
+52751 -217

No files matched your search

+12
View File
@@ -106,3 +106,15 @@ against or offered back to upstream.
handed those fewer than 32 bytes to `from_short`, which refused them: one
identity in 256 (the official client's ones included) could not be imported.
The scalar is padded to 32 bytes now; a test round-trips such keys.
13. **myTeamSpeak connection identity** (`tsproto/src/myts.rs`,
`tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`). Validated, redacted account
credentials retain the original raw signing scalar and validate again when
deserialized from a credential store. Connection-bound account proofs use the
negotiated shared IV and the official raw-scalar signing construction, not
Ed25519 seed expansion. `clientinit` and `updatemytsid` carry the six official
case-sensitive proof fields; clearing an account sends only an empty
`myTeamspeakId`. Connection options retain the latest account for reconnects;
callers cancel and rebuild an in-flight attempt when its snapshot changes.
Tests cover an independent signature vector, persistence validation/redaction,
wire field names, clearing and reconnect snapshot replacement. The account
UUID and the ordinary server identity remain separate.
+21 -2
View File
@@ -44,6 +44,7 @@ use tsproto_packets::packets::{InCommandBuf, OutCommand, OutPacket, PacketType};
#[cfg(feature = "audio")]
pub mod audio;
mod myts;
pub mod prelude;
pub mod resolver;
pub mod sync;
@@ -382,9 +383,11 @@ impl Connection {
address: address.into(),
local_address: None,
identity: None,
myts_identity: None,
server: None,
name: "TeamSpeakUser".into(),
version: Version::Windows_3_X_X__1,
metadata: Cow::Borrowed(""),
hardware_id: "923f136fb1e22ae6ce95e60255529c00,d13231b1bc33edfecfb9169cc7a63bcc".into(),
channel: None,
channel_password: None,
@@ -536,7 +539,7 @@ impl Connection {
.as_ref()
.map(|p| tsproto_types::crypto::encode_password(p.as_bytes()))
.unwrap_or_default();
let packet = c2s::OutClientInitMessage::new(&mut iter::once(c2s::OutClientInitPart {
let mut packet = c2s::OutClientInitMessage::new(&mut iter::once(c2s::OutClientInitPart {
name: Cow::Borrowed(options.name.as_ref()),
version: Cow::Borrowed(client_version),
platform: Cow::Borrowed(client_platform),
@@ -549,7 +552,7 @@ impl Connection {
default_channel: Cow::Borrowed(options.channel.as_deref().unwrap_or_default()),
default_channel_password: Cow::Borrowed(default_channel_password.as_ref()),
password: Cow::Borrowed(password.as_ref()),
metadata: "".into(),
metadata: Cow::Borrowed(options.metadata.as_ref()),
version_sign: Cow::Borrowed(client_version_sign.as_ref()),
client_key_offset: counter,
phonetic_name: "".into(),
@@ -564,6 +567,13 @@ impl Connection {
security_hash: None,
}));
// Voelin patch: account proof is bound to this transport's negotiated IV.
// The generated legacy client_myteamspeak_id field stays absent.
if let Some(identity) = &options.myts_identity {
let params = client.params.as_ref().ok_or(Error::InitserverParamsMissing)?;
identity.proof(&params.shared_iv).write_to(&mut packet);
}
client.send_packet(packet.into_packet()).map_err(Error::SendClientinit)?;
match tokio::time::timeout(
@@ -1711,9 +1721,11 @@ pub struct ConnectOptions {
address: ServerAddress,
local_address: Option<SocketAddr>,
identity: Option<Identity>,
myts_identity: Option<tsproto::myts::Identity>,
server: Option<UidBuf>,
name: Cow<'static, str>,
version: Version,
metadata: Cow<'static, str>,
hardware_id: Cow<'static, str>,
channel: Option<Cow<'static, str>>,
channel_password: Option<Cow<'static, str>>,
@@ -1853,6 +1865,13 @@ impl ConnectOptions {
self
}
/// Application metadata, independently of the signed compatibility version.
/// Voelin patch: carries the actual application name/build to the server.
pub fn metadata<S: Into<Cow<'static, str>>>(mut self, metadata: S) -> Self {
self.metadata = metadata.into();
self
}
/// The hardware ID (HWID) of the client.
///
/// # Default
+91
View File
@@ -0,0 +1,91 @@
//! Voelin patch: connection-bound myTeamSpeak proof and live account changes.
use tsproto::myts::Identity;
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
use crate::{ConnectOptions, Connection, ConnectionState, Error, MessageHandle, Result};
impl ConnectOptions {
/// Snapshot the account credential for the initial connection and reconnects.
/// This is separate from the server identity and account profile UUID.
pub fn myts_identity(mut self, identity: Option<Identity>) -> Self {
self.myts_identity = identity;
self
}
}
impl Connection {
/// Publish a connection-bound account proof, or clear the account identity.
///
/// Always updates the reconnect options, even if currently disconnected or
/// sending fails. A running connection attempt owns its previous snapshot:
/// callers must cancel and rebuild that attempt after `NotConnected`.
/// Await the returned handle's `StreamItem::MessageResult` for server acceptance.
pub fn update_myts_identity(&mut self, identity: Option<Identity>) -> Result<MessageHandle> {
self.options.myts_identity = identity;
let iv = match &self.state {
ConnectionState::Connected { con, .. } => {
con.client.params.as_ref().ok_or(Error::InitserverParamsMissing)?.shared_iv
}
_ => return Err(Error::NotConnected),
};
let packet = update_packet(self.options.myts_identity.as_ref(), &iv);
self.send_command_with_result(packet)
}
}
fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
let mut packet =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid");
if let Some(identity) = identity {
identity.proof(iv).write_to(&mut packet);
} else {
// Empty arguments are serialized without '=' by the existing writer.
packet.write_arg("myTeamspeakId", &"");
}
packet
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clear_contains_no_previous_account_proof() {
let packet = update_packet(None, &[0; 64]).into_packet();
assert_eq!(packet.content(), b"updatemytsid myTeamspeakId");
}
#[test]
fn update_uses_current_connection_challenge() {
// Scalar one and the standard compressed Edwards base point.
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
let identity = Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
let first = update_packet(Some(&identity), &[0; 64]).into_packet();
let second = update_packet(Some(&identity), &[1; 64]).into_packet();
assert_ne!(first.content(), second.content());
let wire = std::str::from_utf8(first.content()).unwrap();
assert!(wire.starts_with("updatemytsid myTeamspeakId="));
assert!(wire.contains(" acTime=42 "));
assert!(!wire.contains("client_myteamspeak_id"));
assert_eq!(wire.split(' ').count(), 7);
}
#[test]
fn failed_update_still_replaces_reconnect_snapshot() {
// Building opens no socket until the connection future is polled.
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
let identity = Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
let mut connection =
Connection::build("localhost").myts_identity(Some(identity)).connect().unwrap();
assert!(connection.options.myts_identity.is_some());
assert!(matches!(connection.update_myts_identity(None), Err(Error::NotConnected)));
assert!(connection.options.myts_identity.is_none());
}
}
+2
View File
@@ -43,8 +43,10 @@ tsproto-packets = { path = "../tsproto-packets", version = "0.1" }
tsproto-types = { path = "../tsproto-types", version = "0.1" }
quicklz = "0.3"
crypto-bigint = "0.6"
zeroize = "1"
[dev-dependencies]
serde_json = "1"
anyhow = "1"
criterion = "0.8"
once_cell = "1"
+1
View File
@@ -26,6 +26,7 @@ pub mod client;
pub mod connection;
pub mod license;
pub mod log;
pub mod myts;
pub mod packet_codec;
pub mod resend;
pub mod utils;
+247
View File
@@ -0,0 +1,247 @@
//! Validated myTeamSpeak signing credentials and connection-bound public proofs.
//!
//! Serializing an [`Identity`] exports its private key. Persist it only in a
//! credential store, never application settings, diagnostics or packet logs.
use std::fmt;
use base64::prelude::*;
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
use serde::{Deserialize, Deserializer, Serialize};
use sha2::{Digest, Sha256, Sha512};
use thiserror::Error;
use tsproto_packets::packets::OutCommand;
use zeroize::Zeroize;
/// An account identity; distinct from the account UUID and server identity.
#[derive(Clone, Serialize)]
pub struct Identity {
myts_id: Vec<u8>,
creation_time: u64,
public_key: [u8; 32],
private_key: [u8; 32],
public_signature: Vec<u8>,
}
#[derive(Debug, Error)]
pub enum IdentityError {
#[error("myTeamSpeak identity must contain 33 bytes")]
InvalidId,
#[error("myTeamSpeak public signature must contain 65 to 4096 bytes")]
InvalidSignature,
#[error("myTeamSpeak private key is zero or does not match its public key")]
InvalidKeyPair,
}
impl fmt::Debug for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Identity([REDACTED])") }
}
impl Drop for Identity {
fn drop(&mut self) { self.private_key.zeroize(); }
}
impl<'de> Deserialize<'de> for Identity {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Stored {
myts_id: Vec<u8>,
creation_time: u64,
public_key: [u8; 32],
private_key: [u8; 32],
public_signature: Vec<u8>,
}
let mut stored = Stored::deserialize(deserializer)?;
let result = Self::new(
stored.myts_id,
stored.creation_time,
stored.public_key,
stored.private_key,
stored.public_signature,
);
stored.private_key.zeroize();
result.map_err(serde::de::Error::custom)
}
}
impl Identity {
/// `creation_time` is the voice protocol's decimal `acTime` integer,
/// byte-swapped from the account service's numeric creation timestamp.
pub fn new(
myts_id: Vec<u8>, creation_time: u64, public_key: [u8; 32], mut private_key: [u8; 32],
public_signature: Vec<u8>,
) -> Result<Self, IdentityError> {
let result = (|| {
if myts_id.len() != 33 {
return Err(IdentityError::InvalidId);
}
if !(65..=4096).contains(&public_signature.len()) {
return Err(IdentityError::InvalidSignature);
}
let mut scalar = Scalar::from_bytes_mod_order(private_key);
let valid = scalar != Scalar::ZERO
&& (ED25519_BASEPOINT_TABLE * &scalar).compress().to_bytes() == public_key;
scalar.zeroize();
if !valid {
return Err(IdentityError::InvalidKeyPair);
}
Ok(Self { myts_id, creation_time, public_key, private_key, public_signature })
})();
private_key.zeroize();
result
}
pub fn id(&self) -> String { BASE64_STANDARD.encode(&self.myts_id) }
/// Sign this connection's challenge with the original raw private scalar.
/// This is not Ed25519's seed expansion: the account already stores a scalar.
pub fn proof(&self, shared_iv: &[u8; 64]) -> Proof {
let mut challenge = Sha256::new();
challenge.update([0x30, 0x08, 0, 0, 0, 0]);
challenge.update(shared_iv);
let mut message = challenge.finalize().to_vec();
message.extend_from_slice(b"MyTeamSpeakID");
let mut nonce_hash = Sha512::new();
nonce_hash.update(self.private_key);
nonce_hash.update(&message);
let mut nonce = Scalar::from_bytes_mod_order_wide(&nonce_hash.finalize().into());
let public_nonce = (ED25519_BASEPOINT_TABLE * &nonce).compress().to_bytes();
let mut hash = Sha512::new();
hash.update(public_nonce);
hash.update(self.public_key);
hash.update(&message);
let challenge = Scalar::from_bytes_mod_order_wide(&hash.finalize().into());
let mut scalar = Scalar::from_bytes_mod_order(self.private_key);
let mut response = challenge * scalar + nonce;
let mut signature = [0; 64];
signature[..32].copy_from_slice(&public_nonce);
signature[32..].copy_from_slice(response.as_bytes());
scalar.zeroize();
nonce.zeroize();
response.zeroize();
Proof {
myteamspeak_id: self.id(),
creation_time: self.creation_time,
public_key: BASE64_STANDARD.encode(self.public_key),
auth_signature: BASE64_STANDARD.encode(signature),
public_signature: BASE64_STANDARD.encode(&self.public_signature[..64]),
public_signature_certificate: BASE64_STANDARD.encode(&self.public_signature[64..]),
}
}
}
/// Public, connection-bound authentication values. Never contains private keys.
#[derive(Clone)]
pub struct Proof {
pub myteamspeak_id: String,
pub creation_time: u64,
pub public_key: String,
pub auth_signature: String,
pub public_signature: String,
pub public_signature_certificate: String,
}
impl fmt::Debug for Proof {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Proof([REDACTED])") }
}
impl Proof {
/// Append the official case-sensitive wire fields to an outgoing command.
pub fn write_to(&self, packet: &mut OutCommand) {
packet.write_arg("myTeamspeakId", &self.myteamspeak_id);
packet.write_arg("acTime", &self.creation_time);
packet.write_arg("userPubKey", &self.public_key);
packet.write_arg("authSign", &self.auth_signature);
packet.write_arg("pubSign", &self.public_signature);
packet.write_arg("pubSignCert", &self.public_signature_certificate);
}
}
#[cfg(test)]
mod tests {
use super::*;
use tsproto_packets::packets::{Direction, Flags, PacketType};
fn hex<const N: usize>(value: &str) -> [u8; N] {
let mut bytes = [0; N];
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16).unwrap();
}
bytes
}
fn identity() -> Identity {
Identity::new(
vec![7; 33],
123456,
hex("ce92350b547b6cf028df0618bf9aba55f949930059308d83ebd727e13472ed99"),
std::array::from_fn(|i| i as u8 + 1),
vec![9; 65],
)
.unwrap()
}
#[test]
fn raw_scalar_signature_matches_independent_vector() {
// Python integer Edwards arithmetic + hashlib, independent of dalek.
let proof = identity().proof(&std::array::from_fn(|i| i as u8));
let expected = hex::<64>(
"d56e1808e1ded53e20fc2849f016603c88eefe0494d75e9b869653e2bacaa495c562b571289d88a561c0f4b568cf90cc515b557b6d4321962e94ccf85f105a08",
);
assert_eq!(BASE64_STANDARD.decode(proof.auth_signature).unwrap(), expected);
assert_ne!(
identity().proof(&[0; 64]).auth_signature,
identity().proof(&[1; 64]).auth_signature
);
}
#[test]
fn credentials_roundtrip_validate_and_redact() {
let identity = identity();
let stored = serde_json::to_value(&identity).unwrap();
let restored: Identity = serde_json::from_value(stored.clone()).unwrap();
assert_eq!(serde_json::to_value(&restored).unwrap(), stored);
assert_eq!(
identity.proof(&[0; 64]).auth_signature,
restored.proof(&[0; 64]).auth_signature
);
assert_eq!(format!("{:?}", restored), "Identity([REDACTED])");
assert_eq!(format!("{:?}", restored.proof(&[0; 64])), "Proof([REDACTED])");
for field in ["myts_id", "public_signature", "public_key", "private_key"] {
let mut invalid = stored.clone();
invalid[field] = serde_json::json!([]);
assert!(serde_json::from_value::<Identity>(invalid).is_err(), "{}", field);
}
for private in [vec![0; 32], vec![1; 32]] {
let mut invalid = stored.clone();
invalid["private_key"] = serde_json::json!(private);
assert!(serde_json::from_value::<Identity>(invalid).is_err());
}
for length in [64, 4097] {
let mut invalid = stored.clone();
invalid["public_signature"] = serde_json::json!(vec![9; length]);
assert!(serde_json::from_value::<Identity>(invalid).is_err());
}
}
#[test]
fn proof_writes_exact_public_wire_fields() {
let mut command =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
identity().proof(&[0; 64]).write_to(&mut command);
let packet = command.into_packet();
let wire = std::str::from_utf8(packet.content()).unwrap();
let fields: Vec<_> =
wire.split(' ').skip(1).map(|field| field.split('=').next().unwrap()).collect();
assert_eq!(fields, [
"myTeamspeakId",
"acTime",
"userPubKey",
"authSign",
"pubSign",
"pubSignCert"
]);
assert!(!wire.contains("private"));
}
}
+1
View File
@@ -55,6 +55,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
voelin-myts = { path = "../voelin-myts" }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
+12 -2
View File
@@ -61,13 +61,14 @@ pub mod settings;
pub mod stream;
#[cfg(feature = "media")]
pub mod studio;
pub mod versions;
mod voice;
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::{
@@ -98,6 +99,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>,
@@ -795,6 +798,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));
@@ -839,6 +843,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() {
@@ -914,6 +922,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()));
@@ -991,7 +1000,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
@@ -81,9 +81,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 }
}
@@ -120,6 +123,7 @@ struct OwnStream {
}
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -184,11 +188,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,
@@ -310,6 +316,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(),
@@ -620,7 +627,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};
@@ -38,7 +39,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`.
@@ -67,6 +68,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,
@@ -223,6 +225,8 @@ fn now_ms() -> i64 {
}
enum Input {
MytsIdentityChanged,
AccountSourceClosed,
Item(Option<Result<StreamItem, tsclientlib::Error>>),
Cmd(Option<VoiceCmd>),
Tick,
@@ -230,6 +234,7 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
Stream(Request),
FileList {
request: RequestId,
@@ -312,35 +317,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);
@@ -378,15 +403,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))) => {
@@ -407,10 +442,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(())
}
@@ -464,7 +541,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) => {
@@ -665,7 +748,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}")));
@@ -923,3 +1006,97 @@ fn transfer_error(error: &tsclientlib::Error) -> String {
e => e.to_string(),
}
}
#[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());
}
}
+149
View File
@@ -0,0 +1,149 @@
//! Opt-in account + isolated server interoperability check. No keys are saved.
//! Requires VOELIN_MYTS_LIVE=1, EMAIL/PASSWORD/DEVICE_ID and optional OTP under
//! the VOELIN_MYTS_ prefix; TEST_TS3/TEST_TS6 and QUERY_TS3/QUERY_TS6 give
//! loopback voice/query addresses. QUERY_PASSWORD authenticates local query.
#![cfg(not(target_os = "android"))]
use std::{sync::Arc, time::Duration};
use anyhow::{Context, Result, bail, ensure};
use tokio::{sync::broadcast, time::timeout};
use voelin_core::{Command, Engine, Event, VoiceOptions, VoiceState};
use voelin_myts::{Client, ServerIdentity};
use voelin_query::{Command as QueryCommand, QueryClient, Row};
fn env(name: &str) -> Result<String> {
std::env::var(format!("VOELIN_MYTS_{name}")).with_context(|| format!("missing {name}"))
}
async fn connected(events: &mut broadcast::Receiver<Event>, session_id: u64) -> Result<u16> {
timeout(Duration::from_secs(35), async {
loop {
match events.recv().await? {
Event::State { session, state }
if session == session_id && state.voice == VoiceState::Connected =>
{
if let Some(id) = state.own_client {
return Ok(id);
}
}
Event::Error { message, .. } => bail!("engine: {message}"),
_ => {}
}
}
})
.await?
}
async fn info(query: &QueryClient, client: u16) -> Result<Row> {
query
.send(&QueryCommand::new("clientinfo").arg("clid", client))
.await?
.into_iter()
.next()
.context("clientinfo missing")
}
async fn wait_id(query: &QueryClient, client: u16, expected: &str) -> Result<()> {
timeout(Duration::from_secs(12), async {
loop {
let row = info(query, client).await?;
if row.get("client_myteamspeak_id") == Some(expected) {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
})
.await
.context("server did not report the expected myTS association")?
}
async fn server(identity: Arc<ServerIdentity>, kind: &str) -> Result<()> {
let address = env(&format!("TEST_{kind}"))?;
let query_address = env(&format!("QUERY_{kind}"))?;
// This test is deliberately limited to caller-owned loopback test servers.
ensure!(address.starts_with("127.0.0.1:"), "voice endpoint must be loopback");
ensure!(query_address.starts_with("127.0.0.1:"), "query endpoint must be loopback");
let (query, _) = QueryClient::connect(&voelin_query::Connect {
transport: if kind == "TS3" {
voelin_query::Transport::Raw
} else {
voelin_query::Transport::Ssh
},
addr: query_address,
user: "serveradmin".into(),
secret: Some(env("QUERY_PASSWORD")?),
server_id: Some(1),
server_port: None,
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
})
.await?;
let engine = Engine::start();
let mut events = engine.subscribe();
let result = async {
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
for session in 1..=2 {
engine.send(Command::ConnectVoice {
session,
options: Box::new(VoiceOptions::new(&address, format!("myts-proof-{session}"))),
});
let client = connected(&mut events, session).await?;
let row = info(&query, client).await?;
let version = voelin_core::versions::native_version()?;
ensure!(row.get("client_platform") == Some(version.get_platform()), "wrong platform");
ensure!(
row.get("client_version") == Some(version.get_version_string()),
"wrong version"
);
let metadata: serde_json::Value =
serde_json::from_str(row.get("client_meta_data").context("missing metadata")?)?;
ensure!(metadata["name"] == "Voelin", "wrong client metadata");
ensure!(metadata["platform"] == std::env::consts::OS, "wrong metadata platform");
eprintln!("{kind}: native platform/Voelin metadata passed");
wait_id(&query, client, &identity.id()).await?;
eprintln!("{kind}: signed clientinit myTS ID passed");
// Two fresh connections prove the signature is bound to each handshake.
engine.send(Command::SetMytsIdentity(None));
wait_id(&query, client, "").await?;
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
wait_id(&query, client, &identity.id()).await?;
eprintln!("{kind}: live clear and reattach passed");
engine.send(Command::CloseSession { session });
}
Ok(())
}
.await;
engine.send(Command::SetMytsIdentity(None));
for session in 1..=2 {
engine.send(Command::CloseSession { session });
}
query.quit().await;
result
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires owner-authorized account and isolated loopback servers"]
async fn authenticated_account_and_server_lifecycle() -> Result<()> {
ensure!(env("LIVE")? == "1", "explicit live opt-in required");
let client = Client::new()?;
let login = client
.login(&env("EMAIL")?, &env("PASSWORD")?, env("OTP").ok().as_deref(), &env("DEVICE_ID")?)
.await?;
// Capture every result before deleting the newly created remote session.
let result = async {
client.validate_session(&login.token).await?;
let identity = Arc::new(login.identity.context("server identity unlock failed")?);
let mut failures = Vec::new();
for kind in ["TS3", "TS6"] {
if let Err(error) = server(identity.clone(), kind).await {
failures.push(format!("{kind}: {error:#}"));
}
}
ensure!(failures.is_empty(), "{}", failures.join("; "));
Ok(())
}
.await;
let logout = client.logout(&login.token).await;
logout.context("remote test session revocation failed")?;
result
}
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "voelin-myts"
version = "0.1.0"
description = "Bounded myTeamSpeak account HTTP client"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# Reuse the workspace's existing crypto crates for the account wire credential.
base64 = "0.22"
aes = "0.9"
aes-gcm = { version = "0.11", features = ["zeroize"] }
ctr = "0.10"
subtle = "2.6"
zeroize = "1.9"
tsproto = { path = "../proto/tsproto" }
pbkdf2 = { version = "0.13", features = ["sha2"] }
schema-api = { path = "../../third_party/schema-api", default-features = false }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2"] }
thiserror = "2.0.21"
tokio = { version = "1.53.1", features = ["rt", "time"] }
[dev-dependencies]
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "net", "io-util"] }
[lints]
workspace = true
+202
View File
@@ -0,0 +1,202 @@
//! Authenticated account-key unwrap; plaintext keys never leave this module
//! except inside the validated, redacted protocol identity.
use aes_gcm::{Aes256Gcm, KeyInit, aead::AeadInOut};
use ctr::cipher::{KeyIvInit, StreamCipher};
use pbkdf2::sha2::{Digest, Sha512};
use schema_api::api;
use subtle::ConstantTimeEq;
use tsproto::myts::Identity;
use zeroize::Zeroizing;
/// Static, non-secret explanation for a usable login without a server identity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum IdentityError {
#[error("sign in with your password to unlock the server identity")]
PasswordRequired,
#[error("the account did not provide a server identity")]
Missing,
#[error("the account uses an unsupported encryption-key version")]
UnsupportedKeyVersion,
#[error("the account encryption key has an invalid format")]
InvalidRootKey,
#[error("the account encryption key could not be authenticated")]
RootAuthentication,
#[error("the account server identity has an invalid format")]
InvalidIdentity,
#[error("the account private key could not be verified")]
PrivateKeyIntegrity,
}
pub(crate) fn encryption_key(email: &str, password: &str) -> Zeroizing<[u8; 32]> {
let salt = Zeroizing::new(format!("{}ts3Encryption{password}", email.to_ascii_lowercase()));
Zeroizing::new(pbkdf2::pbkdf2_hmac_array::<Sha512, 32>(
password.as_bytes(),
salt.as_bytes(),
10_000,
))
}
fn unwrap_root(wrapped: &[u8], key: &[u8; 32]) -> Result<Zeroizing<[u8; 32]>, IdentityError> {
match wrapped.first() {
None => return Err(IdentityError::InvalidRootKey),
Some(2) => {}
Some(_) => return Err(IdentityError::UnsupportedKeyVersion),
}
if wrapped.len() != 61 {
return Err(IdentityError::InvalidRootKey);
}
let mut plaintext = Zeroizing::new([0; 32]);
plaintext.copy_from_slice(&wrapped[29..]);
let cipher = Aes256Gcm::new(key.into());
cipher
.decrypt_inout_detached(
wrapped[17..29].try_into().map_err(|_| IdentityError::InvalidRootKey)?,
b"",
plaintext.as_mut_slice().into(),
wrapped[1..17].try_into().map_err(|_| IdentityError::InvalidRootKey)?,
)
.map_err(|_| IdentityError::RootAuthentication)?;
Ok(plaintext)
}
fn unwrap_private(wrapped: &[u8], root: &[u8; 32]) -> Result<Zeroizing<[u8; 32]>, IdentityError> {
if wrapped.len() != 112 {
return Err(IdentityError::InvalidIdentity);
}
let mut plaintext = Zeroizing::new([0; 32]);
plaintext.copy_from_slice(&wrapped[16..48]);
let mut cipher = ctr::Ctr128LE::<aes::Aes256>::new(
root.into(),
wrapped[..16].try_into().map_err(|_| IdentityError::InvalidIdentity)?,
);
cipher.apply_keystream(plaintext.as_mut_slice());
let digest = Zeroizing::new(<[u8; 64]>::from(Sha512::digest(plaintext.as_slice())));
if !bool::from(digest.as_slice().ct_eq(&wrapped[48..])) {
return Err(IdentityError::PrivateKeyIntegrity);
}
Ok(plaintext)
}
pub(crate) fn decrypt(
response: &api::LoginSession,
key: &[u8; 32],
) -> Result<Identity, IdentityError> {
let data = response.myts_id_data.as_ref().ok_or(IdentityError::Missing)?;
let encrypted = data.user_private_key.as_ref().ok_or(IdentityError::Missing)?;
let public_key =
data.user_public_key.as_slice().try_into().map_err(|_| IdentityError::InvalidIdentity)?;
let root = unwrap_root(&response.key, key)?;
let private = unwrap_private(&encrypted.encrypted_user_private_key, &root)?;
Identity::new(
data.my_teamspeak_id.clone(),
// The HTTP schema uses the numeric timestamp; the voice protocol's
// decimal acTime represents its byte-swapped integer. The server
// verifies pubKey || acTime.to_le_bytes() || myTS ID. The official
// login-to-storage boundary performs this same conversion.
data.account_creation_time.swap_bytes(),
public_key,
*private,
data.public_signature.clone(),
)
.map_err(|_| IdentityError::InvalidIdentity)
}
#[cfg(test)]
mod tests {
use super::*;
// Independent Python hashlib + cryptography AESGCM/AES-ECB fixtures.
// CTR is assembled by incrementing the counter as a little-endian integer.
const ROOT: &str = "0201123b3434c3b04a2b6713e5a14c5f10000102030405060708090a0be7012a4987a157ece9103814f297d77cae6a2084730d7e049895cb0ba2334178";
const PRIVATE: &str = "000102030405060708090a0b0c0d0e0f7a4f26742cde57b1d8077f162eee88bd3afe99c66443d961cd28a368ac98cc2f887af58a36202e05c4c1cfec5bf6c61fad66bca851536004074b31f1b56e4ac93d9c9fc20dc59e01fecab23063ef341b2d2d75c4e8e4fa1e9ba958658260e336";
fn hex(s: &str) -> Vec<u8> {
s.as_bytes()
.chunks_exact(2)
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
.collect()
}
#[test]
fn independent_password_root_and_private_vectors() {
let key = encryption_key("User@Example.TEST", "password");
assert_eq!(
key.as_slice(),
hex("81ccdf8e98030891e11700e5d76dfa6c52ff01121f668ab6a5525742ed18c5ca")
);
let root = unwrap_root(&hex(ROOT), &key).unwrap();
assert_eq!(root.as_slice(), (0..32).collect::<Vec<u8>>());
let private = unwrap_private(&hex(PRIVATE), &root).unwrap();
assert_eq!(private.as_slice(), (32..64).collect::<Vec<u8>>());
}
#[test]
fn decrypts_response_and_rejects_a_mismatched_public_key() {
let key = encryption_key("user@example.test", "password");
let mut response = api::LoginSession {
key: hex(ROOT),
myts_id_data: Some(api::MyTeamSpeakIdData {
// Independently computed scalar multiplication using affine Edwards arithmetic.
user_public_key: hex(
"e67b030457ea1be59391ea3f28748d12abe417fef0f7bb6ad68e54e836eda6c4",
),
user_private_key: Some(api::my_team_speak_id_data::UserPrivateKey {
encrypted_user_private_key: hex(PRIVATE),
// Never trust this alternate server plaintext field.
decrypted_user_private_key: vec![0; 32],
}),
account_creation_time: 123,
my_teamspeak_id: vec![1; 33],
public_signature: vec![2; 65],
}),
..Default::default()
};
let identity = decrypt(&response, &key).unwrap();
assert_eq!(identity.id(), "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB");
assert_eq!(identity.proof(&[0; 64]).creation_time, 123u64.swap_bytes());
response.myts_id_data.as_mut().unwrap().user_public_key[0] ^= 1;
assert_eq!(decrypt(&response, &key).unwrap_err(), IdentityError::InvalidIdentity);
}
#[test]
fn every_authenticated_root_byte_is_checked() {
let key = encryption_key("user@example.test", "password");
for index in 1..61 {
let mut wrapped = hex(ROOT);
wrapped[index] ^= 1;
assert_eq!(unwrap_root(&wrapped, &key).unwrap_err(), IdentityError::RootAuthentication);
}
assert_eq!(
unwrap_root(&hex(ROOT), &[0; 32]).unwrap_err(),
IdentityError::RootAuthentication
);
}
#[test]
fn every_private_item_byte_is_checked() {
let root = std::array::from_fn(|i| i as u8);
for index in 0..112 {
let mut wrapped = hex(PRIVATE);
wrapped[index] ^= 1;
assert_eq!(
unwrap_private(&wrapped, &root).unwrap_err(),
IdentityError::PrivateKeyIntegrity
);
}
}
#[test]
fn missing_unsupported_and_malformed_are_explicit() {
assert_eq!(
decrypt(&api::LoginSession::default(), &[0; 32]).unwrap_err(),
IdentityError::Missing
);
assert_eq!(unwrap_root(&[], &[0; 32]).unwrap_err(), IdentityError::InvalidRootKey);
assert_eq!(unwrap_root(&[1], &[0; 32]).unwrap_err(), IdentityError::UnsupportedKeyVersion);
for size in [1, 60, 62] {
let mut wrapped = vec![0; size];
wrapped[0] = 2;
assert_eq!(unwrap_root(&wrapped, &[0; 32]).unwrap_err(), IdentityError::InvalidRootKey);
}
for size in [0, 111, 113] {
assert_eq!(
unwrap_private(&vec![0; size], &[0; 32]).unwrap_err(),
IdentityError::InvalidIdentity
);
}
}
}
+233
View File
@@ -0,0 +1,233 @@
//! Account sessions over the custom myTeamSpeak HTTP transport.
//!
//! Requests use the official client's method envelope and password derivation.
//! No requests or credentials are logged.
mod identity;
mod transport;
pub use identity::IdentityError;
pub use tsproto::myts::Identity as ServerIdentity;
use zeroize::{Zeroize, Zeroizing};
use base64::{Engine as _, engine::general_purpose::STANDARD};
pub use schema_api::SessionToken;
use schema_api::{api, session, wire};
use std::fmt;
/// Owned account login result. Credential fields are redacted in Debug output.
#[derive(Clone)]
pub struct Login {
pub token: SessionToken,
pub uuid: String,
pub username: String,
pub renewal: Option<Renewal>,
/// Validated server identity, or why this session cannot associate with servers.
pub identity: Result<ServerIdentity, IdentityError>,
}
/// Server-provided alternative login material, stored only in a secret store.
#[derive(Clone)]
pub struct Renewal {
pub token: String,
pub otp_token: String,
pub device_id: String,
}
impl fmt::Debug for Login {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Login([REDACTED])")
}
}
impl fmt::Debug for Renewal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Renewal([REDACTED])")
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("account transport failed")]
Transport(#[from] reqwest::Error),
#[error("invalid account response")]
Decode(#[from] schema_api::prost::DecodeError),
#[error(transparent)]
Session(#[from] session::SessionError),
#[error(transparent)]
Status(#[from] session::CommonStatusError),
#[error("account request exceeds size limit")]
RequestTooLarge,
#[error("account response exceeds size limit")]
ResponseTooLarge,
#[error("account request timed out")]
Timeout,
#[error("account endpoint returned HTTP {0}")]
Http(u16),
#[error("account endpoint returned an unsupported content type")]
ContentType,
#[error("account credential preparation failed")]
CredentialPreparation,
#[error("renewal requires both a renewal token and an auth token")]
MissingRenewalCredentials,
}
impl Error {
pub fn status_code(&self) -> Option<i32> {
match self {
Self::Status(status) | Self::Session(session::SessionError::Api(status)) => {
Some(status.code)
}
_ => None,
}
}
pub fn is_otp_required(&self) -> bool {
self.status_code() == Some(api::ErrorCommon::ErrorAuthRequiresOtp as i32)
}
/// Only the explicit expired-session status permits an automatic renewal.
pub fn is_invalid_session(&self) -> bool {
self.status_code() == Some(api::ErrorCommon::ErrorSessionExpired as i32)
}
}
#[derive(Clone)]
pub struct Client {
transport: transport::Transport,
}
impl Client {
pub fn new() -> Result<Self, Error> {
Ok(Self { transport: transport::Transport::new()? })
}
/// Sign in with the user's password; the protocol credential is derived
/// internally, off the async runtime's worker threads.
pub async fn login(
&self,
email: &str,
password: &str,
otp: Option<&str>,
device: &str,
) -> Result<Login, Error> {
self.login_with_otp_renewal(email, password, otp, device, "").await
}
/// Password login on a remembered device. The OTP renewal token must belong
/// to this account and device; an explicit one-time code takes precedence.
pub async fn login_with_otp_renewal(
&self,
email: &str,
password: &str,
otp: Option<&str>,
device: &str,
otp_renewal: &str,
) -> Result<Login, Error> {
// Check before copying caller-controlled strings into protobuf allocations.
transport::check_input_size(&[
email,
password,
otp.unwrap_or_default(),
device,
otp_renewal,
])?;
let mut request = api::LoginData {
email: email.into(),
password: password.into(),
otp: otp.unwrap_or_default().into(),
device_id: device.into(),
otp_renewal_token: if device.is_empty() || otp.is_some_and(|code| !code.is_empty()) {
String::new()
} else {
otp_renewal.into()
},
device_name: "Voelin".into(),
..Default::default()
};
let (request, encryption_key) = tokio::task::spawn_blocking(move || {
let password = Zeroizing::new(std::mem::take(&mut request.password));
let encryption_key = identity::encryption_key(&request.email, &password);
request.password = login_password(&request.email, &password);
(request, encryption_key)
})
.await
.map_err(|_| Error::CredentialPreparation)?;
self.login_call("login", &wire::encode(&request), Some(encryption_key)).await
}
/// `auth` is the schema's auth_token, not an OTP or device identifier.
/// The official client requires both credentials. Password login does not
/// supply an auth token; callers must not invent one or pass an empty value.
pub async fn login_with_renewal(&self, renewal: &str, auth: &str) -> Result<Login, Error> {
if renewal.is_empty() || auth.is_empty() {
return Err(Error::MissingRenewalCredentials);
}
transport::check_input_size(&[renewal, auth])?;
let request =
api::RenewalTokenLogin { renewal_token: renewal.into(), auth_token: auth.into() };
self.login_call("loginWithRenewalToken", &wire::encode(&request), None).await
}
async fn login_call(
&self,
method: &str,
body: &[u8],
encryption_key: Option<Zeroizing<[u8; 32]>>,
) -> Result<Login, Error> {
let bytes = self.transport.call("authentication", method, body).await?;
let response: api::LoginSession = wire::decode(bytes)?;
let token = SessionToken::try_from(&response)?;
let (response, identity) = tokio::task::spawn_blocking(move || {
let identity = match encryption_key {
Some(key) => identity::decrypt(&response, &key),
None => Err(IdentityError::PasswordRequired),
};
(response, identity)
})
.await
.map_err(|_| Error::CredentialPreparation)?;
Ok(Login {
token,
identity,
uuid: response.uuid,
username: response.username,
renewal: response.alternative_login_info.map(|info| Renewal {
token: info.renewal_token,
otp_token: info.otp_renewal_token,
device_id: info.device_id,
}),
})
}
pub async fn validate_session(&self, token: &SessionToken) -> Result<(), Error> {
let response = self.session_call("session", token).await?;
Ok(session::validate_session_status(&response)?)
}
pub async fn logout(&self, token: &SessionToken) -> Result<(), Error> {
let response = self.session_call("deleteSession", token).await?;
Ok(session::validate_deleted_session_status(&response)?)
}
async fn session_call(
&self,
method: &str,
token: &SessionToken,
) -> Result<api::LoginStatus, Error> {
transport::check_input_size(&[token.as_str()])?;
let bytes = self
.transport
.call("session", method, &wire::encode(&api::Session::from(token)))
.await?;
Ok(wire::decode(bytes)?)
}
}
fn login_password(email: &str, password: &str) -> String {
// Official client's classic-locale bytewise lowercase is ASCII-only.
// These are wire-protocol constants, not configurable password policy.
let salt = Zeroizing::new(format!("{}ts3Login{password}", email.to_ascii_lowercase()));
let mut derived = pbkdf2::pbkdf2_hmac_array::<pbkdf2::sha2::Sha512, 48>(
password.as_bytes(),
salt.as_bytes(),
10_000,
);
let encoded = STANDARD.encode(derived);
derived.zeroize();
encoded
}
#[cfg(test)]
mod tests;
+359
View File
@@ -0,0 +1,359 @@
use super::*;
use std::time::Duration;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
async fn mock(
status: u16,
extra_headers: &str,
body: Vec<u8>,
) -> (Client, tokio::task::JoinHandle<(String, Vec<u8>)>) {
mock_typed(status, "application/ts3cloud", extra_headers, body).await
}
async fn mock_typed(
status: u16,
content_type: &str,
extra_headers: &str,
body: Vec<u8>,
) -> (Client, tokio::task::JoinHandle<(String, Vec<u8>)>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = Client {
transport: transport::Transport::mock(
format!("http://{}", listener.local_addr().unwrap()),
Duration::from_secs(2),
),
};
let extra_headers = extra_headers.to_owned();
let content_type = content_type.to_owned();
let task = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let end = loop {
let mut byte = [0];
stream.read_exact(&mut byte).await.unwrap();
request.push(byte[0]);
if request.ends_with(b"\r\n\r\n") {
break request.len();
}
assert!(request.len() < 8192);
};
let headers = String::from_utf8(request[..end].to_vec()).unwrap();
let length: usize = headers
.lines()
.find_map(|line| {
line.to_ascii_lowercase().strip_prefix("content-length: ").map(str::to_owned)
})
.unwrap()
.parse()
.unwrap();
let mut request_body = vec![0; length];
stream.read_exact(&mut request_body).await.unwrap();
let response = format!(
"HTTP/1.1 {status} Test\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n{extra_headers}\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(&body).await;
(headers, request_body)
});
(client, task)
}
fn success() -> api::LoginSession {
api::LoginSession {
error: 200,
session: "session-secret".into(),
uuid: "account-uuid".into(),
username: "user".into(),
alternative_login_info: Some(api::login_session::AlternativeLoginInformation {
renewal_token: "renewal-secret".into(),
otp_renewal_token: "otp-secret".into(),
device_id: "device".into(),
}),
..Default::default()
}
}
#[test]
fn login_password_matches_independent_vectors_without_normalizing_passwords() {
for email in ["User@Example.TEST", "user@example.test"] {
assert_eq!(
login_password(email, "password"),
"5SG5V/18cFF2iHUFXNrFLrmLeAtbjg0sLgKpSMTZe9W8G/rPorrJyY6uJDm98ICk"
);
}
assert_eq!(
login_password("Case@Example.TEST", " Pässword "),
"NssDyxUbagUiUJS/7Mh7YCeMmF+w3BiAO8uLCgKW0nkH0hQLWYEjuLlV5P28GHNS"
);
assert_eq!(
login_password("éMAIL@Example.TEST", "páss"),
"x6kph1Mku46TD2/zDER1UbqU0w6WV27J6W8t1CNmnDv1JELm6MPKlTyh9Mj+REjB"
);
}
#[tokio::test]
async fn protobuf_response_accepts_the_services_json_content_type() {
let (client, server) = mock_typed(200, "application/json", "", wire::encode(&success())).await;
let login = client.login("mail", "password", None, "device").await.unwrap();
assert_eq!(login.token.as_str(), "session-secret");
server.await.unwrap();
}
#[tokio::test]
async fn login_uses_official_method_prefix_instead_of_a_header() {
let (client, server) = mock(200, "", wire::encode(&success())).await;
client.login("mail", "password", None, "device").await.unwrap();
let (headers, body) = server.await.unwrap();
assert!(body.starts_with(b"\x05login"));
assert!(!headers.to_ascii_lowercase().contains("x-rpc-method"));
let request: api::LoginData = wire::decode(&body[6..]).unwrap();
assert_eq!(request.email, "mail");
// Independent Python hashlib.pbkdf2_hmac fixture with synthetic credentials.
assert_eq!(
request.password,
"TRd/AoYKGWZQ+grEk+YpdbXvhzGyZCyaA358SI+/q99VuAVHz1kByIEF5sNDSqEu"
);
}
#[tokio::test]
async fn login_roundtrip_keeps_credentials_in_body_and_redacts_results() {
let (client, server) = mock(200, "", wire::encode(&success())).await;
let login = client.login("mail", "password-secret", Some("123456"), "device").await.unwrap();
assert_eq!(login.token.as_str(), "session-secret");
assert_eq!(login.username, "user");
assert_eq!(login.uuid, "account-uuid");
assert_eq!(login.identity.as_ref().unwrap_err(), &IdentityError::Missing);
assert!(!format!("{login:?}").contains("secret"));
let renewal = login.renewal.unwrap();
assert_eq!(renewal.token, "renewal-secret");
assert_eq!(renewal.otp_token, "otp-secret");
assert_eq!(renewal.device_id, "device");
assert!(!format!("{renewal:?}").contains("secret"));
let (headers, body) = server.await.unwrap();
assert!(headers.starts_with("POST /authentication HTTP/1.1"));
assert!(headers.to_lowercase().contains("content-type: application/ts3cloud"));
assert!(body.starts_with(b"\x05login"));
assert!(!headers.contains("password-secret"));
let data: api::LoginData = wire::decode(&body[6..]).unwrap();
assert_eq!(data.email, "mail");
assert_eq!(data.password, "MQU48au/lEdA0Hd/DNJ09/M4ZJgqYL5Q+PRF7OILYbUkZWHIpGw4c/kW4t4/Qofk");
assert_eq!(data.otp, "123456");
assert_eq!(data.device_id, "device");
assert!(!data.skip_session);
}
#[tokio::test]
async fn login_requires_explicit_success_nonempty_token_and_preserves_status() {
for code in [0, 202, 208, 98765] {
let mut response = success();
response.error = code;
let (client, server) = mock(200, "", wire::encode(&response)).await;
let error = client.login("e", "p", None, "d").await.unwrap_err();
assert_eq!(error.status_code(), Some(code));
assert_eq!(error.is_otp_required(), code == 208);
server.await.unwrap();
}
let mut response = success();
response.session.clear();
let (client, server) = mock(200, "", wire::encode(&response)).await;
assert!(matches!(
client.login("e", "p", None, "d").await,
Err(Error::Session(session::SessionError::EmptyToken))
));
server.await.unwrap();
}
#[tokio::test]
async fn remembered_otp_requires_a_device_and_yields_to_an_explicit_code() {
for (device, otp, expected_token) in
[("device", None, "otp-renewal"), ("", None, ""), ("device", Some("123456"), "")]
{
let (client, server) = mock(200, "", wire::encode(&success())).await;
client
.login_with_otp_renewal("mail", "password", otp, device, "otp-renewal")
.await
.unwrap();
let (_, body) = server.await.unwrap();
let request: api::LoginData = wire::decode(&body[6..]).unwrap();
assert_eq!(request.otp_renewal_token, expected_token);
assert_eq!(request.device_id, device);
assert_eq!(request.otp, otp.unwrap_or_default());
assert!(!request.password.is_empty());
assert_ne!(request.password, "password");
}
}
#[tokio::test]
async fn renewal_encodes_exact_tokens_and_rejects_missing_credentials_before_network() {
{
let auth = "auth-secret";
let (client, server) = mock(200, "", wire::encode(&success())).await;
let login = client.login_with_renewal("renewal-secret", auth).await.unwrap();
assert_eq!(login.identity.unwrap_err(), IdentityError::PasswordRequired);
let (headers, body) = server.await.unwrap();
assert!(headers.starts_with("POST /authentication HTTP/1.1"));
assert!(body.starts_with(b"\x15loginWithRenewalToken"));
let request: api::RenewalTokenLogin = wire::decode(&body[22..]).unwrap();
assert_eq!(request.renewal_token, "renewal-secret");
assert_eq!(request.auth_token, auth);
}
let client = Client {
transport: transport::Transport::mock("http://127.0.0.1:1".into(), Duration::from_secs(1)),
};
for (renewal, auth) in [("", "auth"), ("renewal", ""), ("", "")] {
assert!(matches!(
client.login_with_renewal(renewal, auth).await,
Err(Error::MissingRenewalCredentials)
));
}
}
#[tokio::test]
async fn session_validation_and_deletion_have_distinct_success_statuses() {
let token = SessionToken::new("secret").unwrap();
for (logout, code, valid) in [
(false, 102, true),
(false, 103, false),
(false, 104, false),
(false, 204, false),
(true, 204, true),
(true, 102, false),
] {
let (client, server) =
mock(200, "", wire::encode(&api::LoginStatus { error: code, ..Default::default() }))
.await;
let result = if logout {
client.logout(&token).await
} else {
client.validate_session(&token).await
};
assert_eq!(result.is_ok(), valid);
if let Err(error) = result {
assert_eq!(error.is_invalid_session(), code == 103);
}
let (headers, body) = server.await.unwrap();
assert!(headers.starts_with("POST /session HTTP/1.1"));
let prefix: &[u8] = if logout { b"\x0ddeleteSession" } else { b"\x07session" };
assert!(body.starts_with(prefix));
assert_eq!(wire::decode::<api::Session>(&body[prefix.len()..]).unwrap().session, "secret");
}
}
#[tokio::test]
async fn transport_rejects_http_redirects_oversize_and_malformed_data() {
for (status, body) in
[(302, vec![]), (500, vec![]), (200, vec![0; transport::MAX_BODY + 1]), (200, vec![0xff])]
{
let (client, server) = mock(status, "Location: http://127.0.0.1:1/leak\r\n", body).await;
let error = client.login("e", "p", None, "d").await.unwrap_err();
match status {
302 | 500 => assert!(matches!(error, Error::Http(code) if code == status)),
_ => assert!(matches!(error, Error::ResponseTooLarge | Error::Decode(_))),
}
server.await.unwrap();
}
let client = Client {
transport: transport::Transport::mock("http://127.0.0.1:1".into(), Duration::from_secs(1)),
};
assert!(matches!(
client.login("e", &"x".repeat(transport::MAX_BODY), None, "d").await,
Err(Error::RequestTooLarge)
));
assert!(matches!(client.login("e", "p", None, "d").await, Err(Error::Transport(_))));
}
#[tokio::test]
async fn transport_bounds_chunked_responses_and_slow_servers() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = Client {
transport: transport::Transport::mock(
format!("http://{}", listener.local_addr().unwrap()),
Duration::from_secs(2),
),
};
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut request = [0; 1024];
let _ = stream.read(&mut request).await;
stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: application/ts3cloud\r\nTransfer-Encoding: chunked\r\n\r\n10001\r\n").await.unwrap();
let _ = stream.write_all(&vec![0; transport::MAX_BODY + 1]).await;
let _ = stream.write_all(b"\r\n0\r\n\r\n").await;
});
assert!(matches!(client.login("e", "p", None, "d").await, Err(Error::ResponseTooLarge)));
server.await.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = Client {
transport: transport::Transport::mock(
format!("http://{}", listener.local_addr().unwrap()),
Duration::from_millis(25),
),
};
assert!(matches!(client.login("e", "p", None, "d").await, Err(Error::Timeout)));
}
#[tokio::test]
async fn transport_rejects_wrong_content_type_and_encoded_overhead() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = Client {
transport: transport::Transport::mock(
format!("http://{}", listener.local_addr().unwrap()),
Duration::from_secs(2),
),
};
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut request = [0; 1024];
let _ = stream.read(&mut request).await;
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 0\r\n\r\n")
.await
.unwrap();
});
assert!(matches!(client.login("e", "p", None, "d").await, Err(Error::ContentType)));
server.await.unwrap();
// The method prefix counts towards the request bound too.
assert!(matches!(
client.transport.call("authentication", "login", &vec![0; transport::MAX_BODY - 5]).await,
Err(Error::RequestTooLarge)
));
}
#[tokio::test]
#[ignore = "owner-authorized live account check; explicit credentials and opt-in required"]
async fn owner_live_login_validate_logout() {
assert_eq!(
std::env::var("VOELIN_MYTS_LIVE").as_deref(),
Ok("1"),
"explicit live opt-in required"
);
let email = std::env::var("VOELIN_MYTS_EMAIL").expect("email required");
let password = std::env::var("VOELIN_MYTS_PASSWORD").expect("password required");
let device = std::env::var("VOELIN_MYTS_DEVICE_ID").expect("device ID required");
let otp = std::env::var("VOELIN_MYTS_OTP").ok();
let client = Client::new().unwrap();
let login =
client.login(&email, &password, otp.as_deref(), &device).await.expect("live login failed");
let validation = client.validate_session(&login.token).await;
let logout = client.logout(&login.token).await;
validation.expect("live validation failed");
logout.expect("live logout failed");
}
#[tokio::test]
async fn unsupported_identity_encryption_preserves_successful_account_login() {
let mut response = success();
response.key = vec![1];
response.myts_id_data = Some(api::MyTeamSpeakIdData {
user_public_key: vec![0; 32],
user_private_key: Some(Default::default()),
..Default::default()
});
let (client, server) = mock(200, "", wire::encode(&response)).await;
let login = client.login("mail", "password", None, "device").await.unwrap();
assert_eq!(login.token.as_str(), "session-secret");
assert_eq!(login.identity.unwrap_err(), IdentityError::UnsupportedKeyVersion);
server.await.unwrap();
}
+107
View File
@@ -0,0 +1,107 @@
use crate::Error;
use std::time::Duration;
pub(crate) const MAX_BODY: usize = 64 * 1024;
const TIMEOUT: Duration = Duration::from_secs(20);
const CONTENT_TYPE: &str = "application/ts3cloud";
pub(crate) fn check_input_size(fields: &[&str]) -> Result<(), Error> {
if fields
.iter()
.try_fold(0usize, |sum, field| sum.checked_add(field.len()))
.is_none_or(|size| size > MAX_BODY)
{
return Err(Error::RequestTooLarge);
}
Ok(())
}
#[derive(Clone)]
pub(crate) struct Transport {
client: reqwest::Client,
base: String,
timeout: Duration,
}
impl Transport {
pub(crate) fn new() -> Result<Self, Error> {
Ok(Self {
client: reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(10))
.timeout(TIMEOUT)
.user_agent("Voelin/0.1")
.build()?,
base: "https://clientapi.myteamspeak.com".into(),
timeout: TIMEOUT,
})
}
#[cfg(test)]
pub(crate) fn mock(base: String, timeout: Duration) -> Self {
Self {
client: reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap(),
base,
timeout,
}
}
pub(crate) async fn call(
&self,
service: &str,
method: &str,
body: &[u8],
) -> Result<Vec<u8>, Error> {
// teamprotobufrpc prefixes the protobuf with a single-byte method-name
// length and the method bytes. Both official desktop clients use this
// envelope; HTTP responses contain only the protobuf message.
if method.len() > 127 || body.len() > MAX_BODY - method.len() - 1 {
return Err(Error::RequestTooLarge);
}
let mut request_body = Vec::with_capacity(1 + method.len() + body.len());
request_body.push(method.len() as u8);
request_body.extend_from_slice(method.as_bytes());
request_body.extend_from_slice(body);
tokio::time::timeout(self.timeout, async {
let mut response = self
.client
.post(format!("{}/{service}", self.base))
.header(reqwest::header::CONTENT_TYPE, CONTENT_TYPE)
.body(request_body)
.send()
.await?;
if !response.status().is_success() {
return Err(Error::Http(response.status().as_u16()));
}
if response.content_length().is_some_and(|length| length > MAX_BODY as u64) {
return Err(Error::ResponseTooLarge);
}
// The live service labels binary protobuf replies application/json.
// Accept that observed label; callers still decode and validate protobuf.
if response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.is_none_or(|value| {
!value.trim().eq_ignore_ascii_case(CONTENT_TYPE)
&& !value.trim().eq_ignore_ascii_case("application/json")
}) {
return Err(Error::ContentType);
}
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
if chunk.len() > MAX_BODY - bytes.len() {
return Err(Error::ResponseTooLarge);
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
})
.await
.map_err(|_| Error::Timeout)?
}
}
+1
View File
@@ -45,6 +45,7 @@ tsclientlib = { path = "../proto/tsclientlib" }
# Desktop: the keyring for passwords, stream media with libvpx, OpenH264, X11
# and PipeWire, global hotkeys through the portal and X11.
[target.'cfg(not(target_os = "android"))'.dependencies]
voelin-myts = { path = "../voelin-myts" }
slint = { version = "1.18", features = ["renderer-software"] }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media-desktop"] }
voelin-platform = { path = "../voelin-platform" }
File diff suppressed because it is too large. Load diff
+29 -4
View File
@@ -97,6 +97,9 @@ fn default_secrets() -> Box<dyn Secrets> {
#[cfg(not(target_os = "android"))]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
if key.starts_with("myts/") {
return self.keyring.get(key);
}
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
@@ -104,6 +107,9 @@ impl Secrets for FallbackSecrets {
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if key.starts_with("myts/") {
return self.keyring.set(key, value);
}
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
@@ -112,6 +118,9 @@ impl Secrets for FallbackSecrets {
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
if key.starts_with("myts/") {
return self.keyring.delete(key);
}
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
@@ -377,6 +386,10 @@ impl Models {
}
pub(crate) struct App {
#[cfg(not(target_os = "android"))]
pub runtime: tokio::runtime::Handle,
#[cfg(not(target_os = "android"))]
pub myts: crate::myts::Account,
pub ui: slint::Weak<MainWindow>,
pub store: Store,
pub secrets: Box<dyn Secrets>,
@@ -616,6 +629,10 @@ pub fn run(options: RunOptions) -> Result<()> {
let mut video = Video::new(&dir, settings.openh264);
video.set_decoder_preference(decoder_preference(&prefs));
let app = App {
#[cfg(not(target_os = "android"))]
runtime: runtime.clone(),
#[cfg(not(target_os = "android"))]
myts: Default::default(),
ui: ui.as_weak(),
store,
secrets: options.secrets.unwrap_or_else(default_secrets),
@@ -671,6 +688,8 @@ pub fn run(options: RunOptions) -> Result<()> {
app.refresh_home();
app.refresh_notices();
app.refresh_pages();
#[cfg(not(target_os = "android"))]
app.start_myts();
if app.demo {
app.start_demo();
}
@@ -730,16 +749,22 @@ pub fn run(options: RunOptions) -> Result<()> {
/// Open a file or folder with the desktop's default application.
pub(crate) fn open_path(path: &Path) -> std::io::Result<()> {
let mut child = desktop_opener(path.as_os_str()).spawn()?;
// Reap it without blocking the UI.
std::thread::spawn(move || child.wait());
Ok(())
}
/// Build an argument-based desktop opener; never pass a target through a shell.
pub(crate) fn desktop_opener(target: &std::ffi::OsStr) -> std::process::Command {
#[cfg(windows)]
let mut command = std::process::Command::new("explorer");
#[cfg(target_os = "macos")]
let mut command = std::process::Command::new("open");
#[cfg(not(any(windows, target_os = "macos")))]
let mut command = std::process::Command::new("xdg-open");
let mut child = command.arg(path).spawn()?;
// Reap it without blocking the UI.
std::thread::spawn(move || child.wait());
Ok(())
command.arg(target);
command
}
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
+20
View File
@@ -6,6 +6,26 @@ use crate::app::{Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
#[cfg(not(target_os = "android"))]
{
bridge.on_myts_login(|email, password, otp| {
with_app(|app| {
app.myts_login(email.to_string(), password.to_string(), otp.to_string())
});
});
bridge.on_myts_logout(|| {
with_app(|app| app.myts_logout());
});
bridge.on_myts_dismiss(|| {
with_app(|app| app.myts_dismiss());
});
bridge.on_myts_retry(|| {
with_app(|app| app.myts_retry());
});
bridge.on_myts_portal(|action| {
with_app(|app| app.myts_portal(action));
});
}
bridge.on_open_settings(|| {
with_app(|app| app.open_settings());
});
+25
View File
@@ -168,6 +168,31 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
for open in &switches.open {
let (what, arg) = open.split_once(':').unwrap_or((open.as_str(), ""));
match what {
"login" if switches.demo_ui => {
let bridge = ui.global::<Bridge>();
let mut account = bridge.get_myts();
account.available = true;
account.prompt = arg != "account";
if arg == "account" {
account.signed_in = true;
account.username = "Alex Example".into();
account.email = "alex@example.test".into();
account.uuid = "00000000-0000-0000-0000-000000000001".into();
account.myts_id = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB".into();
account.identity_status = 1;
nav.invoke_open_settings(SettingsSection::Account);
}
account.otp_required = arg == "otp";
account.can_forget = arg == "saved" || arg == "account";
account.status = if arg == "otp" {
3
} else if arg == "saved" {
2
} else {
0
};
bridge.set_myts(account);
}
"home" => nav.invoke_show(Page::Home),
"server" => nav.invoke_show(Page::Server),
"settings" => nav.invoke_open_settings(section(arg)),
+2
View File
@@ -15,6 +15,8 @@ mod images;
mod inbox;
mod members;
mod messages;
#[cfg(not(target_os = "android"))]
mod myts;
mod previews;
mod servers;
mod settings;
+710
View File
@@ -0,0 +1,710 @@
//! Desktop account state. Only the UI thread mutates state or persists credentials.
use serde::{Deserialize, Serialize};
use slint::ComponentHandle;
use std::sync::Arc;
use voelin_myts::{Client, Login, ServerIdentity, SessionToken};
use voelin_store::Secrets;
use crate::app::{App, Bridge, MytsForm, later};
// One keyring item makes session replacement atomic: a failed write cannot
// combine a new session with another account's renewal material.
const KEY: &str = "myts/session";
#[derive(Default, Serialize, Deserialize)]
struct Saved {
session: String,
email: String,
username: String,
#[serde(default)]
uuid: String,
renewal_token: String,
device_id: String,
#[serde(default)]
otp_token: String,
// Private account identity belongs in the same secret-store transaction.
#[serde(default)]
identity: Option<ServerIdentity>,
}
#[derive(Default)]
pub(crate) struct Account {
saved: Option<Saved>,
signed_in: bool,
busy: bool,
otp_required: bool,
status: i32,
persistence_status: i32,
generation: u64,
started: bool,
prompt: bool,
// Also set after a failed read/delete so the user can retry clearing.
can_forget: bool,
identity_failed: bool,
}
impl Account {
fn load(&mut self, secrets: &dyn Secrets) {
match read_saved(secrets) {
Ok(saved) => {
self.saved = saved;
self.can_forget = false;
self.status = 0;
self.persistence_status = 0;
self.identity_failed = false;
}
Err(()) => {
self.can_forget = true;
self.persistence_status = 1;
}
}
}
fn restored(&mut self) {
self.signed_in = true;
self.prompt = false;
self.otp_required = false;
}
fn device_for(&self, email: &str) -> (String, String) {
self.saved
.as_ref()
.filter(|s| s.email.eq_ignore_ascii_case(email.trim()))
.map(|s| (s.device_id.clone(), s.otp_token.clone()))
.unwrap_or_default()
}
fn accept(&mut self, secrets: &dyn Secrets, login: Login, email: String) {
self.identity_failed = login.identity.is_err();
let (renewal_token, device_id, otp_token) = login
.renewal
.map(|renewal| (renewal.token, renewal.device_id, renewal.otp_token))
.unwrap_or_default();
let saved = Saved {
session: login.token.into_inner(),
email,
username: login.username,
uuid: login.uuid,
renewal_token,
device_id,
otp_token,
identity: login.identity.ok(),
};
self.persistence_status = if save(secrets, &saved) {
0
} else {
// Remove an older credential after a replacement failed. Do not
// silently sign back into the previous account on next startup.
let cleared = secrets.delete(KEY).is_ok();
if cleared { 5 } else { 6 }
};
self.status = 0;
self.saved = Some(saved);
self.restored();
}
fn revocation_failed(&mut self, generation: u64) {
if self.generation == generation && !self.signed_in && !self.busy && !self.can_forget {
self.status = 9;
}
}
fn form(&self) -> MytsForm {
let identity = self.identity();
MytsForm {
available: true,
prompt: self.prompt,
signed_in: self.signed_in,
email: self.saved.as_ref().map(|s| s.email.as_str()).unwrap_or_default().into(),
username: self.saved.as_ref().map(|s| s.username.as_str()).unwrap_or_default().into(),
uuid: self.saved.as_ref().map(|s| s.uuid.as_str()).unwrap_or_default().into(),
myts_id: identity.map(ServerIdentity::id).unwrap_or_default().into(),
identity_status: if !self.signed_in {
0
} else if identity.is_some() {
1
} else if self.identity_failed {
3
} else {
2
},
status: self.status,
persistence_status: self.persistence_status,
busy: self.busy,
otp_required: self.otp_required,
can_forget: self.can_forget || self.saved.is_some(),
}
}
fn identity(&self) -> Option<&ServerIdentity> {
self.saved.as_ref().filter(|_| self.signed_in).and_then(|s| s.identity.as_ref())
}
fn begin(&mut self) -> Option<u64> {
if self.busy {
return None;
}
self.generation += 1;
self.busy = true;
self.status = 0;
Some(self.generation)
}
fn finish(&mut self, generation: u64) -> bool {
if self.generation != generation {
return false;
}
self.busy = false;
true
}
fn forget(&mut self, secrets: &dyn Secrets) -> bool {
self.generation += 1;
self.busy = false;
self.signed_in = false;
self.prompt = true;
self.saved = None;
self.identity_failed = false;
self.otp_required = false;
let cleared = secrets.delete(KEY).is_ok();
self.persistence_status = if cleared { 0 } else { 8 };
self.can_forget = !cleared;
cleared
}
}
fn login_error_status(error: &voelin_myts::Error) -> i32 {
match error.status_code() {
Some(208) => 3,
Some(209) => 14,
Some(203) => 13,
Some(202) => 16,
Some(103 | 206 | 207) => 15,
_ if matches!(error, voelin_myts::Error::Http(429)) => 17,
_ => 4,
}
}
// Fixed official routes only. Neither the session nor an email goes in a URL.
fn portal_url(action: i32) -> Option<&'static str> {
match action {
0 => Some("https://www.myteamspeak.com/register"),
1 => Some("https://www.myteamspeak.com/forgot-password"),
2 => Some("https://www.myteamspeak.com/my-account"),
3 => Some("https://www.myteamspeak.com/resend-activation"),
4 => Some("https://www.myteamspeak.com/my-account/change-username"),
5 => Some("https://www.myteamspeak.com/my-account/change-email"),
6 => Some("https://www.myteamspeak.com/my-account/change-password"),
7 => Some("https://www.myteamspeak.com/my-account/change-2fa"),
8 => Some("https://www.myteamspeak.com/my-account/manage-account"),
9 => Some("https://www.myteamspeak.com/my-account/manage-data"),
_ => None,
}
}
fn read_saved(secrets: &dyn Secrets) -> Result<Option<Saved>, ()> {
secrets
.get(KEY)
.map_err(|_| ())?
.map(|value| {
let saved: Saved = serde_json::from_str(&value).map_err(|_| ())?;
SessionToken::new(saved.session.clone()).map_err(|_| ())?;
Ok(saved)
})
.transpose()
}
fn save(secrets: &dyn Secrets, saved: &Saved) -> bool {
serde_json::to_string(saved).ok().is_some_and(|value| secrets.set(KEY, &value).is_ok())
}
impl App {
fn publish_myts_identity(&self) {
self.engine.send(voelin_core::Command::SetMytsIdentity(
self.myts.identity().cloned().map(Arc::new),
));
}
pub(crate) fn refresh_myts(&self) {
let Some(ui) = self.ui.upgrade() else {
return;
};
ui.global::<Bridge>().set_myts(self.myts.form());
}
pub(crate) fn start_myts(&mut self) {
if self.myts.started {
return;
}
self.myts.started = true;
if self.demo_ui {
self.refresh_myts();
return;
}
self.myts.prompt = true;
self.myts_retry();
}
pub(crate) fn myts_dismiss(&mut self) {
self.myts.prompt = false;
self.refresh_myts();
}
pub(crate) fn myts_portal(&mut self, action: i32) {
let Some(url) = portal_url(action).filter(|_| !self.myts.busy) else {
return;
};
let generation = self.myts.generation;
self.runtime.spawn(async move {
let opened = tokio::task::spawn_blocking(move || {
crate::app::desktop_opener(std::ffi::OsStr::new(url))
.status()
.is_ok_and(|status| status.success())
})
.await
.unwrap_or(false);
later(move |app| {
if app.myts.generation == generation && !app.myts.busy {
app.myts.status = if opened { 11 } else { 10 };
app.refresh_myts();
}
});
});
}
pub(crate) fn myts_retry(&mut self) {
if self.demo_ui || self.myts.busy {
return;
}
if self.myts.saved.is_none() {
self.myts.load(self.secrets.as_ref());
}
let Some(saved) = self.myts.saved.as_ref() else {
self.refresh_myts();
return;
};
let token = SessionToken::new(saved.session.clone()).expect("validated stored token");
let generation = self.myts.begin().expect("startup is idle");
self.refresh_myts();
self.runtime.spawn(async move {
// Password login does not provide the separate auth token required
// by loginWithRenewalToken. Expiry requires a fresh password login.
let result = async { Client::new()?.validate_session(&token).await }.await;
later(move |app| {
if !app.myts.finish(generation) {
return;
}
let was_signed_in = app.myts.signed_in;
match result {
Ok(()) => app.myts.restored(),
Err(error) => {
app.myts.otp_required =
error.is_otp_required() || error.status_code() == Some(209);
app.myts.status = 2;
if error.is_invalid_session() {
app.myts.signed_in = false;
app.myts.status = 15;
}
}
}
if was_signed_in != app.myts.signed_in {
app.publish_myts_identity();
}
app.refresh_myts();
});
});
}
pub(crate) fn myts_login(&mut self, email: String, password: String, otp: String) {
if email.trim().is_empty() || password.is_empty() || self.myts.signed_in {
return;
}
let (device, otp_renewal) = self.myts.device_for(&email);
let Some(generation) = self.myts.begin() else {
return;
};
self.refresh_myts();
self.runtime.spawn(async move {
let result = async {
Client::new()?
.login_with_otp_renewal(
email.trim(),
&password,
(!otp.is_empty()).then_some(otp.as_str()),
&device,
&otp_renewal,
)
.await
}
.await;
later(move |app| {
if !app.myts.finish(generation) {
app.discard_myts_login(result.ok());
return;
}
match result {
Ok(login) => {
app.myts.accept(app.secrets.as_ref(), login, email.trim().to_owned());
app.publish_myts_identity();
}
Err(error) => {
app.myts.otp_required =
error.is_otp_required() || error.status_code() == Some(209);
app.myts.status = login_error_status(&error);
}
}
app.refresh_myts();
});
});
}
// A canceled login can still have created a remote session. Revoke it,
// never publish or save it after a sign-out/replacement.
fn discard_myts_login(&self, login: Option<Login>) {
if let Some(login) = login {
let generation =
(!self.myts.busy && !self.myts.signed_in).then_some(self.myts.generation);
self.runtime.spawn(async move {
let result = async { Client::new()?.logout(&login.token).await }.await;
if result.is_err() {
// Static diagnostic: no credential, account, response body or URL.
tracing::warn!("canceled account sign-in session could not be revoked");
later(move |app| {
if let Some(generation) = generation {
app.myts.revocation_failed(generation);
}
app.refresh_myts();
});
}
});
}
}
pub(crate) fn myts_logout(&mut self) {
let token =
self.myts.saved.as_ref().and_then(|s| SessionToken::new(s.session.clone()).ok());
let cleared = self.myts.forget(self.secrets.as_ref());
self.publish_myts_identity();
self.myts.status = if cleared { 7 } else { 0 };
if let Some(token) = token {
let generation = self.myts.generation;
self.myts.busy = true;
self.runtime.spawn(async move {
let result = async { Client::new()?.logout(&token).await }.await;
later(move |app| {
if !app.myts.finish(generation) {
return;
}
if result.is_err() && cleared {
app.myts.status = 9;
}
app.refresh_myts();
});
});
}
self.refresh_myts();
}
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_store::MemorySecrets;
fn login(name: &str) -> Login {
Login {
token: SessionToken::new(format!("{name}-session")).unwrap(),
uuid: format!("{name}-uuid"),
username: name.into(),
identity: Ok(server_identity()),
renewal: Some(voelin_myts::Renewal {
token: format!("{name}-renewal"),
otp_token: format!("{name}-otp"),
device_id: format!("{name}-device"),
}),
}
}
fn server_identity() -> ServerIdentity {
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58; // Compressed Ed25519 basepoint for scalar one.
ServerIdentity::new(vec![1; 33], 1, public, private, vec![2; 65]).unwrap()
}
#[test]
fn primary_account_persists_restores_after_validation_and_signout_returns_to_login() {
let secrets = MemorySecrets::default();
let mut account = Account { prompt: true, ..Default::default() };
account.load(&secrets);
assert!(account.form().prompt);
assert!(!account.form().signed_in);
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert!(!account.form().prompt);
assert!(account.form().signed_in);
assert_eq!(account.form().identity_status, 1);
assert!(account.identity().is_some());
assert_eq!(account.form().uuid, "Alice-uuid");
let mut restarted = Account { prompt: true, ..Default::default() };
restarted.load(&secrets);
assert!(restarted.identity().is_none(), "unvalidated cache cannot authenticate servers");
assert!(!restarted.form().signed_in, "cached profile is not validated yet");
let generation = restarted.begin().unwrap();
assert!(restarted.finish(generation));
restarted.restored();
assert!(restarted.identity().is_some());
assert!(!restarted.form().prompt);
assert_eq!(restarted.form().username, "Alice");
assert!(restarted.forget(&secrets));
assert!(restarted.form().prompt);
assert_eq!(restarted.form().username, "");
assert_eq!(restarted.form().uuid, "");
assert!(!restarted.form().signed_in);
assert!(restarted.identity().is_none());
assert_eq!(restarted.form().myts_id, "");
}
#[test]
fn switching_primary_account_never_reuses_another_accounts_device_material() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert_eq!(
account.device_for(" ALICE@example.test "),
("Alice-device".into(), "Alice-otp".into())
);
assert_eq!(account.device_for("bob@example.test"), Default::default());
account.forget(&secrets);
assert_eq!(account.device_for("alice@example.test"), Default::default());
let mut bob = login("Bob");
bob.renewal = None;
account.accept(&secrets, bob, "bob@example.test".into());
let saved = read_saved(&secrets).unwrap().unwrap();
assert_eq!(saved.uuid, "Bob-uuid");
assert_eq!(saved.email, "bob@example.test");
assert!(saved.renewal_token.is_empty());
assert!(saved.otp_token.is_empty());
assert!(saved.device_id.is_empty());
}
#[test]
fn missing_server_key_keeps_login_but_never_reuses_previous_identity() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert!(account.identity().is_some());
account.forget(&secrets);
let mut bob = login("Bob");
bob.identity = Err(voelin_myts::IdentityError::Missing);
account.accept(&secrets, bob, "bob@example.test".into());
assert!(account.signed_in);
assert!(account.identity().is_none());
assert_eq!(account.form().identity_status, 3);
assert!(account.form().myts_id.is_empty());
assert!(read_saved(&secrets).unwrap().unwrap().identity.is_none());
}
#[test]
fn corrupted_persisted_private_identity_cannot_be_restored() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
let mut value: serde_json::Value =
serde_json::from_str(&secrets.get(KEY).unwrap().unwrap()).unwrap();
value["identity"]["private_key"] = serde_json::json!(vec![0u8; 32]);
secrets.set(KEY, &value.to_string()).unwrap();
assert!(read_saved(&secrets).is_err());
let mut restored = Account::default();
restored.load(&secrets);
assert!(restored.identity().is_none());
assert_eq!(restored.form().persistence_status, 1);
}
#[test]
fn keyring_retry_and_legacy_bundle_do_not_claim_a_validated_account() {
let secrets = MemorySecrets::default();
secrets.set(KEY, r#"{"session":"legacy","email":"a@example.test","username":"A","renewal_token":"r","device_id":"d"}"#).unwrap();
let mut account = Account { prompt: true, ..Default::default() };
account.load(&Unavailable);
assert_eq!(account.form().persistence_status, 1);
account.load(&secrets);
assert_eq!(account.status, 0);
assert_eq!(account.form().persistence_status, 0);
assert!(!account.can_forget);
assert!(!account.signed_in);
assert!(account.prompt);
assert_eq!(account.form().uuid, "");
account.restored();
assert_eq!(account.form().identity_status, 2);
assert!(account.identity().is_none());
assert_eq!(account.saved.unwrap().otp_token, "");
}
#[test]
fn login_survives_keyring_failure_with_visible_session_only_status() {
let mut account = Account { prompt: true, ..Default::default() };
account.accept(&Unavailable, login("Alice"), "alice@example.test".into());
assert!(account.signed_in);
assert!(!account.prompt);
assert_eq!(account.form().persistence_status, 6);
assert!(account.form().can_forget);
assert_eq!(account.form().username, "Alice");
let generation = account.begin().unwrap();
assert!(account.finish(generation));
account.restored();
assert_eq!(
account.form().persistence_status,
6,
"validation must not hide failed persistence"
);
account.status = 11;
assert_eq!(
account.form().persistence_status,
6,
"opening management must retain the warning"
);
account.forget(&Unavailable);
account.status = 11;
assert_eq!(
account.form().persistence_status,
8,
"failed deletion must remain visible after browser launch"
);
account.forget(&MemorySecrets::default());
assert_eq!(account.form().persistence_status, 0);
}
#[test]
fn portal_actions_are_fixed_official_https_destinations() {
for action in 0..10 {
let url = portal_url(action).unwrap();
assert!(url.starts_with("https://www.myteamspeak.com/"));
assert!(!url.contains(['?', '#', '@']));
}
assert!(portal_url(-1).is_none());
assert!(portal_url(10).is_none());
assert_eq!(portal_url(1), Some("https://www.myteamspeak.com/forgot-password"));
assert_eq!(login_error_status(&voelin_myts::Error::Http(429)), 17);
assert_eq!(login_error_status(&voelin_myts::Error::Timeout), 4);
}
#[test]
fn failed_late_session_revocation_reports_signed_out_without_overwriting_new_login() {
let mut account = Account::default();
let old = account.begin().unwrap();
account.forget(&MemorySecrets::default());
assert!(!account.finish(old));
let signed_out = account.generation;
account.revocation_failed(signed_out);
assert_eq!(account.status, 9);
let new = account.begin().unwrap();
account.revocation_failed(signed_out);
account.revocation_failed(new);
assert_eq!(account.status, 0);
assert!(account.busy);
account.finish(new);
account.signed_in = true;
account.revocation_failed(new);
assert_eq!(account.status, 0);
}
#[test]
fn form_exposes_signed_out_busy_otp_and_signed_in_states_without_tokens() {
let mut account = Account::default();
assert!(account.form().available);
assert!(!account.form().signed_in);
assert!(!account.form().can_forget);
let generation = account.begin().unwrap();
assert!(account.form().busy);
account.finish(generation);
account.otp_required = true;
account.status = 3;
assert!(account.form().otp_required);
assert_eq!(account.form().status, 3);
account.saved = Some(Saved {
session: "secret session".into(),
email: "a@example.test".into(),
username: "Name".into(),
..Default::default()
});
account.signed_in = true;
account.otp_required = false;
let form = account.form();
assert!(form.signed_in);
assert!(form.can_forget);
assert_eq!(form.username, "Name");
assert_eq!(form.email, "a@example.test");
assert!(!form.otp_required);
}
#[test]
fn persistence_roundtrip_and_logout_delete_all_material() {
let secrets = MemorySecrets::default();
let saved = Saved {
session: "session".into(),
email: "email".into(),
renewal_token: "renewal".into(),
device_id: "device".into(),
username: "name".into(),
otp_token: "otp renewal".into(),
uuid: "account-uuid".into(),
identity: Some(server_identity()),
};
assert!(save(&secrets, &saved));
let loaded = read_saved(&secrets).unwrap().unwrap();
assert_eq!(loaded.session, "session");
assert_eq!(loaded.renewal_token, "renewal");
assert_eq!(loaded.email, "email");
assert_eq!(loaded.identity.unwrap().id(), server_identity().id());
let loaded = read_saved(&secrets).unwrap().unwrap();
let mut account = Account { saved: Some(loaded), signed_in: true, ..Default::default() };
assert!(account.forget(&secrets));
assert!(read_saved(&secrets).unwrap().is_none());
assert!(!account.signed_in);
}
#[test]
fn single_operation_and_logout_prevent_stale_resurrection() {
let mut account = Account::default();
let generation = account.begin().unwrap();
assert!(account.begin().is_none());
account.forget(&MemorySecrets::default());
assert!(!account.finish(generation));
let replacement = account.begin().unwrap();
assert!(!account.finish(generation));
assert!(account.busy);
assert!(account.finish(replacement));
}
struct Unavailable;
impl Secrets for Unavailable {
fn get(&self, _: &str) -> voelin_store::Result<Option<String>> {
Err(voelin_store::Error::Secrets("locked".into()))
}
fn set(&self, _: &str, _: &str) -> voelin_store::Result<()> {
Err(voelin_store::Error::Secrets("locked".into()))
}
fn delete(&self, _: &str) -> voelin_store::Result<()> {
Err(voelin_store::Error::Secrets("locked".into()))
}
}
#[test]
fn keyring_failure_is_visible_and_logout_still_clears_memory() {
assert!(read_saved(&Unavailable).is_err());
assert!(!save(&Unavailable, &Saved::default()));
let mut account =
Account { saved: Some(Saved::default()), signed_in: true, ..Default::default() };
assert!(!account.forget(&Unavailable));
assert!(account.saved.is_none());
assert!(!account.signed_in);
assert!(account.can_forget);
}
#[test]
fn malformed_or_empty_session_is_not_used() {
let secrets = MemorySecrets::default();
secrets.set(KEY, "broken").unwrap();
assert!(read_saved(&secrets).is_err());
assert!(save(&secrets, &Saved::default()));
assert!(read_saved(&secrets).is_err());
}
}
+9
View File
@@ -99,6 +99,15 @@ impl App {
return;
}
let mut options = VoiceOptions::new(&b.address, &b.nickname);
if let Some(spec) = &b.client_version {
match voelin_core::versions::resolve(spec) {
Ok(version) => options.client_version = version,
Err(error) => {
self.set_status(format!("Invalid client compatibility version: {error}"));
return;
}
}
}
options.identity = Some(self.identity_for(Some(b.id)));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = channel;
+20 -16
View File
@@ -9,6 +9,7 @@ import "assets/fonts/Inter-Bold.ttf";
import "assets/fonts/Inter-Italic.ttf";
import { Palette } from "std-widgets.slint";
import { LoginPage } from "screens/account.slint";
import { Theme } from "theme.slint";
import { Icons } from "icons.slint";
import { Bridge } from "bridge.slint";
@@ -112,7 +113,7 @@ export component MainWindow inherits Window {
keys := FocusScope {
// Ctrl+K: search.
capture-key-pressed(event) => {
if event.modifiers.control && (event.text == "k" || event.text == "K") && root.chrome {
if event.modifiers.control && (event.text == "k" || event.text == "K") && root.chrome && !Bridge.myts.prompt {
Nav.open-search("");
return accept;
}
@@ -125,9 +126,11 @@ export component MainWindow inherits Window {
padding-right: root.safe-area-insets.right;
padding-bottom: max(root.safe-area-insets.bottom, root.keyboard-inset);
if !root.chrome: StreamViewer { }
if Bridge.myts.prompt: LoginPage { }
if !Nav.narrow && root.chrome: DesktopShell {
if !Bridge.myts.prompt && !root.chrome: StreamViewer { }
if !Bridge.myts.prompt && !Nav.narrow && root.chrome: DesktopShell {
context: Nav.page == Page.settings ? @tr("Settings") : Nav.page == Page.studio ? @tr("Stream Studio") : "";
if Nav.page == Page.home: Sidebar {
HomeNav { }
@@ -213,7 +216,7 @@ export component MainWindow inherits Window {
}
}
if Nav.narrow && root.chrome: MobileShell {
if !Bridge.myts.prompt && Nav.narrow && root.chrome: MobileShell {
title: Nav.page == Page.settings ? @tr("Settings")
: Nav.page == Page.friends ? @tr("Friends")
: Nav.page == Page.messages ? @tr("Messages")
@@ -283,11 +286,12 @@ export component MainWindow inherits Window {
x: (parent.width - self.width) / 2;
y: parent.height - self.height - (Nav.narrow ? 140px : 96px);
text: Bridge.status-text;
visible: self.shown && !Bridge.myts.prompt;
widest: min(560px, parent.width - 32px);
}
// The member card of the members panel, over everything.
if Bridge.member-card.open: Rectangle {
if !Bridge.myts.prompt && (Bridge.member-card.open): Rectangle {
TouchArea {
clicked => { Bridge.open-member(-1); }
}
@@ -297,7 +301,7 @@ export component MainWindow inherits Window {
}
}
if Nav.emoji-open: Rectangle {
if !Bridge.myts.prompt && (Nav.emoji-open): Rectangle {
// Clicks outside the picker close it.
TouchArea {
clicked => { Nav.emoji-open = false; }
@@ -323,7 +327,7 @@ export component MainWindow inherits Window {
}
// The bell's panel, under the bell (the phone: the whole width).
if Nav.notifications-open: Rectangle {
if !Bridge.myts.prompt && (Nav.notifications-open): Rectangle {
TouchArea {
clicked => { Nav.notifications-open = false; }
}
@@ -335,39 +339,39 @@ export component MainWindow inherits Window {
}
}
if Nav.search-open: SearchPalette { }
if !Bridge.myts.prompt && (Nav.search-open): SearchPalette { }
if Nav.lightbox-open: Lightbox { }
if !Bridge.myts.prompt && (Nav.lightbox-open): Lightbox { }
if Nav.event-form-open: EventDialog {
if !Bridge.myts.prompt && (Nav.event-form-open): EventDialog {
form <=> Nav.event-form;
done => { Nav.event-form-open = false; }
}
if Nav.offline-form-open: OfflineDialog {
if !Bridge.myts.prompt && (Nav.offline-form-open): OfflineDialog {
done => { Nav.offline-form-open = false; }
}
if Nav.topic-form-open: TopicDialog {
if !Bridge.myts.prompt && (Nav.topic-form-open): TopicDialog {
done => { Nav.topic-form-open = false; }
}
if Nav.bookmark-open: BookmarkDialog {
if !Bridge.myts.prompt && (Nav.bookmark-open): BookmarkDialog {
form <=> Nav.bookmark-form;
join: Nav.join-open;
done => { Nav.bookmark-open = false; }
}
if Nav.share-open: ShareDialog {
if !Bridge.myts.prompt && (Nav.share-open): ShareDialog {
form <=> Nav.share-form;
done => { Nav.share-open = false; }
}
if Nav.client-open: ClientAudioDialog {
if !Bridge.myts.prompt && (Nav.client-open): ClientAudioDialog {
done => { Nav.client-open = false; }
}
if Nav.about-open: AboutDialog {
if !Bridge.myts.prompt && (Nav.about-open): AboutDialog {
done => { Nav.about-open = false; }
}
}
+23
View File
@@ -748,6 +748,22 @@ export struct AdvancedForm {
}
// Who we are (My Account page).
export struct MytsForm {
prompt: bool,
uuid: string,
myts-id: string,
identity-status: int,
available: bool,
signed_in: bool,
email: string,
username: string,
status: int,
persistence-status: int,
busy: bool,
otp_required: bool,
can_forget: bool,
}
export struct AccountForm {
nickname: string,
identity: string,
@@ -1063,6 +1079,13 @@ export global Bridge {
// Settings pages: a section was shown (its data is loaded then).
callback settings-section(int);
in property <AccountForm> account;
in property <MytsForm> myts;
in property <string> primary-name: myts.signed-in ? (myts.username != "" ? myts.username : myts.email) : nickname != "" ? nickname : app-name;
callback myts-dismiss();
callback myts-retry();
callback myts-portal(int);
callback myts-login(string, string, string);
callback myts-logout();
in property <[IdentityItem]> identities;
in property <[string]> identity-names;
in property <[BookmarkIdentity]> bookmark-identities;
+204
View File
@@ -0,0 +1,204 @@
// Shared account form for first launch and Settings → My Account.
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge } from "../bridge.slint";
import { Button, TextField, Field, Card, ScrollView } from "../components/index.slint";
component Note inherits Text {
// Keep wrapped account copy in the card’s layout bounds.
min-height: self.preferred-height;
color: Theme.text-secondary;
font-size: Theme.font-sm;
wrap: word-wrap;
}
component LoginForm inherits VerticalLayout {
spacing: Theme.space-3;
property <string> otp-text;
function submit() {
if !Bridge.myts.busy && email.text != "" && password.text != "" && (!Bridge.myts.otp-required || otp-text != "") {
Bridge.myts-login(email.text, password.text, otp-text);
password.clear();
otp-text = "";
}
}
Field {
label: @tr("Email");
email := TextField {
text: Bridge.myts.email;
placeholder: @tr("Email");
enabled: !Bridge.myts.busy;
accepted(_) => { root.submit(); }
}
}
Field {
label: @tr("Password");
password := TextField {
placeholder: @tr("Password");
input-type: InputType.password;
enabled: !Bridge.myts.busy;
accepted(_) => { root.submit(); }
}
}
if Bridge.myts.otp-required: Field {
label: @tr("One-time code");
TextField {
text <=> root.otp-text;
placeholder: @tr("One-time code");
input-type: InputType.password;
enabled: !Bridge.myts.busy;
accepted(_) => { root.submit(); }
}
}
Button {
text: @tr("Sign in");
enabled: !Bridge.myts.busy && email.text != "" && password.text != "" && (!Bridge.myts.otp-required || root.otp-text != "");
clicked => { root.submit(); }
}
Button {
text: @tr("Create account in browser");
enabled: !Bridge.myts.busy;
clicked => { Bridge.myts-portal(0); }
}
Button {
text: @tr("Forgot password?");
enabled: !Bridge.myts.busy;
clicked => { Bridge.myts-portal(1); }
}
Note { text: @tr("Registration and password recovery open the official myTeamSpeak website. Return here to sign in when finished."); }
}
export component AccountCard inherits Card {
title: @tr("myTeamSpeak");
icon: Icons.user;
property <string> account-status: Bridge.myts.status == 2 ? @tr("Saved session could not be validated. Your saved credentials were retained; sign in again or clear them.") :
Bridge.myts.status == 3 ? @tr("Enter your password again and the one-time code.") :
Bridge.myts.status == 4 ? @tr("Sign-in failed. Check your credentials and connection; the experimental service may be unavailable.") :
Bridge.myts.status == 7 ? @tr("Signed out.") :
Bridge.myts.status == 9 ? @tr("Signed out and saved credentials cleared. Remote session revocation failed.") :
Bridge.myts.status == 10 ? @tr("Could not open your browser. Visit myteamspeak.com to manage your account.") :
Bridge.myts.status == 11 ? @tr("Account website opened in your browser. When finished, return here and sign in again to apply changes.") :
Bridge.myts.status == 13 ? @tr("Your email address has not been verified. Activate your account using the link in your email, or request a new activation email.") :
Bridge.myts.status == 14 ? @tr("The one-time code was not accepted. Enter your password and a new code.") :
Bridge.myts.status == 15 ? @tr("Your saved session has expired. Sign in again.") :
Bridge.myts.status == 16 ? @tr("Email or password was not accepted. Check your details and try again.") :
Bridge.myts.status == 17 ? @tr("Too many requests. Wait a while before trying again.") : "";
if !Bridge.myts.available: Note { text: @tr("Account sign-in is available on desktop."); }
if Bridge.myts.available && !Bridge.myts.signed-in: LoginForm { }
if Bridge.myts.signed-in: VerticalLayout {
spacing: Theme.space-3;
Note { text: @tr("Primary account"); }
Text {
text: Bridge.primary-name;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
wrap: word-wrap;
}
Note { text: Bridge.myts.email; }
if Bridge.myts.uuid != "": Field {
label: @tr("Account ID");
TextField {
text: Bridge.myts.uuid;
read-only: true;
label: @tr("Account ID");
}
}
if Bridge.myts.myts-id != "": Field {
label: @tr("myTS ID");
TextField {
text: Bridge.myts.myts-id;
read-only: true;
label: @tr("myTS ID");
}
}
if Bridge.myts.identity-status == 1: Note {
text: @tr("Your account identity is available for authentication on voice servers.");
}
if Bridge.myts.identity-status == 2: Note {
text: @tr("Sign out and sign in with your password to enable your myTS ID on voice servers.");
}
if Bridge.myts.identity-status == 3: Note {
text: @tr("Signed in, but the account identity could not be unlocked. Voice servers will not receive your myTS ID. Try signing in again; older account encryption may be unsupported.");
}
Note { text: @tr("This is your main app profile. Server identities and server nicknames are managed separately."); }
Note { text: @tr("Account management opens the official website. Check which account is signed in there. Sign in again here after making changes."); }
Button {
text: @tr("Manage account in browser");
enabled: !Bridge.myts.busy;
clicked => { Bridge.myts-portal(2); }
}
for action in [
{ text: @tr("Change username"), portal: 4 },
{ text: @tr("Change email"), portal: 5 },
{ text: @tr("Change password"), portal: 6 },
{ text: @tr("Two-factor authentication"), portal: 7 },
{ text: @tr("Manage account deletion"), portal: 8 },
{ text: @tr("Export account data"), portal: 9 },
]: Button {
text: action.text;
small: true;
enabled: !Bridge.myts.busy;
clicked => { Bridge.myts-portal(action.portal); }
}
}
if Bridge.myts.busy: Note { text: @tr("Contacting account service…"); }
if root.account-status != "": Note { text: root.account-status; }
if Bridge.myts.persistence-status == 1: Note {
text: @tr("Saved account credentials could not be read. Unlock the keyring or clear the saved session.");
}
if Bridge.myts.persistence-status == 5: Note {
text: @tr("Account credentials could not be saved. This session will not be restored after restarting.");
}
if Bridge.myts.persistence-status == 6: Note {
text: @tr("Account credentials could not be saved, and older credentials could not be removed. Unlock your keyring and clear the saved session.");
}
if Bridge.myts.persistence-status == 8: Note {
text: @tr("Signed out locally, but saved credentials could not be removed. Unlock your keyring and clear the saved session again.");
}
if Bridge.myts.status == 13: Button {
text: @tr("Resend activation email in browser");
enabled: !Bridge.myts.busy;
clicked => { Bridge.myts-portal(3); }
}
if Bridge.myts.can-forget && !Bridge.myts.busy: Button {
text: Bridge.myts.signed-in ? @tr("Check session") : @tr("Retry saved session");
clicked => { Bridge.myts-retry(); }
}
if Bridge.myts.can-forget || Bridge.myts.busy: Button {
text: Bridge.myts.busy ? @tr("Cancel and clear session") : Bridge.myts.signed-in ? @tr("Sign out") : @tr("Clear saved session");
clicked => { Bridge.myts-logout(); }
}
}
export component LoginPage inherits ScrollView {
VerticalLayout {
width: root.visible-width;
padding: Theme.space-4;
spacing: Theme.space-5;
alignment: start;
HorizontalLayout {
Rectangle { horizontal-stretch: 1; }
VerticalLayout {
max-width: 480px;
horizontal-stretch: 1;
spacing: Theme.space-4;
Text {
text: @tr("Welcome to {}", Bridge.app-name);
color: Theme.text;
font-size: Theme.font-xl;
font-weight: Theme.weight-semibold;
wrap: word-wrap;
}
Note { text: @tr("Sign in to make your myTeamSpeak account your main profile."); }
AccountCard { }
Button {
text: @tr("Continue without an account");
clicked => { Bridge.myts-dismiss(); }
}
Note { text: @tr("You can connect to servers without an account and sign in later in Settings → My Account."); }
}
Rectangle { horizontal-stretch: 1; }
}
}
}
+2 -1
View File
@@ -141,7 +141,8 @@ export component YouPage inherits ScrollView {
alignment: center;
horizontal-stretch: 1;
Text {
text: Bridge.nickname != "" ? Bridge.nickname : Bridge.app-name;
text: Bridge.primary-name;
overflow: elide;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
@@ -3,6 +3,7 @@
// (encoding, SRTP, history, cache, logs, every setting); and the rows the
// sections share.
import { AccountCard } from "account.slint";
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, IdentityItem, LayerItem, AudioSourceItem, ConfigItem, PermItem, SettingItem, EncoderItem } from "../bridge.slint";
@@ -168,6 +169,7 @@ component CopyField inherits Field {
export component AccountSection inherits VerticalLayout {
alignment: start;
spacing: Theme.space-5;
AccountCard { }
Card {
title: @tr("Identity in use");
icon: Icons.id-card;
@@ -219,21 +221,6 @@ export component AccountSection inherits VerticalLayout {
text: @tr("Servers know you by this id: your groups and permissions belong to it. Your nickname is set per server, in the server's bookmark.");
}
}
Card {
title: @tr("myTeamSpeak");
icon: Icons.info;
Hint {
text: @tr("{} does not sign in to myTeamSpeak, TeamSpeak's account service: it has no public API, and its terms do not allow using the private one. To use identities synchronised there, sign in once with the official client, then import them under Profiles: they are read from its settings, never written.", Bridge.app-name);
}
HorizontalLayout {
alignment: start;
Button {
icon: Icons.download;
text: @tr("Import identities");
clicked => { Nav.open-settings(SettingsSection.profiles); }
}
}
}
}
// Use as default, export, delete.
+1 -1
View File
@@ -1136,7 +1136,7 @@ export component SettingsPage inherits Rectangle {
: s == SettingsSection.keybinds ? @tr("How your voice goes out, and the keys for it.")
: s == SettingsSection.streaming ? @tr("Defaults of your streams, their layers and their sound.")
: s == SettingsSection.privacy ? @tr("Who can reach you, blocked people, what the app keeps.")
: s == SettingsSection.account ? @tr("Who servers see when you connect.")
: s == SettingsSection.account ? @tr("Your main account and server identity.")
: s == SettingsSection.profiles ? @tr("Your identities: each is a unique id on every server.")
: s == SettingsSection.devices ? @tr("Microphones, speakers, cameras and screens.")
: s == SettingsSection.notifications ? @tr("What the bell and the desktop tell you.")
+5 -5
View File
@@ -164,7 +164,7 @@ export component VoiceButtons inherits HorizontalLayout {
}
}
// Who we are on the current server, and the voice buttons.
// The primary app profile, with current server voice status and controls.
export component UserCard inherits Rectangle {
min-height: 60px;
border-radius: Theme.radius-lg;
@@ -179,9 +179,9 @@ export component UserCard inherits Rectangle {
alignment: center;
Avatar {
size: 38px;
initials: Bridge.nickname != "" ? "" : "?";
initials: Bridge.myts.signed-in || Bridge.nickname != "" ? "" : "?";
tint: Theme.accent;
label: Bridge.nickname;
label: Bridge.primary-name;
// Green ring while our voice goes out.
speaking: Bridge.transmitting;
status: Bridge.voice-connected ? Status.online : Bridge.observing ? Status.info : Status.offline;
@@ -189,7 +189,7 @@ export component UserCard inherits Rectangle {
source: Icons.user;
size: 20px;
tint: #ffffff;
visible: Bridge.nickname != "";
visible: Bridge.myts.signed-in || Bridge.nickname != "";
}
}
}
@@ -197,7 +197,7 @@ export component UserCard inherits Rectangle {
alignment: center;
horizontal-stretch: 1;
Text {
text: Bridge.nickname != "" ? Bridge.nickname : Bridge.app-name;
text: Bridge.primary-name;
color: Theme.text;
font-weight: Theme.weight-semibold;
overflow: elide;