Files
VoelinClient/crates/voelin-ui/src/myts.rs
T
Claude 16aa65383c myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed
Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
  from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
  ID), the signed badges from getSignedBadges and the User Tag's token from
  /tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
  (block types 4-7, leaf type 6, validity, key from the root, cofactorless
  Ed25519); each part is sent with a certificate that verifies it, in
  separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
  ({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
  self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
  three badges to show. The log says what the server published.

Banners:
- The URL (without query) is logged on the first failure; stalls, connect
  failures and missing answers are named; 400/404/410 are retried after
  15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
  downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
  are used, SOCKS included; redirects are followed hop by hop.

Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
  30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
  restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
  losses and the first presence.

tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
  terminal) and lifecycle logs: startup summary, the address the server
  sees for queries, WebSocket connections, logins, refusals, slow requests,
  ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
  connects time out after 10 s; a silent server cannot wedge a connection;
  SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
  counted, every connection holds on a 524).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-06 18:28:09 +00:00

1742 lines
59 KiB
Rust

//! Desktop account state. Only the UI thread mutates state or persists credentials.
use serde::{Deserialize, Serialize};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use voelin_myts::{
Client, Login, OwnAvatar, Presentation, Profile, ServerIdentity, SessionToken, SignedBadge,
};
use voelin_store::Secrets;
use crate::app::{App, Bridge, MytsBadge, 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>,
/// What the account service tells about the account, shown at once on
/// the next start.
#[serde(default)]
profile: SavedProfile,
}
/// The profile of [`voelin_myts::Profile`] worth keeping between runs.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
struct SavedProfile {
description: String,
/// Unix seconds; 0: not known.
registered: i64,
last_login: i64,
badges: Vec<String>,
/// "Name · region · date" per signed-in device.
devices: Vec<String>,
/// The avatar file shown, as the service names it; the picture is
/// [`AVATAR_FILE`] in the account directory.
avatar: String,
}
/// The account's avatar picture, in the account directory.
const AVATAR_FILE: &str = "avatar";
/// What servers are shown of the account ([`SavedPresentation`]), in the
/// account directory: public data, so not in the keyring (whose items are
/// small on some systems).
const PRESENTATION_FILE: &str = "presentation.json";
/// The badges chosen to show on servers, per account (`{account: [badge
/// id]}`), in the account directory: kept across sign-outs.
const BADGES_FILE: &str = "badges.json";
/// Servers are shown at most this many badges, as the official client
/// shows them.
const MAX_SHOWN_BADGES: usize = 3;
/// A User Tag's token is asked for again when it holds for less than this.
const USER_TAG_MARGIN: i64 = 3 * 86_400;
/// While signed in, what servers are shown is asked for again this often
/// (certificates and tokens expire; the avatar may change elsewhere).
const PRESENTATION_REFRESH: Duration = Duration::from_secs(86_400);
/// [`PRESENTATION_FILE`]: whose it is, and what myTeamSpeak handed out for
/// it, as it came (public data: certificates, signatures, links, ids).
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
struct SavedPresentation {
uuid: String,
/// What the last password sign-in brought ([`Presentation`]).
certificate: Vec<u8>,
avatar: Vec<u8>,
/// What myTeamSpeak's avatar service hands out for the account's myTS
/// ID ([`OwnAvatar`]): no password needed.
#[serde(default)]
service_certificate: Vec<u8>,
#[serde(default)]
service_avatar: Vec<u8>,
/// The account's badges as signed for its myTS ID (`SignedUserBadge`s).
#[serde(default)]
badges: Vec<Vec<u8>>,
/// The primary User Tag, and the token that proves it.
#[serde(default)]
user_tag: String,
#[serde(default)]
user_tag_token: Vec<u8>,
}
/// What asking myTeamSpeak again learned; `None`: nothing (an empty or
/// failed answer), and what was known stays.
#[derive(Default)]
struct Fetched {
avatar: Option<OwnAvatar>,
badges: Option<Vec<SignedBadge>>,
user_tag: Option<String>,
/// Checked for the tag before it is taken.
user_tag_token: Option<Vec<u8>>,
}
impl SavedPresentation {
fn merge(&mut self, fetched: Fetched) {
if let Some(own) = fetched.avatar {
self.service_certificate = own.certificate;
self.service_avatar = own.avatar;
}
if let Some(badges) = fetched.badges {
self.badges = badges.iter().map(|b| b.raw().to_vec()).collect();
}
if let Some(tag) = fetched.user_tag {
self.user_tag = tag;
}
if let Some(token) = fetched.user_tag_token {
self.user_tag_token = token;
}
}
fn signed_badges(&self) -> Vec<SignedBadge> {
self.badges.iter().filter_map(|raw| SignedBadge::parse(raw)).collect()
}
}
/// Now, Unix seconds.
fn unix_now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// A date (Unix seconds) as the profile shows it; empty when not known.
fn date(seconds: i64) -> String {
chrono::DateTime::from_timestamp(seconds, 0)
.filter(|_| seconds > 0)
.map(|d| d.with_timezone(&chrono::Local).format("%Y-%m-%d").to_string())
.unwrap_or_default()
}
impl SavedProfile {
/// Take what the service told; empty fields keep what was known.
fn update(&mut self, profile: &Profile) {
if !profile.description.is_empty() {
self.description = profile.description.clone();
}
if profile.registered > 0 {
self.registered = profile.registered;
}
if profile.last_login > 0 {
self.last_login = profile.last_login;
}
if !profile.badges.is_empty() {
self.badges = profile.badges.iter().map(|b| b.name.clone()).collect();
}
if !profile.devices.is_empty() {
self.devices = profile
.devices
.iter()
.map(|d| {
[d.name.as_str(), d.region.as_str(), &date(d.last_login)]
.into_iter()
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" · ")
})
.collect();
}
}
}
#[derive(Default)]
pub(crate) struct Account {
/// Where the avatar picture is kept (`<data>/account`); none in tests.
dir: Option<PathBuf>,
/// The avatar, decoded.
avatar: slint::Image,
saved: Option<Saved>,
/// What servers can be shown of the account: from a password sign-in,
/// and from myTeamSpeak with the session alone.
presentation: Option<SavedPresentation>,
/// The ids of the badges chosen to show on servers, in order.
shown_badges: Vec<String>,
signed_in: bool,
busy: bool,
/// The saved session is being checked (not a password sign-in).
checking: 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 {
pub(crate) fn new(dir: PathBuf) -> Self {
Self { dir: Some(dir), ..Default::default() }
}
fn avatar_path(&self) -> Option<PathBuf> {
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))
}
fn badges_path(&self) -> Option<PathBuf> {
self.dir.as_ref().map(|dir| dir.join(BADGES_FILE))
}
/// The kept presentation and badge choice, if they are the saved
/// account's.
fn load_presentation(&mut self) {
let uuid = self.saved.as_ref().map(|s| s.uuid.clone()).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);
self.load_badge_choice(&uuid);
}
fn save_presentation(&self) {
let (Some(path), Some(kept)) = (self.presentation_path(), self.presentation.as_ref())
else {
return;
};
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");
}
}
/// The kept presentation if it is `uuid`'s, else a new one.
fn presentation_for(&mut self, uuid: &str) -> &mut SavedPresentation {
if self.presentation.as_ref().is_none_or(|kept| kept.uuid != uuid) {
self.presentation =
Some(SavedPresentation { uuid: uuid.to_owned(), ..Default::default() });
}
self.presentation.as_mut().expect("just set")
}
/// A sign-in's presentation, kept for the next start.
fn set_presentation(&mut self, uuid: &str, presentation: Presentation) {
let kept = self.presentation_for(uuid);
kept.certificate = presentation.certificate;
kept.avatar = presentation.avatar;
self.save_presentation();
}
/// What asking myTeamSpeak again learned for the account `uuid`; what
/// it did not learn stays as known.
fn take_fetched(&mut self, uuid: &str, fetched: Fetched) {
self.presentation_for(uuid).merge(fetched);
self.save_presentation();
}
fn forget_presentation(&mut self) {
self.presentation = None;
self.shown_badges.clear();
if let Some(path) = self.presentation_path() {
let _ = std::fs::remove_file(path);
}
}
fn badge_choices(&self) -> HashMap<String, Vec<String>> {
self.badges_path()
.and_then(|path| std::fs::read(path).ok())
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
fn load_badge_choice(&mut self, uuid: &str) {
self.shown_badges = self.badge_choices().remove(uuid).unwrap_or_default();
}
/// Show the badge at `index` (of the signed badges) on servers, or not:
/// at most [`MAX_SHOWN_BADGES`], in the order chosen, kept per account.
/// The choice kept is then what the list shows: a chosen badge
/// myTeamSpeak no longer lists is dropped from it.
fn choose_badge(&mut self, index: usize, on: bool) -> bool {
let Some(account) = self.saved.as_ref().map(|s| s.uuid.clone()) else { return false };
let badges = self.presentation.as_ref().map(SavedPresentation::signed_badges);
let Some(badge) = badges.unwrap_or_default().into_iter().nth(index) else {
return false;
};
let mut chosen: Vec<String> = self.chosen_badges().into_iter().map(|b| b.uuid).collect();
let shown = chosen.contains(&badge.uuid);
if on == shown || (on && chosen.len() >= MAX_SHOWN_BADGES) {
return false;
}
if on {
chosen.push(badge.uuid);
} else {
chosen.retain(|uuid| *uuid != badge.uuid);
}
self.shown_badges = chosen;
if let Some(path) = self.badges_path() {
let mut choices = self.badge_choices();
choices.insert(account, self.shown_badges.clone());
let written =
serde_json::to_vec(&choices).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 which badges servers are shown");
}
}
true
}
/// The chosen badges myTeamSpeak lists, in the order chosen, as it
/// signed them: one it no longer lists takes no place (and no place of
/// the [`MAX_SHOWN_BADGES`]).
fn chosen_badges(&self) -> Vec<SignedBadge> {
let signed = self.presentation.as_ref().map(SavedPresentation::signed_badges);
let signed = signed.unwrap_or_default();
self.shown_badges
.iter()
.filter_map(|uuid| signed.iter().find(|b| b.uuid == *uuid).cloned())
.take(MAX_SHOWN_BADGES)
.collect()
}
/// What voice servers are shown of the signed-in account at `now`
/// (Unix seconds), checked as a TeamSpeak 6 server and its viewers check
/// it: the newest avatar a certificate at hand verifies, the chosen
/// badges if one certificate verifies them all, the User Tag if its
/// token holds. Each with the certificate that verifies it, since the
/// server shows nothing of what it cannot verify.
fn myts_data(&self, now: i64) -> Option<tsclientlib::MytsData> {
self.myts_data_from(&voelin_myts::ROOT_KEY, now)
}
/// [`Self::myts_data`] with certificates from `root` (tests).
fn myts_data_from(&self, root: &[u8; 32], now: i64) -> Option<tsclientlib::MytsData> {
let identity = self.identity()?;
let kept = self.presentation.as_ref()?;
let id = identity.id_bytes();
// The certificates at hand, and where they came from (for the log).
let sources = ["the sign-in's", "the avatar service's", "the myTS ID's"];
let certificates = [
kept.certificate.as_slice(),
kept.service_certificate.as_slice(),
identity.public_signature_certificate(),
];
let avatars = [kept.avatar.as_slice(), kept.service_avatar.as_slice()];
let mut data = tsclientlib::MytsData { myts_id: id.to_vec(), ..Default::default() };
match voelin_myts::choose_avatar_from(root, &avatars, &certificates, id, now) {
// The newest avatar has no pictures: the account has none now.
Some((avatar, _)) if !voelin_myts::avatar_has_pictures(avatars[avatar]) => {
tracing::info!("servers are shown no avatar: the account has none")
}
Some((avatar, certificate)) => {
tracing::info!(
avatar = ["from the sign-in", "from the avatar service"][avatar],
certificate = sources[certificate],
"servers are shown the account's avatar"
);
data.avatar = tsclientlib::Signed {
certificate: certificates[certificate].to_vec(),
data: avatars[avatar].to_vec(),
};
}
None if avatars.iter().all(|a| a.is_empty()) => {
tracing::info!("servers are shown no avatar: myTeamSpeak has not handed one out")
}
None => tracing::info!(
"servers are shown no avatar: no certificate at hand verifies it (expired, or \
another key)"
),
}
let badges = self.chosen_badges();
let badges: Vec<&SignedBadge> = badges.iter().collect();
if !badges.is_empty() {
match voelin_myts::choose_badges_certificate_from(root, &badges, &certificates, id, now)
{
Some(certificate) => {
data.badge_ids = badges.iter().map(|b| b.uuid.clone()).collect();
tracing::info!(
badges = ?data.badge_ids,
certificate = sources[certificate],
"servers are shown the chosen badges"
);
data.badges = tsclientlib::Signed {
certificate: certificates[certificate].to_vec(),
data: voelin_myts::badge_list(badges),
};
}
None => tracing::info!(
"servers are shown no badges: no certificate at hand verifies all the chosen \
ones"
),
}
}
if !kept.user_tag.is_empty() {
if kept.user_tag_token.is_empty() {
tracing::info!("servers are shown no User Tag: myTeamSpeak has not sent its token");
} else {
let token = &kept.user_tag_token;
match voelin_myts::check_user_tag_from(root, token, &kept.user_tag, id, now) {
Ok(_) => {
tracing::info!(tag = %kept.user_tag, "servers are shown the account's User Tag");
data.user_tag = Some(tsclientlib::UserTag {
tag: kept.user_tag.clone(),
token: kept.user_tag_token.clone(),
});
}
Err(error) => tracing::info!(%error, "servers are shown no User Tag"),
}
}
}
Some(data)
}
/// 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());
self.avatar = bytes.map(|b| crate::images::picture("myts-avatar", &b)).unwrap_or_default();
}
/// A new picture from the service: kept on disk and shown.
fn set_avatar(&mut self, name: String, bytes: &[u8]) {
crate::images::forget_picture("myts-avatar");
self.avatar = crate::images::picture("myts-avatar", bytes);
if self.avatar.size().width == 0 {
return;
}
if let Some(path) = self.avatar_path() {
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, bytes));
if let Err(error) = written {
tracing::warn!(%error, "could not keep the account's avatar");
}
}
if let Some(saved) = self.saved.as_mut() {
saved.profile.avatar = name;
}
}
fn forget_avatar(&mut self) {
self.avatar = slint::Image::default();
crate::images::forget_picture("myts-avatar");
if let Some(path) = self.avatar_path() {
let _ = std::fs::remove_file(path);
}
}
fn load(&mut self, secrets: &dyn Secrets) {
match read_saved(secrets) {
Ok(saved) => {
self.saved = saved;
if self.saved.is_some() {
self.load_avatar();
}
self.load_presentation();
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();
// Another account's picture is not this one's.
let same_account =
self.saved.as_ref().is_some_and(|s| !s.uuid.is_empty() && s.uuid == login.uuid);
let mut profile =
if same_account { self.saved.take().unwrap().profile } else { SavedProfile::default() };
if !same_account {
self.forget_avatar();
self.forget_presentation();
self.load_badge_choice(&login.uuid);
}
// 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 {
profile,
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;
}
}
/// Store what the account service told (`Client::profile`).
fn take_profile(&mut self, secrets: &dyn Secrets, profile: &Profile) {
let Some(saved) = self.saved.as_mut() else { return };
if !profile.username.is_empty() {
saved.username = profile.username.clone();
}
saved.profile.update(profile);
if self.persistence_status == 0 && !save(secrets, saved) {
self.persistence_status = 5;
}
}
fn form(&self) -> MytsForm {
let identity = self.identity();
let profile = self.saved.as_ref().map(|s| s.profile.clone()).unwrap_or_default();
let name = self
.saved
.as_ref()
.map(|s| if s.username.is_empty() { s.email.as_str() } else { s.username.as_str() })
.unwrap_or_default();
let strings = |items: Vec<String>| -> ModelRc<SharedString> {
ModelRc::new(VecModel::from(
items.into_iter().map(SharedString::from).collect::<Vec<_>>(),
))
};
let signed = self.presentation.as_ref().map(SavedPresentation::signed_badges);
let chosen: Vec<String> = self.chosen_badges().into_iter().map(|b| b.uuid).collect();
let full = chosen.len() >= MAX_SHOWN_BADGES;
let badge_choice = signed
.unwrap_or_default()
.into_iter()
.map(|badge| {
let place = chosen.iter().position(|uuid| *uuid == badge.uuid);
MytsBadge {
name: badge.name.into(),
shown: place.map_or(0, |place| place as i32 + 1),
can_change: place.is_some() || !full,
}
})
.collect::<Vec<_>>();
MytsForm {
available: true,
prompt: self.prompt,
signed_in: self.signed_in,
// A saved session being checked: its profile shows, not the form.
restoring: !self.signed_in && self.busy && self.checking && self.saved.is_some(),
avatar: self.avatar.clone(),
initials: crate::vm::avatar::initials(name).into(),
description: profile.description.into(),
member_since: date(profile.registered).into(),
last_login: date(profile.last_login).into(),
badges: strings(profile.badges),
badge_choice: ModelRc::new(VecModel::from(badge_choice)),
user_tag: self
.presentation
.as_ref()
.map(|p| p.user_tag.as_str())
.unwrap_or_default()
.into(),
devices: strings(profile.devices),
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.checking = false;
self.status = 0;
Some(self.generation)
}
fn finish(&mut self, generation: u64) -> bool {
if self.generation != generation {
return false;
}
self.busy = false;
self.checking = false;
true
}
fn forget(&mut self, secrets: &dyn Secrets) -> bool {
self.generation += 1;
self.busy = false;
self.checking = 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;
self.forget_avatar();
self.forget_presentation();
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),
));
// What servers are shown of it, after the proof.
self.publish_myts_data();
}
/// What servers are shown of the account (avatar, badges, User Tag):
/// only what changed goes to them.
fn publish_myts_data(&self) {
let data = self.myts.myts_data(unix_now());
if data.is_none() && self.myts.identity().is_some() {
tracing::info!(
"servers are shown nothing of the account but its myTS ID until myTeamSpeak \
answers"
);
}
self.engine.send(voelin_core::Command::SetMytsData(data.map(Arc::new)));
}
/// Ask myTeamSpeak, with the session alone, for what servers are shown
/// of the account: its avatar and a certificate (the avatar service's
/// answer for its own myTS ID), its signed badges, its User Tag and the
/// token that proves it. After a password sign-in, a checked saved
/// session, and then daily. An empty or failed answer changes nothing.
fn refresh_myts_presentation(&self) {
let Some(saved) = self.myts.saved.as_ref().filter(|_| self.myts.signed_in) else {
return;
};
let (Some(identity), Ok(token)) =
(self.myts.identity(), SessionToken::new(saved.session.clone()))
else {
return;
};
if saved.uuid.is_empty() {
return;
}
let uuid = saved.uuid.clone();
let id = identity.id_bytes().to_vec();
let kept_token = self
.myts
.presentation
.as_ref()
.filter(|kept| kept.uuid == uuid)
.map(|kept| kept.user_tag_token.clone())
.unwrap_or_default();
let generation = self.myts.generation;
self.runtime.spawn(async move {
let client = match Client::new() {
Ok(client) => client,
Err(error) => return tracing::debug!(%error, "no account client"),
};
let (avatar, badges, tag) = tokio::join!(
client.own_avatar(&token, &id),
client.signed_badges(&token),
client.user_tag(&token)
);
let mut fetched = Fetched::default();
match avatar {
Ok(Some(own)) => {
tracing::info!(
"myTeamSpeak's avatar service sent the account's avatar and certificate"
);
fetched.avatar = Some(own);
}
Ok(None) => tracing::info!(
"myTeamSpeak's avatar service sent nothing for the account; what was known \
is kept"
),
Err(error) => {
tracing::info!(%error, "the account's avatar for servers was not fetched")
}
}
match badges {
Ok(Some(badges)) => {
tracing::info!(
count = badges.len(),
"myTeamSpeak sent the account's signed badges"
);
fetched.badges = Some(badges);
}
Ok(None) => {
tracing::info!("myTeamSpeak sent no badge list; what was known is kept")
}
Err(error) => {
tracing::info!(%error, "the account's signed badges were not fetched")
}
}
match tag {
Ok(Some(tag)) => {
tracing::info!(%tag, "the account's primary User Tag");
// The token proves all the account's tags; asked for again
// when it would not prove this one in a few days.
let at = unix_now() + USER_TAG_MARGIN;
if voelin_myts::check_user_tag(&kept_token, &tag, &id, at).is_err() {
match client.user_tag_token(&token).await {
Ok(token) => {
match voelin_myts::check_user_tag(&token, &tag, &id, unix_now()) {
Ok(until) => {
tracing::info!(
valid_until = until,
"myTeamSpeak sent the token for the User Tag"
);
fetched.user_tag_token = Some(token);
}
Err(error) => tracing::info!(
%error,
"myTeamSpeak sent a token for the User Tag that viewers would not accept"
),
}
}
Err(error) => {
tracing::info!(%error, "the User Tag's token was not fetched")
}
}
}
fetched.user_tag = Some(tag);
}
Ok(None) => tracing::info!("myTeamSpeak names no User Tag for the account"),
Err(error) => tracing::info!(%error, "the account's User Tag was not fetched"),
}
later(move |app| {
if app.myts.generation != generation || !app.myts.signed_in {
return;
}
if app.myts.saved.as_ref().is_some_and(|s| s.uuid == uuid) {
app.myts.take_fetched(&uuid, fetched);
app.publish_myts_data();
app.refresh_myts();
}
});
tokio::time::sleep(PRESENTATION_REFRESH).await;
later(move |app| {
if app.myts.generation == generation {
app.refresh_myts_presentation();
}
});
});
}
/// Show a badge on servers, or not (Settings → My Account).
pub(crate) fn myts_badge(&mut self, index: i32, on: bool) {
let changed = usize::try_from(index).is_ok_and(|index| self.myts.choose_badge(index, on));
if changed {
self.publish_myts_data();
}
self.refresh_myts();
}
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.load(self.secrets.as_ref());
// Signed in before: no login page. The saved session is checked in
// the background, and only one that has expired asks again. Without
// one, the page shows unless "Continue without an account" was
// chosen before.
self.myts.prompt = self.myts.saved.is_none() && !self.settings.skip_account_prompt;
self.myts_retry();
}
pub(crate) fn myts_dismiss(&mut self) {
self.myts.prompt = false;
if !self.demo_ui && !self.settings.skip_account_prompt {
self.settings.skip_account_prompt = true;
self.store_settings();
}
self.refresh_myts();
}
/// Ask the account service for the profile and avatar of the signed-in
/// account; what comes back is stored and shown.
fn refresh_myts_profile(&self) {
let Some(token) =
self.myts.saved.as_ref().and_then(|s| SessionToken::new(s.session.clone()).ok())
else {
return;
};
let shown = self.myts.saved.as_ref().map(|s| s.profile.avatar.clone()).unwrap_or_default();
let has_picture = self.myts.avatar.size().width > 0;
let generation = self.myts.generation;
self.runtime.spawn(async move {
let client = match Client::new() {
Ok(client) => client,
Err(error) => return tracing::debug!(%error, "no account client"),
};
let profile = match client.profile(&token).await {
Ok(profile) => profile,
Err(error) => return tracing::info!(%error, "account profile not refreshed"),
};
let avatar = profile.avatars.first().cloned();
later(move |app| {
if app.myts.generation == generation && app.myts.signed_in {
app.myts.take_profile(app.secrets.as_ref(), &profile);
app.refresh_myts();
}
});
// The picture only when it changed (or was never fetched).
let Some(name) = avatar.filter(|name| *name != shown || !has_picture) else { return };
match client.avatar(&name).await {
Ok(bytes) => later(move |app| {
if app.myts.generation == generation && app.myts.signed_in {
app.myts.set_avatar(name, &bytes);
if let Some(saved) = app.myts.saved.as_ref() {
let _ = save(app.secrets.as_ref(), saved);
}
app.refresh_myts();
}
}),
Err(error) => tracing::info!(%error, "account avatar not fetched"),
}
});
}
pub(crate) fn myts_portal(&mut self, action: i32) {
let Some(url) = portal_url(action).filter(|_| !self.myts.busy) else {
return;
};
let opened = crate::app::open_target(std::ffi::OsStr::new(url)).is_ok();
self.myts.status = if opened { 11 } else { 10 };
self.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.myts.checking = true;
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();
app.refresh_myts_profile();
app.refresh_myts_presentation();
}
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;
// Expired: ask to sign in again.
app.myts.prompt = true;
}
}
}
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) {
// The sample screens of VOELIN_DEMO_UI sign in nowhere.
if self.demo_ui || 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();
if app.settings.skip_account_prompt {
app.settings.skip_account_prompt = false;
app.store_settings();
}
app.refresh_myts_profile();
app.refresh_myts_presentation();
}
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) {
// Nor do they sign out: no session, keyring or engine account to clear.
if self.demo_ui {
return;
}
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 slint::Model;
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()),
profile: Profile {
description: format!("{name}'s profile"),
avatars: vec![format!("{name}.png")],
..Default::default()
},
renewal: Some(voelin_myts::Renewal {
token: format!("{name}-renewal"),
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.presentation.as_ref().unwrap().certificate, b"Alice-cert");
let data = account.myts_data(NOW).unwrap();
assert_eq!(data.myts_id, [1; 33]);
// Nothing a server would verify: nothing shown.
assert!(data.avatar.is_empty() && data.badges.is_empty() && data.user_tag.is_none());
let mut restarted = Account::new(dir.clone());
restarted.load(&secrets);
assert!(restarted.myts_data(NOW).is_none(), "not before the session is checked");
assert!(restarted.presentation == account.presentation);
restarted.restored();
assert!(restarted.myts_data(NOW).is_some());
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.presentation.is_none());
// What myTeamSpeak hands out with the session alone is Bob's.
restarted.take_fetched("Bob-uuid", fetched_tag("bob@myteamspeak.com"));
let mut again = Account::new(dir.clone());
again.load(&secrets);
assert_eq!(again.presentation.as_ref().unwrap().uuid, "Bob-uuid");
assert_eq!(again.form().user_tag, "bob@myteamspeak.com");
let _ = std::fs::remove_dir_all(dir);
}
use voelin_myts::testing::NOW;
fn fetched_tag(tag: &str) -> Fetched {
Fetched { user_tag: Some(tag.into()), ..Default::default() }
}
/// A `SignedUserBadge` as myTeamSpeak sends it (protobuf by hand).
fn signed_badge(uuid: &str, name: &str) -> Vec<u8> {
let mut badge = vec![0x0a, uuid.len() as u8];
badge.extend_from_slice(uuid.as_bytes());
badge.extend_from_slice(&[0x1a, name.len() as u8]);
badge.extend_from_slice(name.as_bytes());
let mut signed = vec![0x0a, badge.len() as u8];
signed.extend_from_slice(&badge);
signed.extend_from_slice(&[0x12, 64]);
signed.extend_from_slice(&[7; 64]);
signed
}
/// An empty or failed answer changes nothing; an answer replaces only
/// what it is about.
#[test]
fn what_myteamspeak_did_not_tell_stays() {
let mut kept = SavedPresentation {
uuid: "a".into(),
certificate: b"login".to_vec(),
avatar: b"login avatar".to_vec(),
service_certificate: b"service".to_vec(),
service_avatar: b"service avatar".to_vec(),
badges: vec![signed_badge("b1", "One")],
user_tag: "alex@myteamspeak.com".into(),
user_tag_token: b"token".to_vec(),
};
let before = kept.clone();
kept.merge(Fetched::default());
assert!(kept == before);
kept.merge(Fetched {
avatar: Some(OwnAvatar { certificate: b"new".to_vec(), avatar: b"newer".to_vec() }),
..Default::default()
});
assert_eq!(
(kept.service_certificate.as_slice(), kept.service_avatar.as_slice()),
(&b"new"[..], &b"newer"[..])
);
assert_eq!(kept.certificate, b"login", "the sign-in's stays");
assert_eq!(kept.badges, before.badges);
// A list is the list, even an empty one.
kept.merge(Fetched { badges: Some(Vec::new()), ..Default::default() });
assert!(kept.badges.is_empty());
kept.merge(fetched_tag("alex@tschat-1.teamspeak.com"));
assert_eq!(kept.user_tag, "alex@tschat-1.teamspeak.com");
assert_eq!(kept.user_tag_token, b"token", "the token proves all the tags");
kept.merge(Fetched { user_tag_token: Some(b"fresh".to_vec()), ..Default::default() });
assert_eq!(kept.user_tag_token, b"fresh");
}
/// Up to three badges, in the order chosen, kept per account (across
/// sign-outs); none chosen at first.
#[test]
fn badges_shown_on_servers_are_chosen_per_account() {
let dir = std::env::temp_dir().join(format!("voelin-badges-{}", 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());
let badges = ["One", "Two", "Three", "Four"]
.iter()
.enumerate()
.map(|(i, name)| SignedBadge::parse(&signed_badge(&format!("b{i}"), name)).unwrap())
.collect();
account.take_fetched("Alice-uuid", Fetched { badges: Some(badges), ..Default::default() });
assert!(account.shown_badges.is_empty(), "none chosen at first");
assert!(account.chosen_badges().is_empty());
for index in [2, 0, 3] {
assert!(account.choose_badge(index, true));
}
assert!(!account.choose_badge(1, true), "three at most");
assert!(!account.choose_badge(0, true), "already shown");
assert!(!account.choose_badge(9, true));
let names = |account: &Account| {
account.chosen_badges().into_iter().map(|b| b.name).collect::<Vec<_>>()
};
assert_eq!(names(&account), ["Three", "One", "Four"]);
let form = account.form();
let choice: Vec<_> = form.badge_choice.iter().map(|b| (b.shown, b.can_change)).collect();
assert_eq!(choice, [(2, true), (0, false), (1, true), (3, true)]);
assert!(account.choose_badge(0, false));
assert!(account.choose_badge(1, true));
assert_eq!(names(&account), ["Three", "Four", "Two"]);
// Kept for the account, also after signing out and in again.
account.forget(&secrets);
assert!(account.shown_badges.is_empty());
account.accept(&secrets, login("Bob"), "bob@example.test".into());
assert!(account.shown_badges.is_empty(), "Bob chose none");
account.forget(&secrets);
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert_eq!(account.shown_badges, ["b2", "b3", "b1"]);
let _ = std::fs::remove_dir_all(dir);
}
/// A chosen badge myTeamSpeak no longer lists takes no place: the others
/// move up, another can be chosen, and the choice kept is then what the
/// list shows.
#[test]
fn a_badge_no_longer_listed_takes_no_place() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
let listed = |names: &[&str]| Fetched {
badges: Some(
names.iter().map(|n| SignedBadge::parse(&signed_badge(n, n)).unwrap()).collect(),
),
..Default::default()
};
account.take_fetched("Alice-uuid", listed(&["b0", "b1", "b2", "b3"]));
for index in [0, 1, 2] {
assert!(account.choose_badge(index, true));
}
// b1 is gone.
account.take_fetched("Alice-uuid", listed(&["b0", "b2", "b3"]));
let names = |account: &Account| {
account.chosen_badges().into_iter().map(|b| b.name).collect::<Vec<_>>()
};
assert_eq!(names(&account), ["b0", "b2"]);
let choice = |account: &Account| {
account.form().badge_choice.iter().map(|b| (b.shown, b.can_change)).collect::<Vec<_>>()
};
assert_eq!(choice(&account), [(1, true), (2, true), (0, true)]);
assert!(account.choose_badge(2, true), "a place is free");
assert_eq!(account.shown_badges, ["b0", "b2", "b3"]);
assert_eq!(choice(&account), [(1, true), (2, true), (3, true)]);
// Back again, b1 is not chosen: the choice is what the list showed.
account.take_fetched("Alice-uuid", listed(&["b0", "b1", "b2", "b3"]));
assert_eq!(names(&account), ["b0", "b2", "b3"]);
// A choice kept from before (badges.json) with more than three listed:
// three are shown.
account.shown_badges = ["b3", "b1", "b0", "b2"].map(String::from).to_vec();
assert_eq!(names(&account), ["b3", "b1", "b0"]);
assert_eq!(choice(&account)[2], (0, false));
}
/// Servers are shown what verifies, each part with the certificate that
/// verifies it: here the avatar service's newer avatar with its own
/// certificate, the chosen badges with the sign-in's, the User Tag with
/// its token. (Certificates from a synthetic root: TeamSpeak's verifies
/// none of it.)
#[test]
fn servers_are_shown_what_verifies_with_its_certificate() {
use voelin_myts::testing::Chain;
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
let id = [1; 33];
let sign_in = Chain::signing(1);
// Valid for an hour only.
let service = Chain::new(2, 6, NOW - 3600, NOW + 3600);
let chat = Chain::new(3, 4, NOW - 3600, NOW + 86_400);
let root = sign_in.root;
let uuids = [
"a2a2a2a2-0000-4000-8000-000000000001",
"a2a2a2a2-0000-4000-8000-000000000002",
"a2a2a2a2-0000-4000-8000-000000000003",
];
let badges: Vec<SignedBadge> = uuids
.iter()
.zip(["One", "Two", "Three"])
.map(|(uuid, name)| SignedBadge::parse(&sign_in.badge(&id, uuid, name)).unwrap())
.collect();
account.set_presentation(
"Alice-uuid",
Presentation {
certificate: sign_in.certificate.clone(),
avatar: sign_in.avatar(&id, 100),
},
);
let tag = "alice@myteamspeak.com";
let token = chat.user_tag_token(&["alice@tschat-1.teamspeak.com", tag], &id);
account.take_fetched(
"Alice-uuid",
Fetched {
avatar: Some(OwnAvatar {
certificate: service.certificate.clone(),
avatar: service.avatar(&id, 200),
}),
badges: Some(badges),
user_tag: Some(tag.into()),
user_tag_token: Some(token.clone()),
},
);
assert!(account.choose_badge(2, true) && account.choose_badge(0, true));
let data = account.myts_data_from(&root, NOW).unwrap();
assert_eq!(data.myts_id, id);
assert!(
data.avatar
== tsclientlib::Signed {
certificate: service.certificate.clone(),
data: service.avatar(&id, 200),
}
);
assert_eq!(data.badges.certificate, sign_in.certificate);
let chosen = account.chosen_badges();
assert_eq!(data.badges.data, voelin_myts::badge_list(&chosen));
assert_eq!(data.badge_ids, [uuids[2], uuids[0]]);
assert!(data.user_tag == Some(tsclientlib::UserTag { tag: tag.into(), token }));
// The avatar and the badges with two certificates: two commands.
assert_eq!(data.updates(&tsclientlib::MytsData::default(), false).len(), 2);
// Two hours on, the avatar service's certificate has expired: the
// sign-in's avatar, with the sign-in's certificate, and one command.
let later = account.myts_data_from(&root, NOW + 7200).unwrap();
assert!(
later.avatar
== tsclientlib::Signed {
certificate: sign_in.certificate.clone(),
data: sign_in.avatar(&id, 100),
}
);
assert_eq!(later.updates(&tsclientlib::MytsData::default(), false).len(), 1);
// A day on, the User Tag's token no longer holds.
assert!(account.myts_data_from(&root, NOW + 86_400).unwrap().user_tag.is_none());
// For another myTS ID, nothing verifies.
account.saved.as_mut().unwrap().identity = Some(server_identity_for(2));
let other = account.myts_data_from(&root, NOW).unwrap();
assert!(other.avatar.is_empty() && other.badges.is_empty() && other.user_tag.is_none());
// TeamSpeak's root verifies none of it.
account.saved.as_mut().unwrap().identity = Some(server_identity());
let data = account.myts_data(NOW).unwrap();
assert!(data.avatar.is_empty() && data.badges.is_empty() && data.user_tag.is_none());
}
fn server_identity() -> ServerIdentity {
server_identity_for(1)
}
/// An identity with the myTS ID `[id; 33]`.
fn server_identity_for(id: u8) -> 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![id; 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 a_saved_session_being_checked_shows_its_profile_not_the_form() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert_eq!(account.form().description, "Alice's profile");
let mut restarted = Account { prompt: true, ..Default::default() };
restarted.load(&secrets);
restarted.begin().unwrap();
restarted.checking = true;
let form = restarted.form();
assert!(form.restoring && !form.signed_in);
assert_eq!((form.username.as_str(), form.initials.as_str()), ("Alice", "AL"));
// A password sign-in over an expired saved session shows the form.
restarted.finish(restarted.generation);
restarted.begin().unwrap();
assert!(!restarted.form().restoring);
}
#[test]
fn the_service_profile_is_kept_and_another_account_starts_empty() {
let secrets = MemorySecrets::default();
let mut account = Account::default();
account.accept(&secrets, login("Alice"), "alice@example.test".into());
let profile = Profile {
username: "Alice B".into(),
registered: 1_600_000_000,
badges: vec![voelin_myts::Badge { name: "Early".into(), ..Default::default() }],
devices: vec![voelin_myts::Device {
name: "Voelin".into(),
region: "EU".into(),
last_login: 0,
}],
..Default::default()
};
account.take_profile(&secrets, &profile);
let saved = read_saved(&secrets).unwrap().unwrap();
assert_eq!(saved.username, "Alice B");
assert_eq!(saved.profile.registered, 1_600_000_000);
assert_eq!(saved.profile.badges, ["Early"]);
assert_eq!(saved.profile.devices, ["Voelin · EU"]);
assert_eq!(saved.profile.description, "Alice's profile", "kept: not in this reply");
let form = account.form();
assert_eq!(form.member_since, date(1_600_000_000));
assert_eq!(form.badges.row_count(), 1);
// The same account signing in again keeps it, another one does not.
account.accept(&secrets, login("Alice"), "alice@example.test".into());
assert_eq!(account.saved.as_ref().unwrap().profile.registered, 1_600_000_000);
account.accept(&secrets, login("Bob"), "bob@example.test".into());
let bob = &account.saved.as_ref().unwrap().profile;
assert_eq!((bob.registered, bob.description.as_str()), (0, "Bob's profile"));
}
#[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()),
profile: SavedProfile { description: "Hi".into(), ..Default::default() },
};
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());
}
}