mod web;
use crate::{Permission, add_http};
use anyhow::bail;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as b64};
use clap::Subcommand;
use clap_complete::{ArgValueCompleter, CompletionCandidate};
use ordinary_host::client::{AccountMeta, OrdinaryHostClient};
use qrcodegen::{QrCode, QrCodeEcc};
use saferlmdb::Environment;
use std::env::home_dir;
use std::sync::Arc;
use time::UtcDateTime;
use time::format_description::BorrowedFormatItem;
use time::macros::format_description;
use tracing::instrument;
pub static GMT_FORMAT: &[BorrowedFormatItem<'static>] = format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"
);
#[derive(Subcommand, Debug)]
pub enum Accounts {
Register {
host: String,
#[arg(long, env = "ORDINARY_ACCOUNT")]
account: Option<String>,
#[arg(
long,
requires("account"),
requires("invite"),
conflicts_with = "password",
env = "ORDINARY_OIDC_PROVIDER"
)]
oidc: Option<String>,
#[arg(
long,
requires("account"),
requires("invite"),
env = "ORDINARY_ACCOUNT_PASSWORD"
)]
password: Option<String>,
#[arg(long, env = "ORDINARY_ACCOUNT_INVITE")]
invite: Option<String>,
},
Login {
host: String,
#[arg(long, env = "ORDINARY_ACCOUNT")]
account: Option<String>,
#[arg(
long,
requires("account"),
conflicts_with = "password",
env = "ORDINARY_OIDC_PROVIDER"
)]
oidc: Option<String>,
#[arg(
long,
requires("account"),
requires("mfa"),
env = "ORDINARY_ACCOUNT_PASSWORD"
)]
password: Option<String>,
#[arg(long, env = "ORDINARY_ACCOUNT_MFA")]
mfa: Option<String>,
},
Logout,
Access {
#[command(subcommand)]
access: Access,
},
Password {
#[command(subcommand)]
password: Password,
},
Mfa {
#[command(subcommand)]
mfa: Mfa,
},
RecoveryCodes {
#[command(subcommand)]
recovery_codes: RecoveryCodes,
},
Delete {
host: String,
account: String,
#[arg(long)]
password: Option<String>,
#[arg(long)]
mfa: Option<String>,
},
Invite {
app: String,
#[arg(long)]
account: String,
#[arg(long)]
#[clap(visible_aliases(["perm", "perms"]))]
permissions: Vec<Permission>,
},
Current,
List,
Switch {
#[arg(add = ArgValueCompleter::new(list_domains))]
domain: String,
account: String,
},
}
#[derive(Subcommand, Debug)]
pub enum Access {
Get {
#[arg(short, long)]
min: Option<u16>,
},
}
#[derive(Subcommand, Debug)]
pub enum Password {
Reset {
#[arg(long)]
password: Option<String>,
#[arg(long)]
new_password: Option<String>,
#[arg(long)]
mfa: Option<String>,
},
Forgot {
#[arg(long)]
new_password: Option<String>,
#[arg(long)]
recovery_code: Option<String>,
},
}
#[derive(Subcommand, Debug)]
pub enum Mfa {
Reset {
#[arg(long)]
password: Option<String>,
#[arg(long)]
mfa: Option<String>,
},
Lost {
#[arg(long)]
password: Option<String>,
#[arg(long)]
recovery_code: Option<String>,
},
}
#[derive(Subcommand, Debug)]
pub enum RecoveryCodes {
Reset {
#[arg(long)]
password: Option<String>,
#[arg(long)]
mfa: Option<String>,
},
}
fn switch_account(host: &str, domain: &str, account: &str) -> anyhow::Result<()> {
tracing::debug!("switching accounts");
let cli_path = home_dir()
.expect("failed to get home dir")
.join(".ordinary")
.join("cli");
if !cli_path.exists() {
fs_err::create_dir_all(&cli_path)?;
}
let host = if let Some(stripped) = host.strip_prefix("https://") {
stripped
} else if let Some(stripped) = host.strip_prefix("http://") {
stripped
} else {
host
};
let domain = if let Some(stripped) = domain.strip_prefix("https://") {
stripped
} else if let Some(stripped) = domain.strip_prefix("http://") {
stripped
} else {
domain
};
let account_path = cli_path.join("account");
fs_err::write(account_path, format!("{account}@{domain}@{host}"))?;
tracing::info!(to = %format!("{account}@{domain}"), "switched");
Ok(())
}
pub struct HostDomainAccount(pub String, pub String, pub String);
pub fn get_current_account() -> anyhow::Result<HostDomainAccount> {
tracing::debug!("getting current account");
let account_path = home_dir()
.expect("failed to get home dir")
.join(".ordinary")
.join("cli")
.join("account");
if !account_path.exists() {
bail!("not logged in")
}
let pair = fs_err::read_to_string(account_path)?;
let split_pair = pair.split('@').collect::<Vec<&str>>();
Ok(HostDomainAccount(
split_pair[2].to_string(),
split_pair[1].to_string(),
split_pair[0].to_string(),
))
}
pub fn get_current_account_meta(
insecure: bool,
client: &OrdinaryHostClient,
) -> anyhow::Result<AccountMeta> {
tracing::debug!("getting current account meta");
let HostDomainAccount(host, domain, account) = get_current_account()?;
let mut account_meta = client.get_account(&host, &domain, &account)?;
account_meta.host = add_http(&account_meta.host, insecure);
Ok(account_meta)
}
impl Accounts {
#[expect(clippy::too_many_lines)]
#[instrument(skip_all, name = "accounts")]
pub async fn handle(
&self,
host_domain: Option<&str>,
accept_invalid_certs: bool,
insecure: bool,
env: &Arc<Environment>,
) -> anyhow::Result<()> {
match self {
Self::Register {
host,
account,
password,
invite,
oidc,
} => {
if let Some(account) = account
&& let Some(password) = password
&& let Some(invite) = invite
{
let client = OrdinaryHostClient::new(
host,
account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
let (totp, recovery_codes_str) = client.host_register(password, invite).await?;
Self::print_mfa(&totp.to_url()?)?;
Self::print_recovery_codes(&recovery_codes_str);
println!("\nlog in: `ordinary host accounts login --help`");
} else {
let account = web::register(
host,
host_domain,
accept_invalid_certs,
oidc.as_deref(),
invite.as_deref(),
account.as_deref(),
env,
)
.await?;
switch_account(host, host_domain.unwrap_or(host), &account)?;
}
}
Self::Login {
host,
account,
password,
mfa,
oidc,
} => {
if let Some(account) = account
&& let Some(password) = password
&& let Some(mfa) = mfa
{
let client = OrdinaryHostClient::new(
host,
account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
client.host_login(password, mfa).await?;
switch_account(host, host_domain.unwrap_or(host), account)?;
} else {
let account = web::login(
host,
host_domain,
accept_invalid_certs,
oidc.as_deref(),
account.as_deref(),
env,
)
.await?;
switch_account(host, host_domain.unwrap_or(host), &account)?;
}
}
Self::Logout => {
println!("todo: logout");
}
Self::Access { access } => match access {
Access::Get { min } => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
let access_token = client
.host_get_access(min.map(|m| u32::from(m) * 60), None)
.await?;
let b64_token = b64.encode(access_token);
println!("{b64_token}");
}
},
Self::Password { password } => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
match password {
Password::Reset {
password,
new_password,
mfa,
} => {
let password = password.to_owned().unwrap_or_default();
let new_password = new_password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
client
.host_reset_password(&password, &mfa, &new_password)
.await?;
}
Password::Forgot {
new_password,
recovery_code,
} => {
let new_password = new_password.to_owned().unwrap_or_default();
let recovery_code = recovery_code.to_owned().unwrap_or_default();
client
.host_forgot_password(&new_password, &recovery_code)
.await?;
}
}
}
Self::Mfa { mfa } => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
match mfa {
Mfa::Reset { password, mfa } => {
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
let totp = client.host_mfa_totp_reset(&password, &mfa).await?;
Self::print_mfa(&totp.to_url()?)?;
}
Mfa::Lost {
password,
recovery_code,
} => {
let password = password.to_owned().unwrap_or_default();
let recovery_code = recovery_code.to_owned().unwrap_or_default();
let totp = client
.host_mfa_totp_reset(&password, &recovery_code)
.await?;
Self::print_mfa(&totp.to_url()?)?;
}
}
}
Self::RecoveryCodes { recovery_codes } => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
match recovery_codes {
RecoveryCodes::Reset { password, mfa } => {
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
let recovery_codes_str =
client.host_recovery_codes_reset(&password, &mfa).await?;
Self::print_recovery_codes(&recovery_codes_str);
}
}
}
Self::Delete {
host,
account,
password,
mfa,
} => {
let client = OrdinaryHostClient::new(
host,
account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
client.host_delete_account(&password, &mfa).await?;
}
Self::Invite {
account: their_account,
app: _domain,
permissions,
} => {
let HostDomainAccount(host, domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
let AccountMeta { project, .. } = get_current_account_meta(insecure, &client)?;
if !project.is_empty() && project != domain {
bail!("projects do not match");
}
let invite_token = client
.host_invite_account(
&domain,
their_account,
permissions
.iter()
.map(Permission::as_u8)
.collect::<Vec<u8>>(),
)
.await?;
println!("INVITE TOKEN: {invite_token}");
}
Self::Current => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
let curr = get_current_account_meta(insecure, &client)?;
let accounts = client
.list_accounts_meta()?
.iter()
.filter(|&account| account.name == curr.name && account.domain == curr.domain)
.cloned()
.collect::<Vec<AccountMeta>>();
Self::account_meta_to_readable(accounts)?;
}
Self::List => {
let HostDomainAccount(host, _domain, account) = get_current_account()?;
let client = OrdinaryHostClient::new(
&host,
&account,
host_domain,
accept_invalid_certs,
crate::USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
Self::account_meta_to_readable(client.list_accounts_meta()?)?;
}
Self::Switch { domain, account } => {
let host = OrdinaryHostClient::get_host(domain, account)?;
switch_account(&host, domain, account)?;
}
}
Ok(())
}
fn print_recovery_codes(recovery_codes_str: &str) {
let mut recovery_code = String::new();
let mut recovery_codes: Vec<String> = vec![];
for (i, c) in recovery_codes_str.chars().enumerate() {
if i > 0 && i % 11 == 0 {
recovery_codes.push(recovery_code.clone());
recovery_code = c.to_string();
} else if i == recovery_codes_str.len() - 1 {
recovery_code.push(c);
recovery_codes.push(recovery_code.clone());
} else {
recovery_code.push(c);
}
}
println!("recovery codes:");
for code in recovery_codes {
println!("- {code}");
}
}
fn print_mfa(mfa_url: &str) -> anyhow::Result<()> {
let qr: QrCode = QrCode::encode_text(mfa_url, QrCodeEcc::Medium)?;
let border: i32 = 1;
for y in -border..qr.size() + border {
for x in -border..qr.size() + border {
let c: char = if qr.get_module(x, y) { '█' } else { ' ' };
print!("{c}{c}");
}
println!();
}
println!("{mfa_url}");
Ok(())
}
fn account_meta_to_readable(accounts: Vec<AccountMeta>) -> anyhow::Result<()> {
use comfy_table::Table;
let mut table = Table::new();
table.set_header(vec![
"Host Domain",
"Host Account",
"Host URL",
"App Domain",
"App Permissions",
"Refresh Token ID",
"Refresh Token Expiration",
"Access Token ID",
"Access Token Expiration",
]);
for account in accounts {
let mut perms_str = String::new();
for permission in account.permissions {
perms_str.push_str(Permission::from_u8(permission).as_str());
perms_str.push(' ');
}
perms_str.pop();
let refresh_exp = if account.refresh_exp > 0 {
let exp = UtcDateTime::from_unix_timestamp(account.refresh_exp.cast_signed())?;
exp.format(&GMT_FORMAT)?
} else {
"N/A".to_string()
};
let access_exp = if account.access_exp > 0 {
let exp = UtcDateTime::from_unix_timestamp(account.access_exp.cast_signed())?;
exp.format(&GMT_FORMAT)?
} else {
"N/A".to_string()
};
table.add_row(vec![
account.domain,
account.name,
format!("http(s)://{}", account.host),
account.project,
perms_str,
account.refresh_token_id,
refresh_exp,
account.access_token_id,
access_exp,
]);
}
println!("{table}");
Ok(())
}
}
fn list_domains(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
let Some(current) = current.to_str() else {
return vec![];
};
let accounts = OrdinaryHostClient::list_accounts();
match accounts {
Ok(accounts) => accounts
.iter()
.filter(|&a| a.1.starts_with(current))
.map(|a| CompletionCandidate::new(a.1.clone()))
.collect::<Vec<CompletionCandidate>>(),
Err(_) => {
vec![]
}
}
}