use std::io::Write as _;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys, DEFAULT_KDF};
use teter_common::account::{AccountReply, AccountRequest};
use zeroize::Zeroizing;
#[derive(clap::Args)]
pub struct SignupArgs {
relay: String,
#[arg(long)]
name: String,
#[arg(long, env = "TETER_INVITE", hide_env_values = true, default_value = "")]
invite: String,
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct LoginArgs {
relay: String,
#[arg(long)]
name: String,
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct LogoutArgs {
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct Saved {
pub(crate) relay: String,
pub(crate) name: String,
pub(crate) token: String,
pub(crate) public_keys: String,
pub(crate) private_keys: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) ca_cert: Option<PathBuf>,
}
const LOGOUT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
const RELOGIN_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
pub(crate) fn load() -> std::io::Result<Saved> {
let path = account_file()?;
match std::fs::read(&path).map(Zeroizing::new) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(std::io::Error::other),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(std::io::Error::other(
"this device is not logged in: run teter login",
)),
Err(e) => Err(e),
}
}
impl Drop for Saved {
fn drop(&mut self) {
zeroize::Zeroize::zeroize(&mut self.private_keys);
zeroize::Zeroize::zeroize(&mut self.token);
}
}
pub(crate) fn account_file() -> std::io::Result<PathBuf> {
let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
if let Some(config) = var("XDG_CONFIG_HOME") {
return Ok(PathBuf::from(config).join("teter/account.json"));
}
let home = var("HOME").ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
"neither XDG_CONFIG_HOME nor HOME is set: no place for the account",
)
})?;
Ok(PathBuf::from(home).join(".config/teter/account.json"))
}
fn password(prompt: &str, confirm: bool) -> std::io::Result<Zeroizing<String>> {
if let Ok(password) = std::env::var("TETER_PASSWORD") {
if password.is_empty() {
return Err(std::io::Error::other("TETER_PASSWORD is empty"));
}
return Ok(Zeroizing::new(password));
}
let first = Zeroizing::new(rpassword::prompt_password(prompt)?);
if confirm {
let again = Zeroizing::new(rpassword::prompt_password("the same password again: ")?);
if *first != *again {
return Err(std::io::Error::other("the two passwords differ"));
}
}
if first.is_empty() {
return Err(std::io::Error::other("an empty password"));
}
Ok(first)
}
pub async fn signup(args: SignupArgs) -> std::io::Result<()> {
let password = password(
&format!("password for the new account {}: ", args.name),
true,
)?;
let salt = account::new_salt(DEFAULT_KDF)?;
let derived = account::derive(&password, &salt).map_err(std::io::Error::other)?;
let keys = AccountKeys::generate()?;
let request = AccountRequest::Signup {
name: args.name.clone(),
salt,
auth_key: derived.auth_key.to_vec(),
public_keys: keys.public_keys(),
wrapped_keys: keys.wrap(&derived, &args.name)?,
invite: args.invite.clone(),
};
let reply = ask(&args.relay, args.ca_cert.as_deref(), &request).await?;
let AccountReply::SignedUp = reply else {
return Err(unexpected(&reply));
};
log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
println!("made the account {} and logged in", args.name);
Ok(())
}
pub async fn login(args: LoginArgs) -> std::io::Result<()> {
let password = password(&format!("password for {}: ", args.name), false)?;
log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
println!("logged in to {}", args.name);
Ok(())
}
async fn log_in(
relay: &str,
name: &str,
password: &str,
ca_cert: Option<&Path>,
) -> std::io::Result<()> {
let ca_cert = ca_cert.map(std::path::absolute).transpose()?;
let ca_cert = ca_cert.as_deref();
let reply = ask(
relay,
ca_cert,
&AccountRequest::Salt {
name: name.to_owned(),
},
)
.await?;
let AccountReply::Salt { salt } = reply else {
return Err(unexpected(&reply));
};
let derived = account::derive(password, &salt).map_err(std::io::Error::other)?;
let request = AccountRequest::Login {
name: name.to_owned(),
auth_key: derived.auth_key.to_vec(),
};
let reply = ask(relay, ca_cert, &request).await?;
let AccountReply::LoggedIn {
token,
public_keys,
wrapped_keys,
} = reply
else {
return Err(unexpected(&reply));
};
let keys = AccountKeys::unwrap(&derived, name, &wrapped_keys, &public_keys)
.map_err(std::io::Error::other)?;
let before = read_saved();
save(&Saved {
relay: relay.to_owned(),
name: name.to_owned(),
token,
public_keys: hex(&public_keys),
private_keys: hex(keys.private_bytes().as_ref()),
ca_cert: ca_cert.map(Path::to_path_buf),
})?;
if let Ok(Some(before)) = before {
let same_relay =
crate::endpoint(&before.relay, "account") == crate::endpoint(relay, "account");
let ca = if same_relay {
ca_cert.or(before.ca_cert.as_deref())
} else {
before.ca_cert.as_deref()
};
match end_login(&before, ca, RELOGIN_WAIT).await {
Ok(AccountReply::LoggedOut) => {}
Ok(other) => {
eprintln!("teter: the relay did not end this device's login before: {other:?}")
}
Err(e) => eprintln!("teter: could not end this device's login before: {e}"),
}
}
Ok(())
}
fn read_saved() -> std::io::Result<Option<Saved>> {
match std::fs::read(account_file()?).map(Zeroizing::new) {
Ok(bytes) => serde_json::from_slice(&bytes)
.map(Some)
.map_err(std::io::Error::other),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
async fn end_login(
saved: &Saved,
ca_cert: Option<&Path>,
wait: std::time::Duration,
) -> std::io::Result<AccountReply> {
let request = AccountRequest::Logout {
token: saved.token.clone(),
};
let ca_cert = ca_cert.or(saved.ca_cert.as_deref());
tokio::time::timeout(wait, account::request(&saved.relay, ca_cert, &request))
.await
.map_err(|elapsed| std::io::Error::new(std::io::ErrorKind::TimedOut, elapsed))?
.map_err(std::io::Error::other)
}
pub async fn logout(args: LogoutArgs) -> std::io::Result<()> {
let path = account_file()?;
let Some(saved) = read_saved()? else {
return Err(std::io::Error::other("this device is not logged in"));
};
let told = end_login(&saved, args.ca_cert.as_deref(), LOGOUT_WAIT).await;
std::fs::remove_file(&path)?;
if let Err(e) = crate::approve::forget_all() {
eprintln!("teter: could not remove the pending token secrets: {e}");
}
match told {
Ok(AccountReply::LoggedOut) => println!("logged out of {}", saved.name),
Ok(other) => eprintln!(
"teter: the relay did not end the login: {other:?}; the keys here are removed"
),
Err(e) => {
eprintln!("teter: the relay could not be reached ({e}); the keys here are removed")
}
}
Ok(())
}
fn save(saved: &Saved) -> std::io::Result<()> {
crate::approve::forget_all()?;
let path = account_file()?;
if let Some(dir) = path.parent() {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
}
let temporary = path.with_extension(format!("new.{}", std::process::id()));
match std::fs::remove_file(&temporary) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
let mut file = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(&temporary)?;
let text = Zeroizing::new(serde_json::to_vec(saved).map_err(std::io::Error::other)?);
let written = file
.write_all(&text)
.and_then(|()| file.sync_all())
.and_then(|()| std::fs::rename(&temporary, &path));
if written.is_err() {
drop(std::fs::remove_file(&temporary));
}
written
}
pub(crate) async fn ask(
relay: &str,
ca_cert: Option<&Path>,
request: &AccountRequest,
) -> std::io::Result<AccountReply> {
let reply = account::request(relay, ca_cert, request)
.await
.map_err(std::io::Error::other)?;
if let AccountReply::Refused { reason } = reply {
return Err(std::io::Error::other(reason));
}
Ok(reply)
}
pub(crate) fn unexpected(reply: &AccountReply) -> std::io::Error {
std::io::Error::other(format!("the relay answered out of turn: {reply:?}"))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}