use std::path::Path;
use rand::RngCore;
pub fn ensure_api_token(config_dir: &Path) -> anyhow::Result<String> {
let token_path = config_dir.join("api_token");
if token_path.exists() {
let token = std::fs::read_to_string(&token_path)?.trim().to_string();
if !token.is_empty() {
return Ok(token);
}
}
let mut bytes = [0u8; 32];
rand::rng().fill_bytes(&mut bytes);
let token = hex::encode(bytes);
std::fs::create_dir_all(config_dir)?;
std::fs::write(&token_path, &token)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600))?;
}
tracing::info!(path = %token_path.display(), "Generated new API token");
Ok(token)
}