diff --git a/Cargo.lock b/Cargo.lock index 73a9174..ffaba47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -86,6 +86,18 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -162,12 +174,27 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -358,6 +385,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -974,6 +1002,7 @@ name = "omega-proxy" version = "0.1.0" dependencies = [ "anyhow", + "argon2", "axum", "bytes", "chacha20poly1305", @@ -1034,6 +1063,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "percent-encoding" version = "2.3.2" diff --git a/Cargo.toml b/Cargo.toml index cc4154d..00fec21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ license = "MIT" [workspace.dependencies] anyhow = "1" +argon2 = "0.5" axum = "0.8" bytes = "1" chacha20poly1305 = "0.10" diff --git a/proxy/Cargo.toml b/proxy/Cargo.toml index 391870e..f395fb1 100644 --- a/proxy/Cargo.toml +++ b/proxy/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true [dependencies] anyhow.workspace = true +argon2.workspace = true axum.workspace = true bytes.workspace = true chacha20poly1305.workspace = true diff --git a/proxy/src/accounts.rs b/proxy/src/accounts.rs index 036df5c..27638ca 100644 --- a/proxy/src/accounts.rs +++ b/proxy/src/accounts.rs @@ -31,6 +31,22 @@ pub struct Session { pub note: String, } +fn hash_password(password: &str) -> Result { + use argon2::password_hash::{PasswordHasher, SaltString}; + let mut salt = [0u8; 16]; + rand::rng().fill_bytes(&mut salt); + let salt = SaltString::encode_b64(&salt).map_err(|e| anyhow::anyhow!("Salz: {e}"))?; + let hash = argon2::Argon2::default() + .hash_password(password.as_bytes(), &salt) + .map_err(|e| anyhow::anyhow!("Passwort-Hash: {e}"))?; + Ok(hash.to_string()) +} + +fn password_matches(password: &str, stored: &str) -> bool { + use argon2::password_hash::{PasswordHash, PasswordVerifier}; + PasswordHash::new(stored).is_ok_and(|h| argon2::Argon2::default().verify_password(password.as_bytes(), &h).is_ok()) +} + fn hash_token(token: &str) -> String { hex::encode(Sha256::digest(token.as_bytes())) } @@ -362,6 +378,39 @@ impl Db { names.into_iter().map(|n| Ok((n.clone(), self.user_by_name(&n)?))).collect() } + /// Setzt das Passwort für die Anmeldung mit Passwort (nur zum Testen). + pub fn set_password(&self, actor: &str, username: &str, password: &str) -> Result<()> { + let user = self.existing_user(username)?; + let hash = hash_password(password)?; + self.conn().execute("UPDATE users SET password_hash = ?1 WHERE id = ?2", params![hash, user.id])?; + self.audit(actor, "user.password", username) + } + + /// Prüft Benutzername und Passwort; gesperrte und deaktivierte Benutzer werden abgewiesen. + pub fn check_password(&self, username: &str, password: &str) -> Result> { + let stored: Option> = self + .conn() + .query_row("SELECT password_hash FROM users WHERE username = ?1", params![username], |r| r.get(0)) + .optional()?; + let Some(Some(stored)) = stored else { + // Gleich lange rechnen, ob es den Benutzer gibt oder nicht + let _ = hash_password(password); + return Ok(None); + }; + if !password_matches(password, &stored) { + return Ok(None); + } + Ok(self.user_by_name(username)?.filter(|u| u.active && !u.blocked)) + } + + /// ID der Sitzung zu einem Token, etwa zum Abmelden + pub fn session_id(&self, token: &str) -> Result> { + Ok(self + .conn() + .query_row("SELECT id FROM sessions WHERE token_hash = ?1", params![hash_token(token)], |r| r.get(0)) + .optional()?) + } + /// Legt eine Sitzung an und gibt ihr Token im Klartext zurück; gespeichert wird nur der Hash. pub fn create_session(&self, user: &User, days: u32, note: &str) -> Result<(i64, String)> { let mut bytes = [0u8; 24]; diff --git a/proxy/src/api.rs b/proxy/src/api.rs index c177e83..e789f9e 100644 --- a/proxy/src/api.rs +++ b/proxy/src/api.rs @@ -68,8 +68,10 @@ fn done() -> ApiResult { pub fn router(state: AppState) -> Router { let private = Router::new() .route("/me", get(me)) + .route("/logout", post(logout)) .route("/users", get(list_users).post(add_user)) .route("/users/{username}", axum::routing::patch(update_user)) + .route("/users/{username}/password", post(set_password)) .route("/groups", get(list_groups).post(create_group)) .route("/groups/{name}", get(show_group).delete(delete_group)) .route("/groups/{name}/members", post(add_members)) @@ -93,22 +95,56 @@ pub fn router(state: AppState) -> Router { .layer(middleware::from_fn_with_state(state, session_auth)); Router::new() .route("/public/dashboard", get(public_dashboard)) + .route("/login", post(login)) .merge(private) .fallback(|| async { (StatusCode::NOT_FOUND, Json(json!({ "error": "unbekannter Endpunkt" }))) }) } +const COOKIE: &str = "omega_session"; + +/// Token aus dem Cookie der Oberfläche +fn cookie_token(headers: &axum::http::HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|c| c.trim().split_once('=')) + .find(|(name, _)| *name == COOKIE) + .map(|(_, value)| value.to_string()) +} + +/// Die aktuelle Sitzung, über die Kopfzeile Authorization (Skripte) oder das Cookie (Browser) +#[derive(Clone)] +struct SessionToken(String); + async fn session_auth(State(st): State, mut req: Request, next: Next) -> Response { - let token = req + let unauthorized = |m: &str| (StatusCode::UNAUTHORIZED, Json(json!({ "error": m }))).into_response(); + let bearer = req .headers() .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) - .map(str::trim); - let unauthorized = |m: &str| (StatusCode::UNAUTHORIZED, Json(json!({ "error": m }))).into_response(); - let Some(token) = token else { return unauthorized("Anmeldung fehlt (Authorization: Bearer )") }; - match st.db.session_user(token) { + .map(|v| v.trim().to_string()); + let token = match bearer { + Some(t) => t, + None => { + let Some(t) = cookie_token(req.headers()) else { + return unauthorized("Anmeldung fehlt (Authorization: Bearer )"); + }; + // Gegen Cross-Site Request Forgery: Ein Cookie allein genügt für Änderungen nicht, + // die Oberfläche schickt zusätzlich diese Kopfzeile, die fremde Seiten nicht setzen können. + let safe = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD); + if !safe && req.headers().get("x-omega-csrf").is_none() { + return (StatusCode::FORBIDDEN, Json(json!({ "error": "Kopfzeile X-Omega-CSRF fehlt" }))).into_response(); + } + t + } + }; + match st.db.session_user(&token) { Ok(Some(user)) => { req.extensions_mut().insert(Actor::User(user)); + req.extensions_mut().insert(SessionToken(token)); next.run(req).await } Ok(None) => unauthorized("Sitzung ungültig oder abgelaufen"), @@ -116,6 +152,40 @@ async fn session_auth(State(st): State, mut req: Request, next: Next) } } +#[derive(Deserialize)] +struct LoginInput { + username: String, + password: String, +} + +fn session_cookie(st: &AppState, value: &str, max_age: i64) -> String { + let secure = if st.ui.secure_cookie { "; Secure" } else { "" }; + format!("{COOKIE}={value}; Path=/omega; HttpOnly; SameSite=Strict; Max-Age={max_age}{secure}") +} + +/// Anmeldung mit Passwort für die Oberfläche (nur zum Testen, siehe ui.password_login) +async fn login(State(st): State, Json(input): Json) -> ApiResult { + if !st.ui.password_login { + return Err(crate::service::forbidden("Die Anmeldung mit Passwort ist ausgeschaltet").into()); + } + let Some(user) = st.db.check_password(&input.username, &input.password)? else { + st.db.audit(&input.username, "login.failed", "Passwort")?; + return Ok((StatusCode::UNAUTHORIZED, Json(json!({ "error": "Benutzername oder Passwort falsch" }))).into_response()); + }; + let days = st.ui.session_days.clamp(1, 365); + let (_, token) = st.db.create_session(&user, days, "Anmeldung im Browser")?; + st.db.audit(&user.username, "login", "Passwort")?; + let cookie = session_cookie(&st, &token, i64::from(days) * 86_400); + Ok(([(header::SET_COOKIE, cookie)], Json(json!({ "user": user }))).into_response()) +} + +async fn logout(State(st): State, Extension(actor): Extension, Extension(token): Extension) -> ApiResult { + if let (Actor::User(user), Some(id)) = (&actor, st.db.session_id(&token.0)?) { + st.db.revoke_session(user, id)?; + } + Ok(([(header::SET_COOKIE, session_cookie(&st, "", 0))], StatusCode::NO_CONTENT).into_response()) +} + #[derive(Deserialize)] struct HoursQuery { hours: Option, @@ -148,6 +218,21 @@ async fn update_user( ok(Service::new(&st.db, &actor).update_user(&username, &patch)?) } +#[derive(Deserialize)] +struct PasswordInput { + password: String, +} + +async fn set_password( + State(st): State, + Extension(actor): Extension, + Path(username): Path, + Json(input): Json, +) -> ApiResult { + Service::new(&st.db, &actor).set_password(&username, &input.password)?; + done() +} + // Gruppen #[derive(Deserialize)] diff --git a/proxy/src/cli.rs b/proxy/src/cli.rs index 98b41c7..c27c2f6 100644 --- a/proxy/src/cli.rs +++ b/proxy/src/cli.rs @@ -68,6 +68,10 @@ pub fn user(db: &Db, actor: &Actor, cmd: UserCommand) -> Result<()> { UserCommand::Role { username, role } => { patch(username, UserPatch { role: Some(role.clone()), ..Default::default() }, &format!("hat jetzt die Rolle {role}"))? } + UserCommand::Password { username, password } => { + svc.set_password(&username, &password)?; + println!("Passwort von {username} gesetzt"); + } UserCommand::Block { username } => patch( username, UserPatch { blocked: Some(true), ..Default::default() }, diff --git a/proxy/src/config.rs b/proxy/src/config.rs index d527744..bfc24df 100644 --- a/proxy/src/config.rs +++ b/proxy/src/config.rs @@ -19,9 +19,30 @@ pub struct Config { pub recording: RecordingConfig, #[serde(default)] pub dashboard: DashboardConfig, + #[serde(default)] + pub ui: UiConfig, pub nodes: Vec, } +/// Weboberfläche +#[derive(Debug, Deserialize, Clone)] +#[serde(deny_unknown_fields, default)] +pub struct UiConfig { + /// Anmeldung mit Benutzername und Passwort, nur zum Testen; im Betrieb melden sich Benutzer + /// mit Magic Link, Passkey oder 2FA an. + pub password_login: bool, + /// So lange gilt eine Anmeldung im Browser + pub session_days: u32, + /// Cookie nur über HTTPS senden; hinter einem HTTPS-Reverse-Proxy einschalten + pub secure_cookie: bool, +} + +impl Default for UiConfig { + fn default() -> Self { + Self { password_login: false, session_days: 7, secure_cookie: false } + } +} + /// Daten für die Dashboards #[derive(Debug, Deserialize, Clone)] #[serde(deny_unknown_fields, default)] diff --git a/proxy/src/db.rs b/proxy/src/db.rs index bcc8269..756ed33 100644 --- a/proxy/src/db.rs +++ b/proxy/src/db.rs @@ -817,6 +817,9 @@ fn has_column(conn: &Connection, table: &str, column: &str) -> Result { /// Ältere Datenbanken auf den aktuellen Stand bringen fn migrate(conn: &Connection) -> Result<()> { + if !has_column(conn, "users", "password_hash")? { + conn.execute("ALTER TABLE users ADD COLUMN password_hash TEXT", [])?; + } if !has_column(conn, "api_keys", "is_super")? { conn.execute("ALTER TABLE api_keys ADD COLUMN is_super INTEGER NOT NULL DEFAULT 0", [])?; } diff --git a/proxy/src/main.rs b/proxy/src/main.rs index 8ab98a1..ef9028f 100644 --- a/proxy/src/main.rs +++ b/proxy/src/main.rs @@ -12,6 +12,7 @@ mod routes; mod schedule; mod scheduler; mod service; +mod ui; use std::{path::PathBuf, sync::Arc, time::Duration}; @@ -130,6 +131,8 @@ enum UserCommand { List, /// Zum Lecturer oder Administrator ernennen oder zurückstufen Role { username: String, role: String }, + /// Passwort für die Anmeldung mit Passwort setzen (nur zum Testen, siehe ui.password_login) + Password { username: String, password: String }, /// Sperren: keine Anmeldung, Keys werden abgewiesen Block { username: String }, Unblock { username: String }, @@ -409,7 +412,8 @@ async fn serve(config: Config, db: Arc) -> Result<()> { } } }); - let app = routes::router(AppState { db, recorder, sched, http }); + let ui = Arc::new(config.ui.clone()); + let app = routes::router(AppState { db, ui, recorder, sched, http }); let listener = tokio::net::TcpListener::bind(&config.listen).await?; tracing::info!("Omega AI Proxy lauscht auf {}", config.listen); diff --git a/proxy/src/routes.rs b/proxy/src/routes.rs index 449a3cf..c683005 100644 --- a/proxy/src/routes.rs +++ b/proxy/src/routes.rs @@ -28,6 +28,7 @@ use crate::{ #[derive(Clone)] pub struct AppState { pub db: Arc, + pub ui: Arc, pub recorder: Arc, pub sched: Arc, /// Ohne Gesamt-Timeout, weil Antworten lange streamen können @@ -44,6 +45,7 @@ pub fn router(state: AppState) -> Router { .layer(middleware::from_fn_with_state(state.clone(), auth)); Router::new() .nest("/omega/api", crate::api::router(state.clone())) + .merge(crate::ui::router()) .merge(proxy) .layer(DefaultBodyLimit::max(256 * 1024 * 1024)) .with_state(state) @@ -150,6 +152,13 @@ async fn ollama( body: Bytes, ) -> Response { let path = uri.path().to_string(); + // Ein Browser auf der Wurzel bekommt die Oberfläche; Ollama-Clients erwarten hier die API. + if path == "/" + && method == Method::GET + && headers.get(header::ACCEPT).and_then(|v| v.to_str().ok()).is_some_and(|a| a.contains("text/html")) + { + return axum::response::Redirect::temporary("/omega/").into_response(); + } if path.starts_with("/api/blobs") || matches!(path.as_str(), "/api/pull" | "/api/push" | "/api/delete" | "/api/copy" | "/api/create") { diff --git a/proxy/src/service.rs b/proxy/src/service.rs index 0f0accc..0ed48e4 100644 --- a/proxy/src/service.rs +++ b/proxy/src/service.rs @@ -429,6 +429,18 @@ impl<'a> Service<'a> { self.user(username) } + /// Passwort setzen: Administratoren für alle, sonst nur das eigene + pub fn set_password(&self, username: &str, password: &str) -> Result<()> { + if self.actor.role() < Role::Admin && self.who() != username { + return Err(forbidden("nur das eigene Passwort, außer als Administrator")); + } + if password.chars().count() < 4 { + return Err(invalid("das Passwort braucht mindestens 4 Zeichen")); + } + self.user(username)?; + self.db.set_password(self.who(), username, password) + } + // Gruppen (Lecturer) pub fn create_group(&self, name: &str) -> Result { diff --git a/proxy/src/ui.rs b/proxy/src/ui.rs new file mode 100644 index 0000000..f31d85a --- /dev/null +++ b/proxy/src/ui.rs @@ -0,0 +1,67 @@ +//! Weboberfläche unter /omega/. HTML, CSS, JavaScript und Schriften sind ins Programm +//! eingebettet; die Content-Security-Policy erlaubt dem Browser nur Anfragen an den Proxy selbst. + +use axum::{ + Router, + extract::Path, + http::{StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::get, +}; + +use crate::routes::AppState; + +const INDEX: &str = include_str!("../ui/index.html"); + +/// Eingebettete Dateien: Name, Medientyp, Inhalt +const ASSETS: &[(&str, &str, &[u8])] = &[ + ("app.css", "text/css; charset=utf-8", include_bytes!("../ui/app.css")), + ("app.js", "text/javascript; charset=utf-8", include_bytes!("../ui/app.js")), + ("ibm-plex-sans-400.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-sans-400.woff2")), + ("ibm-plex-sans-500.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-sans-500.woff2")), + ("ibm-plex-sans-600.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-sans-600.woff2")), + ("ibm-plex-mono-400.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-mono-400.woff2")), + ("ibm-plex-mono-500.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-mono-500.woff2")), + ("ibm-plex-mono-600.woff2", "font/woff2", include_bytes!("../ui/fonts/ibm-plex-mono-600.woff2")), +]; + +/// Nur Inhalte vom Proxy selbst; keine fremden Schriften, Skripte oder Verbindungen +const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; \ + connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"; + +pub fn router() -> Router { + Router::new() + .route("/omega", get(|| async { Redirect::permanent("/omega/") })) + .route("/omega/", get(index)) + .route("/omega/assets/{name}", get(asset)) +} + +fn security_headers() -> [(header::HeaderName, &'static str); 4] { + [ + (header::CONTENT_SECURITY_POLICY, CSP), + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + (header::REFERRER_POLICY, "no-referrer"), + (header::X_FRAME_OPTIONS, "DENY"), + ] +} + +async fn index() -> Response { + ( + security_headers(), + [(header::CONTENT_TYPE, "text/html; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], + INDEX, + ) + .into_response() +} + +async fn asset(Path(name): Path) -> Response { + match ASSETS.iter().find(|(n, _, _)| *n == name) { + Some((_, mime, body)) => ( + security_headers(), + [(header::CONTENT_TYPE, *mime), (header::CACHE_CONTROL, "no-cache")], + *body, + ) + .into_response(), + None => StatusCode::NOT_FOUND.into_response(), + } +} diff --git a/proxy/ui/app.css b/proxy/ui/app.css new file mode 100644 index 0000000..b8e3fba --- /dev/null +++ b/proxy/ui/app.css @@ -0,0 +1,205 @@ +/* Omega AI Proxy – Oberfläche. Farben, Schriften und Bausteine nach den UI-Mockups. + Alle Schriften liegen im Proxy; der Browser lädt nichts von außen. */ + +@font-face { font-family: 'IBM Plex Sans'; font-weight: 400; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-sans-400.woff2) format('woff2'); } +@font-face { font-family: 'IBM Plex Sans'; font-weight: 500; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-sans-500.woff2) format('woff2'); } +@font-face { font-family: 'IBM Plex Sans'; font-weight: 600; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-sans-600.woff2) format('woff2'); } +@font-face { font-family: 'IBM Plex Mono'; font-weight: 400; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-mono-400.woff2) format('woff2'); } +@font-face { font-family: 'IBM Plex Mono'; font-weight: 500; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-mono-500.woff2) format('woff2'); } +@font-face { font-family: 'IBM Plex Mono'; font-weight: 600; font-style: normal; font-display: swap; src: url(/omega/assets/ibm-plex-mono-600.woff2) format('woff2'); } + +:root { + --bg: #141518; + --panel: #1b1c20; + --panel-2: #17181c; + --sunken: #131417; + --line: #2c2f35; + --line-2: #383b43; + --line-3: #34373e; + --hover: #26282d; + --raised: #22242a; + --text: #e6e7ea; + --text-2: #c3c7ce; + --text-3: #b9bec6; + --muted: #9aa0aa; + --cap: #8d939d; + --accent: #f08a3c; + --accent-2: #ffb27a; + --accent-bg: #3a2a1e; + --accent-text: #ffe2c6; + --accent-ink: #1a1209; + --good: #9fd69a; + --good-bg: #17241a; + --bad: #f0a098; + --bad-bg: #2e1a18; + --ollama: #5fb4ff; + --llama: #b48cf0; + --vllm: #ffd166; + --sans: 'IBM Plex Sans', system-ui, sans-serif; + --mono: 'IBM Plex Mono', ui-monospace, monospace; +} + +* { box-sizing: border-box; } +html, body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--sans); font-size: 14px; } +a { color: var(--accent); } +a:hover { color: var(--accent-2); } +h1, h2, h3 { margin: 0; } +.mono { font-family: var(--mono); } +.muted { color: var(--muted); } +.cap { font-size: 11px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: var(--cap); } +.loading { padding: 40px; color: var(--muted); } +.sr-only { position: absolute; left: -9999px; } + +/* Gerüst mit Seitenleiste */ +.shell { min-height: 100vh; display: flex; flex-wrap: wrap; } +.side { flex: 1 1 240px; max-width: 280px; background: var(--panel); border-right: 1px solid var(--line); padding: 20px 14px; display: flex; flex-direction: column; gap: 24px; } +.main { flex: 999 1 560px; min-width: 0; padding: 28px 32px 48px; display: flex; flex-direction: column; gap: 20px; } +.brand { display: flex; align-items: center; gap: 10px; padding: 0 6px; } +.logo { width: 34px; height: 34px; border-radius: 8px; background: #2c2117; color: var(--accent); display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 600; flex: 0 0 auto; } +.logo.big { width: 44px; height: 44px; border-radius: 10px; font-size: 26px; } +.brand-name { display: flex; flex-direction: column; } +.brand-name b { font-size: 15px; font-weight: 600; } +.brand-name span { font-size: 12px; color: var(--muted); } +.nav { display: flex; flex-direction: column; gap: 2px; } +.nav .cap { padding: 14px 10px 6px; } +.nav .cap:first-child { padding-top: 6px; } +.nav a { display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 6px; color: var(--text-2); text-decoration: none; font-size: 14px; } +.nav a:hover { background: var(--hover); color: var(--text); } +.nav a.on { background: var(--accent-bg); color: var(--accent-text); } +.nav svg { flex: 0 0 auto; } +.me { margin-top: auto; display: flex; align-items: center; gap: 10px; padding: 12px 8px 0; border-top: 1px solid var(--line); } +.avatar { width: 32px; height: 32px; border-radius: 50%; background: var(--raised); border: 1px solid var(--line-2); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 600; color: var(--text-2); flex: 0 0 auto; } +.me-name { display: flex; flex-direction: column; min-width: 0; flex: 1; } +.me-name b { font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; } +.me-name span { font-size: 12px; color: var(--muted); } +.menu-toggle { display: none; } + +/* Kopf einer Seite */ +.page-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; } +.page-head h1 { margin-top: 4px; font-size: 26px; font-weight: 600; letter-spacing: -0.01em; } +.page-head p { margin: 6px 0 0; color: var(--muted); } +.actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } + +/* Bausteine */ +.btn { font: 500 14px var(--sans); min-height: 40px; padding: 0 14px; border-radius: 6px; border: 1px solid var(--line-3); background: var(--raised); color: var(--text); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; white-space: nowrap; } +.btn:hover { background: var(--hover); color: var(--text); } +.btn:disabled { opacity: .5; cursor: default; } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; } +.btn.primary:hover { background: var(--accent-2); color: var(--accent-ink); } +.btn.danger { border-color: #5a2c28; color: var(--bad); } +.btn.danger:hover { background: var(--bad-bg); } +.btn.small { min-height: 32px; padding: 0 10px; font-size: 13px; } +.btn.wide { width: 100%; min-height: 44px; } +.btn.icon { width: 40px; padding: 0; } +.btn.icon.small { width: 32px; } +.stack { display: flex; flex-direction: column; gap: 20px; min-width: 0; } +.row { display: flex; flex-wrap: wrap; gap: 12px; } +.row.top { align-items: flex-start; } +.grow { flex: 1 1 320px; min-width: 0; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 18px 20px; display: flex; flex-direction: column; gap: 14px; min-width: 0; } +.card h2 { font-size: 15px; font-weight: 600; } +.card-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; } +.kpis { display: flex; flex-wrap: wrap; gap: 12px; } +.kpi { flex: 1 1 180px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px 18px; display: flex; flex-direction: column; gap: 6px; } +.kpi > span:first-child { font-size: 13px; color: var(--muted); } +.kpi .value { font-family: var(--mono); font-size: 26px; font-weight: 500; } +.kpi .value.accent { color: var(--accent); } +.kpi .value.bad { color: var(--bad); } +.kpi .sub { font-size: 13px; color: var(--muted); } +.chip { display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 9px; border-radius: 999px; font-size: 12px; font-weight: 500; white-space: nowrap; background: var(--raised); color: var(--text-2); } +.chip.ollama { background: rgba(95,180,255,.14); color: #8ccaff; } +.chip.llamacpp { background: rgba(180,140,240,.16); color: #cdb4f6; } +.chip.vllm { background: rgba(255,209,102,.14); color: #ffd98a; } +.chip.good { background: var(--good-bg); color: var(--good); } +.chip.bad { background: var(--bad-bg); color: var(--bad); } +.chip.accent { background: var(--accent-bg); color: var(--accent-text); } +.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); display: inline-block; } +.dot.good { background: var(--good); } +.dot.accent { background: var(--accent); } +.dot.bad { background: var(--bad); } +.status { display: inline-flex; align-items: center; gap: 6px; } +.empty { color: var(--muted); padding: 8px 0; } + +/* Tabellen */ +.table-wrap { overflow-x: auto; } +table { border-collapse: collapse; width: 100%; } +th { text-align: left; font-size: 12px; font-weight: 500; color: var(--muted); padding: 8px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; } +td { padding: 10px 12px; border-bottom: 1px solid var(--line); font-size: 14px; vertical-align: middle; white-space: nowrap; } +tr:last-child td { border-bottom: 0; } +td.num, th.num { text-align: right; font-family: var(--mono); } +td.wrap { white-space: normal; } +tr.dim td { color: var(--muted); } +td .actions { justify-content: flex-end; flex-wrap: nowrap; } + +/* Formulare */ +form { display: flex; flex-direction: column; gap: 14px; } +.fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; } +.field-group { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +label { font-size: 13px; color: var(--text-3); } +.hint { font-size: 12px; color: var(--muted); } +.field { font: 14px var(--sans); width: 100%; height: 40px; padding: 0 12px; background: var(--sunken); border: 1px solid var(--line-2); border-radius: 6px; color: var(--text); } +textarea.field { height: auto; min-height: 72px; padding: 10px 12px; resize: vertical; } +.field:focus { outline: none; border-color: var(--accent); } +.field.mono { font-family: var(--mono); } +fieldset { border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px 14px; margin: 0; display: flex; flex-direction: column; gap: 12px; min-width: 0; } +legend { padding: 0 6px; font-size: 13px; color: var(--text-3); } +.check { display: flex; align-items: center; gap: 8px; } + +/* Meldungen */ +.notice { border-radius: 8px; padding: 12px 14px; font-size: 14px; border: 1px solid var(--line); background: var(--panel-2); display: flex; gap: 10px; align-items: flex-start; } +.notice.error { border-color: #5a2c28; background: var(--bad-bg); color: var(--bad); } +.notice.ok { border-color: #2b4430; background: var(--good-bg); color: var(--good); } +.notice.warn { border-color: #5a4126; background: #2a2017; color: var(--accent-text); } +.secret { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; background: var(--sunken); border: 1px solid var(--line-2); border-radius: 8px; padding: 12px 14px; } +.secret code { font-family: var(--mono); font-size: 14px; word-break: break-all; flex: 1 1 280px; } + +/* Fortschritt und Speicher */ +.meter { display: flex; flex-direction: column; gap: 5px; } +.meter-head { display: flex; justify-content: space-between; gap: 8px; font-size: 13px; } +.meter-head .mono { color: var(--text-2); } +.track { height: 6px; border-radius: 3px; background: var(--line); overflow: hidden; } +.track > div { height: 6px; border-radius: 3px; background: var(--accent); } +.track > div.full { background: var(--bad); } +.membar { display: flex; gap: 2px; height: 34px; border-radius: 6px; overflow: hidden; background: var(--sunken); border: 1px solid var(--line); padding: 2px; } +.membar > div { border-radius: 4px; font-family: var(--mono); font-size: 12px; font-weight: 500; display: flex; align-items: center; padding: 0 8px; overflow: hidden; white-space: nowrap; min-width: 3px; } +.membar .ollama { background: var(--ollama); color: #0b1a29; } +.membar .llamacpp { background: var(--llama); color: #1c1029; } +.membar .vllm { background: var(--vllm); color: #2a1f05; } +.membar .loading { opacity: .55; } +.legend { display: flex; flex-wrap: wrap; gap: 18px; font-size: 12px; color: var(--muted); } +.legend span { display: inline-flex; align-items: center; gap: 6px; } +.swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; } +.swatch.ollama { background: var(--ollama); } +.swatch.llamacpp { background: var(--llama); } +.swatch.vllm { background: var(--vllm); } +.swatch.free { border: 1px solid var(--line-2); } + +/* Diagramme */ +.chart { display: flex; align-items: flex-end; gap: 4px; height: 200px; border-bottom: 1px solid var(--line-2); } +.chart > div { flex: 1; min-height: 1px; border-radius: 3px 3px 0 0; background: #6b4a2c; } +.chart > div.now { background: var(--accent); } +.chart-axis { display: flex; justify-content: space-between; font-family: var(--mono); font-size: 11px; color: var(--muted); } +.events { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; font-size: 13px; } +.events li { display: flex; gap: 12px; } +.events .mono { color: var(--muted); flex: 0 0 auto; } +details summary { cursor: pointer; color: var(--text-2); } +pre.settings { margin: 8px 0 0; background: var(--sunken); border: 1px solid var(--line); border-radius: 6px; padding: 10px 12px; font: 12px var(--mono); color: var(--text-2); white-space: pre-wrap; } + +/* Anmeldung */ +.login { min-height: 100vh; display: flex; flex-wrap: wrap; } +.login-panel { flex: 1 1 420px; display: flex; align-items: center; justify-content: center; padding: 48px 24px; background: var(--panel); border-right: 1px solid var(--line); } +.login-box { width: 100%; max-width: 380px; display: flex; flex-direction: column; gap: 28px; } +.login-box h1 { font-size: 24px; font-weight: 600; } +.login-public { flex: 999 1 560px; min-width: 0; padding: 48px; display: flex; flex-direction: column; justify-content: center; gap: 24px; } +.privacy { margin: 0; display: flex; gap: 10px; font-size: 12px; line-height: 1.5; color: var(--muted); } + +/* Schmale Bildschirme: Seitenleiste wird zur Kopfleiste mit Menü */ +@media (max-width: 860px) { + .side { flex: 1 1 100%; max-width: none; border-right: 0; border-bottom: 1px solid var(--line); padding: 12px 16px; gap: 12px; } + .side .brand { justify-content: space-between; } + .menu-toggle { display: inline-flex; } + .side .nav, .side .me { display: none; } + .side.open .nav, .side.open .me { display: flex; } + .main { padding: 20px 16px 40px; } + .login-public { padding: 32px 16px; } +} diff --git a/proxy/ui/app.js b/proxy/ui/app.js new file mode 100644 index 0000000..2c5025b --- /dev/null +++ b/proxy/ui/app.js @@ -0,0 +1,865 @@ +// Omega AI Proxy – Oberfläche. Eine kleine Single-Page-App ohne Bibliotheken über der +// Verwaltungs-API unter /omega/api. Inhalte vom Server kommen nur als Text ins DOM. +'use strict'; + +// ---------- Werkzeuge ---------- + +const app = document.getElementById('app'); +const state = { me: null, flash: null }; + +/** Element bauen: h('div', { class: 'x', onclick: f, style: { width: '5%' } }, kind1, 'Text', …) */ +function h(tag, props, ...children) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(props || {})) { + if (v === null || v === undefined || v === false) continue; + if (k === 'class') el.className = v; + else if (k === 'style') Object.assign(el.style, v); + else if (k.startsWith('on')) el.addEventListener(k.slice(2), v); + else if (k === 'value') el.value = v; + else if (k === 'checked' || k === 'selected' || k === 'disabled') el[k] = !!v; + else el.setAttribute(k, v === true ? '' : v); + } + append(el, children); + return el; +} + +function append(el, children) { + for (const c of children.flat(Infinity)) { + if (c === null || c === undefined || c === false) continue; + el.append(c instanceof Node ? c : document.createTextNode(String(c))); + } +} + +const SVG = 'http://www.w3.org/2000/svg'; +const ICONS = { + overview: ['rect 2 2 5 5', 'rect 9 2 5 5', 'rect 2 9 5 5', 'rect 9 9 5 5'], + keys: ['circle 5 11 3', 'path M7.2 8.8 13 3M11 5l2 2'], + account: ['path M8 1.5 13.5 3.5v4c0 3.5-2.4 5.9-5.5 7-3.1-1.1-5.5-3.5-5.5-7v-4z'], + groups: ['circle 6 5.5 2.5', 'path M1.5 14c.5-2.5 2.3-4 4.5-4s4 1.5 4.5 4M10.5 3.2a2.5 2.5 0 0 1 0 4.6M12 10.2c1.4.5 2.3 1.9 2.5 3.8'], + status: ['rect 2 2.5 12 4.5', 'rect 2 9 12 4.5', 'path M4.5 4.75h.01M4.5 11.25h.01'], + schedule: ['rect 2 3 12 11', 'path M2 6.5h12M5.5 1.5v3M10.5 1.5v3'], + users: ['circle 8 5.5 3', 'path M2.5 14.5c.6-3 2.8-4.5 5.5-4.5s4.9 1.5 5.5 4.5'], + audit: ['path M5 4h9M5 8h9M5 12h9M2 4h.01M2 8h.01M2 12h.01'], + public: ['path M2 14h12M4 11V7M8 11V3M12 11V8'], + menu: ['path M2 4h12M2 8h12M2 12h12'], + lock: ['rect 3 7 10 7', 'path M5 7V5a3 3 0 0 1 6 0v2'], +}; + +function icon(name, size = 16) { + const svg = document.createElementNS(SVG, 'svg'); + for (const [k, v] of Object.entries({ width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', + 'stroke-width': '1.5', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(k, v); + for (const part of ICONS[name] || []) { + const [kind, ...a] = part.split(' '); + const el = document.createElementNS(SVG, kind); + if (kind === 'rect') { el.setAttribute('x', a[0]); el.setAttribute('y', a[1]); el.setAttribute('width', a[2]); el.setAttribute('height', a[3]); el.setAttribute('rx', '1'); } + if (kind === 'circle') { el.setAttribute('cx', a[0]); el.setAttribute('cy', a[1]); el.setAttribute('r', a[2]); } + if (kind === 'path') el.setAttribute('d', a.join(' ')); + svg.append(el); + } + return svg; +} + +const nf = new Intl.NumberFormat('de-DE'); +const num = (n) => nf.format(n || 0); +function tokens(n) { + n = n || 0; + if (n >= 1e6) return (n / 1e6).toLocaleString('de-DE', { maximumFractionDigits: 2 }) + ' M'; + if (n >= 1e4) return Math.round(n / 1e3).toLocaleString('de-DE') + ' k'; + return num(n); +} +function mb(n) { + if (n === null || n === undefined) return '–'; + return n >= 1024 ? (n / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' GB' : num(n) + ' MB'; +} +function when(ts) { + if (!ts) return '–'; + return new Date(ts * 1000).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); +} +function clock(ts) { + return new Date(ts * 1000).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' }); +} +const tok = (c) => (c ? c.prompt_tokens + c.completion_tokens : 0); +const ROLE = { user: 'User', lecturer: 'Lecturer', admin: 'Administrator' }; +const ENGINE = { ollama: 'Ollama', llamacpp: 'llama.cpp', vllm: 'vLLM' }; +const PERIOD = { hour: 'Stunde', day: 'Tag', week: 'Woche', month: 'Monat', total: 'gesamt' }; +const role = () => (state.me && state.me.user ? state.me.user.role : null); +const atLeast = (r) => ({ user: 1, lecturer: 2, admin: 3 }[role()] || 0) >= ({ user: 1, lecturer: 2, admin: 3 }[r]); + +// ---------- Verbindung zur API ---------- + +class ApiError extends Error { + constructor(status, message) { super(message); this.status = status; } +} + +async function api(method, path, body, quiet) { + const res = await fetch('/omega/api' + path, { + method, + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', 'X-Omega-CSRF': '1' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await res.text(); + let data = null; + try { data = text ? JSON.parse(text) : null; } catch { data = text; } + if (!res.ok) { + const message = (data && data.error) || res.statusText || 'Fehler'; + if (res.status === 401 && !quiet && path !== '/login') { state.me = null; go('login'); } + throw new ApiError(res.status, message); + } + return data; +} + +/** Aktion mit Rückmeldung oben auf der Seite; lädt danach die Seite neu. */ +async function act(fn, ok) { + try { + const result = await fn(); + if (ok) state.flash = { kind: 'ok', text: typeof ok === 'function' ? ok(result) : ok }; + await render(); + return result; + } catch (e) { + state.flash = { kind: 'error', text: e.message }; + await render(); + return null; + } +} + +function formData(form) { + const data = {}; + for (const el of form.elements) { + if (!el.name) continue; + if (el.type === 'checkbox') data[el.name] = el.checked; + else data[el.name] = el.value.trim(); + } + return data; +} +const optional = (v) => (v === '' || v === undefined ? undefined : v); +const optNum = (v) => (v === '' || v === undefined ? undefined : Number(v)); +const list = (v) => (v ? v.split(/[\s,;]+/).filter(Boolean) : []); + +// ---------- Navigation ---------- + +function route() { + const hash = location.hash.replace(/^#\/?/, ''); + const [page, ...rest] = hash.split('/'); + return { page: page || '', arg: rest.map(decodeURIComponent).join('/') }; +} +function go(page) { location.hash = '#/' + page; } +window.addEventListener('hashchange', () => render()); + +const PAGES = { + '': { title: 'Übersicht', icon: 'overview', render: overview, section: 'Persönlich' }, + keys: { title: 'API-Keys', icon: 'keys', render: keysPage, section: 'Persönlich' }, + account: { title: 'Konto & Sicherheit', icon: 'account', render: accountPage, section: 'Persönlich' }, + groups: { title: 'Gruppen & Kontingente', icon: 'groups', render: groupsPage, section: 'Lehre', role: 'lecturer' }, + group: { render: groupPage, parent: 'groups', role: 'lecturer' }, + quota: { render: quotaPage, parent: 'groups' }, + status: { title: 'Sparks & Modelle', icon: 'status', render: statusPage, section: 'Administration', role: 'admin' }, + schedule: { title: 'Zeitplan', icon: 'schedule', render: schedulePage, section: 'Administration', role: 'admin' }, + users: { title: 'Benutzer', icon: 'users', render: usersPage, section: 'Administration', role: 'admin' }, + audit: { title: 'Audit-Log', icon: 'audit', render: auditPage, section: 'Administration', role: 'admin' }, + public: { title: 'Öffentliches Dashboard', icon: 'public', render: publicPage, section: 'Administration', open: true }, +}; + +function initials(name) { + return name.split(/[^a-zA-Z]/).filter(Boolean).map((p) => p[0]).join('').slice(0, 2).toUpperCase() || name.slice(0, 2).toUpperCase(); +} + +function shell(current, content) { + const nav = h('nav', { class: 'nav', 'aria-label': 'Hauptnavigation' }); + let section = null; + for (const [key, p] of Object.entries(PAGES)) { + if (!p.title || (p.role && !atLeast(p.role))) continue; + // Ohne Administration hängt das öffentliche Dashboard am letzten Bereich. + const sec = key === 'public' && !atLeast('admin') ? section : p.section; + if (sec !== section) { nav.append(h('span', { class: 'cap' }, sec)); section = sec; } + const on = current === key || PAGES[current] && PAGES[current].parent === key; + nav.append(h('a', { href: '#/' + key, class: on ? 'on' : null, 'aria-current': on ? 'page' : null }, icon(p.icon), p.title)); + } + const user = state.me.user; + const side = h('aside', { class: 'side' }, + h('div', { class: 'brand' }, + h('div', { class: 'brand' }, h('div', { class: 'logo' }, 'Ω'), h('div', { class: 'brand-name' }, h('b', {}, 'Omega AI Proxy'), h('span', {}, 'Fakultät EFI'))), + h('button', { class: 'btn icon small menu-toggle', type: 'button', 'aria-label': 'Menü', onclick: () => side.classList.toggle('open') }, icon('menu'))), + nav, + h('div', { class: 'me' }, + h('div', { class: 'avatar' }, initials(user.username)), + h('div', { class: 'me-name' }, h('b', {}, user.username), h('span', {}, ROLE[user.role])), + h('button', { class: 'btn small', type: 'button', onclick: logout }, 'Abmelden'))); + nav.addEventListener('click', () => side.classList.remove('open')); + return h('div', { class: 'shell' }, side, h('main', { class: 'main' }, flash(), content)); +} + +function flash() { + if (!state.flash) return null; + const { kind, text } = state.flash; + state.flash = null; + return h('div', { class: 'notice ' + kind, role: kind === 'error' ? 'alert' : 'status' }, text); +} + +function head(section, title, sub, ...actions) { + return h('header', { class: 'page-head' }, + h('div', {}, h('div', { class: 'cap' }, section), h('h1', {}, title), sub ? h('p', {}, sub) : null), + actions.length ? h('div', { class: 'actions' }, actions) : null); +} + +async function render() { + const { page, arg } = route(); + const def = PAGES[page] || PAGES['']; + if (!state.me) { + try { state.me = await api('GET', '/me', undefined, true); } catch { state.me = null; } + } + if (!state.me) { + // Ohne Anmeldung gibt es nur das öffentliche Dashboard und die Anmeldung. + if (page === 'public') { + app.replaceChildren(h('main', { class: 'main' }, await publicContent())); + return; + } + return renderLogin(); + } + if (page === 'login') return go(''); + if (def.role && !atLeast(def.role)) return go(''); + let content; + try { + content = await def.render(arg); + } catch (e) { + content = h('div', { class: 'notice error', role: 'alert' }, e.message); + } + app.replaceChildren(shell(page in PAGES ? page : '', content)); + document.title = (def.title || 'Omega AI Proxy') + ' · Omega AI Proxy'; +} + +async function logout() { + try { await api('POST', '/logout'); } catch { /* abgemeldet ist abgemeldet */ } + state.me = null; + go('login'); + render(); +} + +// ---------- Anmeldung ---------- + +async function renderLogin() { + const error = h('div', { class: 'notice error', role: 'alert', hidden: true }); + const form = h('form', { + onsubmit: async (e) => { + e.preventDefault(); + const d = formData(form); + try { + await api('POST', '/login', { username: d.username, password: d.password }); + state.me = await api('GET', '/me'); + go(''); + render(); + } catch (err) { + error.textContent = err.message; + error.hidden = false; + } + }, + }, + h('div', { class: 'field-group' }, h('label', { for: 'user' }, 'Benutzername'), + h('input', { id: 'user', name: 'username', class: 'field mono', autocomplete: 'username', required: true, autofocus: true })), + h('div', { class: 'field-group' }, h('label', { for: 'password' }, 'Passwort'), + h('input', { id: 'password', name: 'password', type: 'password', class: 'field', autocomplete: 'current-password', required: true })), + error, + h('button', { class: 'btn primary wide', type: 'submit' }, 'Anmelden'), + h('span', { class: 'hint' }, 'Testbetrieb: Anmeldung mit Passwort. Später mit Passkey, Magic Link oder 2FA-Code.')); + + let pub; + try { pub = await publicContent(); } catch { pub = h('p', { class: 'muted' }, 'Auslastung nicht verfügbar.'); } + app.replaceChildren(h('div', { class: 'login' }, + h('section', { class: 'login-panel' }, + h('div', { class: 'login-box' }, + h('div', { class: 'brand' }, h('div', { class: 'logo big' }, 'Ω'), + h('div', { class: 'brand-name' }, h('b', {}, 'Omega AI Proxy'), h('span', {}, 'KI-Modelle der Fakultät EFI'))), + h('div', {}, h('h1', {}, 'Anmelden'), h('p', { class: 'muted' }, 'Mit deinem Benutzernamen der Hochschule.')), + form, + h('p', { class: 'privacy' }, icon('lock'), + 'Anfragen und Antworten werden nicht gespeichert. Der Proxy erfasst nur Metadaten wie Modell, Token und Zeitpunkt.'))), + h('section', { class: 'login-public' }, pub))); + document.title = 'Anmelden · Omega AI Proxy'; +} + +// ---------- Öffentliches Dashboard ---------- + +/** Balkendiagramm aus Werten; der letzte Balken ist hervorgehoben. */ +function bars(values, label, axis) { + const max = Math.max(1, ...values); + return [ + h('div', { class: 'chart', role: 'img', 'aria-label': label }, + values.map((v, i) => h('div', { class: i === values.length - 1 ? 'now' : null, style: { height: (v / max * 100) + '%' }, title: num(v) }))), + axis ? h('div', { class: 'chart-axis' }, axis.map((a) => h('span', {}, a))) : null, + ]; +} + +async function publicContent() { + const pub = await api('GET', '/public/dashboard?hours=24'); + // Letzte Probe je Rechner + const latest = {}; + for (const s of pub.samples) latest[s.node] = s; + const nodes = Object.values(latest); + const budget = nodes.reduce((a, s) => a + (s.budget_mb || 0), 0); + const used = nodes.reduce((a, s) => a + s.used_mb, 0); + const share = budget ? Math.round(used / budget * 100) : 0; + const hourly = pub.hourly; + const total = hourly.reduce((a, x) => a + x.requests, 0); + const peak = hourly.reduce((a, x) => (x.requests > a.requests ? x : a), hourly[0] || { requests: 0, hour: '' }); + const waiting = nodes.reduce((a, s) => a + s.waiting, 0); + return h('div', { class: 'stack' }, + h('div', {}, h('div', { class: 'cap' }, 'Öffentlich · ohne Anmeldung'), h('h1', {}, 'Auslastung')), + h('div', { class: 'kpis' }, + h('div', { class: 'kpi' }, h('span', {}, 'Speicher gerade'), h('span', { class: 'value accent' }, share + ' %'), h('span', { class: 'sub' }, mb(used) + ' von ' + mb(budget))), + h('div', { class: 'kpi' }, h('span', {}, 'Anfragen 24 h'), h('span', { class: 'value' }, num(total))), + h('div', { class: 'kpi' }, h('span', {}, 'Meiste Anfragen'), h('span', { class: 'value' }, peak && peak.requests ? peak.hour.slice(11, 16) + ' Uhr' : '–')), + h('div', { class: 'kpi' }, h('span', {}, 'Warteschlange'), h('span', { class: 'value' }, num(waiting)))), + h('figure', { class: 'card' }, + h('figcaption', { class: 'card-head' }, h('b', {}, 'Letzte 24 Stunden'), h('span', { class: 'muted' }, 'Anfragen je Stunde')), + bars(hourly.map((x) => x.requests), 'Anfragen je Stunde der letzten 24 Stunden', + hourly.length ? [hourly[0].hour.slice(11, 16), hourly[Math.floor(hourly.length / 2)].hour.slice(11, 16), 'jetzt'] : [])), + h('div', { class: 'row' }, nodes.map((s) => h('div', { class: 'card grow' }, + h('div', { class: 'card-head' }, h('h2', { class: 'mono' }, s.node), h('span', { class: 'mono muted' }, mb(s.used_mb) + ' / ' + mb(s.budget_mb))), + meter('Speicher', s.used_mb, s.budget_mb, mb), + h('span', { class: 'muted' }, s.loaded + ' Modelle geladen · ' + s.in_flight + ' Anfragen laufen · ' + s.waiting + ' warten'))))); +} + +async function publicPage() { + return publicContent(); +} + +// ---------- Bausteine für Verbrauch ---------- + +function meter(label, used, limit, fmt = num) { + const share = limit ? Math.min(100, used / limit * 100) : 0; + return h('div', { class: 'meter' }, + h('div', { class: 'meter-head' }, h('span', {}, label), h('span', { class: 'mono' }, fmt(used) + (limit ? ' / ' + fmt(limit) : ''))), + h('div', { class: 'track' }, h('div', { class: share >= 90 ? 'full' : null, style: { width: share + '%' } }))); +} + +/** Fortschritt eines Kontingents für alle begrenzten Zeiträume */ +function quotaMeters(q, usage) { + const rows = []; + for (const p of Object.keys(PERIOD)) { + if (q.tokens[p] != null) rows.push(meter('Token · ' + PERIOD[p], tok(usage[p]), q.tokens[p], tokens)); + if (q.requests[p] != null) rows.push(meter('Anfragen · ' + PERIOD[p], usage[p].requests, q.requests[p])); + } + if (!rows.length) rows.push(h('span', { class: 'muted' }, 'Ohne Mengengrenzen · ' + tokens(tok(usage.total)) + ' Token insgesamt')); + return rows; +} + +function keyState(k) { + if (k.key.revoked) return h('span', { class: 'muted' }, 'widerrufen'); + if (k.recording) return h('span', { class: 'status' }, h('span', { class: 'dot accent' }), k.recording); + return h('span', { class: 'status' }, h('span', { class: 'dot good' }), 'aktiv'); +} + +function quotaLabel(k) { + if (k.key.is_super) return h('span', { class: 'chip accent' }, 'Super-Key'); + if (!k.quota) return h('span', { class: 'muted' }, 'unbegrenzt'); + return k.quota.name; +} + +// ---------- Übersicht ---------- + +async function overview() { + const me = state.me = await api('GET', '/me'); + const active = me.keys.filter((k) => !k.key.revoked); + const sum = (f) => active.reduce((a, k) => a + f(k.usage), 0); + const parts = [ + head('Persönlich', 'Übersicht', 'Deine Nutzung über alle Keys.'), + h('div', { class: 'kpis' }, + h('div', { class: 'kpi' }, h('span', {}, 'Token heute'), h('span', { class: 'value' }, tokens(sum((u) => tok(u.day))))), + h('div', { class: 'kpi' }, h('span', {}, 'Anfragen heute'), h('span', { class: 'value' }, num(sum((u) => u.day.requests)))), + h('div', { class: 'kpi' }, h('span', {}, 'Token diesen Monat'), h('span', { class: 'value' }, tokens(sum((u) => tok(u.month))))), + h('div', { class: 'kpi' }, h('span', {}, 'Aktive Keys'), h('span', { class: 'value' }, num(active.length)))), + ]; + const quotaCard = h('section', { class: 'card grow' }, h('h2', {}, 'Kontingente'), + me.quotas.length ? me.quotas.map((q) => h('div', { class: 'meter' }, + h('b', {}, q.name), h('span', { class: 'hint' }, q.describe), quotaMeters(q, q.usage[0].usage))) + : h('p', { class: 'empty' }, atLeast('lecturer') ? 'Dir ist kein Kontingent zugeteilt; als ' + ROLE[role()] + ' kannst du unbegrenzte Keys anlegen.' + : 'Dir ist noch kein Kontingent zugeteilt. Sobald dich eine Lehrkraft in eine Gruppe aufnimmt, kannst du Keys anlegen.')); + parts.push(h('div', { class: 'row top' }, keysTableCard(me.keys, true), quotaCard)); + if (me.managed) { + parts.push(h('section', { class: 'card' }, + h('div', { class: 'card-head' }, h('h2', {}, 'Meine Kontingente'), h('a', { href: '#/groups' }, 'Gruppen & Kontingente')), + me.managed.quotas.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Kontingent'), h('th', {}, 'Zugeteilt'), h('th', {}, 'Person'), h('th', { class: 'num' }, 'Token heute'), h('th', { class: 'num' }, 'Anfragen heute'), h('th', { class: 'num' }, 'Token gesamt'))), + h('tbody', {}, me.managed.quotas.flatMap((q) => (q.usage.length ? q.usage : [{ user: null, usage: null }]).map((p) => h('tr', {}, + h('td', {}, h('a', { href: '#/quota/' + q.id }, q.name)), h('td', {}, q.target || '–'), h('td', { class: 'mono' }, p.user || (p.usage ? '(ohne Inhaber)' : 'noch keine Nutzung')), + h('td', { class: 'num' }, p.usage ? tokens(tok(p.usage.day)) : '–'), h('td', { class: 'num' }, p.usage ? num(p.usage.day.requests) : '–'), + h('td', { class: 'num' }, p.usage ? tokens(tok(p.usage.total)) : '–'))))))) + : h('p', { class: 'empty' }, 'Noch keine Kontingente. Lege unter Gruppen & Kontingente eine Gruppe und ein Kontingent an.'))); + } + if (me.system) { + const s = me.system; + parts.push(h('section', { class: 'card' }, + h('div', { class: 'card-head' }, h('h2', {}, 'System'), h('span', { class: 'muted' }, num(s.users) + ' Benutzer · ' + num(s.keys) + ' aktive Keys')), + h('div', { class: 'kpis' }, + h('div', { class: 'kpi' }, h('span', {}, 'Anfragen heute'), h('span', { class: 'value' }, num(s.usage.day.requests))), + h('div', { class: 'kpi' }, h('span', {}, 'Token heute'), h('span', { class: 'value' }, tokens(tok(s.usage.day)))), + h('div', { class: 'kpi' }, h('span', {}, 'Token gesamt'), h('span', { class: 'value' }, tokens(tok(s.usage.total))))), + bars(s.hourly.map((x) => x.requests), 'Anfragen je Stunde der letzten 24 Stunden', + s.hourly.length ? [s.hourly[0].hour.slice(11, 16), s.hourly[12].hour.slice(11, 16), 'jetzt'] : []))); + } + return h('div', { class: 'stack' }, parts); +} + +function keysTableCard(keys, compact) { + return h('section', { class: 'card grow' }, + h('div', { class: 'card-head' }, h('h2', {}, 'Keys'), compact ? h('a', { href: '#/keys' }, 'Alle Keys verwalten') : null), + keys.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Key'), h('th', {}, 'Kontingent'), h('th', { class: 'num' }, 'Token heute'), h('th', { class: 'num' }, 'Anfragen heute'), h('th', { class: 'num' }, 'Token gesamt'), h('th', {}, 'Status'))), + h('tbody', {}, keys.map((k) => h('tr', { class: k.key.revoked ? 'dim' : null }, + h('td', { class: 'mono' }, k.key.name), h('td', {}, quotaLabel(k)), + h('td', { class: 'num' }, tokens(tok(k.usage.day))), h('td', { class: 'num' }, num(k.usage.day.requests)), + h('td', { class: 'num' }, tokens(tok(k.usage.total))), h('td', {}, keyState(k))))))) + : h('p', { class: 'empty' }, 'Noch keine Keys.')); +} + +// ---------- API-Keys ---------- + +async function keysPage() { + const [keys, quotas, recordings] = await Promise.all([api('GET', '/keys'), api('GET', '/quotas'), api('GET', '/recordings')]); + const me = state.me.user; + const own = keys.filter((k) => k.key.user_id === me.id); + const others = keys.filter((k) => k.key.user_id !== me.id); + const usable = quotas; + const created = state.createdKey; + state.createdKey = null; + + const form = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(form); + const body = { name: d.name }; + if (d.kind === 'super') body.is_super = true; + else if (d.kind !== 'none') body.quota_id = Number(d.kind); + act(async () => { state.createdKey = { ...(await api('POST', '/keys', body)), name: d.name }; }); + }, + }, + h('div', { class: 'fields' }, + h('div', { class: 'field-group' }, h('label', { for: 'key-name' }, 'Name'), + h('input', { id: 'key-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. laptop' })), + h('div', { class: 'field-group' }, h('label', { for: 'key-kind' }, 'Abgerechnet gegen'), + h('select', { id: 'key-kind', name: 'kind', class: 'field' }, + usable.map((q) => h('option', { value: q.id }, q.name + (q.target ? ' · ' + q.target : ''))), + atLeast('lecturer') ? h('option', { value: 'none' }, 'Unbegrenzt (ohne Kontingent)') : null, + atLeast('admin') ? h('option', { value: 'super' }, 'Super-Key (ohne alle Einschränkungen)') : null))), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit', disabled: !usable.length && !atLeast('lecturer') }, 'Key erstellen'))); + + const parts = [head('Persönlich', 'API-Keys', 'Ein Key gilt für alle Endpunkte: Ollama, llama.cpp und vLLM.')]; + if (created) { + parts.push(h('section', { class: 'card' }, + h('div', { class: 'notice warn' }, 'Der Key wird nur dieses eine Mal angezeigt. Kopiere ihn jetzt.'), + h('div', { class: 'secret' }, h('code', {}, created.key), + h('button', { class: 'btn small', type: 'button', onclick: (e) => copy(created.key, e.currentTarget) }, 'Kopieren')), + h('span', { class: 'hint' }, 'Key „' + created.name + '“ angelegt.'))); + } + parts.push(h('section', { class: 'card' }, h('h2', {}, 'Neuer Key'), + !usable.length && !atLeast('lecturer') ? h('p', { class: 'empty' }, 'Dir ist noch kein Kontingent zugeteilt.') : form)); + parts.push(keysManageCard('Meine Keys', own, true)); + if (others.length) parts.push(keysManageCard(atLeast('admin') ? 'Keys anderer Personen' : 'Keys gegen meine Kontingente', others, false)); + parts.push(recordingsCard(recordings)); + parts.push(endpointsCard()); + return h('div', { class: 'stack' }, parts); +} + +function keysManageCard(title, keys, own) { + return h('section', { class: 'card' }, h('h2', {}, title), + keys.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Name'), own ? null : h('th', {}, 'Inhaber'), h('th', {}, 'Key'), h('th', {}, 'Kontingent'), + h('th', { class: 'num' }, 'Token (Monat)'), h('th', { class: 'num' }, 'Anfragen (Monat)'), h('th', {}, 'Status'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, keys.map((k) => h('tr', { class: k.key.revoked ? 'dim' : null }, + h('td', { class: 'mono' }, k.key.name), own ? null : h('td', { class: 'mono' }, k.owner || '–'), + h('td', { class: 'mono muted' }, k.key.prefix + '…'), h('td', {}, quotaLabel(k)), + h('td', { class: 'num' }, tokens(tok(k.usage.month))), h('td', { class: 'num' }, num(k.usage.month.requests)), + h('td', {}, keyState(k)), + h('td', {}, k.key.revoked ? null : h('div', { class: 'actions' }, + own && !k.recording ? h('button', { class: 'btn small', type: 'button', onclick: () => startRecording(k) }, 'Aufzeichnen') : null, + own && k.recording ? h('button', { class: 'btn small', type: 'button', onclick: () => act(() => api('POST', '/recordings/stop', { key_id: k.key.id }), 'Aufzeichnung beendet; sie liegt jetzt zum Herunterladen bereit.') }, 'Aufzeichnung beenden') : null, + h('button', { class: 'btn small danger', type: 'button', onclick: () => revokeKey(k) }, 'Widerrufen')))))))) + : h('p', { class: 'empty' }, 'Keine Keys.')); +} + +function revokeKey(k) { + if (!confirm('Key „' + k.key.name + '“ widerrufen? Anwendungen, die ihn nutzen, werden sofort abgewiesen.')) return; + act(() => api('DELETE', '/keys/' + k.key.id), 'Key „' + k.key.name + '“ widerrufen.'); +} + +function startRecording(k) { + const answer = prompt('Wie viele der nächsten Anfragen von „' + k.key.name + '“ sollen samt Antworten aufgezeichnet werden? (1 bis 100)', '20'); + if (!answer) return; + act(() => api('POST', '/recordings', { key_id: k.key.id, count: Number(answer) }), 'Aufzeichnung gestartet.'); +} + +function recordingsCard(recordings) { + return h('section', { class: 'card' }, + h('div', { class: 'card-head' }, h('h2', {}, 'Aufzeichnung für Debugging'), + h('span', { class: 'muted' }, 'Verschlüsselt gespeichert, nur für dich abrufbar, eine Stunde bereit, nach dem Download gelöscht.')), + recordings.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Nr.'), h('th', {}, 'Key'), h('th', { class: 'num' }, 'Einträge'), h('th', {}, 'Stand'), h('th', {}, 'Ende'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, recordings.slice().reverse().map((r) => h('tr', {}, + h('td', { class: 'mono' }, r.id), h('td', { class: 'mono' }, '#' + r.key_id), h('td', { class: 'num' }, r.written + ' / ' + r.count), + h('td', {}, r.state), h('td', { class: 'muted' }, r.end_reason || '–'), + h('td', {}, r.state.startsWith('bereit') ? h('a', { class: 'btn small primary', href: '/omega/api/recordings/' + r.id + '/download', download: 'aufzeichnung-' + r.id + '.jsonl', onclick: () => setTimeout(render, 1500) }, 'JSONL herunterladen') : null)))))) + : h('p', { class: 'empty' }, 'Noch keine Aufzeichnungen. Starte eine über „Aufzeichnen“ bei einem deiner Keys.')); +} + +function endpointsCard() { + const base = location.origin; + const rows = [['Ollama', base], ['llama.cpp (OpenAI-kompatibel)', base + '/llamacpp/v1'], ['vLLM (OpenAI-kompatibel)', base + '/vllm/v1']]; + return h('section', { class: 'card' }, h('h2', {}, 'Endpunkte'), + h('div', { class: 'table-wrap' }, h('table', {}, h('tbody', {}, rows.map(([name, url]) => h('tr', {}, + h('td', {}, name), h('td', { class: 'mono' }, url), + h('td', {}, h('button', { class: 'btn small', type: 'button', onclick: (e) => copy(url, e.currentTarget) }, 'Kopieren'))))))), + h('span', { class: 'hint' }, 'Den Key als „Authorization: Bearer …“ mitschicken.')); +} + +async function copy(text, button) { + try { + await navigator.clipboard.writeText(text); + button.textContent = 'Kopiert'; + } catch { + button.textContent = 'Bitte von Hand kopieren'; + } +} + +// ---------- Konto ---------- + +async function accountPage() { + const sessions = await api('GET', '/sessions'); + const u = state.me.user; + const pw = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(pw); + act(() => api('POST', '/users/' + encodeURIComponent(u.username) + '/password', { password: d.password }), 'Passwort geändert.'); + }, + }, + h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 'pw' }, 'Neues Passwort'), + h('input', { id: 'pw', name: 'password', type: 'password', class: 'field', autocomplete: 'new-password', required: true, minlength: 4 }))), + h('div', { class: 'actions' }, h('button', { class: 'btn', type: 'submit' }, 'Passwort ändern'))); + return h('div', { class: 'stack' }, + head('Persönlich', 'Konto & Sicherheit'), + h('div', { class: 'row top' }, + h('section', { class: 'card grow' }, h('h2', {}, 'Konto'), + h('table', {}, h('tbody', {}, + h('tr', {}, h('td', { class: 'muted' }, 'Benutzername'), h('td', { class: 'mono' }, u.username)), + h('tr', {}, h('td', { class: 'muted' }, 'Rolle'), h('td', {}, ROLE[u.role])), + h('tr', {}, h('td', { class: 'muted' }, 'E-Mail'), h('td', {}, u.email || '–')), + h('tr', {}, h('td', { class: 'muted' }, 'Gruppen'), h('td', { class: 'wrap' }, state.me.groups.join(', ') || '–'))))), + h('section', { class: 'card grow' }, h('h2', {}, 'Passwort (Testbetrieb)'), + h('p', { class: 'hint' }, 'Im Betrieb meldest du dich mit Passkey, Magic Link oder 2FA-Code an.'), pw)), + h('section', { class: 'card' }, h('h2', {}, 'Angemeldete Sitzungen'), + h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Sitzung'), h('th', {}, 'Angelegt'), h('th', {}, 'Gültig bis'), h('th', {}, 'Anmerkung'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, sessions.slice().reverse().map((s) => h('tr', { class: s.revoked ? 'dim' : null }, + h('td', { class: 'mono' }, s.prefix + '…'), h('td', {}, when(s.created_at)), h('td', {}, s.revoked ? 'widerrufen' : when(s.expires_at)), h('td', {}, s.note), + h('td', {}, s.revoked ? null : h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/sessions/' + s.id), 'Sitzung beendet.') }, 'Beenden'))))))))); +} + +// ---------- Gruppen & Kontingente ---------- + +async function groupsPage() { + const [groups, quotas] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas')]); + const me = state.me.user; + const managed = groups.filter((g) => g.owner_id === me.id || atLeast('admin')); + const groupForm = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(groupForm); + act(async () => { await api('POST', '/groups', { name: d.name }); go('group/' + encodeURIComponent(d.name)); }, 'Gruppe „' + d.name + '“ angelegt.'); + }, + }, + h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 'group-name' }, 'Name der Gruppe'), + h('input', { id: 'group-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. ki-praktikum-ws26' }))), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Gruppe anlegen'))); + return h('div', { class: 'stack' }, + head('Lehre', 'Gruppen & Kontingente', 'Gruppen anlegen, Personen aufnehmen und Kontingente zuteilen.'), + h('div', { class: 'row top' }, + h('section', { class: 'card grow' }, h('h2', {}, 'Gruppen'), + managed.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Gruppe'), h('th', { class: 'num' }, 'Mitglieder'), h('th', {}, 'Verwaltet von'))), + h('tbody', {}, managed.map((g) => h('tr', {}, + h('td', {}, h('a', { class: 'mono', href: '#/group/' + encodeURIComponent(g.name) }, g.name)), h('td', { class: 'num' }, g.members), h('td', { class: 'mono' }, g.owner || '–')))))) + : h('p', { class: 'empty' }, 'Noch keine Gruppen.')), + h('section', { class: 'card grow' }, h('h2', {}, 'Neue Gruppe'), groupForm)), + h('section', { class: 'card' }, h('h2', {}, 'Kontingente'), quotasTable(quotas)), + quotaForm(managed, null)); +} + +function quotasTable(quotas) { + return quotas.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Kontingent'), h('th', {}, 'Zugeteilt'), h('th', {}, 'Grenzen'), h('th', { class: 'num' }, 'Keys'))), + h('tbody', {}, quotas.map((q) => h('tr', {}, + h('td', {}, h('a', { href: '#/quota/' + q.id }, q.name)), h('td', {}, q.target || '–'), h('td', { class: 'wrap' }, q.describe), h('td', { class: 'num' }, q.keys)))))) + : h('p', { class: 'empty' }, 'Noch keine Kontingente.'); +} + +/** Formular für ein neues Kontingent, für eine feste Gruppe oder mit Auswahl */ +function quotaForm(groups, fixedGroup) { + const limit = (name, label) => h('div', { class: 'field-group' }, h('label', { for: 'q-' + name }, label), + h('input', { id: 'q-' + name, name, class: 'field mono', type: 'number', min: 1, inputmode: 'numeric', placeholder: 'unbegrenzt' })); + const form = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(form); + const body = { + name: d.name, + tokens: { hour: optNum(d.tokens_hour), day: optNum(d.tokens_day), week: optNum(d.tokens_week), month: optNum(d.tokens_month), total: optNum(d.tokens_total) }, + requests: { hour: optNum(d.requests_hour), day: optNum(d.requests_day), week: optNum(d.requests_week), month: optNum(d.requests_month), total: optNum(d.requests_total) }, + models: d.models ? list(d.models) : undefined, + from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note, + }; + const target = fixedGroup || d.target; + if (target.startsWith('group:')) body.group = target.slice(6); + else if (target === 'user') body.user = d.username; + act(() => api('POST', '/quotas', body), (q) => 'Kontingent „' + q.name + '“ angelegt: ' + q.describe); + }, + }, + h('div', { class: 'fields' }, + h('div', { class: 'field-group' }, h('label', { for: 'q-name' }, 'Name'), h('input', { id: 'q-name', name: 'name', class: 'field', required: true, placeholder: 'z. B. KI-Praktikum WS 26/27' })), + fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-target' }, 'Zugeteilt an'), + h('select', { id: 'q-target', name: 'target', class: 'field' }, + groups.map((g) => h('option', { value: 'group:' + g.name }, 'Gruppe ' + g.name + ' (je Mitglied)')), + h('option', { value: 'user' }, 'Eine Person …'))), + fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-username' }, 'Benutzername (bei einer Person)'), + h('input', { id: 'q-username', name: 'username', class: 'field mono' }))), + h('fieldset', {}, h('legend', {}, 'Token'), h('div', { class: 'fields' }, + limit('tokens_hour', 'je Stunde'), limit('tokens_day', 'je Tag'), limit('tokens_week', 'je Woche'), limit('tokens_month', 'je Monat'), limit('tokens_total', 'insgesamt'))), + h('fieldset', {}, h('legend', {}, 'Anfragen'), h('div', { class: 'fields' }, + limit('requests_hour', 'je Stunde'), limit('requests_day', 'je Tag'), limit('requests_week', 'je Woche'), limit('requests_month', 'je Monat'), limit('requests_total', 'insgesamt'))), + h('fieldset', {}, h('legend', {}, 'Wann und womit'), h('div', { class: 'fields' }, + h('div', { class: 'field-group' }, h('label', { for: 'q-models' }, 'Nur diese Modelle'), h('input', { id: 'q-models', name: 'models', class: 'field mono', placeholder: 'ollama/qwen3:0.6b, vllm/…' })), + h('div', { class: 'field-group' }, h('label', { for: 'q-weekly' }, 'Wochentage'), h('input', { id: 'q-weekly', name: 'weekly', class: 'field mono', placeholder: 'mo-fr' })), + h('div', { class: 'field-group' }, h('label', { for: 'q-time' }, 'Uhrzeit'), h('input', { id: 'q-time', name: 'time', class: 'field mono', placeholder: '08:00-18:00' })), + h('div', { class: 'field-group' }, h('label', { for: 'q-from' }, 'Gültig ab'), h('input', { id: 'q-from', name: 'from', class: 'field mono', placeholder: '2026-10-01' })), + h('div', { class: 'field-group' }, h('label', { for: 'q-until' }, 'Gültig bis'), h('input', { id: 'q-until', name: 'until', class: 'field mono', placeholder: '2027-02-15' })), + h('div', { class: 'field-group' }, h('label', { for: 'q-note' }, 'Anmerkung'), h('input', { id: 'q-note', name: 'note', class: 'field' }))), + h('span', { class: 'hint' }, 'Leere Felder heißen unbegrenzt. Ein Gruppenkontingent gilt je Mitglied. Tage und Monate sind Kalenderzeiträume.')), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Kontingent anlegen'))); + return h('section', { class: 'card' }, h('h2', {}, fixedGroup ? 'Neues Kontingent für diese Gruppe' : 'Neues Kontingent'), form); +} + +async function groupPage(name) { + const g = await api('GET', '/groups/' + encodeURIComponent(name)); + const add = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const users = list(formData(add).usernames); + act(() => api('POST', '/groups/' + encodeURIComponent(name) + '/members', { usernames: users }), + (r) => r.map((x) => x.username + ': ' + ({ New: 'aufgenommen', NoAccount: 'aufgenommen, hat noch kein Konto', Existing: 'war schon Mitglied' }[x.result])).join(' · ')); + }, + }, + h('div', { class: 'field-group' }, h('label', { for: 'members' }, 'Benutzernamen, getrennt durch Komma oder Zeilen'), + h('textarea', { id: 'members', name: 'usernames', class: 'field mono', required: true, placeholder: 'mueller\nmeier' })), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Aufnehmen'))); + return h('div', { class: 'stack' }, + head('Lehre · Gruppe', g.name, 'Verwaltet von ' + (g.owner || '–') + ' · ' + g.members.length + ' Mitglieder', + h('a', { class: 'btn', href: '#/groups' }, 'Zurück'), + h('button', { class: 'btn danger', type: 'button', onclick: () => { + if (confirm('Gruppe „' + g.name + '“ löschen?')) act(async () => { await api('DELETE', '/groups/' + encodeURIComponent(g.name)); go('groups'); }, 'Gruppe gelöscht.'); + } }, 'Gruppe löschen')), + h('div', { class: 'row top' }, + h('section', { class: 'card grow' }, h('h2', {}, 'Mitglieder'), + g.members.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Benutzer'), h('th', {}, 'Stand'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, g.members.map((m) => h('tr', {}, + h('td', { class: 'mono' }, m.username), + h('td', {}, m.state === 'noch kein Konto' ? h('span', { class: 'chip' }, 'noch kein Konto') : m.state === 'gesperrt' || m.state === 'deaktiviert' ? h('span', { class: 'chip bad' }, m.state) : ROLE[m.state] || m.state), + h('td', {}, h('div', { class: 'actions' }, h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/groups/' + encodeURIComponent(g.name) + '/members/' + encodeURIComponent(m.username)), m.username + ' entfernt.') }, 'Entfernen')))))))) + : h('p', { class: 'empty' }, 'Noch keine Mitglieder.')), + h('section', { class: 'card grow' }, h('h2', {}, 'Personen aufnehmen'), add, + h('span', { class: 'hint' }, 'Wer noch kein Konto hat, wird Mitglied, sobald es angelegt ist.'))), + h('section', { class: 'card' }, h('h2', {}, 'Kontingente der Gruppe'), + quotasTable(g.quotas.map((q) => ({ ...q, target: 'Gruppe ' + g.name, describe: describeQuota(q), keys: '–' })))), + quotaForm([], 'group:' + g.name)); +} + +function describeQuota(q) { + const parts = []; + for (const p of Object.keys(PERIOD)) { + if (q.tokens[p] != null) parts.push(num(q.tokens[p]) + ' Token/' + PERIOD[p]); + if (q.requests[p] != null) parts.push(num(q.requests[p]) + ' Anfragen/' + PERIOD[p]); + } + if (q.models) parts.push('Modelle: ' + q.models.join(', ')); + return parts.join('; ') || 'ohne Mengengrenzen'; +} + +async function quotaPage(id) { + const q = await api('GET', '/quotas/' + id); + const manages = atLeast('admin') || q.owner_id === state.me.user.id; + return h('div', { class: 'stack' }, + head('Kontingent', q.name, (q.target ? q.target + ' · ' : '') + 'verwaltet von ' + (q.owner || '–'), + h('a', { class: 'btn', href: manages ? '#/groups' : '#/' }, 'Zurück'), + manages ? h('button', { class: 'btn danger', type: 'button', onclick: () => { + if (confirm('Kontingent „' + q.name + '“ entfernen? Das geht nur, wenn keine Keys mehr daran hängen.')) act(async () => { await api('DELETE', '/quotas/' + q.id); go('groups'); }, 'Kontingent entfernt.'); + } }, 'Entfernen') : null), + h('section', { class: 'card' }, h('h2', {}, 'Grenzen'), h('p', {}, q.describe), q.note ? h('p', { class: 'muted' }, q.note) : null), + h('section', { class: 'card' }, h('h2', {}, manages ? 'Verbrauch je Person' : 'Dein Verbrauch'), + q.usage.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Person'), Object.values(PERIOD).map((p) => h('th', { class: 'num' }, 'Token ' + p)), h('th', { class: 'num' }, 'Anfragen heute'))), + h('tbody', {}, q.usage.map((p) => h('tr', {}, + h('td', { class: 'mono' }, p.user || '(ohne Inhaber)'), + Object.keys(PERIOD).map((k) => h('td', { class: 'num' }, tokens(tok(p.usage[k])) + (q.tokens[k] != null ? ' / ' + tokens(q.tokens[k]) : ''))), + h('td', { class: 'num' }, num(p.usage.day.requests) + (q.requests.day != null ? ' / ' + num(q.requests.day) : ''))))))) + : h('p', { class: 'empty' }, 'Noch keine Nutzung.'))); +} + +// ---------- Sparks & Modelle ---------- + +async function statusPage() { + const status = await api('GET', '/status'); + const loaded = status.nodes.reduce((a, n) => a + n.models.length, 0); + const waiting = status.nodes.reduce((a, n) => a + n.models.reduce((b, m) => b + m.waiting, 0), 0); + const running = status.nodes.reduce((a, n) => a + n.models.reduce((b, m) => b + m.in_flight, 0), 0); + const issues = status.nodes.reduce((a, n) => a + n.issues.length, 0); + return h('div', { class: 'stack' }, + head('Administration', 'Sparks & Modelle', status.nodes.length + ' Rechner · ' + loaded + ' Modelle geladen · ' + waiting + ' Anfragen warten', + h('button', { class: 'btn', type: 'button', onclick: () => render() }, 'Aktualisieren')), + h('div', { class: 'kpis' }, + h('div', { class: 'kpi' }, h('span', {}, 'Laufende Anfragen'), h('span', { class: 'value' }, num(running))), + h('div', { class: 'kpi' }, h('span', {}, 'Warteschlange'), h('span', { class: 'value' + (waiting ? ' accent' : '') }, num(waiting))), + h('div', { class: 'kpi' }, h('span', {}, 'Geladene Modelle'), h('span', { class: 'value' }, num(loaded))), + h('div', { class: 'kpi' }, h('span', {}, 'Hinweise zu Engines'), h('span', { class: 'value' + (issues ? ' bad' : '') }, num(issues)))), + h('div', { class: 'row top' }, status.nodes.map(nodeCard)), + h('div', { class: 'legend' }, + h('span', {}, h('span', { class: 'swatch ollama' }), 'Ollama'), h('span', {}, h('span', { class: 'swatch llamacpp' }), 'llama.cpp'), + h('span', {}, h('span', { class: 'swatch vllm' }), 'vLLM'), h('span', {}, h('span', { class: 'swatch free' }), 'frei'))); +} + +function nodeCard(n) { + const budget = n.budget_mb || 0; + const models = n.models.slice().sort((a, b) => b.mb - a.mb); + const state = (m) => { + if (m.state === 'loading') return h('span', { class: 'muted' }, 'wird geladen'); + if (m.state === 'unloading') return h('span', { class: 'muted' }, 'wird entladen'); + if (m.in_flight) return h('span', { class: 'status' }, h('span', { class: 'dot accent' }), m.in_flight + (m.in_flight === 1 ? ' laufende Anfrage' : ' laufende Anfragen')); + return h('span', { class: 'muted' }, 'Leerlauf ' + Math.round(m.idle_secs / 60) + ' min'); + }; + return h('section', { class: 'card grow' }, + h('div', { class: 'card-head' }, + h('div', { class: 'actions' }, h('h2', { class: 'mono' }, n.name), + n.budget_mb == null ? h('span', { class: 'chip bad' }, 'Speicher unbekannt') : h('span', { class: 'chip good' }, 'erreichbar')), + h('span', { class: 'mono muted' }, mb(n.used_mb) + ' / ' + mb(n.budget_mb))), + h('div', { class: 'membar', role: 'img', 'aria-label': 'Speicherbelegung ' + n.name + ': ' + models.map((m) => m.model + ' ' + mb(m.mb)).join(', ') }, + models.map((m) => h('div', { class: m.engine + (m.state === 'loaded' ? '' : ' loading'), style: { width: (budget ? m.mb / budget * 100 : 0) + '%' }, title: m.model + ' · ' + mb(m.mb) }, m.model))), + n.issues.map((i) => h('div', { class: 'notice warn' }, i)), + models.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Modell'), h('th', {}, 'Engine'), h('th', { class: 'num' }, 'Speicher'), h('th', {}, 'Status'), h('th', { class: 'num' }, 'Wartend'))), + h('tbody', {}, models.map((m) => h('tr', {}, + h('td', { class: 'mono' }, m.model), h('td', {}, h('span', { class: 'chip ' + m.engine }, ENGINE[m.engine] || m.engine)), + h('td', { class: 'num' }, mb(m.mb)), h('td', {}, m.pinned ? h('span', { class: 'chip accent' }, 'gepinnt') : null, ' ', state(m)), + h('td', { class: 'num' }, m.waiting || '–')))))) + : h('p', { class: 'empty' }, 'Kein Modell geladen.'), + n.events.length ? h('details', {}, h('summary', {}, 'Ereignisse der Engines (' + n.events.length + ')'), + h('ol', { class: 'events' }, n.events.map((e) => h('li', {}, h('span', { class: 'mono' }, clock(e.ts)), h('span', {}, e.message))))) : null, + h('details', {}, h('summary', {}, 'Empfohlene Einstellungen der Engines'), + (n.engines || []).map((e) => h('pre', { class: 'settings' }, ENGINE[e.engine] + '\n' + e.settings.join('\n'))))); +} + +// ---------- Zeitplan ---------- + +async function schedulePage() { + const entries = await api('GET', '/schedule'); + const kindSel = h('select', { id: 's-kind', name: 'kind', class: 'field', onchange: () => update() }, + h('option', { value: 'pin' }, 'Pin: Modell garantiert im Speicher'), + h('option', { value: 'exclusive' }, 'Exklusiv: nur bestimmte Gruppen oder Personen'), + h('option', { value: 'window' }, 'Modellzeitfenster: nur bestimmte Modelle')); + const field = (name, label, placeholder, hint) => h('div', { class: 'field-group', 'data-for': hint }, + h('label', { for: 's-' + name }, label), h('input', { id: 's-' + name, name, class: 'field mono', placeholder })); + const form = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(form); + const body = { kind: d.kind, from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note }; + if (d.kind === 'pin') Object.assign(body, { model: d.model, node: optional(d.node) }); + if (d.kind === 'exclusive') Object.assign(body, { groups: list(d.groups), users: list(d.users) }); + if (d.kind === 'window') body.models = list(d.models); + act(() => api('POST', '/schedule', body), (e2) => 'Eintrag angelegt: ' + e2.subject + ', ' + e2.describe); + }, + }, + h('div', { class: 'fields' }, + h('div', { class: 'field-group' }, h('label', { for: 's-kind' }, 'Art'), kindSel), + field('model', 'Modell', 'ollama/qwen3:0.6b', 'pin'), + field('node', 'Rechner (bei mehreren)', 'spark1', 'pin'), + field('groups', 'Gruppen', 'ki-2026', 'exclusive'), + field('users', 'Personen', 'hofmannol', 'exclusive'), + field('models', 'Modelle', 'ollama/qwen3:0.6b, vllm/…', 'window')), + h('div', { class: 'fields' }, + field('from', 'Beginn', '2026-11-24 08:00 oder +10m'), field('until', 'Ende', '2026-11-24 12:00'), + field('weekly', 'Wochentage', 'mo,mi'), field('time', 'Uhrzeit', '08:00-11:15'), field('note', 'Anmerkung', 'Vorlesung KI')), + h('span', { class: 'hint' }, 'Ohne Zeitangaben gilt ein Eintrag dauerhaft. Der Proxy lehnt Einträge ab, die nicht in den Speicher passen oder sich widersprechen.'), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Eintrag anlegen'))); + function update() { + for (const el of form.querySelectorAll('[data-for]')) { + const kind = el.getAttribute('data-for'); + if (kind !== 'undefined') el.hidden = kind !== kindSel.value; + } + } + update(); + const kinds = { pin: 'Pin', exklusiv: 'Exklusiv', fenster: 'Zeitfenster' }; + return h('div', { class: 'stack' }, + head('Administration', 'Zeitplan', 'Pins, exklusive Nutzung und Modellzeitfenster in einem Plan.'), + h('section', { class: 'card' }, h('h2', {}, 'Einträge'), + entries.length ? h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Art'), h('th', {}, 'Was'), h('th', {}, 'Wann'), h('th', {}, 'Stand'), h('th', {}, 'Anmerkung'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, entries.map((e) => h('tr', {}, + h('td', {}, h('span', { class: 'chip' + (e.entry.kind.kind === 'pin' ? ' accent' : '') }, kinds[e.entry.kind.kind] || e.entry.kind.kind)), + h('td', { class: 'mono wrap' }, e.subject), h('td', { class: 'wrap' }, e.describe), + h('td', {}, e.active ? h('span', { class: 'status' }, h('span', { class: 'dot good' }), 'aktiv') : h('span', { class: 'muted' }, 'inaktiv')), + h('td', { class: 'wrap' }, e.entry.note), + h('td', {}, h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/schedule/' + e.entry.id), 'Eintrag entfernt.') }, 'Entfernen'))))))) + : h('p', { class: 'empty' }, 'Der Zeitplan ist leer.')), + h('section', { class: 'card' }, h('h2', {}, 'Neuer Eintrag'), form)); +} + +// ---------- Benutzer ---------- + +async function usersPage() { + const users = await api('GET', '/users'); + const patch = (u, body, done) => act(() => api('PATCH', '/users/' + encodeURIComponent(u.username), body), done); + const form = h('form', { + onsubmit: (e) => { + e.preventDefault(); + const d = formData(form); + act(async () => { + await api('POST', '/users', { username: d.username, email: optional(d.email), role: d.role }); + if (d.password) await api('POST', '/users/' + encodeURIComponent(d.username) + '/password', { password: d.password }); + }, 'Benutzer ' + d.username + ' angelegt.'); + }, + }, + h('div', { class: 'fields' }, + h('div', { class: 'field-group' }, h('label', { for: 'u-name' }, 'Benutzername'), h('input', { id: 'u-name', name: 'username', class: 'field mono', required: true })), + h('div', { class: 'field-group' }, h('label', { for: 'u-mail' }, 'E-Mail'), h('input', { id: 'u-mail', name: 'email', type: 'email', class: 'field' })), + h('div', { class: 'field-group' }, h('label', { for: 'u-role' }, 'Rolle'), + h('select', { id: 'u-role', name: 'role', class: 'field' }, Object.entries(ROLE).map(([v, l]) => h('option', { value: v }, l)))), + h('div', { class: 'field-group' }, h('label', { for: 'u-pw' }, 'Passwort (Testbetrieb)'), h('input', { id: 'u-pw', name: 'password', type: 'password', class: 'field', autocomplete: 'new-password' }))), + h('span', { class: 'hint' }, 'Im Betrieb registrieren sich Personen selbst mit dem Login der Hochschule (LDAP).'), + h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Benutzer anlegen'))); + const me = state.me.user; + return h('div', { class: 'stack' }, + head('Administration', 'Benutzer', users.length + ' Konten'), + h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Benutzer'), h('th', {}, 'E-Mail'), h('th', {}, 'Rolle'), h('th', {}, 'Gruppen'), h('th', {}, 'Stand'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))), + h('tbody', {}, users.map((u) => h('tr', { class: u.blocked || !u.active ? 'dim' : null }, + h('td', { class: 'mono' }, u.username), h('td', {}, u.email || '–'), + h('td', {}, h('select', { class: 'field', 'aria-label': 'Rolle von ' + u.username, onchange: (e) => patch(u, { role: e.target.value }, u.username + ' ist jetzt ' + ROLE[e.target.value] + '.') }, + Object.entries(ROLE).map(([v, l]) => h('option', { value: v, selected: v === u.role }, l)))), + h('td', { class: 'wrap' }, u.groups.join(', ') || '–'), + h('td', {}, u.blocked ? h('span', { class: 'chip bad' }, 'gesperrt') : !u.active ? h('span', { class: 'chip bad' }, 'deaktiviert') : h('span', { class: 'chip good' }, 'aktiv')), + h('td', {}, u.id === me.id ? null : h('div', { class: 'actions' }, + h('button', { class: 'btn small' + (u.blocked ? '' : ' danger'), type: 'button', onclick: () => patch(u, { blocked: !u.blocked }, u.username + (u.blocked ? ' entsperrt.' : ' gesperrt; seine Keys werden abgewiesen.')) }, u.blocked ? 'Entsperren' : 'Sperren'))))))))), + h('section', { class: 'card' }, h('h2', {}, 'Neuer Benutzer'), form)); +} + +// ---------- Audit-Log ---------- + +async function auditPage() { + const entries = await api('GET', '/audit?limit=300'); + return h('div', { class: 'stack' }, + head('Administration', 'Audit-Log', 'Die letzten 300 Vorgänge. Inhalte von Anfragen und Antworten stehen hier nie.'), + h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {}, + h('thead', {}, h('tr', {}, h('th', {}, 'Zeit'), h('th', {}, 'Wer'), h('th', {}, 'Vorgang'), h('th', {}, 'Details'))), + h('tbody', {}, entries.map((e) => h('tr', {}, + h('td', { class: 'mono muted' }, when(e.ts)), h('td', { class: 'mono' }, e.actor), h('td', { class: 'mono' }, e.action), h('td', { class: 'wrap mono' }, e.detail)))))))); +} + +render(); diff --git a/proxy/ui/fonts/OFL.txt b/proxy/ui/fonts/OFL.txt new file mode 100644 index 0000000..e89cc25 --- /dev/null +++ b/proxy/ui/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 IBM Corp. All rights reserved. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/proxy/ui/fonts/ibm-plex-mono-400.woff2 b/proxy/ui/fonts/ibm-plex-mono-400.woff2 new file mode 100644 index 0000000..a6c77d6 Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-mono-400.woff2 differ diff --git a/proxy/ui/fonts/ibm-plex-mono-500.woff2 b/proxy/ui/fonts/ibm-plex-mono-500.woff2 new file mode 100644 index 0000000..99c2610 Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-mono-500.woff2 differ diff --git a/proxy/ui/fonts/ibm-plex-mono-600.woff2 b/proxy/ui/fonts/ibm-plex-mono-600.woff2 new file mode 100644 index 0000000..59e4f52 Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-mono-600.woff2 differ diff --git a/proxy/ui/fonts/ibm-plex-sans-400.woff2 b/proxy/ui/fonts/ibm-plex-sans-400.woff2 new file mode 100644 index 0000000..93bcd64 Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-sans-400.woff2 differ diff --git a/proxy/ui/fonts/ibm-plex-sans-500.woff2 b/proxy/ui/fonts/ibm-plex-sans-500.woff2 new file mode 100644 index 0000000..adbbd4c Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-sans-500.woff2 differ diff --git a/proxy/ui/fonts/ibm-plex-sans-600.woff2 b/proxy/ui/fonts/ibm-plex-sans-600.woff2 new file mode 100644 index 0000000..0ac91d6 Binary files /dev/null and b/proxy/ui/fonts/ibm-plex-sans-600.woff2 differ diff --git a/proxy/ui/index.html b/proxy/ui/index.html new file mode 100644 index 0000000..bc16be9 --- /dev/null +++ b/proxy/ui/index.html @@ -0,0 +1,14 @@ + + + + + +Omega AI Proxy + + + + +

Lädt …

+ + + diff --git a/tests/multispark/demo.sh b/tests/multispark/demo.sh new file mode 100755 index 0000000..7ea90b2 --- /dev/null +++ b/tests/multispark/demo.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Testbenutzer und etwas Beispielnutzung für die Oberfläche (nach start.sh). +# admin (Administrator, aus first_admin), dozent (Lecturer), student (User); Passwort jeweils 1234. +set -e +cd "$(dirname "$0")" +P="../../target/debug/omega-proxy -c proxy.toml" +$P user add dozent --role lecturer --email dozent@th-nuernberg.de +$P user add student --role user --email student@th-nuernberg.de +for u in admin dozent student; do $P user password $u 1234; done + +# Gruppe mit Kontingent, ein Key für student und ein paar Anfragen +$P --as dozent group create ki-praktikum +$P --as dozent group add ki-praktikum student +$P --as dozent quota create ki-praktikum --group ki-praktikum --tokens-day 20000 --requests-hour 60 --note "KI-Praktikum" +KEY=$($P --as student key create laptop --quota 1 | awk '{print $NF}') +for i in 1 2 3; do + curl -s -o /dev/null -H "Authorization: Bearer $KEY" http://127.0.0.1:8000/api/generate \ + -d '{"model":"smollm2:135m","prompt":"Hallo","stream":false,"options":{"num_predict":8}}' +done +echo "Oberfläche: http://127.0.0.1:8000/omega/ (admin, dozent, student; Passwort 1234)" diff --git a/tests/multispark/proxy.toml b/tests/multispark/proxy.toml index 69f4fb0..07f0d4e 100644 --- a/tests/multispark/proxy.toml +++ b/tests/multispark/proxy.toml @@ -2,6 +2,9 @@ listen = "127.0.0.1:8000" database = "run/test.db" first_admin = "admin" +[ui] +password_login = true + [dashboard] sample_secs = 2 diff --git a/tests/multispark/ui_test.py b/tests/multispark/ui_test.py new file mode 100644 index 0000000..ec2cdaa --- /dev/null +++ b/tests/multispark/ui_test.py @@ -0,0 +1,79 @@ +"""Test der Weboberfläche ohne Browser: Auslieferung, keine externen Quellen, Anmeldung mit +Passwort, Cookie, Schutz gegen CSRF, Abmelden. Erwartet [ui] password_login = true und demo.sh.""" + +import http.client +import json +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from common import check, failures # noqa: E402 + + +def request(method, path, body=None, headers=None): + conn = http.client.HTTPConnection("127.0.0.1", 8000, timeout=30) + data = json.dumps(body).encode() if body is not None else None + hdrs = {"Content-Type": "application/json", **(headers or {})} + conn.request(method, path, body=data, headers=hdrs) + r = conn.getresponse() + content = r.read() + result = (r.status, {k.lower(): v for k, v in r.getheaders()}, content) + conn.close() + return result + + +print("1) Browser und Ollama-Clients auf der Wurzel") +st, hdrs, _ = request("GET", "/", headers={"Accept": "text/html,application/xhtml+xml"}) +check(st in (302, 307) and hdrs.get("location") == "/omega/", f"Browser wird nach /omega/ umgeleitet ({st})") +st, _, body = request("GET", "/") +check(st == 200 and b"Ollama is running" in body, "Ollama-Clients bekommen weiter die Ollama-Antwort") + +print("2) Oberfläche ohne externe Quellen") +st, hdrs, index = request("GET", "/omega/") +csp = hdrs.get("content-security-policy", "") +check(st == 200 and "default-src 'none'" in csp and "font-src 'self'" in csp and "connect-src 'self'" in csp, + "Content-Security-Policy erlaubt nur den Proxy selbst") +assets = re.findall(rb'(?:href|src)="(/omega/assets/[^"]+)"', index) +css = request("GET", "/omega/assets/app.css")[2] +fonts = re.findall(rb"url\((/omega/assets/[^)]+)\)", css) +files = {p.decode(): request("GET", p.decode()) for p in assets + fonts} +print(f" {len(files)} Dateien: {', '.join(os.path.basename(p) for p in files)}") +check(len(fonts) == 6 and all(r[0] == 200 for r in files.values()), "alle Dateien und sechs Schriften werden ausgeliefert") +check(all(r[2][:4] == b"wOF2" and r[1]["content-type"] == "font/woff2" for p, r in files.items() if p.endswith(".woff2")), + "Schriften als WOFF2") +external = [p for p, r in list(files.items()) + [("/omega/", (st, hdrs, index))] + if not p.endswith(".woff2") and re.search(rb"https?://(?!www\.w3\.org/2000/svg)", r[2])] +check(not external, f"keine externen Adressen in HTML, CSS oder JavaScript {external}") +check(request("GET", "/omega/assets/gibtsnicht.js")[0] == 404, "unbekannte Datei: 404") + +print("3) Anmeldung mit Passwort") +st, _, body = request("POST", "/omega/api/login", {"username": "student", "password": "falsch"}) +check(st == 401, f"falsches Passwort: {st} {body[:60]!r}") +st, _, _ = request("POST", "/omega/api/login", {"username": "niemand", "password": "1234"}) +check(st == 401, "unbekannter Benutzer: 401") +cookies = {} +for user in ["admin", "dozent", "student"]: + st, hdrs, body = request("POST", "/omega/api/login", {"username": user, "password": "1234"}) + cookie = hdrs.get("set-cookie", "") + cookies[user] = cookie.split(";")[0] + check(st == 200 and json.loads(body)["user"]["username"] == user, f"{user} meldet sich mit 1234 an") +check(all(a in cookie for a in ["HttpOnly", "SameSite=Strict", "Path=/omega"]), f"Cookie: {cookie.split(';', 1)[1].strip()}") +st, _, body = request("GET", "/omega/api/me", headers={"Cookie": cookies["dozent"]}) +me = json.loads(body) +check(st == 200 and me["user"]["role"] == "lecturer" and me["managed"] is not None, "Cookie genügt zum Lesen") +st, _, body = request("POST", "/omega/api/groups", {"name": "ohne-header"}, headers={"Cookie": cookies["dozent"]}) +check(st == 403 and b"CSRF" in body, "Ändern nur mit Kopfzeile X-Omega-CSRF") +st, _, _ = request("POST", "/omega/api/groups", {"name": "mit-header"}, headers={"Cookie": cookies["dozent"], "X-Omega-CSRF": "1"}) +check(st == 201, "mit Kopfzeile: angelegt") +st, _, body = request("GET", "/omega/api/me", headers={"Cookie": cookies["student"]}) +me = json.loads(body) +check(me["keys"] and me["quotas"] and me["quotas"][0]["usage"][0]["usage"]["day"]["requests"] >= 3, + "student sieht Key und Kontingent aus demo.sh") + +print("4) Abmelden") +st, hdrs, _ = request("POST", "/omega/api/logout", headers={"Cookie": cookies["student"], "X-Omega-CSRF": "1"}) +check(st == 204 and "Max-Age=0" in hdrs.get("set-cookie", ""), "Abmelden löscht das Cookie") +check(request("GET", "/omega/api/me", headers={"Cookie": cookies["student"]})[0] == 401, "die Sitzung ist widerrufen") + +print("ERGEBNIS:", "alles bestanden" if not failures else f"{len(failures)} Fehler: {failures}")