use std::{fs, path::PathBuf, sync::Arc}; use anyhow::{bail, Context, Result}; use cookie::Key; use jacquard::client::FileAuthStore; use jacquard::common::deps::fluent_uri::Uri; use jacquard::oauth::{ atproto::AtprotoClientMetadata, client::OAuthClient, keyset::Keyset, scopes::Scopes, session::ClientData, }; use jacquard_identity::PublicResolver; use sqlx::SqlitePool; pub type AppOAuthClient = OAuthClient; pub struct AppState { pub oauth: Arc, pub cookie_key: Key, pub base_url: String, pub db: SqlitePool, } pub struct Config { pub base_url: String, pub listen: String, pub data_dir: PathBuf, } impl Config { pub fn from_env() -> Self { Self { base_url: std::env::var("BASE_URL") .unwrap_or_else(|_| "http://127.0.0.1:8080".to_string()) .trim_end_matches('/') .to_string(), listen: std::env::var("LISTEN").unwrap_or_else(|_| "127.0.0.1:8080".to_string()), data_dir: std::env::var("DATA_DIR") .map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from("./data")), } } } impl AppState { pub fn new(config: &Config, db: SqlitePool) -> Result { fs::create_dir_all(&config.data_dir) .with_context(|| format!("failed to create {}", config.data_dir.display()))?; let cookie_key = load_or_generate_cookie_key(&config.data_dir.join("cookie.key"))?; let base = &config.base_url; let redirect_uri = Uri::parse(format!("{base}/oauth/callback")) .map_err(|(err, _)| anyhow::anyhow!("invalid BASE_URL: {err}"))?; let scopes = Scopes::builder() .atproto() .repo_collection("community.lexicon.calendar.event")? .repo_collection("community.lexicon.calendar.rsvp")? .build() .context("failed to build OAuth scopes")?; // Loopback (http://) dev clients carry their metadata in the client_id // query string per the AT Protocol localhost client spec, and must be // public (no keyset). Hosted https:// clients serve metadata from // /oauth-client-metadata.json and authenticate with private_key_jwt. let localhost = base.starts_with("http://"); let (metadata, keyset) = if localhost { ( AtprotoClientMetadata::new_localhost(Some(vec![redirect_uri]), Some(scopes)), None, ) } else { let client_id = Uri::parse(format!("{base}/oauth-client-metadata.json")) .map_err(|(err, _)| anyhow::anyhow!("invalid BASE_URL: {err}"))?; ( AtprotoClientMetadata::new(vec![redirect_uri], client_id, Some(scopes)), Some(load_or_generate_keyset( &config.data_dir.join("oauth-client-keyset.json"), )?), ) }; let client_data = ClientData::new(keyset, metadata); let sessions_path = config.data_dir.join("oauth-sessions.json"); let oauth = OAuthClient::new( FileAuthStore::new(sessions_path.to_string_lossy().into_owned()), client_data, reqwest::Client::new(), ); Ok(Self { oauth: Arc::new(oauth), cookie_key, base_url: config.base_url.clone(), db, }) } } fn load_or_generate_keyset(path: &PathBuf) -> Result { match fs::read(path) { Ok(bytes) => serde_json::from_slice(&bytes) .with_context(|| format!("failed to parse {}", path.display())), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { let keyset = Keyset::generate_es256("partytool") .map_err(|err| anyhow::anyhow!("failed to generate keyset: {err}"))?; write_secret(path, &serde_json::to_vec_pretty(&keyset)?)?; Ok(keyset) } Err(err) => Err(err).with_context(|| format!("failed to read {}", path.display())), } } fn load_or_generate_cookie_key(path: &PathBuf) -> Result { use rand::RngCore; match fs::read(path) { Ok(bytes) if bytes.len() == 64 => Ok(Key::from(&bytes[..])), Ok(_) => bail!("{} must contain exactly 64 bytes", path.display()), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { let mut bytes = [0u8; 64]; rand::rngs::OsRng.fill_bytes(&mut bytes); write_secret(path, &bytes)?; Ok(Key::from(&bytes[..])) } Err(err) => Err(err).with_context(|| format!("failed to read {}", path.display())), } } fn write_secret(path: &PathBuf, bytes: &[u8]) -> Result<()> { fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; fs::set_permissions(path, fs::Permissions::from_mode(0o600)) .with_context(|| format!("failed to restrict permissions on {}", path.display()))?; } Ok(()) }