account: show servers the account's avatar
As the official TeamSpeak 6 client does once connected and after a sign-in, Voelin sends updatemytsdata with the account's certificate and its avatar (LoginSession.mytsid_user_cert.cert and user_avatar, raw bytes with TeamSpeak's escaping only; \a and \b now escaped too). The avatar is sliced out of the login response as it came: its signature covers it. Both come from a password sign-in; they are kept per account next to the avatar picture (public data, outside the keyring) and published to every voice connection that presents the account (Command::SetMytsData, beside the identity). A refusal is only logged. Accounts signed in before need one password sign-in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
11 files changed
+448
-7
No files matched your search
@@ -61,6 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage;
|
||||
pub use ts_bookkeeping::*;
|
||||
pub use tsproto::resend::{ConnectionStats, PacketStat};
|
||||
pub use tsproto::Identity;
|
||||
pub use myts::MytsData;
|
||||
pub use tsproto_types::errors::Error as TsError;
|
||||
|
||||
/// Wait this time for initserver, in seconds.
|
||||
|
||||
@@ -14,7 +14,38 @@ impl ConnectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6),
|
||||
/// as myTeamSpeak signed it: the account's certificate and its avatar
|
||||
/// (`LoginSession.user_avatar` as it came). The server shows the avatar to
|
||||
/// everyone (`client_myteamspeak_avatar`).
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct MytsData {
|
||||
pub certificate: Vec<u8>,
|
||||
/// Empty: none.
|
||||
pub avatar: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for MytsData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MytsData")
|
||||
.field("certificate", &self.certificate.len())
|
||||
.field("avatar", &self.avatar.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Show the server the account's certificate and avatar
|
||||
/// (`updatemytsdata`), as the official client does once connected and
|
||||
/// after a sign-in, after the account proof (`updatemytsid`).
|
||||
/// Await the returned handle's `StreamItem::MessageResult` for the answer.
|
||||
pub fn send_myts_data(&mut self, data: &MytsData) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(data_packet(data))
|
||||
}
|
||||
|
||||
/// Publish a connection-bound account proof, or clear the account identity.
|
||||
///
|
||||
/// Always updates the reconnect options, even if currently disconnected or
|
||||
@@ -34,6 +65,18 @@ impl Connection {
|
||||
}
|
||||
}
|
||||
|
||||
/// The values are the raw bytes with TeamSpeak's escaping only (no
|
||||
/// base64), as the official client sends them; an empty avatar is left out.
|
||||
fn data_packet(data: &MytsData) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata");
|
||||
packet.write_bin_arg("myts_certificate", &data.certificate);
|
||||
if !data.avatar.is_empty() {
|
||||
packet.write_bin_arg("myts_avatar", &data.avatar);
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid");
|
||||
@@ -50,6 +93,22 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn account_data_goes_raw_and_escaped() {
|
||||
let data = MytsData {
|
||||
certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(),
|
||||
avatar: vec![0x0a, 0x02, b'h', b'i'],
|
||||
};
|
||||
let packet = data_packet(&data).into_packet();
|
||||
assert_eq!(
|
||||
packet.content(),
|
||||
b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff myts_avatar=\\n\x02hi"
|
||||
);
|
||||
// Without an avatar: the certificate alone.
|
||||
let packet = data_packet(&MytsData { avatar: Vec::new(), ..data }).into_packet();
|
||||
assert!(!packet.content().windows(11).any(|w| w == b"myts_avatar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_contains_no_previous_account_proof() {
|
||||
let packet = update_packet(None, &[0; 64]).into_packet();
|
||||
|
||||
@@ -968,6 +968,10 @@ impl io::Write for EscapedWriter<'_> {
|
||||
self.0.reserve(buf.len());
|
||||
for c in buf {
|
||||
match c {
|
||||
// Voelin patch: \a and \b as TeamSpeak escapes them (binary
|
||||
// values, e.g. `updatemytsdata`).
|
||||
b'\x07' => self.0.extend_from_slice(b"\\a"),
|
||||
b'\x08' => self.0.extend_from_slice(b"\\b"),
|
||||
b'\x0b' => self.0.extend_from_slice(b"\\v"),
|
||||
b'\x0c' => self.0.extend_from_slice(b"\\f"),
|
||||
b'\\' => self.0.extend_from_slice(b"\\\\"),
|
||||
|
||||
@@ -104,6 +104,10 @@ pub type SessionId = u64;
|
||||
pub enum Command {
|
||||
/// Main account proof for every current and future voice connection.
|
||||
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
|
||||
/// What voice servers are shown of the main account (its certificate
|
||||
/// and avatar, TeamSpeak 6): sent to every connection that presents the
|
||||
/// account, once connected and when it changes.
|
||||
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
|
||||
ConnectVoice {
|
||||
session: SessionId,
|
||||
options: Box<VoiceOptions>,
|
||||
@@ -818,6 +822,7 @@ async fn run(
|
||||
contacts.load().await;
|
||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||
let (myts_identity, _) = watch::channel(None);
|
||||
let (myts_data, _) = 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));
|
||||
@@ -875,6 +880,16 @@ async fn run(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetMytsData(data) => {
|
||||
myts_data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetAudioSettings(new) => {
|
||||
settings = (*new).clone();
|
||||
for s in sessions.values() {
|
||||
@@ -951,6 +966,7 @@ async fn run(
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1029,6 +1045,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
|
||||
@@ -87,10 +87,12 @@ impl SessionHandle {
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity).run(rx),
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
|
||||
.run(rx),
|
||||
);
|
||||
Self { tx }
|
||||
}
|
||||
@@ -190,6 +192,7 @@ struct OwnStream {
|
||||
|
||||
struct Session {
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
state: SessionState,
|
||||
@@ -270,12 +273,14 @@ impl Session {
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> 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,
|
||||
myts_data,
|
||||
cache,
|
||||
contacts,
|
||||
contacts_rx,
|
||||
@@ -411,6 +416,7 @@ impl Session {
|
||||
}
|
||||
let link = VoiceLink {
|
||||
myts_identity: self.myts_identity.clone(),
|
||||
myts_data: self.myts_data.clone(),
|
||||
session: self.id,
|
||||
events: self.events.clone(),
|
||||
settings: self.settings.clone(),
|
||||
@@ -733,6 +739,7 @@ impl Session {
|
||||
}
|
||||
// Engine-wide.
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::CloseSession { .. }
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
@@ -2056,7 +2063,17 @@ mod banner_tests {
|
||||
// No myTeamSpeak account; its source stays open, as the engine's does
|
||||
// (a closed one ends voice connections).
|
||||
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
(Session::new(1, events, frames, AudioSettings::default(), shared, myts_identity), receiver)
|
||||
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let session = Session::new(
|
||||
1,
|
||||
events,
|
||||
frames,
|
||||
AudioSettings::default(),
|
||||
shared,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
);
|
||||
(session, receiver)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -70,6 +70,8 @@ impl VoiceOptions {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct VoiceLink {
|
||||
pub myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
|
||||
pub myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
pub session: SessionId,
|
||||
pub events: broadcast::Sender<Event>,
|
||||
pub settings: SharedSettings,
|
||||
@@ -227,6 +229,7 @@ fn now_ms() -> i64 {
|
||||
|
||||
enum Input {
|
||||
MytsIdentityChanged,
|
||||
MytsDataChanged,
|
||||
AccountSourceClosed,
|
||||
Item(Option<Result<StreamItem, tsclientlib::Error>>),
|
||||
Cmd(Option<VoiceCmd>),
|
||||
@@ -236,6 +239,8 @@ enum Input {
|
||||
/// A command waiting for the server's answer.
|
||||
enum Pending {
|
||||
MytsIdentity(Instant),
|
||||
/// `updatemytsdata`: its answer is only logged.
|
||||
MytsData,
|
||||
Stream(Request),
|
||||
FileList {
|
||||
request: RequestId,
|
||||
@@ -366,6 +371,7 @@ async fn run_inner(
|
||||
builder = builder.channel(channel.clone());
|
||||
}
|
||||
let mut identity = link.myts_identity.clone();
|
||||
let mut data = link.myts_data.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 {
|
||||
@@ -435,6 +441,10 @@ async fn run_inner(
|
||||
transfers: HashMap::new(),
|
||||
};
|
||||
voice.publish_state()?;
|
||||
// The account's avatar, for everyone on the server (as the official
|
||||
// client, once connected).
|
||||
data.borrow_and_update();
|
||||
voice.send_myts_data(&identity, &data);
|
||||
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
@@ -445,7 +455,9 @@ async fn run_inner(
|
||||
}) {
|
||||
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
|
||||
}
|
||||
let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await;
|
||||
let input =
|
||||
next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data)
|
||||
.await;
|
||||
match input {
|
||||
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
|
||||
Input::MytsIdentityChanged => {
|
||||
@@ -456,6 +468,12 @@ async fn run_inner(
|
||||
}
|
||||
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
|
||||
}
|
||||
// After the proof, what is shown of the account (a sign-in).
|
||||
voice.send_myts_data(&identity, &data);
|
||||
}
|
||||
Input::MytsDataChanged => {
|
||||
data.borrow_and_update();
|
||||
voice.send_myts_data(&identity, &data);
|
||||
}
|
||||
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
|
||||
Input::Item(Some(Err(e))) => break Err(e.into()),
|
||||
@@ -488,6 +506,7 @@ async fn next_input(
|
||||
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
|
||||
tick: &mut tokio::time::Interval,
|
||||
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: &mut watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Input {
|
||||
tokio::select! {
|
||||
biased;
|
||||
@@ -496,6 +515,11 @@ async fn next_input(
|
||||
} else {
|
||||
Input::AccountSourceClosed
|
||||
},
|
||||
changed = data.changed() => if changed.is_ok() {
|
||||
Input::MytsDataChanged
|
||||
} else {
|
||||
Input::AccountSourceClosed
|
||||
},
|
||||
input = async {
|
||||
// Keep account changes first without starving network or timers when
|
||||
// the audio command queue remains ready.
|
||||
@@ -802,6 +826,10 @@ impl Voice {
|
||||
self.link.emit(Event::OfflineMessage { session, request, result });
|
||||
}
|
||||
Pending::Quiet | Pending::MytsIdentity(_) => {}
|
||||
Pending::MytsData => match result {
|
||||
Ok(()) => debug!("the server took the account's avatar"),
|
||||
Err(e) => warn!(error = %e, "the server refused the account's avatar"),
|
||||
},
|
||||
Pending::Report(what) => {
|
||||
if let Err(e) = result {
|
||||
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
|
||||
@@ -810,6 +838,27 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the server the account's certificate and avatar
|
||||
/// (`updatemytsdata`), when connected with the account.
|
||||
fn send_myts_data(
|
||||
&mut self,
|
||||
identity: &watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: &watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) {
|
||||
if identity.borrow().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(data) = data.borrow().clone().filter(|d| !d.certificate.is_empty()) else {
|
||||
return;
|
||||
};
|
||||
match self.con.send_myts_data(&data) {
|
||||
Ok(handle) => {
|
||||
self.pending.insert(handle, Pending::MytsData);
|
||||
}
|
||||
Err(e) => warn!(error = %e, "the account's avatar was not sent"),
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> {
|
||||
let handle = cmd.send_with_result(&mut self.con)?;
|
||||
self.pending.insert(handle, pending);
|
||||
@@ -1116,6 +1165,7 @@ mod account_tests {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn account_priority_preserves_ready_network_and_timer_progress() {
|
||||
let (account, mut identity) = watch::channel(None);
|
||||
let (account_data, mut data) = watch::channel(None);
|
||||
let (commands, mut receiver) = mpsc::unbounded_channel();
|
||||
for _ in 0..512 {
|
||||
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
|
||||
@@ -1126,14 +1176,22 @@ mod account_tests {
|
||||
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,
|
||||
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
|
||||
Input::MytsIdentityChanged
|
||||
));
|
||||
identity.borrow_and_update();
|
||||
// What is shown of the account changes too, ahead of the rest.
|
||||
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(matches!(
|
||||
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
|
||||
Input::MytsDataChanged
|
||||
));
|
||||
data.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 {
|
||||
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await
|
||||
{
|
||||
Input::Item(_) => network += 1,
|
||||
Input::Tick => timers += 1,
|
||||
Input::Cmd(_) => audio += 1,
|
||||
@@ -1168,6 +1226,7 @@ mod account_tests {
|
||||
events,
|
||||
settings: SharedSettings::new(crate::settings::Settings::default()),
|
||||
myts_identity: identity,
|
||||
myts_data: watch::channel(None).1,
|
||||
};
|
||||
let (_commands, commands) = mpsc::unbounded_channel();
|
||||
let (events, mut received) = mpsc::unbounded_channel();
|
||||
|
||||
@@ -6,7 +6,7 @@ mod identity;
|
||||
mod profile;
|
||||
mod transport;
|
||||
pub use identity::IdentityError;
|
||||
pub use profile::{Badge, Device, Profile};
|
||||
pub use profile::{Badge, Device, Presentation, Profile};
|
||||
pub use tsproto::myts::Identity as ServerIdentity;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
@@ -27,6 +27,9 @@ pub struct Login {
|
||||
/// What the login response tells about the account (the avatar's file
|
||||
/// names, the description); [`Client::profile`] tells more.
|
||||
pub profile: Profile,
|
||||
/// What voice servers are shown of the account (its avatar), as
|
||||
/// signed by myTeamSpeak.
|
||||
pub presentation: Presentation,
|
||||
}
|
||||
|
||||
/// Server-provided alternative login material, stored only in a secret store.
|
||||
@@ -181,7 +184,17 @@ impl Client {
|
||||
encryption_key: Option<Zeroizing<[u8; 32]>>,
|
||||
) -> Result<Login, Error> {
|
||||
let bytes = self.transport.call("authentication", method, body).await?;
|
||||
// The avatar exactly as it came: its signature covers its bytes.
|
||||
let avatar = profile::raw_field(&bytes, profile::USER_AVATAR).unwrap_or_default().to_vec();
|
||||
let response: api::LoginSession = wire::decode(bytes)?;
|
||||
let presentation = Presentation {
|
||||
certificate: response
|
||||
.mytsid_user_cert
|
||||
.as_ref()
|
||||
.map(|c| c.cert.clone())
|
||||
.unwrap_or_default(),
|
||||
avatar,
|
||||
};
|
||||
let token = SessionToken::try_from(&response)?;
|
||||
let (response, identity) = tokio::task::spawn_blocking(move || {
|
||||
let identity = match encryption_key {
|
||||
@@ -197,6 +210,7 @@ impl Client {
|
||||
token,
|
||||
identity,
|
||||
profile,
|
||||
presentation,
|
||||
uuid: response.uuid,
|
||||
username: response.username,
|
||||
renewal: response.alternative_login_info.map(|info| Renewal {
|
||||
|
||||
@@ -5,6 +5,81 @@ use crate::Error;
|
||||
use schema_api::SessionToken;
|
||||
use schema_api::api::{self, user};
|
||||
|
||||
/// `LoginSession.user_avatar`, the account's avatar as myTeamSpeak signed
|
||||
/// it.
|
||||
pub(crate) const USER_AVATAR: u32 = 11;
|
||||
|
||||
/// What voice servers show of the account (TeamSpeak 6): sent to each
|
||||
/// server once connected (`updatemytsdata`), as the official client does.
|
||||
/// Public data, as myTeamSpeak signed it; empty without it.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct Presentation {
|
||||
/// The account's certificate (`LoginSession.mytsid_user_cert.cert`).
|
||||
pub certificate: Vec<u8>,
|
||||
/// The avatar (`LoginSession.user_avatar`, an `AvatarData`: its
|
||||
/// pictures' links, a timestamp and myTeamSpeak's signature), the bytes
|
||||
/// exactly as they came: the signature covers them, and fields this
|
||||
/// version does not know would be lost by encoding them again.
|
||||
pub avatar: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Presentation {
|
||||
/// Whether there is anything to show (a certificate, without which a
|
||||
/// server takes nothing).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.certificate.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Presentation {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Presentation")
|
||||
.field("certificate", &self.certificate.len())
|
||||
.field("avatar", &self.avatar.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the last length-delimited field `number` at the top level
|
||||
/// of a protobuf message, as they are; `None` without one or for a message
|
||||
/// that does not parse.
|
||||
pub(crate) fn raw_field(message: &[u8], number: u32) -> Option<&[u8]> {
|
||||
fn varint(data: &[u8], at: &mut usize) -> Option<u64> {
|
||||
let mut value = 0u64;
|
||||
for shift in (0..64).step_by(7) {
|
||||
let byte = *data.get(*at)?;
|
||||
*at += 1;
|
||||
value |= u64::from(byte & 0x7f) << shift;
|
||||
if byte & 0x80 == 0 {
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
let mut at = 0;
|
||||
let mut found = None;
|
||||
while at < message.len() {
|
||||
let key = varint(message, &mut at)?;
|
||||
let skip = match key & 7 {
|
||||
0 => {
|
||||
varint(message, &mut at)?;
|
||||
0
|
||||
}
|
||||
1 => 8,
|
||||
2 => usize::try_from(varint(message, &mut at)?).ok()?,
|
||||
5 => 4,
|
||||
// Groups are not used by myTeamSpeak.
|
||||
_ => return None,
|
||||
};
|
||||
let end = at.checked_add(skip).filter(|end| *end <= message.len())?;
|
||||
if key & 7 == 2 && key >> 3 == u64::from(number) {
|
||||
found = Some(&message[at..end]);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `ERROR_SESSION_EXPIRED` of the `/user` service.
|
||||
pub(crate) const SESSION_EXPIRED: i32 = user::ErrorReturnCode::ErrorSessionExpired as i32;
|
||||
/// Avatars are small pictures; anything larger is not one.
|
||||
@@ -141,6 +216,36 @@ fn unix_seconds(value: i64) -> i64 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_avatar_is_kept_as_it_came() {
|
||||
let avatar = api::AvatarData {
|
||||
info: Some(api::AvatarInfo { map: vec![map(api::AvatarState::Online, "https://a/o")] }),
|
||||
timestamp: 1_760_000_000,
|
||||
sign: vec![7; 64],
|
||||
..Default::default()
|
||||
};
|
||||
// A field this version does not know, inside the avatar.
|
||||
let mut raw = schema_api::wire::encode(&avatar);
|
||||
raw.extend_from_slice(&[0x78, 0x01]);
|
||||
let mut message = schema_api::wire::encode(&api::LoginSession {
|
||||
session: "s".into(),
|
||||
username: "u".into(),
|
||||
..Default::default()
|
||||
});
|
||||
message.push(((USER_AVATAR << 3) | 2) as u8);
|
||||
message.push(raw.len() as u8);
|
||||
message.extend_from_slice(&raw);
|
||||
message.extend_from_slice(&schema_api::wire::encode(&api::LoginSession {
|
||||
push_token: "after".into(),
|
||||
..Default::default()
|
||||
}));
|
||||
assert_eq!(raw_field(&message, USER_AVATAR), Some(raw.as_slice()));
|
||||
assert_eq!(raw_field(&message, 13), None);
|
||||
// Cut short: nothing rather than a part.
|
||||
assert_eq!(raw_field(&message[..message.len() - 3], USER_AVATAR), None);
|
||||
assert!(Presentation::default().is_empty());
|
||||
}
|
||||
|
||||
fn map(state: api::AvatarState, name: &str) -> api::avatar_info::AvatarMap {
|
||||
api::avatar_info::AvatarMap { state: state as i32, name: name.into() }
|
||||
}
|
||||
|
||||
@@ -145,6 +145,26 @@ async fn login_roundtrip_keeps_credentials_in_body_and_redacts_results() {
|
||||
assert!(!data.skip_session);
|
||||
}
|
||||
|
||||
/// What servers are shown of the account comes with the login: the
|
||||
/// certificate, and the avatar as it came.
|
||||
#[tokio::test]
|
||||
async fn the_login_brings_the_accounts_presentation() {
|
||||
let avatar = api::AvatarData { timestamp: 42, sign: vec![1; 64], ..Default::default() };
|
||||
let response = api::LoginSession {
|
||||
mytsid_user_cert: Some(api::MyTsUserCertificate { cert: vec![9, 8, 7] }),
|
||||
user_avatar: Some(avatar.clone()),
|
||||
..success()
|
||||
};
|
||||
let (client, _server) = mock(200, "", wire::encode(&response)).await;
|
||||
let login = client.login("mail", "password", None, "device").await.unwrap();
|
||||
assert_eq!(login.presentation.certificate, [9, 8, 7]);
|
||||
assert_eq!(login.presentation.avatar, wire::encode(&avatar));
|
||||
// Without them: nothing to show.
|
||||
let (client, _server) = mock(200, "", wire::encode(&success())).await;
|
||||
let login = client.login("mail", "password", None, "device").await.unwrap();
|
||||
assert!(login.presentation.is_empty() && login.presentation.avatar.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn login_requires_explicit_success_nonempty_token_and_preserves_status() {
|
||||
for code in [0, 202, 208, 98765] {
|
||||
|
||||
@@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use voelin_myts::{Client, Login, Profile, ServerIdentity, SessionToken};
|
||||
use voelin_myts::{Client, Login, Presentation, Profile, ServerIdentity, SessionToken};
|
||||
use voelin_store::Secrets;
|
||||
|
||||
use crate::app::{App, Bridge, MytsForm, later};
|
||||
@@ -50,6 +50,18 @@ struct SavedProfile {
|
||||
|
||||
/// The account's avatar picture, in the account directory.
|
||||
const AVATAR_FILE: &str = "avatar";
|
||||
/// What servers are shown of the account ([`Presentation`]), in the
|
||||
/// account directory: public data, so not in the keyring (whose items are
|
||||
/// small on some systems).
|
||||
const PRESENTATION_FILE: &str = "presentation.json";
|
||||
|
||||
/// [`PRESENTATION_FILE`]: whose it is, and what.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct SavedPresentation {
|
||||
uuid: String,
|
||||
certificate: Vec<u8>,
|
||||
avatar: Vec<u8>,
|
||||
}
|
||||
|
||||
/// A date (Unix seconds) as the profile shows it; empty when not known.
|
||||
fn date(seconds: i64) -> String {
|
||||
@@ -97,6 +109,9 @@ pub(crate) struct Account {
|
||||
/// The avatar, decoded.
|
||||
avatar: slint::Image,
|
||||
saved: Option<Saved>,
|
||||
/// What servers are shown of the account; only from a password
|
||||
/// sign-in (a kept session is not told again).
|
||||
presentation: Option<Presentation>,
|
||||
signed_in: bool,
|
||||
busy: bool,
|
||||
/// The saved session is being checked (not a password sign-in).
|
||||
@@ -121,6 +136,57 @@ impl Account {
|
||||
self.dir.as_ref().map(|dir| dir.join(AVATAR_FILE))
|
||||
}
|
||||
|
||||
fn presentation_path(&self) -> Option<PathBuf> {
|
||||
self.dir.as_ref().map(|dir| dir.join(PRESENTATION_FILE))
|
||||
}
|
||||
|
||||
/// The kept presentation, if it is the saved account's.
|
||||
fn load_presentation(&mut self) {
|
||||
let uuid = self.saved.as_ref().map(|s| s.uuid.as_str()).unwrap_or_default();
|
||||
self.presentation = self
|
||||
.presentation_path()
|
||||
.and_then(|path| std::fs::read(path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<SavedPresentation>(&bytes).ok())
|
||||
.filter(|kept| !uuid.is_empty() && kept.uuid == uuid)
|
||||
.map(|kept| Presentation { certificate: kept.certificate, avatar: kept.avatar });
|
||||
}
|
||||
|
||||
/// A sign-in's presentation, kept for the next start.
|
||||
fn set_presentation(&mut self, uuid: &str, presentation: Presentation) {
|
||||
if let Some(path) = self.presentation_path() {
|
||||
let kept = SavedPresentation {
|
||||
uuid: uuid.to_owned(),
|
||||
certificate: presentation.certificate.clone(),
|
||||
avatar: presentation.avatar.clone(),
|
||||
};
|
||||
let written =
|
||||
serde_json::to_vec(&kept).map_err(std::io::Error::other).and_then(|json| {
|
||||
path.parent().map_or(Ok(()), std::fs::create_dir_all)?;
|
||||
std::fs::write(&path, json)
|
||||
});
|
||||
if let Err(error) = written {
|
||||
tracing::warn!(%error, "could not keep what servers are shown of the account");
|
||||
}
|
||||
}
|
||||
self.presentation = Some(presentation);
|
||||
}
|
||||
|
||||
fn forget_presentation(&mut self) {
|
||||
self.presentation = None;
|
||||
if let Some(path) = self.presentation_path() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// What voice servers are shown of the signed-in account.
|
||||
fn myts_data(&self) -> Option<tsclientlib::MytsData> {
|
||||
self.identity()?;
|
||||
self.presentation.as_ref().filter(|p| !p.is_empty()).map(|p| tsclientlib::MytsData {
|
||||
certificate: p.certificate.clone(),
|
||||
avatar: p.avatar.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The kept picture, shown while the session is checked.
|
||||
fn load_avatar(&mut self) {
|
||||
let bytes = self.avatar_path().and_then(|path| std::fs::read(path).ok());
|
||||
@@ -162,6 +228,7 @@ impl Account {
|
||||
self.saved = saved;
|
||||
if self.saved.is_some() {
|
||||
self.load_avatar();
|
||||
self.load_presentation();
|
||||
}
|
||||
self.can_forget = false;
|
||||
self.status = 0;
|
||||
@@ -202,6 +269,11 @@ impl Account {
|
||||
if same_account { self.saved.take().unwrap().profile } else { SavedProfile::default() };
|
||||
if !same_account {
|
||||
self.forget_avatar();
|
||||
self.forget_presentation();
|
||||
}
|
||||
// A sign-in without it keeps the same account's known one.
|
||||
if !login.presentation.is_empty() {
|
||||
self.set_presentation(&login.uuid, login.presentation);
|
||||
}
|
||||
profile.update(&login.profile);
|
||||
let saved = Saved {
|
||||
@@ -327,6 +399,7 @@ impl Account {
|
||||
self.persistence_status = if cleared { 0 } else { 8 };
|
||||
self.can_forget = !cleared;
|
||||
self.forget_avatar();
|
||||
self.forget_presentation();
|
||||
cleared
|
||||
}
|
||||
}
|
||||
@@ -381,6 +454,13 @@ impl App {
|
||||
self.engine.send(voelin_core::Command::SetMytsIdentity(
|
||||
self.myts.identity().cloned().map(Arc::new),
|
||||
));
|
||||
// What servers are shown of it (its avatar), after the proof.
|
||||
let data = self.myts.myts_data();
|
||||
if data.is_none() && self.myts.identity().is_some() {
|
||||
// Signed in before Voelin kept it: only a password sign-in tells it.
|
||||
tracing::info!("servers see no avatar of the account until the next password sign-in");
|
||||
}
|
||||
self.engine.send(voelin_core::Command::SetMytsData(data.map(Arc::new)));
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_myts(&self) {
|
||||
@@ -642,9 +722,37 @@ mod tests {
|
||||
otp_token: format!("{name}-otp"),
|
||||
device_id: format!("{name}-device"),
|
||||
}),
|
||||
presentation: Presentation {
|
||||
certificate: format!("{name}-cert").into_bytes(),
|
||||
avatar: format!("{name}-avatar").into_bytes(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// What servers are shown of the account is kept for it, told once its
|
||||
/// session is valid again, and never shown for another account.
|
||||
#[test]
|
||||
fn what_servers_are_shown_is_kept_per_account() {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-presentation-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let secrets = MemorySecrets::default();
|
||||
let mut account = Account::new(dir.clone());
|
||||
account.accept(&secrets, login("Alice"), "alice@example.test".into());
|
||||
assert_eq!(account.myts_data().unwrap().certificate, b"Alice-cert");
|
||||
let mut restarted = Account::new(dir.clone());
|
||||
restarted.load(&secrets);
|
||||
assert!(restarted.myts_data().is_none(), "not before the session is checked");
|
||||
restarted.restored();
|
||||
assert_eq!(restarted.myts_data().unwrap().avatar, b"Alice-avatar");
|
||||
restarted.forget(&secrets);
|
||||
assert!(!dir.join(PRESENTATION_FILE).exists());
|
||||
let mut bob = login("Bob");
|
||||
bob.presentation = Presentation::default();
|
||||
restarted.accept(&secrets, bob, "bob@example.test".into());
|
||||
assert!(restarted.myts_data().is_none());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
fn server_identity() -> ServerIdentity {
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
|
||||
@@ -108,6 +108,43 @@ file names and description are used until then. What is kept goes into the
|
||||
same secret-store bundle as the session (`profile`), never the token into a
|
||||
URL.
|
||||
|
||||
### Presenting the account's avatar, and other clients' avatars (TeamSpeak 6)
|
||||
|
||||
Voice servers show the account's avatar (and the blurred banner behind it
|
||||
in the client-info view) from what the client sends once connected, not
|
||||
from `clientinit` (the official 6.0.0-beta4.1 client never sets
|
||||
`client_myteamspeak_avatar` or `client_signed_badges` itself):
|
||||
|
||||
updatemytsdata myts_certificate=<cert> [myts_signed_badge=<list>] [myts_avatar=<AvatarData>]
|
||||
|
||||
built at 0x1f38520: `myts_certificate` is `LoginSession.mytsid_user_cert.cert`,
|
||||
`myts_avatar` the serialized `LoginSession.user_avatar` (`AvatarData` with its
|
||||
timestamp and myTeamSpeak's signature, which covers `AvatarInfo`, the myTS
|
||||
id and the timestamp), `myts_signed_badge` a `UserBadgesSignedList` from
|
||||
`getSignedBadges`. The values are the raw bytes with TeamSpeak's escaping
|
||||
only (`\a` and `\b` included), no base64. It is sent once the connection is
|
||||
established, after a sign-in (after `updatemytsid`), after an avatar upload
|
||||
and after a badge change. Voelin sends the certificate and the avatar: both
|
||||
come only from a password sign-in (`LoginSession`, fields 10 and 11), the
|
||||
avatar sliced out of the response as it came (encoding it again would drop
|
||||
fields this version does not know and break the signature). They are kept
|
||||
in `<data>/account/presentation.json` (public data) and sent to every
|
||||
connection that presents the account; a refusal is only logged.
|
||||
|
||||
Other clients' avatars arrive as `client_myteamspeak_avatar`, plain text
|
||||
`<state>,<url>;<state>,<url>…` with myTeamSpeak's `AvatarState` numbers
|
||||
(`request_avatar_with_ts_server_client_property`, 0x1ae2840): an entry
|
||||
that is not `<number>,<url>` (an empty one from a trailing `;` too) spoils
|
||||
the whole value; the online picture is shown, else away, do not disturb,
|
||||
offline; the server's own avatar (`client_flag_avatar`) wins when it loads.
|
||||
Voelin downloads it (HTTPS, 4 MiB) where the server's is not shown: none
|
||||
set, no voice connection (observing), or its download gave up.
|
||||
|
||||
`client_user_tag` (the "User Tag", a TeamSpeak chat alias) is set by the
|
||||
client as JSON `{"myts_token":…,"tag":…,"updated":<ms>}` with a token from
|
||||
`requestSignedAllowedIdentifierList` at `/tschat`; receivers show it only
|
||||
after verifying the token. Voelin does not set it yet.
|
||||
|
||||
`requestAvatarSignedUrl` is not a download call: it signs *upload* links.
|
||||
In the TS6 6.0.0-beta4.1 Linux client, `Account_Manager_Impl::
|
||||
request_avatar_signed_urls`'s reply goes only to `upload_avatar`, whose
|
||||
|
||||
Reference in new issue
Block a user