pub mod account;
pub mod api;
pub mod controllers;
pub mod events;
pub mod jobs;
pub mod mails;
pub mod mcp;
pub mod middleware;
pub mod migrations;
pub mod models;
pub mod notifications;
pub mod policies;
pub mod routes;
pub mod seeders;
use axum::extract::FromRef;
use migrations::Migrator;
use ryuk::{
api::DbRateLimit,
apikey::ApiKeys,
app::{App, Config},
db,
inertia::{self, InertiaConfig},
mail::Mailer,
oauth_server::OAuthServer,
passkey::{Passkeys, webauthn_from_env},
push::Push,
session::DbStore,
tenancy::Tenancy,
throttle::Throttle,
tokens::Tokens,
};
use sea_orm::DatabaseConnection;
use sea_orm_migration::MigratorTrait;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
pub struct AppState {
pub db: DatabaseConnection,
pub inertia: InertiaConfig,
pub mailer: Mailer,
pub throttle: Throttle,
pub ip_throttle: Throttle,
pub mail_throttle: Throttle,
pub tokens: Tokens,
pub api_keys: ApiKeys,
pub oauth: OAuthServer,
pub passkeys: Passkeys,
pub tenancy: Tenancy,
pub push: Push,
pub session_store: DbStore,
pub ops: Ops,
}
#[derive(Clone, Debug)]
pub struct Ops {
pub min_app_version_ios: Option<String>,
pub min_app_version_android: Option<String>,
pub rate_limit_memory: bool,
pub rate_limit_max: u32,
pub rate_limit_window_secs: u64,
pub apple_app_id: Option<String>,
pub apple_app_paths: Vec<String>,
pub android_package: Option<String>,
pub android_cert_fingerprints: Vec<String>,
}
impl Ops {
pub fn from_env() -> Self {
Self::from_lookup(|k| std::env::var(k).ok())
}
pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self {
let text = |k: &str| get(k).map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
let list = |k: &str| -> Vec<String> {
text(k).map(|v| v.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect()).unwrap_or_default()
};
let num = |k: &str| text(k).and_then(|v| v.parse::<u64>().ok()).filter(|n| *n > 0);
Ops {
min_app_version_ios: text("MIN_APP_VERSION_IOS"),
min_app_version_android: text("MIN_APP_VERSION_ANDROID"),
rate_limit_memory: text("API_RATE_LIMIT").is_some_and(|v| v.eq_ignore_ascii_case("memory")),
rate_limit_max: num("API_RATE_LIMIT_MAX").map_or(120, |n| n.min(u32::MAX as u64) as u32),
rate_limit_window_secs: num("API_RATE_LIMIT_WINDOW_SECS").unwrap_or(60),
apple_app_id: text("APPLE_APP_ID"),
apple_app_paths: Some(list("APPLE_APP_PATHS")).filter(|p| !p.is_empty()).unwrap_or_else(|| vec!["*".into()]),
android_package: text("ANDROID_PACKAGE"),
android_cert_fingerprints: list("ANDROID_SHA256_CERT_FINGERPRINTS"),
}
}
}
impl Default for Ops {
fn default() -> Self {
Self::from_lookup(|_| None)
}
}
impl FromRef<AppState> for InertiaConfig {
fn from_ref(s: &AppState) -> Self {
s.inertia.clone()
}
}
impl FromRef<AppState> for Tenancy {
fn from_ref(s: &AppState) -> Self {
s.tenancy.clone()
}
}
impl FromRef<AppState> for OAuthServer {
fn from_ref(s: &AppState) -> Self {
s.oauth.clone()
}
}
const THEME_SCRIPT: &str = r#"<script>try{var t=localStorage.getItem("ryuk-theme");if(t==="light"||t==="dark")document.documentElement.dataset.theme=t}catch(e){}</script>"#;
fn io(e: impl std::error::Error + Send + Sync + 'static) -> std::io::Error {
std::io::Error::other(e)
}
pub async fn build(config: &Config) -> std::io::Result<App<AppState>> {
build_with(config, Ops::from_env()).await
}
pub async fn build_with(config: &Config, ops: Ops) -> std::io::Result<App<AppState>> {
Ok(routes_for(state(config, ops).await?))
}
pub async fn state(config: &Config, ops: Ops) -> std::io::Result<AppState> {
let db = db::connect(&config.database_url).await.map_err(io)?;
if std::env::var("AUTO_MIGRATE").map(|v| v != "false" && v != "0").unwrap_or(true) {
Migrator::up(&db, None).await.map_err(io)?;
}
mail_guard(&config.app_env, std::env::var("MAIL_DRIVER").ok().as_deref(), std::env::var("ALLOW_LOG_MAIL").ok().as_deref()).map_err(std::io::Error::other)?;
let (throttle, tokens) = (Throttle::new(db.clone()), Tokens::new(db.clone()));
let (ip_throttle, mail_throttle) = (throttle.clone().max_attempts(50), throttle.clone().max_attempts(10));
throttle.ensure_tables().await.map_err(io)?;
tokens.ensure_tables().await.map_err(io)?;
let (api_keys, oauth) = (ApiKeys::new(db.clone()), OAuthServer::new(db.clone()));
api_keys.ensure_tables().await.map_err(io)?;
oauth.ensure_tables().await.map_err(io)?;
let passkeys = Passkeys::new(db.clone(), Arc::new(webauthn_from_env().map_err(std::io::Error::other)?));
passkeys.ensure_tables().await.map_err(io)?;
let tenancy = Tenancy::new(db.clone());
tenancy.ensure_tables().await.map_err(io)?;
ryuk::queue::Queue::new(db.clone()).ensure_tables().await.map_err(io)?;
let store = DbStore::new(db.clone());
store.ensure_table().await.map_err(io)?;
DbRateLimit::new(db.clone()).ensure_tables().await.map_err(io)?;
let push = Push::from_env(db.clone()).await.map_err(io)?;
push.devices().ensure_tables().await.map_err(io)?;
let state = AppState {
inertia: inertia::with_head(inertia::Config::from_env("{{name}}"), THEME_SCRIPT),
mailer: Mailer::from_env().map_err(io)?,
db: db.clone(),
throttle,
ip_throttle,
mail_throttle,
tokens,
api_keys,
oauth,
passkeys,
tenancy,
push,
session_store: store.clone(),
ops,
};
let s2 = state.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(3600)).await;
prune(&s2).await;
}
});
Ok(state)
}
pub fn mail_guard(app_env: &str, mail_driver: Option<&str>, allow_log_mail: Option<&str>) -> Result<(), String> {
let log_driver = mail_driver.map(str::trim).is_none_or(|d| d.is_empty() || d.eq_ignore_ascii_case("log"));
if ryuk::security::is_production_env(app_env) && log_driver && allow_log_mail.map(str::trim) != Some("true") {
return Err("APP_ENV=production with the log mail driver: set MAIL_DRIVER=smtp (and MAIL_HOST...), or ALLOW_LOG_MAIL=true to accept that mails (links included) only go to the log".into());
}
Ok(())
}
pub fn client_scopes_ok(first_party: bool, scopes: &[String]) -> Result<(), String> {
if !first_party && scopes.iter().any(|s| s == "account") {
return Err("--scope account is only for --first-party clients (it allows deleting the account)".into());
}
Ok(())
}
pub fn fresh_allowed(app_env: &str, force: bool) -> Result<(), String> {
if ryuk::security::is_production_env(app_env) && !force {
return Err("migrate:fresh drops every table; refusing with APP_ENV=production (pass --force to do it anyway)".into());
}
Ok(())
}
const DAY: Duration = Duration::from_secs(86_400);
pub async fn prune(s: &AppState) -> Vec<(&'static str, u64)> {
fn count<E: std::fmt::Display>(what: &'static str, r: Result<u64, E>) -> (&'static str, u64) {
(what, r.unwrap_or_else(|e| {
tracing::warn!(task = what, error = %e, "prune failed");
0
}))
}
let oauth = s.oauth.prune(30 * DAY).await.map(|r| r.codes + r.tokens);
let rows = vec![
count("sessions", s.session_store.delete_expired().await),
count("one_time_tokens", s.tokens.prune().await),
count("throttle", s.throttle.prune().await),
count("oauth", oauth),
count("api_keys", s.api_keys.prune(30 * DAY).await),
count("push_devices", s.push.devices().prune(30 * DAY, 270 * DAY).await),
count("api_rate_limits", DbRateLimit::new(s.db.clone()).prune().await),
count("org_invites", s.tenancy.prune_invites().await),
];
tracing::info!(pruned = ?rows, "maintenance");
rows
}
fn routes_for(state: AppState) -> App<AppState> {
let (db, store, ops) = (state.db.clone(), state.session_store.clone(), state.ops.clone());
let (api_keys, oauth) = (state.api_keys.clone(), state.oauth.clone());
let app_url = std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost:3000".into());
let mut app = App::new(state)
.title("{{name}}")
.version(env!("CARGO_PKG_VERSION"))
.sessions(store)
.database(&db)
.web(routes::router())
.api(api::router())
.api_verifier(api_keys)
.api_verifier(oauth)
.public(OAuthServer::token_routes())
.web(OAuthServer::web_routes())
.public(controllers::well_known::router())
.routes(controllers::social::social().routes(controllers::social::AppUsers::new(db.clone())))
.routes(controllers::passkeys::router())
.oauth2_scheme(
&format!("{app_url}/oauth/authorize"),
&format!("{app_url}/oauth/token"),
&[
("profile", "Read your name and email"),
("posts:read", "Read your posts"),
("posts:write", "Create, edit and delete your posts"),
("devices", "Register and remove push notification devices"),
("account", "Manage sessions and authorized apps, and delete the account"),
],
)
.api_rate_limit(ops.rate_limit_max, Duration::from_secs(ops.rate_limit_window_secs));
if !ops.rate_limit_memory {
app = app.api_rate_limit_store(DbRateLimit::new(db));
}
for (platform, min) in [("ios", &ops.min_app_version_ios), ("android", &ops.min_app_version_android)] {
if let Some(min) = min {
app = app.min_app_version(platform, min);
}
}
app
}
pub async fn worker(config: &Config) -> std::io::Result<ryuk::queue::Queue> {
let queue = ryuk::queue::Queue::new(db::connect(&config.database_url).await.map_err(io)?);
queue.ensure_tables().await.map_err(io)?;
Ok(queue.register::<jobs::send_push::SendPush>())
}
#[cfg(test)]
mod tests {
use super::{Ops, client_scopes_ok, fresh_allowed, mail_guard};
fn ops(pairs: &[(&str, &str)]) -> Ops {
Ops::from_lookup(|k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()))
}
#[test]
fn ops_defaults_and_parsing() {
let d = ops(&[]);
assert_eq!((d.rate_limit_memory, d.rate_limit_max, d.rate_limit_window_secs), (false, 120, 60));
assert_eq!((d.min_app_version_ios, d.apple_app_id, d.apple_app_paths), (None, None, vec!["*".to_string()]));
let o = ops(&[("API_RATE_LIMIT", "Memory"), ("API_RATE_LIMIT_MAX", "5"), ("API_RATE_LIMIT_WINDOW_SECS", "0"), ("MIN_APP_VERSION_IOS", " 1.2 "), ("MIN_APP_VERSION_ANDROID", "")]);
assert_eq!((o.rate_limit_memory, o.rate_limit_max, o.rate_limit_window_secs), (true, 5, 60), "zero or junk falls back");
assert_eq!((o.min_app_version_ios.as_deref(), o.min_app_version_android), (Some("1.2"), None));
}
#[test]
fn production_refuses_the_log_mail_driver() {
for driver in [None, Some(""), Some("log"), Some("LOG")] {
assert!(mail_guard("production", driver, None).is_err(), "{driver:?}");
assert!(mail_guard("production", driver, Some("false")).is_err());
assert!(mail_guard("production", driver, Some("true")).is_ok(), "explicit opt-out");
assert!(mail_guard("local", driver, None).is_ok());
}
assert!(mail_guard("production", Some("smtp"), None).is_ok());
for env in ["Production", " production ", "prod", "PRODUCTION"] {
assert!(mail_guard(env, None, None).is_err(), "{env:?}");
assert!(fresh_allowed(env, false).is_err(), "{env:?}");
}
}
#[test]
fn cli_guards() {
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
assert!(client_scopes_ok(false, &s(&["profile", "account"])).is_err());
assert!(client_scopes_ok(true, &s(&["account"])).is_ok() && client_scopes_ok(false, &s(&["profile"])).is_ok());
assert!(fresh_allowed("production", false).is_err());
assert!(fresh_allowed("production", true).is_ok() && fresh_allowed("local", false).is_ok());
}
}