ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! App-link files for universal links (iOS) and app links (Android). Public, stateless, `application/json`.
//! Each answers 404 until its env vars are set (see `Ops` in src/lib.rs and `.env.example`).
use crate::{AppState, Ops};
use axum::{Json, extract::State, http::StatusCode};
use serde_json::{Value, json};
use utoipa_axum::{router::OpenApiRouter, routes};

pub fn router() -> OpenApiRouter<AppState> {
    OpenApiRouter::new().routes(routes!(apple_app_site_association)).routes(routes!(asset_links))
}

fn apple(o: &Ops) -> Option<Value> {
    let id = o.apple_app_id.as_ref()?;
    Some(json!({ "applinks": { "apps": [], "details": [{ "appID": id, "paths": o.apple_app_paths }] } }))
}

fn android(o: &Ops) -> Option<Value> {
    let pkg = o.android_package.as_ref().filter(|_| !o.android_cert_fingerprints.is_empty())?;
    Some(json!([{
        "relation": ["delegate_permission/common.handle_all_urls"],
        "target": { "namespace": "android_app", "package_name": pkg, "sha256_cert_fingerprints": o.android_cert_fingerprints }
    }]))
}

#[utoipa::path(get, path = "/.well-known/apple-app-site-association",
    responses((status = 200, description = "iOS universal links (APPLE_APP_ID)"), (status = 404, description = "Not configured")))]
pub async fn apple_app_site_association(State(s): State<AppState>) -> Result<Json<Value>, StatusCode> {
    apple(&s.ops).map(Json).ok_or(StatusCode::NOT_FOUND)
}

#[utoipa::path(get, path = "/.well-known/assetlinks.json",
    responses((status = 200, description = "Android app links (ANDROID_PACKAGE, ANDROID_SHA256_CERT_FINGERPRINTS)"), (status = 404, description = "Not configured")))]
pub async fn asset_links(State(s): State<AppState>) -> Result<Json<Value>, StatusCode> {
    android(&s.ops).map(Json).ok_or(StatusCode::NOT_FOUND)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ops(pairs: &[(&str, &str)]) -> Ops {
        Ops::from_lookup(|k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()))
    }

    #[test]
    fn files_need_their_env_and_have_the_right_shape() {
        assert!(apple(&ops(&[])).is_none() && android(&ops(&[])).is_none());
        let a = apple(&ops(&[("APPLE_APP_ID", "TEAM.com.example"), ("APPLE_APP_PATHS", "/a/*, /b")])).unwrap();
        assert_eq!(a["applinks"]["details"][0], json!({ "appID": "TEAM.com.example", "paths": ["/a/*", "/b"] }));
        assert_eq!(apple(&ops(&[("APPLE_APP_ID", "T.x")])).unwrap()["applinks"]["details"][0]["paths"], json!(["*"]));
        assert!(android(&ops(&[("ANDROID_PACKAGE", "com.example")])).is_none(), "fingerprints are required");
        let g = android(&ops(&[("ANDROID_PACKAGE", "com.example"), ("ANDROID_SHA256_CERT_FINGERPRINTS", "AA:BB, CC:DD")])).unwrap();
        assert_eq!(g[0]["target"]["sha256_cert_fingerprints"], json!(["AA:BB", "CC:DD"]));
    }
}