Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
Browser UI on other devices, behind a password
Gabriele Lozupone25df98f0dcb5
diff --git a/Cargo.lock b/Cargo.lockindex a7a0566..16baf9c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -77,6 +77,18 @@ dependencies = ["x11rb",]+[[package]]+name = "argon2"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures 0.3.1",+ "password-hash",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -313,6 +325,12 @@ 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 = "bit-set"version = "0.8.0"@@ -343,6 +361,15 @@ dependencies = ["serde_core",]+[[package]]+name = "blake2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"+dependencies = [+ "digest 0.11.3",+]+[[package]]name = "block-buffer"version = "0.10.4"@@ -580,6 +607,12 @@ dependencies = ["error-code",]+[[package]]+name = "cmov"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"+[[package]]name = "color_quant"version = "1.1.0"@@ -767,6 +800,15 @@ version = "1.0.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"+[[package]]+name = "ctutils"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"+dependencies = [+ "cmov",+]+[[package]]name = "darling"version = "0.24.1"@@ -903,6 +945,7 @@ dependencies = ["block-buffer 0.12.1","const-oid","crypto-common 0.2.2",+ "ctutils",][[package]]@@ -2488,6 +2531,16 @@ version = "0.3.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]+name = "mime_guess"+version = "2.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"+dependencies = [+ "mime",+ "unicase",+]+[[package]]name = "minisign-verify"version = "0.2.5"@@ -3058,6 +3111,16 @@ dependencies = ["windows-link",]+[[package]]+name = "password-hash"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"+dependencies = [+ "getrandom 0.4.3",+ "phc",+]+[[package]]name = "percent-encoding"version = "2.3.2"@@ -3075,6 +3138,17 @@ dependencies = ["indexmap 2.14.2",]+[[package]]+name = "phc"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"+dependencies = [+ "base64ct",+ "ctutils",+ "getrandom 0.4.3",+]+[[package]]name = "phf"version = "0.13.1"@@ -3313,6 +3387,7 @@ name = "qls-core"version = "0.10.2"dependencies = ["anyhow",+ "argon2","base64 0.23.1","chrono","dirs",@@ -3343,11 +3418,15 @@ dependencies = ["axum","futures-util","qls-core",+ "rpassword",+ "rust-embed","serde","serde_json","sysinfo",+ "tempfile","tokio","tokio-stream",+ "tower","tower-http 0.7.1","tracing","tracing-appender",@@ -3555,6 +3634,17 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "rpassword"+version = "7.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"+dependencies = [+ "libc",+ "rtoolbox",+ "windows-sys 0.61.2",+]+[[package]]name = "rsqlite-vfs"version = "0.1.1"@@ -3565,6 +3655,16 @@ dependencies = ["thiserror 2.0.21",]+[[package]]+name = "rtoolbox"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "rusqlite"version = "0.40.2"@@ -3580,6 +3680,42 @@ dependencies = ["sqlite-wasm-rs",]+[[package]]+name = "rust-embed"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23"+dependencies = [+ "rust-embed-impl",+ "rust-embed-utils",+ "walkdir",+]++[[package]]+name = "rust-embed-impl"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053"+dependencies = [+ "mime_guess",+ "proc-macro2",+ "quote",+ "rust-embed-utils",+ "syn 2.0.119",+ "walkdir",+]++[[package]]+name = "rust-embed-utils"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a"+dependencies = [+ "mime_guess",+ "sha2 0.11.0",+ "walkdir",+]+[[package]]name = "rustc-hash"version = "2.1.3"@@ -5261,6 +5397,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "unicase"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"+[[package]]name = "unicode-ident"version = "1.0.26"diff --git a/crates/qls-core/Cargo.toml b/crates/qls-core/Cargo.tomlindex fde5dab..431c2c3 100644--- a/crates/qls-core/Cargo.toml+++ b/crates/qls-core/Cargo.toml@@ -6,6 +6,7 @@ edition.workspace = true[dependencies]anyhow = "1.0.104"+argon2 = "0.6.0"base64 = "0.23.1"chrono = { version = "0.4.45", features = ["serde"] }dirs = "7.0.0"diff --git a/crates/qls-core/src/config.rs b/crates/qls-core/src/config.rsindex 4e62d75..61a6178 100644--- a/crates/qls-core/src/config.rs+++ b/crates/qls-core/src/config.rs@@ -17,6 +17,8 @@ const LEGACY_DATA_DIR: &str = "QwenLocalStudio";pub const DATA_DIR_NAME: &str = "KokonData";pub const DEFAULT_SERVER_PORT: u16 = 39150;pub const DEFAULT_SERVICE_PORT: u16 = 39151;+/// Port for access from other devices (`remote_access`); the token API stays on loopback.+pub const DEFAULT_REMOTE_PORT: u16 = 39152;/// Schema 8 (2026-10-12): the upscalers folder setting is gone (always `<sdcpp>/models/upscalers`)/// and ESRGAN tile sizes reset to automatic./// Schema 9 (2026-10-16, #14): profiles record their model and source; model paths edited by@@ -280,6 +282,11 @@ pub struct AppConfig {pub gpu_backend: GpuBackend,pub server_port: u16,pub service_port: u16,+ /// Open the browser UI to other devices on the network (`remote_port`, all interfaces).+ /// Needs a password first (`remote::PasswordFile`). Changed only through `/remote`: a+ /// whole-config save keeps the current values (`Engine::set_config`).+ pub remote_access: bool,+ pub remote_port: u16,pub active_profile: String,pub profiles: Vec<ModelProfile>,/// ggml device name for diffusion + VAE, e.g. "cuda0" (see `sd-server --list-devices`).@@ -359,6 +366,8 @@ impl Default for AppConfig {gpu_backend: GpuBackend::default(),server_port: DEFAULT_SERVER_PORT,service_port: DEFAULT_SERVICE_PORT,+ remote_access: false,+ remote_port: DEFAULT_REMOTE_PORT,device: "cuda0".into(),text_encoder_placement: TextEncoderPlacement::Ram,vram_reserve_gib: 1.0,@@ -424,7 +433,11 @@ impl LoraEntry {}}+/// `QLS_OUTPUT_DIR` sets it for a new install (the Docker image's `/gallery` volume).pub fn default_output_dir() -> PathBuf {+ if let Ok(p) = std::env::var("QLS_OUTPUT_DIR") {+ return PathBuf::from(p);+ }dirs::picture_dir().or_else(|| dirs::home_dir().map(|h| h.join("Pictures"))).unwrap_or_else(|| PathBuf::from("."))@@ -824,11 +837,30 @@ impl AppConfig {self.upscaler().map(|(_, p)| p)}+ /// A save from a browser (another device) changes the app's settings, not the computer's:+ /// folders, model files, ports, engine arguments and network access keep their values in+ /// `current`. Those take a path on the server or decide what runs there, and only the+ /// desktop app (or the config file) sets them.+ pub fn keep_computer_settings(&mut self, current: &AppConfig) {+ self.sdcpp_dir = current.sdcpp_dir.clone();+ self.output_dir = current.output_dir.clone();+ self.profiles = current.profiles.clone();+ self.active_profile = current.active_profile.clone();+ self.extra_server_args = current.extra_server_args.clone();+ self.server_port = current.server_port;+ self.service_port = current.service_port;+ self.remote_access = current.remote_access;+ self.remote_port = current.remote_port;+ }+pub fn validate(&self) -> Result<(), AppError> {if self.server_port == self.service_port {return Err(AppError::new(ErrorCode::InvalidConfig, "The inference server and the app service cannot use the same port."));}- if self.server_port < 1024 || self.service_port < 1024 {+ if self.remote_port == self.server_port || self.remote_port == self.service_port {+ return Err(AppError::new(ErrorCode::InvalidConfig, "The port for other devices must differ from the app's own ports."));+ }+ if self.server_port < 1024 || self.service_port < 1024 || self.remote_port < 1024 {return Err(AppError::new(ErrorCode::InvalidConfig, "Ports must be 1024 or higher."));}if !(0.0..=64.0).contains(&self.vram_reserve_gib) {@@ -1236,7 +1268,45 @@ mod tests {c.service_port = c.server_port;assert!(c.validate().is_err());let mut c = AppConfig::default();+ c.remote_port = c.service_port;+ assert!(c.validate().is_err());+ let mut c = AppConfig::default();c.device = "cuda0; rm".into();assert!(c.validate().is_err());}++ /// A 0.10.2 config file (no network fields) loads with access from other devices off.+ #[test]+ fn config_from_0_10_2_keeps_network_access_off() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("config.json");+ let old = r#"{"schemaVersion": 10, "serverPort": 39150, "servicePort": 39151, "setupComplete": true,+ "hardwarePreset": "16gb", "outputDir": "/home/me/Pictures/Kokon", "ui": {"quality": "balanced"}}"#;+ std::fs::write(&path, old).unwrap();+ let c = AppConfig::load_from(&path);+ assert!(!c.remote_access);+ assert_eq!(c.remote_port, DEFAULT_REMOTE_PORT);+ assert!(c.setup_complete);+ assert_eq!(c.output_dir, PathBuf::from("/home/me/Pictures/Kokon"));+ assert_eq!(c.ui["quality"], "balanced");+ assert!(c.validate().is_ok());+ }++ #[test]+ fn browser_saves_keep_the_computers_settings() {+ let current = AppConfig { remote_access: true, extra_server_args: vec!["--x".into()], ..AppConfig::default() };+ let mut sent = current.clone();+ sent.sdcpp_dir = PathBuf::from("/tmp/evil");+ sent.output_dir = PathBuf::from("/etc");+ sent.extra_server_args = vec!["--rpc".into()];+ sent.profiles[0].diffusion_model = PathBuf::from("/etc/passwd");+ sent.service_port = 40000;+ sent.remote_access = false;+ sent.remote_port = 40001;+ sent.flash_attention = !current.flash_attention;+ sent.keep_computer_settings(¤t);+ let mut expected = current.clone();+ expected.flash_attention = sent.flash_attention;+ assert_eq!(sent, expected, "only the app setting changed");+ }}diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rsindex e6bdc9b..cb5f545 100644--- a/crates/qls-core/src/engine.rs+++ b/crates/qls-core/src/engine.rs@@ -283,8 +283,14 @@ impl Engine {/// Replaces the configuration. Returns true when the backend must restart.pub fn set_config(&self, mut new: AppConfig) -> AppResult<bool> {- // LoRAs change only through `set_loras` (a Settings save may carry an older list).- new.loras = self.cfg.read().unwrap().loras.clone();+ // LoRAs change only through `set_loras`, network access only through `set_remote` (a+ // Settings save may carry older values).+ {+ let cur = self.cfg.read().unwrap();+ new.loras = cur.loras.clone();+ new.remote_access = cur.remote_access;+ new.remote_port = cur.remote_port;+ }// The official profile follows the folder and preset; see `AppConfig::normalize`.new.normalize();new.validate()?;@@ -305,6 +311,19 @@ impl Engine {Ok(restart)}+ /// Turns access from other devices on or off (Settings → Access from other devices).+ pub fn set_remote(&self, enabled: bool, port: u16) -> AppResult<()> {+ let mut new = self.config();+ new.remote_access = enabled;+ new.remote_port = port;+ new.validate()?;+ new.save()?;+ let mut g = self.cfg.write().unwrap();+ g.remote_access = enabled;+ g.remote_port = port;+ Ok(())+ }+/// Replaces the LoRA list (callers hold `lora::LIBRARY`).fn set_loras(&self, loras: Vec<LoraEntry>) -> AppResult<()> {let mut new = self.config();diff --git a/crates/qls-core/src/error.rs b/crates/qls-core/src/error.rsindex c89d536..1e74fe9 100644--- a/crates/qls-core/src/error.rs+++ b/crates/qls-core/src/error.rs@@ -24,6 +24,12 @@ pub enum ErrorCode {Cancelled,GenerationFailed,Unauthorized,+ /// A browser without a valid session: show the password screen.+ LoginRequired,+ /// Not allowed from a browser (paths on the server, settings of the computer it runs on).+ Forbidden,+ /// Too many wrong passwords from this address: wait `retry_after_s` seconds.+ TooManyAttempts,Internal,}@@ -67,9 +73,10 @@ impl AppError {pub fn http_status(&self) -> u16 {match self.code {ErrorCode::InvalidInput | ErrorCode::InvalidPath | ErrorCode::MalformedRequest | ErrorCode::ImageDecode => 400,- ErrorCode::Unauthorized => 401,+ ErrorCode::Unauthorized | ErrorCode::LoginRequired => 401,+ ErrorCode::Forbidden => 403,ErrorCode::NotFound => 404,- ErrorCode::QueueFull => 429,+ ErrorCode::QueueFull | ErrorCode::TooManyAttempts => 429,ErrorCode::Unsupported => 422,ErrorCode::ServerUnavailable | ErrorCode::ServerStartFailed | ErrorCode::ServerCrashed => 503,_ => 500,diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rsindex e422d05..c87d53f 100644--- a/crates/qls-core/src/lib.rs+++ b/crates/qls-core/src/lib.rs@@ -18,6 +18,7 @@ pub mod paths;pub mod pipeline;pub mod planner;pub mod process;+pub mod remote;pub mod sdcpp;pub mod speed;pub mod store;diff --git a/crates/qls-core/src/remote.rs b/crates/qls-core/src/remote.rsnew file mode 100644index 0000000..5e454e2--- /dev/null+++ b/crates/qls-core/src/remote.rs@@ -0,0 +1,327 @@+//! Access from other devices: the browser UI on the local network (or through a VPN such as+//! Tailscale), behind a password. The rules live here so they can be tested without HTTP:+//!+//! - the password is stored only as an Argon2id hash (`remote-auth.json` in the data folder,+//! never in `config.json`, which the API returns);+//! - a login opens a session (a random cookie value, kept in memory: a restart signs browsers+//! out); changing the password ends every session;+//! - 5 wrong passwords in a row from one address lock it for 1 minute, doubling up to 15;+//! - a browser session may use only the endpoints the UI needs, and never one that takes a+//! path on the server or changes what the computer runs (see [`browser_allowed`]).++use std::collections::HashMap;+use std::net::IpAddr;+use std::path::{Path, PathBuf};+use std::sync::Mutex;+use std::time::{Duration, Instant};++use argon2::{+ Argon2,+ password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},+};+use serde::{Deserialize, Serialize};++use crate::error::{AppError, AppResult, ErrorCode};+use crate::planner::GenerationRequest;++pub const MIN_PASSWORD_CHARS: usize = 8;+/// Long enough that a phone or laptop rarely asks again; a new password ends it sooner.+pub const SESSION_TTL: Duration = Duration::from_secs(90 * 24 * 3600);+pub const SESSION_COOKIE: &str = "kokon_session";+/// Wrong passwords in a row before an address waits.+pub const FREE_ATTEMPTS: u32 = 5;+const FIRST_LOCK: Duration = Duration::from_secs(60);+const MAX_LOCK: Duration = Duration::from_secs(15 * 60);+/// Sessions kept at most (oldest dropped): one per browser that logged in.+const MAX_SESSIONS: usize = 200;++#[derive(Serialize, Deserialize)]+struct AuthFile {+ password_hash: String,+}++/// `<data dir>/remote-auth.json`.+pub fn password_file(data_dir: &Path) -> PathBuf {+ data_dir.join("remote-auth.json")+}++/// The stored hash, if a password was set (and the file is readable and well-formed).+pub fn load_hash(file: &Path) -> Option<String> {+ let f: AuthFile = serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()?;+ PasswordHash::new(&f.password_hash).ok()?;+ Some(f.password_hash)+}++/// Hashes `password` and writes it to `file` (readable by the owner only on Unix).+pub fn set_password(file: &Path, password: &str) -> AppResult<String> {+ if password.chars().count() < MIN_PASSWORD_CHARS {+ return Err(AppError::invalid(format!("Use at least {MIN_PASSWORD_CHARS} characters.")));+ }+ let hash = Argon2::default().hash_password(password.as_bytes()).map_err(AppError::internal)?.to_string();+ let body = serde_json::to_string_pretty(&AuthFile { password_hash: hash.clone() }).map_err(AppError::internal)?;+ let tmp = file.with_extension("json.tmp");+ std::fs::write(&tmp, body).map_err(|e| AppError::io("save the password", &tmp, e))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));+ }+ std::fs::rename(&tmp, file).map_err(|e| AppError::io("save the password", file, e))?;+ Ok(hash)+}++/// Removes the password (access from other devices then stays closed).+pub fn clear_password(file: &Path) -> AppResult<()> {+ match std::fs::remove_file(file) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(AppError::io("remove the password", file, e)),+ _ => Ok(()),+ }+}++/// Slow on purpose (Argon2): call it off the async runtime.+pub fn verify(hash: &str, password: &str) -> bool {+ PasswordHash::new(hash).is_ok_and(|h| Argon2::default().verify_password(password.as_bytes(), &h).is_ok())+}++struct Failures {+ count: u32,+ locked_until: Option<Instant>,+}++/// Wrong passwords per address.+#[derive(Default)]+pub struct Limiter {+ by_ip: Mutex<HashMap<IpAddr, Failures>>,+}++impl Limiter {+ /// `Err(seconds)` while `ip` has to wait before trying again.+ pub fn check(&self, ip: IpAddr, now: Instant) -> Result<(), u64> {+ match self.by_ip.lock().unwrap().get(&ip).and_then(|f| f.locked_until) {+ Some(t) if t > now => Err((t - now).as_secs().max(1)),+ _ => Ok(()),+ }+ }++ /// A wrong password; returns how long `ip` now waits (0 = it can try again at once).+ pub fn fail(&self, ip: IpAddr, now: Instant) -> u64 {+ let mut m = self.by_ip.lock().unwrap();+ if m.len() > 10_000 {+ m.retain(|_, f| f.locked_until.is_some_and(|t| t > now));+ }+ let f = m.entry(ip).or_insert(Failures { count: 0, locked_until: None });+ f.count += 1;+ if f.count < FREE_ATTEMPTS {+ return 0;+ }+ let lock = FIRST_LOCK.saturating_mul(1 << (f.count - FREE_ATTEMPTS).min(10)).min(MAX_LOCK);+ f.locked_until = Some(now + lock);+ lock.as_secs()+ }++ pub fn succeed(&self, ip: IpAddr) {+ self.by_ip.lock().unwrap().remove(&ip);+ }+}++/// Signed-in browsers: cookie value → expiry.+#[derive(Default)]+pub struct Sessions {+ by_id: Mutex<HashMap<String, Instant>>,+}++impl Sessions {+ pub fn create(&self, now: Instant) -> String {+ let id = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());+ let mut m = self.by_id.lock().unwrap();+ m.retain(|_, exp| *exp > now);+ if m.len() >= MAX_SESSIONS+ && let Some(oldest) = m.iter().min_by_key(|(_, exp)| **exp).map(|(k, _)| k.clone())+ {+ m.remove(&oldest);+ }+ m.insert(id.clone(), now + SESSION_TTL);+ id+ }++ pub fn valid(&self, id: &str, now: Instant) -> bool {+ self.by_id.lock().unwrap().get(id).is_some_and(|exp| *exp > now)+ }++ pub fn remove(&self, id: &str) {+ self.by_id.lock().unwrap().remove(id);+ }++ /// The password changed or was removed: every browser signs in again.+ pub fn clear(&self) {+ self.by_id.lock().unwrap().clear();+ }+}++/// What a browser session may call, by method and path under `/api/v1`. Everything the UI+/// needs, minus what takes a path on the server (`/inputs/import`, `/models/scan`, exports,+/// `/loras` add, `/luts/import`, `/image-info`), the scripting endpoints that accept paths+/// (`/generate`, `/edit`...), `/shutdown` and the network settings (`/remote`). Jobs and plans+/// are also checked by [`stored_sources_only`]; config saves by `AppConfig::keep_computer_settings`.+#[allow(clippy::match_like_matches_macro)]+pub fn browser_allowed(method: &str, path: &str) -> bool {+ let seg: Vec<&str> = path.trim_matches('/').split('/').collect();+ match (method, seg.as_slice()) {+ ("GET", ["status" | "setup" | "models" | "upscalers" | "config" | "diagnostics" | "logs" | "jobs" | "events" | "gallery" | "loras" | "luts"]) => true,+ ("GET", ["setup", "hardware" | "install" | "legacy-upscalers"]) => true,+ ("GET", ["enhancer", "defaults"]) => true,+ ("GET", ["jobs", _] | ["jobs", _, "wait"]) => true,+ ("GET", ["inputs", _] | ["inputs", _, "image" | "thumb"]) => true,+ ("GET", ["gallery", _] | ["gallery", _, "image" | "thumb" | "original"]) => true,+ ("GET", ["luts", _, "preview"]) => true,+ ("PUT", ["config"]) => true,+ ("POST", ["setup", "install" | "gpu"] | ["setup", "install", "cancel"]) => true,+ ("POST", ["models", "use" | "vae"]) => true,+ ("POST", ["upscalers", _, "download"]) => true,+ ("POST", ["backend", "start" | "stop" | "restart"]) => true,+ ("POST", ["plan" | "jobs" | "inputs" | "examples"]) => true,+ ("POST", ["jobs", _, "cancel"]) => true,+ ("POST", ["private", "clear"]) => true,+ ("POST", ["luts", _, "apply"]) => true,+ ("POST", ["session", "heartbeat" | "release"]) => true,+ ("PATCH", ["gallery", _] | ["loras", _]) => true,+ ("DELETE", ["gallery", _] | ["loras", _] | ["luts", _] | ["setup", "legacy-upscalers"]) => true,+ _ => false,+ }+}++/// A browser's job or plan may use only images already in Kokon (uploads and results), never+/// a path on the server, and saves to the gallery only.+pub fn stored_sources_only(req: &GenerationRequest, workspace: Option<&str>) -> AppResult<()> {+ let stored = |s: &str| s.starts_with("input:") || s.starts_with("gen:");+ if !req.images.iter().all(|s| stored(s)) || !req.mask.as_deref().is_none_or(stored) {+ return Err(AppError::new(ErrorCode::Forbidden, "From a browser, upload the image first."));+ }+ if req.output_path.is_some() || workspace.is_some_and(|w| !w.trim().is_empty()) {+ return Err(AppError::new(ErrorCode::Forbidden, "From a browser, results go to the gallery."));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn password_is_stored_as_a_hash_only() {+ let dir = tempfile::tempdir().unwrap();+ let f = password_file(dir.path());+ assert!(load_hash(&f).is_none());+ assert!(set_password(&f, "short").is_err(), "fewer than 8 characters");+ set_password(&f, "correct horse").unwrap();+ let text = std::fs::read_to_string(&f).unwrap();+ assert!(!text.contains("correct horse"));+ let hash = load_hash(&f).unwrap();+ assert!(hash.starts_with("$argon2id$"));+ assert!(verify(&hash, "correct horse"));+ assert!(!verify(&hash, "correct horsE"));+ assert!(!verify("not a hash", "correct horse"));+ clear_password(&f).unwrap();+ assert!(load_hash(&f).is_none());+ clear_password(&f).unwrap();+ }++ #[test]+ fn a_broken_password_file_counts_as_no_password() {+ let dir = tempfile::tempdir().unwrap();+ let f = password_file(dir.path());+ std::fs::write(&f, r#"{"password_hash": "plain text"}"#).unwrap();+ assert!(load_hash(&f).is_none());+ }++ #[test]+ fn five_wrong_passwords_lock_the_address_for_longer_each_time() {+ let l = Limiter::default();+ let ip: IpAddr = "192.168.1.30".parse().unwrap();+ let other: IpAddr = "192.168.1.31".parse().unwrap();+ let t = Instant::now();+ for _ in 0..FREE_ATTEMPTS - 1 {+ assert_eq!(l.fail(ip, t), 0);+ assert!(l.check(ip, t).is_ok());+ }+ assert_eq!(l.fail(ip, t), 60);+ assert_eq!(l.check(ip, t + Duration::from_secs(10)), Err(50));+ assert!(l.check(other, t).is_ok(), "other devices are not locked");+ assert!(l.check(ip, t + Duration::from_secs(61)).is_ok());+ assert_eq!(l.fail(ip, t + Duration::from_secs(61)), 120);+ let mut wait = 0;+ for _ in 0..10 {+ wait = l.fail(ip, t);+ }+ assert_eq!(wait, 900, "at most 15 minutes");+ l.succeed(ip);+ assert!(l.check(ip, t).is_ok());+ assert_eq!(l.fail(ip, t), 0, "a login starts the count again");+ }++ #[test]+ fn sessions_expire_and_end_with_a_new_password() {+ let s = Sessions::default();+ let t = Instant::now();+ let a = s.create(t);+ let b = s.create(t);+ assert_ne!(a, b);+ assert_eq!(a.len(), 64);+ assert!(s.valid(&a, t) && s.valid(&b, t));+ assert!(!s.valid("nope", t));+ assert!(!s.valid(&a, t + SESSION_TTL + Duration::from_secs(1)));+ s.remove(&a);+ assert!(!s.valid(&a, t) && s.valid(&b, t));+ s.clear();+ assert!(!s.valid(&b, t));+ }++ #[test]+ fn browsers_cannot_reach_paths_on_the_server() {+ for (m, p) in [+ ("GET", "/status"),+ ("GET", "/gallery/abc/image"),+ ("GET", "/events"),+ ("POST", "/jobs"),+ ("POST", "/inputs"),+ ("PUT", "/config"),+ ("POST", "/session/heartbeat"),+ ("DELETE", "/gallery/abc"),+ ] {+ assert!(browser_allowed(m, p), "{m} {p}");+ }+ for (m, p) in [+ ("POST", "/inputs/import"),+ ("POST", "/models/scan"),+ ("POST", "/models/inspect"),+ ("POST", "/models/user"),+ ("POST", "/gallery/abc/export"),+ ("POST", "/image-info"),+ ("POST", "/loras"),+ ("POST", "/luts/import"),+ ("POST", "/generate"),+ ("POST", "/edit"),+ ("POST", "/shutdown"),+ ("GET", "/remote"),+ ("POST", "/remote"),+ ("POST", "/remote/password"),+ ("DELETE", "/jobs"),+ ("GET", "/gallery/a/b/c"),+ ] {+ assert!(!browser_allowed(m, p), "{m} {p}");+ }+ }++ #[test]+ fn browser_jobs_use_stored_images_only() {+ let ok = GenerationRequest { images: vec!["input:a".into(), "gen:b".into()], mask: Some("input:m".into()), ..Default::default() };+ assert!(stored_sources_only(&ok, None).is_ok());+ let path = GenerationRequest { images: vec!["/etc/passwd".into()], ..Default::default() };+ assert_eq!(stored_sources_only(&path, None).unwrap_err().code, ErrorCode::Forbidden);+ let mask = GenerationRequest { mask: Some("C:\\secret.png".into()), ..Default::default() };+ assert!(stored_sources_only(&mask, None).is_err());+ let out = GenerationRequest { output_path: Some("/tmp/x.png".into()), ..Default::default() };+ assert!(stored_sources_only(&out, None).is_err());+ assert!(stored_sources_only(&GenerationRequest::default(), Some("/home")).is_err());+ }+}diff --git a/crates/qls-service/Cargo.toml b/crates/qls-service/Cargo.tomlindex 062aa64..688fb74 100644--- a/crates/qls-service/Cargo.toml+++ b/crates/qls-service/Cargo.toml@@ -13,6 +13,8 @@ path = "src/main.rs"axum = "0.8.9"futures-util = "0.3.34"qls-core = { version = "0.10.0", path = "../qls-core" }+rpassword = "7.5.4"+rust-embed = { version = "8.13.0", features = ["mime-guess"] }serde = { version = "1.0.229", features = ["derive"] }serde_json = "1.0.151"sysinfo = "0.39.6"@@ -23,3 +25,7 @@ tracing = "0.1.44"tracing-appender = "0.2.5"tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }uuid = { version = "1.27.0", features = ["v4"] }++[dev-dependencies]+tempfile = "3.27.0"+tower = { version = "0.5.3", features = ["util"] }diff --git a/crates/qls-service/build.rs b/crates/qls-service/build.rsnew file mode 100644index 0000000..7e7c240--- /dev/null+++ b/crates/qls-service/build.rs@@ -0,0 +1,4 @@+// Rebuild when the UI build changes: release builds embed dist/ (remote.rs, rust-embed).+fn main() {+ println!("cargo:rerun-if-changed=../../dist");+}diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rsindex 128dd28..34c0e60 100644--- a/crates/qls-service/src/api.rs+++ b/crates/qls-service/src/api.rs@@ -1,5 +1,6 @@-//! Stable local API, versioned under /api/v1. Loopback-only, token-protected, and-//! independent of sd-server's own schema (the engine adapts between the two).+//! Stable local API, versioned under /api/v1, independent of sd-server's own schema (the+//! engine adapts between the two). On loopback it takes the token (desktop app, MCP, scripts)+//! or a signed-in browser; on the network listener only a signed-in browser (see `remote`).use std::convert::Infallible;use std::path::{Path, PathBuf};@@ -9,7 +10,7 @@ use std::time::{Duration, Instant};use axum::{Json, Router,body::{Body, Bytes},- extract::{DefaultBodyLimit, Path as AxPath, Query, Request, State},+ extract::{DefaultBodyLimit, Extension, Path as AxPath, Query, Request, State},http::{HeaderMap, HeaderValue, Method, StatusCode, header},middleware::{self, Next},response::{IntoResponse, Response, Sse, sse::Event as SseEvent},@@ -33,6 +34,7 @@ use serde::Deserialize;use serde_json::{Value, json};use tokio_stream::StreamExt;+use crate::remote::{self as web, Caller};use crate::{AppState, Lease};type St = State<Arc<AppState>>;@@ -56,7 +58,9 @@ type ApiResult<T> = Result<T, ApiError>;const ALLOWED_ORIGINS: &[&str] = &["http://tauri.localhost", "https://tauri.localhost", "tauri://localhost", "http://localhost:1420"];-pub fn router(state: Arc<AppState>) -> Router {+/// The API and the UI. `lan`: the network listener, where the token is refused.+pub fn router(state: Arc<AppState>, lan: bool) -> Router {+ let ctx = AuthCtx { app: state.clone(), lan };let api = Router::new().route("/status", get(status)).route("/setup", get(setup))@@ -114,16 +118,28 @@ pub fn router(state: Arc<AppState>) -> Router {.route("/session/heartbeat", post(heartbeat)).route("/session/release", post(release)).route("/shutdown", post(shutdown))- .layer(middleware::from_fn_with_state(state.clone(), auth))+ .route("/remote", get(remote_status).post(remote_set))+ .route("/remote/password", post(remote_password).delete(remote_password_clear))+ .layer(middleware::from_fn_with_state(ctx.clone(), auth)).layer(DefaultBodyLimit::max(4 * 1024 * 1024));let uploads = Router::new().route("/inputs", post(upload_input)).layer(DefaultBodyLimit::max(210 * 1024 * 1024));Router::new().route("/api/v1/ping", get(ping))- .nest("/api/v1", api.merge(uploads.layer(middleware::from_fn_with_state(state.clone(), auth))))+ .route("/api/v1/auth/session", get(web::session))+ .route("/api/v1/auth/login", post(web::login))+ .route("/api/v1/auth/logout", post(web::logout))+ .nest("/api/v1", api.merge(uploads.layer(middleware::from_fn_with_state(ctx, auth))))+ .fallback(web::ui).layer(middleware::from_fn(cors)).with_state(state)}+#[derive(Clone)]+struct AuthCtx {+ app: Arc<AppState>,+ lan: bool,+}+/// CORS for the desktop webview origins only; everything else gets no CORS headers.async fn cors(req: Request, next: Next) -> Response {let origin = req.headers().get(header::ORIGIN).and_then(|o| o.to_str().ok()).map(str::to_owned);@@ -157,28 +173,48 @@ fn set_cors(h: &mut HeaderMap, origin: &str) {h.insert(header::VARY, HeaderValue::from_static("Origin"));}-/// Bearer token (or `?token=` for <img>/EventSource), and a foreign-Origin block so web-/// pages open in a browser cannot drive the local API.-async fn auth(State(s): St, req: Request, next: Next) -> Response {- if let Some(o) = req.headers().get(header::ORIGIN).and_then(|o| o.to_str().ok())- && !ALLOWED_ORIGINS.contains(&o)- {- return ApiError(AppError::new(ErrorCode::Unauthorized, "Requests from web pages are not allowed.")).into_response();- }+/// Bearer token (or `?token=` for <img>/EventSource) on loopback, with a foreign-Origin block+/// so web pages open in a browser cannot drive the local API; or a signed-in browser, limited+/// to what the UI needs (`qls_core::remote::browser_allowed`) and sending the CSRF header with+/// every change. The network listener never takes the token.+async fn auth(State(c): State<AuthCtx>, mut req: Request, next: Next) -> Response {+ let s = &c.app;let header_tok = req.headers().get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).map(str::to_owned);- let query_tok = req.uri().query().and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("token=")).map(str::to_owned));- let ok = header_tok.or(query_tok).map(|t| constant_eq(t.as_bytes(), s.token.as_bytes())).unwrap_or(false);- if !ok {- return ApiError(AppError::new(ErrorCode::Unauthorized, "Missing or invalid API token (see service.json).")).into_response();+ let query_tok = req.uri().query().and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("token=")).map(str::to_owned)).filter(|t| !t.is_empty());+ if let Some(t) = header_tok.or(query_tok)+ && !c.lan+ {+ if let Some(o) = req.headers().get(header::ORIGIN).and_then(|o| o.to_str().ok())+ && !ALLOWED_ORIGINS.contains(&o)+ {+ return ApiError(AppError::new(ErrorCode::Unauthorized, "Requests from web pages are not allowed.")).into_response();+ }+ if !constant_eq(t.as_bytes(), s.token.as_bytes()) {+ return ApiError(AppError::new(ErrorCode::Unauthorized, "Missing or invalid API token (see service.json).")).into_response();+ }+ req.extensions_mut().insert(Caller::Local);+ // No `touch()` here: heartbeats and status polls are not work, and counting them kept+ // the model loaded for as long as an MCP client stayed connected.+ return next.run(req).await;+ }+ if web::browser_session(s, req.headers()) {+ let path = req.uri().path();+ let path = path.strip_prefix("/api/v1").unwrap_or(path);+ if !qls_core::remote::browser_allowed(req.method().as_str(), path) {+ return ApiError(AppError::new(ErrorCode::Forbidden, "This is not available from a browser.")).into_response();+ }+ if !matches!(*req.method(), Method::GET | Method::HEAD) && !web::has_csrf_header(req.headers()) {+ return ApiError(AppError::new(ErrorCode::Forbidden, "Requests from other sites are not allowed.")).into_response();+ }+ req.extensions_mut().insert(Caller::Browser);+ return next.run(req).await;}- // No `touch()` here: heartbeats and status polls are not work, and counting them kept- // the model loaded for as long as an MCP client stayed connected.- next.run(req).await+ ApiError(AppError::new(ErrorCode::LoginRequired, "Sign in with the password (scripts on this computer: the API token in service.json).")).into_response()}fn constant_eq(a: &[u8], b: &[u8]) -> bool {@@ -479,7 +515,10 @@ async fn enhancer_defaults() -> Json<Value> {Json(json!({ "t2i": enhancer::T2I_SYSTEM_PROMPT, "edit": enhancer::EDIT_SYSTEM_PROMPT, "compose": enhancer::COMPOSE_SYSTEM_PROMPT, "max_chars": enhancer::MAX_SYSTEM_PROMPT_CHARS }))}-async fn put_config(State(s): St, Json(cfg): Json<AppConfig>) -> ApiResult<Json<Value>> {+async fn put_config(State(s): St, Extension(caller): Extension<Caller>, Json(mut cfg): Json<AppConfig>) -> ApiResult<Json<Value>> {+ if caller == Caller::Browser {+ cfg.keep_computer_settings(&s.engine.config());+ }let restart = s.engine.set_config(cfg)?;let st = s.engine.server.status();if restart && st.owned && st.state == qls_core::process::ServerState::Ready && !s.engine.has_pending_work() {@@ -630,7 +669,12 @@ fn workspace_path(w: Option<&str>) -> Result<Option<PathBuf>, AppError> {}}-async fn create_job(State(s): St, Json(b): Json<JobBody>) -> ApiResult<(StatusCode, Json<JobView>)> {+async fn create_job(State(s): St, Extension(caller): Extension<Caller>, Json(mut b): Json<JobBody>) -> ApiResult<(StatusCode, Json<JobView>)> {+ if caller == Caller::Browser {+ qls_core::remote::stored_sources_only(&b.request, b.workspace.as_deref())?;+ // Browser jobs outlive the desktop window (`client_left` cancels "ui" jobs).+ b.request.client = Some("web".into());+ }let ws = workspace_path(b.workspace.as_deref())?;let j = s.engine.submit(b.request, ws)?;Ok((StatusCode::ACCEPTED, Json(j)))@@ -768,7 +812,10 @@ struct PlanBody {}/// Dry run: resolved mode, working/output size and notes for the current inputs.-async fn plan(State(s): St, Json(b): Json<PlanBody>) -> ApiResult<Json<Value>> {+async fn plan(State(s): St, Extension(caller): Extension<Caller>, Json(b): Json<PlanBody>) -> ApiResult<Json<Value>> {+ if caller == Caller::Browser {+ qls_core::remote::stored_sources_only(&b.request, b.workspace.as_deref())?;+ }let engine = s.engine.clone();let ws = workspace_path(b.workspace.as_deref())?;let v = tokio::task::spawn_blocking(move || -> Result<Value, AppError> {@@ -810,10 +857,28 @@ fn source_size(engine: &qls_core::engine::Engine, src: &str, ws: Option<&Path>)// Events (SSE)// ----------------------------------------------------------------------------------------async fn events(State(s): St) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {+async fn events(State(s): St, Extension(caller): Extension<Caller>) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {let rx = s.engine.events.subscribe();let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(|r| r.ok()).map(|ev| Ok(SseEvent::default().json_data(ev).unwrap_or_default()));- Sse::new(stream).keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))+ // Streams end when the service shuts down (an open browser tab would otherwise hold the+ // graceful shutdown, and with it an app update), and a browser's with its session (new+ // password, access turned off).+ let mut epoch = s.remote.epoch.subscribe();+ let st = s.clone();+ let ended = async move {+ let session_ended = async {+ if caller == Caller::Browser {+ let _ = epoch.changed().await;+ } else {+ std::future::pending::<()>().await;+ }+ };+ tokio::select! {+ _ = st.shutdown.notified() => {}+ _ = session_ended => {}+ }+ };+ Sse::new(futures_util::StreamExt::take_until(stream, ended)).keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))}// ---------------------------------------------------------------------------------------@@ -1130,9 +1195,13 @@ struct HeartbeatBody {pid: Option<u32>,}-async fn heartbeat(State(s): St, Json(b): Json<HeartbeatBody>) -> Json<Value> {- let kind = b.kind.unwrap_or_else(|| "client".into());- s.leases.lock().unwrap().insert(b.client_id.chars().take(80).collect(), Lease { kind, last_seen: Instant::now(), pid: b.pid });+async fn heartbeat(State(s): St, Extension(caller): Extension<Caller>, Json(b): Json<HeartbeatBody>) -> Json<Value> {+ // A browser holds its lease by heartbeat only, and never as the desktop window.+ let (kind, pid) = match caller {+ Caller::Local => (b.kind.unwrap_or_else(|| "client".into()), b.pid),+ Caller::Browser => ("web".to_string(), None),+ };+ s.leases.lock().unwrap().insert(b.client_id.chars().take(80).collect(), Lease { kind, last_seen: Instant::now(), pid });*s.exit_deadline.lock().unwrap() = None;s.quick_exit.store(false, std::sync::atomic::Ordering::Relaxed);Json(json!({ "ok": true, "ttl_s": crate::LEASE_TTL.as_secs() }))@@ -1153,6 +1222,53 @@ async fn release(State(s): St, Json(b): Json<HeartbeatBody>) -> Json<Value> {Json(json!({ "ok": true, "remaining_clients": remaining }))}+// ---------------------------------------------------------------------------------------+// Access from other devices (desktop app Settings; never from a browser)+// ---------------------------------------------------------------------------------------++async fn remote_status(State(s): St) -> Json<Value> {+ Json(web::status_json(&s))+}++#[derive(Deserialize)]+struct RemoteBody {+ enabled: bool,+ port: Option<u16>,+}++async fn remote_set(State(s): St, Json(b): Json<RemoteBody>) -> ApiResult<Json<Value>> {+ if b.enabled && !s.remote.password_set() {+ return Err(AppError::invalid("Set a password first.").into());+ }+ let port = b.port.unwrap_or(s.engine.config().remote_port);+ s.engine.set_remote(b.enabled, port)?;+ web::sync_listener(&s);+ Ok(Json(web::status_json(&s)))+}++#[derive(Deserialize)]+struct PasswordBody {+ password: String,+}++/// Sets or changes the password; every browser signs in again.+async fn remote_password(State(s): St, Json(b): Json<PasswordBody>) -> ApiResult<Json<Value>> {+ let r = s.clone();+ tokio::task::spawn_blocking(move || r.remote.set_password(&b.password)).await.map_err(AppError::internal)??;+ tracing::info!("password for other devices changed");+ web::sync_listener(&s);+ Ok(Json(web::status_json(&s)))+}++/// Removes the password and closes access from other devices.+async fn remote_password_clear(State(s): St) -> ApiResult<Json<Value>> {+ s.remote.clear_password()?;+ let port = s.engine.config().remote_port;+ s.engine.set_remote(false, port)?;+ web::sync_listener(&s);+ Ok(Json(web::status_json(&s)))+}+async fn shutdown(State(s): St) -> Json<Value> {s.shutdown.notify_waiters();Json(json!({ "ok": true }))diff --git a/crates/qls-service/src/main.rs b/crates/qls-service/src/main.rsindex aa05422..abc3583 100644--- a/crates/qls-service/src/main.rs+++ b/crates/qls-service/src/main.rs@@ -2,13 +2,17 @@//!//! Owns the generation engine and the sd-server process, and exposes the stable local API//! (`http://127.0.0.1:<port>/api/v1/...`) used by the desktop app, the MCP server and-//! scripts. Exactly one instance runs (the port bind is the lock). It exits by itself when-//! no client holds a lease and no work is pending, stopping sd-server unless the user-//! chose to keep it running.+//! scripts, plus the browser UI at `/`. With access from other devices on (and a password+//! set) the UI also listens on all interfaces (`remote.rs`). Exactly one instance runs (the+//! port bind is the lock). It exits by itself when no client holds a lease and no work is+//! pending, stopping sd-server unless the user chose to keep it running.#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]mod api;+mod remote;+#[cfg(test)]+mod security_tests;use std::collections::HashMap;use std::net::SocketAddr;@@ -49,6 +53,7 @@ pub struct AppState {pub quick_exit: std::sync::atomic::AtomicBool,pub shutdown: tokio::sync::Notify,pub started: Instant,+ pub remote: remote::RemoteState,}pub const LEASE_TTL: Duration = Duration::from_secs(45);@@ -112,13 +117,18 @@ fn init_logging(dir: &std::path::Path) -> tracing_appender::non_blocking::Workerconst HELP: &str = "\kokon-service — headless engine for Kokon (generation, job queue, gallery)-Usage: kokon-service [--port <n>] [--persistent]+Usage: kokon-service [--port <n>] [--persistent] [--remote]+ kokon-service --set-passwordOptions:- --port <n> Port of the local API (default: the configured service_port, 39151)- --persistent Keep sd-server running after the last client disconnects- -h, --help Print this help and exit- --version Print the version and exit+ --port <n> Port of the local API (default: the configured service_port, 39151)+ --persistent Keep sd-server running after the last client disconnects+ --remote Open the browser UI to other devices (the configured remote_port, 39152,+ on all interfaces) for this run. Needs a password first+ --set-password Set the password other devices sign in with (asked on the terminal, or+ one line on stdin), then exit. A running service picks it up+ -h, --help Print this help and exit+ --version Print the version and exitEnvironment:QLS_DATA_DIR Data folder: gallery, logs, models (default: the OS local app data folder)@@ -158,12 +168,56 @@ fn main() {print_meta(&text);return;}+ if args.iter().any(|a| a == "--set-password") {+ std::process::exit(set_password_cli());+ }run(args)}+/// `--set-password`: asked twice without echo on a terminal, else one line from stdin+/// (`docker exec -i ... --set-password < file`).+fn set_password_cli() -> i32 {+ use std::io::IsTerminal;+ let password = if std::io::stdin().is_terminal() {+ let first = rpassword::prompt_password("Password for other devices: ");+ let again = rpassword::prompt_password("Again: ");+ match (first, again) {+ (Ok(a), Ok(b)) if a == b => a,+ (Ok(_), Ok(_)) => {+ eprintln!("The two passwords differ; nothing changed.");+ return 1;+ }+ (Err(e), _) | (_, Err(e)) => {+ eprintln!("Could not read the password: {e}");+ return 1;+ }+ }+ } else {+ let mut line = String::new();+ if let Err(e) = std::io::stdin().read_line(&mut line) {+ eprintln!("Could not read the password: {e}");+ return 1;+ }+ line.trim_end_matches(['\r', '\n']).to_string()+ };+ let dir = data_dir();+ let _ = std::fs::create_dir_all(&dir);+ match qls_core::remote::set_password(&qls_core::remote::password_file(&dir), &password) {+ Ok(_) => {+ println!("Password saved. Browsers sign in again; a running kokon-service uses it within a few seconds.");+ 0+ }+ Err(e) => {+ eprintln!("{}", e.message);+ 1+ }+ }+}+#[tokio::main(flavor = "multi_thread", worker_threads = 4)]async fn run(args: Vec<String>) {let persistent = args.iter().any(|a| a == "--persistent");+ let forced_remote = args.iter().any(|a| a == "--remote");let dir = data_dir();let _ = std::fs::create_dir_all(&dir);// Rotate the service log at startup (keep one previous).@@ -232,14 +286,21 @@ async fn run(args: Vec<String>) {quick_exit: std::sync::atomic::AtomicBool::new(false),shutdown: tokio::sync::Notify::new(),started: Instant::now(),+ remote: remote::RemoteState::new(&dir, forced_remote),});+ remote::sync_listener(&state);+ if forced_remote && !state.remote.password_set() {+ let msg = "--remote: no password is set yet, so other devices cannot connect. Run `kokon-service --set-password` (Docker: `docker exec -it kokon kokon-service --set-password`); it applies without a restart.";+ tracing::warn!("{msg}");+ eprintln!("{msg}");+ }tokio::spawn(engine.clone().run_worker());tokio::spawn(lifecycle(state.clone()));tokio::spawn(server_watch(state.clone()));tokio::spawn(qls_core::engine_manifest::run(APP_VERSION));- let app = api::router(state.clone());+ let app = api::router(state.clone(), false).into_make_service_with_connect_info::<SocketAddr>();let st = state.clone();let serve = axum::serve(listener, app).with_graceful_shutdown(async move { st.shutdown.notified().await });if let Err(e) = serve.await {@@ -277,10 +338,15 @@ async fn lifecycle(state: Arc<AppState>) {let gap = last_tick.elapsed();last_tick = Instant::now();let resumed = gap > Duration::from_secs(20);+ // A password set from a terminal (`--set-password`) while running.+ if state.remote.reload_if_changed() {+ tracing::info!("password for other devices changed on disk");+ remote::sync_listener(&state);+ }if resumed {tracing::info!("resumed after {} s (computer asleep?): waiting for clients to check in", gap.as_secs());}- let (n_leases, has_ui, lost) = {+ let (n_leases, has_ui, has_window, lost) = {let mut leases = state.leases.lock().unwrap();if resumed {leases.values_mut().for_each(|l| l.last_seen = Instant::now());@@ -293,7 +359,8 @@ async fn lifecycle(state: Arc<AppState>) {}alive});- (leases.len(), leases.values().any(|l| l.kind == "ui"), lost)+ // A browser tab keeps the model loaded like the desktop window does.+ (leases.len(), leases.values().any(|l| l.kind == "ui"), leases.values().any(|l| l.kind == "ui" || l.kind == "web"), lost)};for (id, kind) in &lost {tracing::info!("client {id} ({kind}) is gone");@@ -325,7 +392,7 @@ async fn lifecycle(state: Arc<AppState>) {// Idle unload (MCP-only or scripted use): free VRAM after N idle minutes.let cfg = state.engine.config();let st = state.engine.server.status();- if !has_ui+ if !has_window&& !busy&& cfg.idle_unload_minutes > 0&& st.state == ServerState::Ready@@ -384,7 +451,7 @@ mod tests {assert_eq!(cli_meta(&args("--version")).unwrap(), format!("kokon-service {APP_VERSION}"));for flag in ["--help", "-h"] {let help = cli_meta(&args(flag)).unwrap();- for needle in ["--port", "--persistent", "QLS_DATA_DIR", "QLS_CONFIG_DIR", "QLS_LOG"] {+ for needle in ["--port", "--persistent", "--remote", "--set-password", "QLS_DATA_DIR", "QLS_CONFIG_DIR", "QLS_LOG"] {assert!(help.contains(needle), "{flag} does not mention {needle}");}}diff --git a/crates/qls-service/src/remote.rs b/crates/qls-service/src/remote.rsnew file mode 100644index 0000000..7e88499--- /dev/null+++ b/crates/qls-service/src/remote.rs@@ -0,0 +1,330 @@+//! Access from other devices: the browser UI, the password login and the network listener.+//! The rules (hashing, sessions, attempt limit, what a browser may call) are in+//! `qls_core::remote`; this file is the HTTP side.+//!+//! Two listeners serve the same router: loopback (`service_port`, the desktop app, the MCP+//! server and scripts, with the token) and, only while access is on *and* a password is set,+//! all interfaces (`remote_port`), where the token is refused and only a signed-in browser+//! gets in. Both serve the UI at `/`.++use std::net::{IpAddr, Ipv4Addr, SocketAddr};+use std::path::PathBuf;+use std::sync::{Arc, Mutex, RwLock};+use std::time::{Instant, SystemTime};++use axum::{+ Json,+ body::Body,+ extract::{ConnectInfo, Request, State},+ http::{HeaderMap, HeaderValue, Method, StatusCode, header},+ response::{IntoResponse, Response},+};+use qls_core::{+ error::{AppError, ErrorCode},+ remote::{self, Limiter, SESSION_COOKIE, SESSION_TTL, Sessions},+};+use serde::Deserialize;+use serde_json::{Value, json};++use crate::AppState;++/// Who is calling: the token (desktop app, MCP, scripts on this computer) or a browser+/// signed in with the password.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Caller {+ Local,+ Browser,+}++/// Header a browser adds to every request that changes something. Another site cannot send+/// it (it would need a CORS preflight, which only the desktop origins pass), so together with+/// the `SameSite=Strict` cookie it stops cross-site requests.+pub const CSRF_HEADER: &str = "x-kokon-csrf";++pub struct RemoteState {+ file: PathBuf,+ hash: RwLock<Option<String>>,+ /// Modification time of the password file when last read (a `--set-password` from a+ /// terminal is picked up without a restart).+ seen: Mutex<Option<SystemTime>>,+ pub sessions: Sessions,+ pub limiter: Limiter,+ /// `--remote`: on for this run whatever the setting says (headless, Docker).+ pub forced: bool,+ listener: Mutex<Option<Lan>>,+ error: Mutex<Option<String>>,+ /// Bumped when every session ends, so open event streams of browsers close too.+ pub epoch: tokio::sync::watch::Sender<u64>,+}++struct Lan {+ port: u16,+ task: tokio::task::JoinHandle<()>,+}++impl RemoteState {+ pub fn new(data_dir: &std::path::Path, forced: bool) -> Self {+ let file = remote::password_file(data_dir);+ let s = Self {+ hash: RwLock::new(None),+ seen: Mutex::new(None),+ file,+ sessions: Sessions::default(),+ limiter: Limiter::default(),+ forced,+ listener: Mutex::new(None),+ error: Mutex::new(None),+ epoch: tokio::sync::watch::channel(0).0,+ };+ s.reload_if_changed();+ s+ }++ pub fn password_set(&self) -> bool {+ self.hash.read().unwrap().is_some()+ }++ fn end_sessions(&self) {+ self.sessions.clear();+ self.epoch.send_modify(|e| *e += 1);+ }++ /// Reads the password file again if it changed; returns whether it did.+ pub fn reload_if_changed(&self) -> bool {+ let mtime = std::fs::metadata(&self.file).and_then(|m| m.modified()).ok();+ let mut seen = self.seen.lock().unwrap();+ if *seen == mtime {+ return false;+ }+ *seen = mtime;+ let new = remote::load_hash(&self.file);+ let mut h = self.hash.write().unwrap();+ if *h == new {+ return false;+ }+ *h = new;+ drop(h);+ self.end_sessions();+ true+ }++ pub fn set_password(&self, password: &str) -> Result<(), AppError> {+ let hash = remote::set_password(&self.file, password)?;+ *self.hash.write().unwrap() = Some(hash);+ *self.seen.lock().unwrap() = std::fs::metadata(&self.file).and_then(|m| m.modified()).ok();+ self.end_sessions();+ Ok(())+ }++ pub fn clear_password(&self) -> Result<(), AppError> {+ remote::clear_password(&self.file)?;+ *self.hash.write().unwrap() = None;+ *self.seen.lock().unwrap() = None;+ self.end_sessions();+ Ok(())+ }++ fn hash(&self) -> Option<String> {+ self.hash.read().unwrap().clone()+ }+}++/// Opens or closes the network listener to match the setting (or `--remote`) and the+/// password: it listens only while both say so.+pub fn sync_listener(state: &Arc<AppState>) {+ let cfg = state.engine.config();+ let r = &state.remote;+ let want = (cfg.remote_access || r.forced) && r.password_set();+ let mut cur = r.listener.lock().unwrap();+ if let Some(l) = cur.as_ref()+ && (!want || l.port != cfg.remote_port)+ {+ l.task.abort();+ tracing::info!("access from other devices closed (port {})", l.port);+ *cur = None;+ // Browsers signed in over the network sign in again next time.+ r.end_sessions();+ }+ if !want || cur.is_some() {+ if (cfg.remote_access || r.forced) && !r.password_set() {+ *r.error.lock().unwrap() = Some("Set a password first.".into());+ } else if !want {+ *r.error.lock().unwrap() = None;+ }+ return;+ }+ let port = cfg.remote_port;+ let bound = std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)))+ .and_then(|l| l.set_nonblocking(true).map(|_| l))+ .and_then(tokio::net::TcpListener::from_std);+ match bound {+ Ok(listener) => {+ let app = crate::api::router(state.clone(), true).into_make_service_with_connect_info::<SocketAddr>();+ let task = tokio::spawn(async move {+ if let Err(e) = axum::serve(listener, app).await {+ tracing::error!("network listener error: {e}");+ }+ });+ tracing::info!("access from other devices open on port {port} (all interfaces)");+ *r.error.lock().unwrap() = None;+ *cur = Some(Lan { port, task });+ }+ Err(e) => {+ tracing::error!("cannot open port {port} for other devices: {e}");+ *r.error.lock().unwrap() = Some(format!("Port {port} cannot be opened: {e}"));+ }+ }+}++/// This computer's address on the local network, as other devices reach it: the address the+/// system would send from (no packet is sent).+fn lan_address() -> Option<IpAddr> {+ let s = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;+ s.connect((Ipv4Addr::new(192, 0, 2, 1), 9)).ok()?;+ s.local_addr().ok().map(|a| a.ip()).filter(|ip| !ip.is_loopback() && !ip.is_unspecified())+}++pub fn status_json(state: &AppState) -> Value {+ let cfg = state.engine.config();+ let r = &state.remote;+ let listening = r.listener.lock().unwrap().as_ref().map(|l| l.port);+ let url = listening.and_then(|p| lan_address().map(|ip| format!("http://{ip}:{p}")));+ json!({+ "enabled": cfg.remote_access || r.forced, "forced": r.forced, "port": cfg.remote_port,+ "password_set": r.password_set(), "listening": listening.is_some(), "url": url,+ "error": r.error.lock().unwrap().clone(), "min_password_chars": remote::MIN_PASSWORD_CHARS,+ })+}++fn cookie_value(headers: &HeaderMap) -> Option<String> {+ headers.get_all(header::COOKIE).iter().filter_map(|v| v.to_str().ok()).flat_map(|v| v.split(';')).find_map(|kv| {+ let (k, v) = kv.trim().split_once('=')?;+ (k == SESSION_COOKIE).then(|| v.to_string())+ })+}++/// A signed-in browser (valid session cookie).+pub fn browser_session(state: &AppState, headers: &HeaderMap) -> bool {+ cookie_value(headers).is_some_and(|id| state.remote.sessions.valid(&id, Instant::now()))+}++fn peer_ip(req: &Request) -> IpAddr {+ let ext = req.extensions();+ ext.get::<ConnectInfo<SocketAddr>>()+ .map(|c| c.0.ip())+ .or_else(|| ext.get::<axum::extract::connect_info::MockConnectInfo<SocketAddr>>().map(|c| c.0.ip()))+ .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))+}++pub fn has_csrf_header(headers: &HeaderMap) -> bool {+ headers.get(CSRF_HEADER).is_some_and(|v| v == "1")+}++fn err(code: ErrorCode, msg: &str) -> Response {+ let e = AppError::new(code, msg);+ (StatusCode::from_u16(e.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), Json(json!({ "error": e }))).into_response()+}++/// `GET /api/v1/auth/session`: whether this browser is signed in and a password exists.+pub async fn session(State(s): State<Arc<AppState>>, headers: HeaderMap) -> Json<Value> {+ Json(json!({ "signed_in": browser_session(&s, &headers), "password_set": s.remote.password_set() }))+}++#[derive(Deserialize)]+pub struct LoginBody {+ password: String,+}++/// `POST /api/v1/auth/login`: the password for a session cookie. 5 wrong passwords in a row+/// from one address lock it (1 min, doubling up to 15); a locked address gets 429 whatever+/// it sends, so the lock tells nothing about the password.+pub async fn login(State(s): State<Arc<AppState>>, req: Request) -> Response {+ if !has_csrf_header(req.headers()) {+ return err(ErrorCode::Forbidden, "Requests from other sites are not allowed.");+ }+ let ip = peer_ip(&req);+ let bytes = match axum::body::to_bytes(req.into_body(), 64 * 1024).await {+ Ok(b) => b,+ Err(_) => return err(ErrorCode::InvalidInput, "The request was too large."),+ };+ let Ok(body) = serde_json::from_slice::<LoginBody>(&bytes) else {+ return err(ErrorCode::InvalidInput, "Send the password as JSON: {\"password\": \"...\"}.");+ };+ let Some(hash) = s.remote.hash() else {+ return err(ErrorCode::Forbidden, "No password is set. Set one in Kokon on the computer it runs on.");+ };+ if let Err(wait) = s.remote.limiter.check(ip, Instant::now()) {+ return locked(wait);+ }+ let ok = tokio::task::spawn_blocking(move || remote::verify(&hash, &body.password)).await.unwrap_or(false);+ if !ok {+ let wait = s.remote.limiter.fail(ip, Instant::now());+ tracing::warn!("wrong password from {ip}");+ if wait > 0 {+ tracing::warn!("{ip} waits {wait} s after too many wrong passwords");+ return locked(wait);+ }+ return err(ErrorCode::LoginRequired, "Wrong password.");+ }+ s.remote.limiter.succeed(ip);+ let id = s.remote.sessions.create(Instant::now());+ tracing::info!("browser signed in from {ip}");+ let cookie = format!("{SESSION_COOKIE}={id}; Path=/; HttpOnly; SameSite=Strict; Max-Age={}", SESSION_TTL.as_secs());+ let mut r = Json(json!({ "signed_in": true })).into_response();+ r.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_str(&cookie).unwrap());+ r+}++fn locked(wait: u64) -> Response {+ let mins = wait.div_ceil(60);+ let e = AppError::new(ErrorCode::TooManyAttempts, format!("Too many wrong passwords. Try again in {mins} minute{}.", if mins == 1 { "" } else { "s" }));+ let mut r = (StatusCode::TOO_MANY_REQUESTS, Json(json!({ "error": e, "retry_after_s": wait }))).into_response();+ r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from(wait));+ r+}++/// `POST /api/v1/auth/logout`.+pub async fn logout(State(s): State<Arc<AppState>>, headers: HeaderMap) -> Response {+ if !has_csrf_header(&headers) {+ return err(ErrorCode::Forbidden, "Requests from other sites are not allowed.");+ }+ if let Some(id) = cookie_value(&headers) {+ s.remote.sessions.remove(&id);+ }+ let mut r = Json(json!({ "signed_in": false })).into_response();+ r.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0")).unwrap());+ r+}++/// The built UI (`dist/`, from `npm run build`), compiled into the binary for release builds.+#[derive(rust_embed::Embed)]+#[folder = "../../dist"]+#[allow_missing = true]+struct Ui;++/// `GET /` and the UI's files. Public: the page itself holds no data; it asks for the+/// password before anything else.+pub async fn ui(method: Method, req: Request<Body>) -> Response {+ if method != Method::GET && method != Method::HEAD {+ return StatusCode::NOT_FOUND.into_response();+ }+ let path = req.uri().path().trim_start_matches('/');+ let path = if path.is_empty() { "index.html" } else { path };+ let Some(file) = Ui::get(path) else {+ if Ui::get("index.html").is_none() {+ return (StatusCode::NOT_FOUND, "The Kokon UI is not part of this build (run npm run build, then build kokon-service).").into_response();+ }+ return StatusCode::NOT_FOUND.into_response();+ };+ let mut r = Response::new(Body::from(file.data.into_owned()));+ let h = r.headers_mut();+ if let Ok(v) = HeaderValue::from_str(file.metadata.mimetype()) {+ h.insert(header::CONTENT_TYPE, v);+ }+ // Hashed asset names never change; the page itself is checked every time.+ let cache = if path.starts_with("assets/") { "public, max-age=31536000, immutable" } else { "no-cache" };+ h.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));+ h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));+ h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));+ r+}diff --git a/crates/qls-service/src/security_tests.rs b/crates/qls-service/src/security_tests.rsnew file mode 100644index 0000000..a059ad7--- /dev/null+++ b/crates/qls-service/src/security_tests.rs@@ -0,0 +1,303 @@+//! Security tests for access from other devices, through the real router: who gets in on each+//! listener, the attempt limit, what a signed-in browser can and cannot reach, and sessions+//! ending with a new password or a logout. No GPU, no network port opened.++use std::collections::HashMap;+use std::net::SocketAddr;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Instant;++use axum::{+ Router,+ body::Body,+ extract::connect_info::MockConnectInfo,+ http::{HeaderMap, Request, StatusCode, header},+};+use qls_core::{config::AppConfig, engine::Engine};+use serde_json::{Value, json};+use tower::ServiceExt;++use crate::{AppState, api, remote::RemoteState};++const PASSWORD: &str = "home server 42";++/// Settings are saved under `QLS_CONFIG_DIR`: a temporary folder, never the user's.+fn isolate_settings() {+ static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();+ DIR.get_or_init(|| {+ let d = tempfile::tempdir().unwrap();+ // SAFETY: set once, before any test reads it (every test calls this first).+ unsafe { std::env::set_var("QLS_CONFIG_DIR", d.path()) };+ d+ });+}++struct Fixture {+ _dir: tempfile::TempDir,+ state: Arc<AppState>,+}++fn fixture(with_password: bool) -> Fixture {+ isolate_settings();+ let dir = tempfile::tempdir().unwrap();+ let engine = Engine::new(AppConfig::default(), dir.path()).unwrap();+ let state = Arc::new(AppState {+ engine,+ token: "t".repeat(64),+ leases: Mutex::new(HashMap::new()),+ exit_deadline: Mutex::new(None),+ persistent: true,+ quick_exit: std::sync::atomic::AtomicBool::new(false),+ shutdown: tokio::sync::Notify::new(),+ started: Instant::now(),+ remote: RemoteState::new(dir.path(), false),+ });+ if with_password {+ state.remote.set_password(PASSWORD).unwrap();+ }+ Fixture { _dir: dir, state }+}++fn app(f: &Fixture, lan: bool, ip: &str) -> Router {+ let addr: SocketAddr = format!("{ip}:50000").parse().unwrap();+ api::router(f.state.clone(), lan).layer(MockConnectInfo(addr))+}++struct Reply {+ status: StatusCode,+ headers: HeaderMap,+ body: Value,+}++impl Reply {+ fn code(&self) -> &str {+ self.body["error"]["code"].as_str().unwrap_or("")+ }+}++async fn send(app: &Router, method: &str, path: &str, headers: &[(&str, &str)], body: Option<Value>) -> Reply {+ let mut req = Request::builder().method(method).uri(path);+ for (k, v) in headers {+ req = req.header(*k, *v);+ }+ let req = match body {+ Some(b) => req.header(header::CONTENT_TYPE, "application/json").body(Body::from(b.to_string())),+ None => req.body(Body::empty()),+ }+ .unwrap();+ let res = app.clone().oneshot(req).await.unwrap();+ let status = res.status();+ let headers = res.headers().clone();+ let bytes = axum::body::to_bytes(res.into_body(), 16 << 20).await.unwrap();+ Reply { status, headers, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null) }+}++const CSRF: (&str, &str) = ("x-kokon-csrf", "1");++async fn login(app: &Router, password: &str) -> Reply {+ send(app, "POST", "/api/v1/auth/login", &[CSRF], Some(json!({ "password": password }))).await+}++/// The `Cookie` header value for a successful login.+async fn sign_in(app: &Router) -> String {+ let r = login(app, PASSWORD).await;+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.body);+ let set = r.headers[header::SET_COOKIE].to_str().unwrap();+ for attr in ["HttpOnly", "SameSite=Strict", "Path=/"] {+ assert!(set.contains(attr), "cookie lacks {attr}: {set}");+ }+ set.split(';').next().unwrap().to_string()+}++#[tokio::test]+async fn nothing_without_credentials() {+ let f = fixture(true);+ for lan in [false, true] {+ let a = app(&f, lan, "192.168.1.50");+ for (m, p) in [("GET", "/api/v1/status"), ("GET", "/api/v1/gallery"), ("GET", "/api/v1/events"), ("POST", "/api/v1/jobs")] {+ let r = send(&a, m, p, &[], None).await;+ assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{m} {p} lan={lan}");+ assert_eq!(r.code(), "login_required");+ }+ let r = send(&a, "GET", "/api/v1/gallery/x/image?token=", &[], None).await;+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);+ // A cookie that no login handed out.+ let r = send(&a, "GET", "/api/v1/status", &[("cookie", "kokon_session=0123456789abcdef")], None).await;+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);+ }+}++#[tokio::test]+async fn the_token_works_on_loopback_only() {+ let f = fixture(true);+ let auth = format!("Bearer {}", f.state.token);+ let local = app(&f, false, "127.0.0.1");+ assert_eq!(send(&local, "GET", "/api/v1/remote", &[("authorization", &auth)], None).await.status, StatusCode::OK);+ let wrong = send(&local, "GET", "/api/v1/status", &[("authorization", "Bearer nope")], None).await;+ assert_eq!((wrong.status, wrong.code()), (StatusCode::UNAUTHORIZED, "unauthorized"));+ // From a web page in a browser, even with the token.+ let page = send(&local, "GET", "/api/v1/status", &[("authorization", &auth), ("origin", "http://evil.example")], None).await;+ assert_eq!(page.status, StatusCode::UNAUTHORIZED);+ // The network listener never takes it.+ let lan = app(&f, true, "192.168.1.50");+ let r = send(&lan, "GET", "/api/v1/status", &[("authorization", &auth)], None).await;+ assert_eq!((r.status, r.code()), (StatusCode::UNAUTHORIZED, "login_required"));+ let r = send(&lan, "GET", &format!("/api/v1/status?token={}", f.state.token), &[], None).await;+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);+}++#[tokio::test]+async fn no_login_without_a_password() {+ let f = fixture(false);+ let a = app(&f, true, "192.168.1.50");+ let r = login(&a, "anything at all").await;+ assert_eq!((r.status, r.code()), (StatusCode::FORBIDDEN, "forbidden"));+ let s = send(&a, "GET", "/api/v1/auth/session", &[], None).await;+ assert_eq!(s.body, json!({ "signed_in": false, "password_set": false }));+}++#[tokio::test]+async fn login_needs_the_csrf_header() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.50");+ let r = send(&a, "POST", "/api/v1/auth/login", &[], Some(json!({ "password": PASSWORD }))).await;+ assert_eq!(r.status, StatusCode::FORBIDDEN);+ assert!(!r.headers.contains_key(header::SET_COOKIE));+}++#[tokio::test]+async fn wrong_passwords_lock_the_address() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.66");+ for _ in 0..4 {+ let r = login(&a, "guess guess").await;+ assert_eq!((r.status, r.code()), (StatusCode::UNAUTHORIZED, "login_required"));+ }+ let r = login(&a, "guess guess").await;+ assert_eq!((r.status, r.code()), (StatusCode::TOO_MANY_REQUESTS, "too_many_attempts"));+ assert_eq!(r.body["retry_after_s"], 60);+ assert_eq!(r.headers[header::RETRY_AFTER], "60");+ // Locked: even the right password gets the same answer, and no cookie.+ let r = login(&a, PASSWORD).await;+ assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);+ assert!(!r.headers.contains_key(header::SET_COOKIE));+ // Another device on the network is not affected.+ sign_in(&app(&f, true, "192.168.1.67")).await;+}++#[tokio::test]+async fn a_browser_gets_the_ui_api_but_no_paths_on_the_server() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.50");+ let cookie = sign_in(&a).await;+ let c = ("cookie", cookie.as_str());+ assert_eq!(send(&a, "GET", "/api/v1/status", &[c], None).await.status, StatusCode::OK);+ assert_eq!(send(&a, "GET", "/api/v1/gallery", &[c], None).await.status, StatusCode::OK);+ let s = send(&a, "GET", "/api/v1/auth/session", &[c], None).await;+ assert_eq!(s.body, json!({ "signed_in": true, "password_set": true }));+ for (m, p, body) in [+ ("POST", "/api/v1/inputs/import", json!({ "path": "/etc/passwd" })),+ ("POST", "/api/v1/models/scan", json!({ "dir": "/" })),+ ("POST", "/api/v1/models/inspect", json!({ "path": "/etc/shadow" })),+ ("POST", "/api/v1/gallery/x/export", json!({ "path": "/tmp/x.png" })),+ ("POST", "/api/v1/image-info", json!({ "path": "/etc/passwd" })),+ ("POST", "/api/v1/loras", json!({ "path": "/tmp/x.safetensors" })),+ ("POST", "/api/v1/luts/import", json!({ "path": "/tmp/x.cube" })),+ ("POST", "/api/v1/generate", json!({ "prompt": "x", "output_path": "/tmp/x.png" })),+ ("POST", "/api/v1/shutdown", json!({})),+ ("POST", "/api/v1/remote/password", json!({ "password": "taken over!" })),+ ("POST", "/api/v1/remote", json!({ "enabled": true })),+ ("GET", "/api/v1/remote", Value::Null),+ ] {+ let body = (!body.is_null()).then_some(body);+ let r = send(&a, m, p, &[c, CSRF], body).await;+ assert_eq!((r.status, r.code()), (StatusCode::FORBIDDEN, "forbidden"), "{m} {p}");+ }+ // A job may only use images already in Kokon, and saves to the gallery.+ for job in [json!({ "prompt": "x", "mode": "edit", "images": ["/etc/passwd"] }), json!({ "prompt": "x", "output_path": "/tmp/x.png" })] {+ let r = send(&a, "POST", "/api/v1/jobs", &[c, CSRF], Some(job)).await;+ assert_eq!(r.status, StatusCode::FORBIDDEN);+ let r = send(&a, "POST", "/api/v1/plan", &[c, CSRF], Some(json!({ "prompt": "x", "mode": "edit", "images": ["C:\\Users\\me\\x.png"] }))).await;+ assert_eq!(r.status, StatusCode::FORBIDDEN);+ }+ // The password is never in the settings the API returns.+ let cfg = send(&a, "GET", "/api/v1/config", &[c], None).await;+ assert!(!cfg.body.to_string().contains("argon2"));+}++#[tokio::test]+async fn browser_changes_need_the_csrf_header() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.50");+ let cookie = sign_in(&a).await;+ let c = ("cookie", cookie.as_str());+ let beat = json!({ "client_id": "tab-1" });+ let r = send(&a, "POST", "/api/v1/session/heartbeat", &[c], Some(beat.clone())).await;+ assert_eq!(r.status, StatusCode::FORBIDDEN);+ let r = send(&a, "POST", "/api/v1/session/heartbeat", &[c, CSRF], Some(beat)).await;+ assert_eq!(r.status, StatusCode::OK);+ // A browser's lease is never the desktop window's, and never kept alive by a pid.+ let l = f.state.leases.lock().unwrap();+ assert_eq!((l["tab-1"].kind.as_str(), l["tab-1"].pid), ("web", None));+}++#[tokio::test]+async fn browser_settings_saves_keep_the_computers_settings() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.50");+ let cookie = sign_in(&a).await;+ let c = ("cookie", cookie.as_str());+ let before = f.state.engine.config();+ let mut sent = serde_json::to_value(&before).unwrap();+ sent["sdcppDir"] = json!("/tmp/elsewhere");+ sent["extraServerArgs"] = json!(["--rpc", "evil:50052"]);+ sent["remoteAccess"] = json!(true);+ sent["flashAttention"] = json!(!before.flash_attention);+ let r = send(&a, "PUT", "/api/v1/config", &[c, CSRF], Some(sent)).await;+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.body);+ let after = f.state.engine.config();+ assert_eq!(after.sdcpp_dir, before.sdcpp_dir);+ assert_eq!(after.extra_server_args, before.extra_server_args);+ assert!(!after.remote_access);+ assert_eq!(after.flash_attention, !before.flash_attention, "an app setting does change");+}++#[tokio::test]+async fn a_new_password_or_a_logout_ends_sessions() {+ let f = fixture(true);+ let a = app(&f, true, "192.168.1.50");+ let phone = sign_in(&a).await;+ let laptop = sign_in(&a).await;+ let r = send(&a, "POST", "/api/v1/auth/logout", &[("cookie", &laptop), CSRF], None).await;+ assert_eq!(r.status, StatusCode::OK);+ assert!(r.headers[header::SET_COOKIE].to_str().unwrap().contains("Max-Age=0"));+ assert_eq!(send(&a, "GET", "/api/v1/status", &[("cookie", &laptop)], None).await.status, StatusCode::UNAUTHORIZED);+ assert_eq!(send(&a, "GET", "/api/v1/status", &[("cookie", &phone)], None).await.status, StatusCode::OK);+ // Changed from the desktop app (token, loopback).+ let local = app(&f, false, "127.0.0.1");+ let auth = format!("Bearer {}", f.state.token);+ let r = send(&local, "POST", "/api/v1/remote/password", &[("authorization", &auth)], Some(json!({ "password": "a brand new one" }))).await;+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.body);+ assert_eq!(send(&a, "GET", "/api/v1/status", &[("cookie", &phone)], None).await.status, StatusCode::UNAUTHORIZED);+ assert_eq!(login(&a, PASSWORD).await.status, StatusCode::UNAUTHORIZED);+ assert_eq!(login(&a, "a brand new one").await.status, StatusCode::OK);+ let short = send(&local, "POST", "/api/v1/remote/password", &[("authorization", &auth)], Some(json!({ "password": "short" }))).await;+ assert_eq!(short.status, StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn the_network_stays_closed_without_a_password() {+ let f = fixture(false);+ let local = app(&f, false, "127.0.0.1");+ let auth = format!("Bearer {}", f.state.token);+ let r = send(&local, "POST", "/api/v1/remote", &[("authorization", &auth)], Some(json!({ "enabled": true }))).await;+ assert_eq!(r.status, StatusCode::BAD_REQUEST);+ let st = send(&local, "GET", "/api/v1/remote", &[("authorization", &auth)], None).await.body;+ assert_eq!((st["enabled"].as_bool(), st["listening"].as_bool(), st["password_set"].as_bool()), (Some(false), Some(false), Some(false)));+ // Removing the password turns access off.+ f.state.engine.set_remote(true, f.state.engine.config().remote_port).unwrap();+ let r = send(&local, "DELETE", "/api/v1/remote/password", &[("authorization", &auth)], None).await;+ assert_eq!(r.status, StatusCode::OK);+ assert!(!f.state.engine.config().remote_access);+ assert_eq!(r.body["listening"], false);+}diff --git a/mcp/src/service.ts b/mcp/src/service.tsindex 682e0d3..ffc589b 100644--- a/mcp/src/service.ts+++ b/mcp/src/service.ts@@ -27,12 +27,17 @@ export class ServiceError extends Error {}}+/** The service's `dirs::data_local_dir()`: %LOCALAPPDATA%, ~/Library/Application Support, or+ * $XDG_DATA_HOME (default ~/.local/share) on Linux. */+export function localDataBase(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, home: string): string {+ if (platform === "win32") return env.LOCALAPPDATA ?? path.join(env.USERPROFILE ?? "C:\\", "AppData", "Local");+ if (platform === "darwin") return path.join(home, "Library", "Application Support");+ return env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : path.join(home, ".local", "share");+}+export function dataDir(): string {if (process.env.QLS_DATA_DIR) return process.env.QLS_DATA_DIR;- // Same folder as the service's dirs::data_local_dir().- const base = WIN- ? (process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? "C:\\", "AppData", "Local"))- : path.join(os.homedir(), "Library", "Application Support");+ const base = localDataBase(process.platform, process.env, os.homedir());// The service moves the folder of the app's old name (QwenLocalStudio) to KokonData on its// first start; until then the old one is read.const [next, old] = [path.join(base, "KokonData"), path.join(base, "QwenLocalStudio")];diff --git a/mcp/test/datadir.test.ts b/mcp/test/datadir.test.tsnew file mode 100644index 0000000..8c15447--- /dev/null+++ b/mcp/test/datadir.test.ts@@ -0,0 +1,14 @@+import path from "node:path";+import { describe, expect, it } from "vitest";+import { localDataBase } from "../src/service.js";++// Must match the service's dirs::data_local_dir(), or the MCP server misses service.json.+describe("data folder", () => {+ it("follows each system's local data folder", () => {+ expect(localDataBase("win32", { LOCALAPPDATA: "C:\Users\me\AppData\Local" }, "C:\Users\me")).toBe("C:\Users\me\AppData\Local");+ expect(localDataBase("darwin", {}, "/Users/me")).toBe(path.join("/Users/me", "Library", "Application Support"));+ expect(localDataBase("linux", {}, "/home/me")).toBe(path.join("/home/me", ".local", "share"));+ expect(localDataBase("linux", { XDG_DATA_HOME: "/data/xdg" }, "/home/me")).toBe("/data/xdg");+ expect(localDataBase("linux", { XDG_DATA_HOME: "relative" }, "/home/me")).toBe(path.join("/home/me", ".local", "share"));+ });+});diff --git a/scripts/build-release-linux.sh b/scripts/build-release-linux.shindex 38c3ae9..44ab2f4 100644--- a/scripts/build-release-linux.sh+++ b/scripts/build-release-linux.sh@@ -40,7 +40,9 @@ npm ci --no-audit --no-fund(cd mcp && npm ci --no-audit --no-fund)echo "2/5 Tests (Rust core + frontend)"-cargo test -p qls-core --release --quiet+cargo test -p qls-core -p qls-service --release --quiet+# kokon-service embeds the built UI (dist/) for browsers on other devices: build it first.+npm run build# The MCP protocol test runs the newest target/*/kokon-service: build this version's first.cargo build -p qls-service --releasenpx vitest rundiff --git a/scripts/build-release-mac.sh b/scripts/build-release-mac.shindex db65faa..7737f2e 100755--- a/scripts/build-release-mac.sh+++ b/scripts/build-release-mac.sh@@ -18,7 +18,9 @@ npm ci --no-audit --no-fund(cd mcp && npm ci --no-audit --no-fund)echo "2/5 Tests (Rust core + frontend)"-cargo test -p qls-core --release --quiet+cargo test -p qls-core -p qls-service --release --quiet+# kokon-service embeds the built UI (dist/) for browsers on other devices: build it first.+npm run build# The MCP protocol test runs the newest target/*/kokon-service, which Tauri overwrites with the# bundled sidecar of the previous release: build this version's service first.cargo build -p qls-service --releasediff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1index c2ec161..94c7205 100644--- a/scripts/build-release.ps1+++ b/scripts/build-release.ps1@@ -11,8 +11,11 @@ Set-Location $root$env:Path = "$env:USERPROFILE\.cargo\bin;$env:Path"Write-Host "1/5 Tests (Rust core + frontend + MCP)" -ForegroundColor Cyan-cargo test -p qls-core --release --quiet+cargo test -p qls-core -p qls-service --release --quietif ($LASTEXITCODE) { throw "Rust tests failed" }+# kokon-service embeds the built UI (dist\) for browsers on other devices: build it first.+npm run build+if ($LASTEXITCODE) { throw "UI build failed" }# The MCP protocol test runs the newest target\*\kokon-service.exe, which Tauri overwrites with# the bundled sidecar of the previous release: build this version's service first.cargo build -p qls-service --releasediff --git a/src/App.tsx b/src/App.tsxindex 6b1506b..2518c2f 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,12 +1,14 @@import { getCurrentWebview } from "@tauri-apps/api/webview";import { Star, X } from "lucide-react";import { useEffect, useRef, useState } from "react";-import { api, configure } from "./lib/api";+import { api, configure, setSignedOutHandler } from "./lib/api";import { native } from "./lib/native";+import { inBrowser } from "./lib/platform";import {- addExampleProjects, addInputs, closeStarPrompt, dismissToast, getState, initStarPrompt, redoVersion, refreshLoras, refreshStatus, selectItem, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoVersion, useStore,+ addExampleProjects, closeStarPrompt, dismissToast, getState, initStarPrompt, redoVersion, refreshLoras, refreshStatus, selectItem, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoVersion, useStore,} from "./lib/store";-import { Composer, importPaths } from "./components/Composer";+import { Composer, importPaths, uploadFiles } from "./components/Composer";+import { Login } from "./components/Login";import { ExpandEditor } from "./components/ExpandEditor";import { Gallery } from "./components/Gallery";import { InpaintEditor } from "./components/InpaintEditor";@@ -99,16 +101,13 @@ function StarPrompt() {);}-async function uploadBlobs(files: File[]) {- const recs = [];- for (const f of files) {- try {- recs.push(await api.upload(f, f.name || "pasted.png"));- } catch (e) {- toastError(e);- }- }- addInputs(recs);+/** Browser: a lease while the tab is open, so the service does not exit under it (the desktop+ * app holds its lease from Rust). The service drops it 45 s after the last beat. */+function startBrowserHeartbeat() {+ const id = `web-${crypto.randomUUID?.() ?? Math.random().toString(36).slice(2)}`;+ const beat = () => api.heartbeat(id).catch(() => {});+ beat();+ window.setInterval(beat, 15_000);}export default function App() {@@ -117,7 +116,9 @@ export default function App() {const compareUpscalers = useStore((s) => s.compareUpscalers);const sidebar = useStore((s) => s.sidebar);const editing = useStore((s) => s.composer.refs.length > 0 && s.session.length > 0);- const [boot, setBoot] = useState<"connecting" | "ok" | string>("connecting");+ const [boot, setBoot] = useState<"connecting" | "login" | "ok" | string>("connecting");+ // Bumped after signing in, to run the start-up again.+ const [attempt, setAttempt] = useState(0);const [dragging, setDragging] = useState(false);// First launch: the tour starts once the main window is free (after welcome and setup).const tourPending = useRef(false);@@ -136,6 +137,15 @@ export default function App() {const conn = await native.connect();if (cancelled) return;configure(conn.baseUrl, conn.token);+ if (inBrowser) {+ // Another device: sign in first. A session that ends later (new password) reloads the page.+ if (!(await api.session()).signed_in) {+ if (!cancelled) setBoot("login");+ return;+ }+ setSignedOutHandler(() => location.reload());+ startBrowserHeartbeat();+ }startEvents();const cfg = await api.config();const st = await refreshStatus();@@ -155,7 +165,7 @@ export default function App() {const engineUpdate = whatsNew && !!st?.engine?.update_needed;setState({ needsSetup: !cfg.setupComplete, ...(!welcomeSeen ? { overlay: "welcome" } : whatsNew ? { overlay: "whats-new" } : {}) });setBoot("ok");- autoCheckForUpdate();+ if (!inBrowser) autoCheckForUpdate();// Preload the model so the first generation starts immediately (not an engine about to be replaced).if (cfg.setupComplete && !engineUpdate && st && st.server.state === "stopped") api.startBackend().then(refreshStatus, () => refreshStatus());} catch (e) {@@ -165,10 +175,42 @@ export default function App() {return () => {cancelled = true;};+ }, [attempt]);++ // Browser: files dropped from this device are uploaded.+ useEffect(() => {+ if (!inBrowser) return;+ const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes("Files");+ const over = (e: DragEvent) => {+ if (!hasFiles(e)) return;+ e.preventDefault();+ setDragging(true);+ };+ const leave = (e: DragEvent) => {+ if (!e.relatedTarget) setDragging(false);+ };+ const drop = (e: DragEvent) => {+ if (!hasFiles(e)) return;+ e.preventDefault();+ setDragging(false);+ const all = Array.from(e.dataTransfer?.files ?? []);+ const files = all.filter((f) => f.type.startsWith("image/") || IMAGE_EXT.test(f.name));+ if (files.length) uploadFiles(files);+ else if (all.length) toastInfo("Only image files can be added.");+ };+ window.addEventListener("dragover", over);+ window.addEventListener("dragleave", leave);+ window.addEventListener("drop", drop);+ return () => {+ window.removeEventListener("dragover", over);+ window.removeEventListener("dragleave", leave);+ window.removeEventListener("drop", drop);+ };}, []);// Native file drops (paths) — efficient: the service reads the files itself.useEffect(() => {+ if (inBrowser) return;let un: (() => void) | undefined;getCurrentWebview().onDragDropEvent((ev) => {@@ -194,13 +236,13 @@ export default function App() {const files = Array.from(e.clipboardData?.files ?? []).filter((f) => f.type.startsWith("image/"));if (files.length) {e.preventDefault();- uploadBlobs(files);+ uploadFiles(files);return;}if (e.clipboardData?.getData("text")) return;try {const png = await native.readClipboardImage();- if (png) uploadBlobs([new File([png as BlobPart], "pasted.png", { type: "image/png" })]);+ if (png) uploadFiles([new File([png as BlobPart], "pasted.png", { type: "image/png" })]);} catch {/* nothing to paste */}@@ -249,6 +291,19 @@ export default function App() {return () => window.removeEventListener("keydown", onKey);}, []);+ if (boot === "login") {+ return (+ <div className="app" style={{ display: "grid", placeItems: "center" }}>+ <Login+ onSignedIn={() => {+ setBoot("connecting");+ setAttempt((n) => n + 1);+ }}+ />+ </div>+ );+ }+if (boot !== "ok") {return (<div className="app" style={{ display: "grid", placeItems: "center" }}>@@ -257,7 +312,7 @@ export default function App() {<BootSplash />) : (<div className="failed">- <strong>Could not start the local service</strong>+ <strong>{inBrowser ? "Could not reach Kokon" : "Could not start the local service"}</strong><span>{boot}</span><button className="btn" onClick={() => location.reload()}>Try againdiff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex ada82c9..54a3577 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import { activeLoras, activeOverrides, aspectLabel, buildRequest, composing, editing, enhancerApplies, expansionPixels, formatDuration, hasOutpaint, imageName, MAX_LORAS, moveRef, needsPrompt, parseRatio, toggleLora, wantsPromptReview, type Ref } from "../lib/logic";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import {addAsReference, addInputs, cancelPromptReview, editShownImage, enhancerAvailable, getState, itemSource, openSettings, selectedItem, sessionLabels, setProjectLoras, setState, startNewImage, submitComposer, toastError, undoEnhancedPrompt, updateComposer, useStore, type SessionItem,} from "../lib/store";@@ -27,6 +28,19 @@ const INPAINT_ACTIONS: { value: InpaintAction; label: string; placeholder: strinconst INPAINT_VERB: Record<InpaintAction, string> = { edit: "Changing", remove: "Clearing", replace: "Replacing", add: "Adding to" };+/** Images from this device (browser picker, drop, paste): uploaded to the service. */+export async function uploadFiles(files: File[]) {+ const recs = [];+ for (const f of files) {+ try {+ recs.push(await api.upload(f, f.name || "pasted.png"));+ } catch (e) {+ toastError(e);+ }+ }+ addInputs(recs);+}+export async function importPaths(paths: string[]) {const recs = [];for (const p of paths) {@@ -237,7 +251,7 @@ function AddImage() {const s = itemSource(i);return s && !used.has(s);});- const browse = async () => importPaths(await native.pickImages());+ const browse = async () => (inBrowser ? uploadFiles(await native.pickImageFiles()) : importPaths(await native.pickImages()));// In a project, images added while not editing are references for a new image.const asReference = refs.length > 0 || create || session.length > 0;const title = asReference ? "Add a reference image" : "Add an image to edit";diff --git a/src/components/Gallery.tsx b/src/components/Gallery.tsxindex 378320e..17d2c68 100644--- a/src/components/Gallery.tsx+++ b/src/components/Gallery.tsx@@ -2,6 +2,7 @@ import { ArrowLeft, Check, FolderOpen, Heart, Loader2, Maximize2, Search, Trash2import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import { forgetGeneration, openGeneration, setState, toastError, useStore } from "../lib/store";import { MODE_LABEL, neighbourAfterRemoval, previewIndex } from "../lib/logic";import type { GenerationRecord } from "../lib/types";@@ -195,9 +196,11 @@ export function Gallery() {onChange={setSort}/></div>- <IconButton title="Open the images folder" onClick={() => api.config().then((c) => native.openFolder(c.outputDir)).catch(toastError)}>- <FolderOpen size={17} />- </IconButton>+ {!inBrowser && (+ <IconButton title="Open the images folder" onClick={() => api.config().then((c) => native.openFolder(c.outputDir)).catch(toastError)}>+ <FolderOpen size={17} />+ </IconButton>+ )}<span className="spacer" />{items.length > 0 && (<button className={`btn ${selecting ? "primary" : ""}`} onClick={() => setPicked(selecting ? null : new Set())} title={selecting ? "Stop selecting (Esc)" : "Select several images to delete them at once (or Ctrl/⌘-click)"}>diff --git a/src/components/Login.tsx b/src/components/Login.tsxnew file mode 100644index 0000000..b14d200--- /dev/null+++ b/src/components/Login.tsx@@ -0,0 +1,69 @@+// Sign-in for Kokon opened in a browser on another device: the password set in the desktop app+// (Settings → Other devices) or with `kokon-service --set-password`. Once per browser; the+// session lasts 90 days or until the password changes.++import { useEffect, useRef, useState } from "react";+import { ApiError, api } from "../lib/api";+import { KokonMark } from "./Welcome";++export function Login({ onSignedIn }: { onSignedIn: () => void }) {+ const [password, setPassword] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [noPassword, setNoPassword] = useState(false);+ const input = useRef<HTMLInputElement>(null);++ useEffect(() => {+ api.session().then((s) => setNoPassword(!s.password_set), () => {});+ input.current?.focus();+ }, []);++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!password || busy) return;+ setBusy(true);+ setError(null);+ try {+ await api.login(password);+ onSignedIn();+ } catch (err) {+ setError(err instanceof ApiError ? err.body.message : "Kokon is not reachable.");+ setPassword("");+ input.current?.focus();+ } finally {+ setBusy(false);+ }+ };++ return (+ <form className="login" onSubmit={submit}>+ <KokonMark size={48} />+ <strong>Sign in to Kokon</strong>+ {noPassword ? (+ <span className="muted">No password is set yet. On the computer running Kokon, open Settings → Other devices and set one.</span>+ ) : (+ <>+ <span className="muted">Enter the password set on the computer running Kokon. This browser stays signed in.</span>+ <input+ ref={input}+ className="input"+ type="password"+ autoComplete="current-password"+ placeholder="Password"+ aria-label="Password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ />+ {error && (+ <span className="login-error" role="alert">+ {error}+ </span>+ )}+ <button className="btn primary" type="submit" disabled={!password || busy}>+ {busy ? "Signing in…" : "Sign in"}+ </button>+ </>+ )}+ </form>+ );+}diff --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsxindex d608f6d..dd61b4a 100644--- a/src/components/LoraSettings.tsx+++ b/src/components/LoraSettings.tsx@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";import { api } from "../lib/api";import { formatBytes, MAX_LORAS } from "../lib/logic";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import { refreshLoras, toastError, toastInfo, useStore } from "../lib/store";import type { LoraItem } from "../lib/types";import { Switch } from "./ui";@@ -126,9 +127,11 @@ export function LoraSettings() {LoRA button next to the prompt, up to {MAX_LORAS} at a time.</span></div>- <button className="btn primary" disabled={busy} onClick={add}>- <Plus size={15} /> {busy ? "Checking…" : "Load a LoRA…"}- </button>+ {!inBrowser && (+ <button className="btn primary" disabled={busy} onClick={add}>+ <Plus size={15} /> {busy ? "Checking…" : "Load a LoRA…"}+ </button>+ )}</div><span className="muted">Beta: tested on Windows with an NVIDIA card. It should work the same on Mac and Linux, but it hasn't been tested there yet: please tell us how it goes on GitHub.diff --git a/src/components/Lut.tsx b/src/components/Lut.tsxindex 962d665..fed2bb7 100644--- a/src/components/Lut.tsx+++ b/src/components/Lut.tsx@@ -3,6 +3,7 @@ import { useEffect, useState } from "react";import { api } from "../lib/api";import { lutLabel } from "../lib/logic";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import { toastError } from "../lib/store";import type { LutEntry } from "../lib/types";import { Popover } from "./ui";@@ -60,19 +61,21 @@ function LutList({ current, onPick, close }: { current?: string; onPick: (lut: L{row(e)}</div>))}- <button- className="opt"- onClick={async () => {- close();- const e = await openCubeFile();- if (e) onPick(e);- }}- >- <span className="check">- <FolderOpen size={15} />- </span>- <span>Open a .cube file…</span>- </button>+ {!inBrowser && (+ <button+ className="opt"+ onClick={async () => {+ close();+ const e = await openCubeFile();+ if (e) onPick(e);+ }}+ >+ <span className="check">+ <FolderOpen size={15} />+ </span>+ <span>Open a .cube file…</span>+ </button>+ )}</div>);}diff --git a/src/components/RemoteAccess.tsx b/src/components/RemoteAccess.tsxnew file mode 100644index 0000000..3fd5e38--- /dev/null+++ b/src/components/RemoteAccess.tsx@@ -0,0 +1,141 @@+// Settings → Other devices (desktop app only): open Kokon in a browser on a phone, tablet or+// laptop on the same network. Off until the user sets a password and turns it on; the service+// opens the network port only then (crates/qls-service/src/remote.rs).++import { Copy, ExternalLink } from "lucide-react";+import { useEffect, useState } from "react";+import { writeText } from "@tauri-apps/plugin-clipboard-manager";+import { api, type RemoteStatus } from "../lib/api";+import { native } from "../lib/native";+import { toastError, toastInfo } from "../lib/store";+import { Switch } from "./ui";++const GUIDE_URL = "https://github.com/GabrieleLozupone/kokon/blob/master/docs/remote-access.md";++function PasswordForm({ status, onSaved }: { status: RemoteStatus; onSaved: (s: RemoteStatus) => void }) {+ const [password, setPassword] = useState("");+ const [busy, setBusy] = useState(false);+ const short = password.length > 0 && password.length < status.min_password_chars;+ const save = async (e: React.FormEvent) => {+ e.preventDefault();+ if (short || !password) return;+ setBusy(true);+ try {+ const first = !status.password_set;+ let s = await api.setRemotePassword(password);+ // Setting the first password is the step before turning access on: do both.+ if (first && !s.enabled) s = await api.setRemote(true);+ setPassword("");+ onSaved(s);+ toastInfo(first ? "Password set" : "Password changed. Other devices sign in again.");+ } catch (err) {+ toastError(err);+ } finally {+ setBusy(false);+ }+ };+ return (+ <form className="field" onSubmit={save}>+ <span>{status.password_set ? "Change the password" : "Choose a password"}</span>+ <div className="path-row">+ <input+ className="input"+ type="password"+ autoComplete="new-password"+ placeholder={`At least ${status.min_password_chars} characters`}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ />+ <button className="btn primary" type="submit" disabled={!password || short || busy}>+ {status.password_set ? "Change" : "Set and turn on"}+ </button>+ </div>+ <span className="muted">+ {short ? `At least ${status.min_password_chars} characters.` : "Each browser asks for it once. Stored only as a secure hash on this computer."}+ </span>+ </form>+ );+}++export function RemoteAccess() {+ const [st, setSt] = useState<RemoteStatus | null>(null);+ const [port, setPort] = useState("");+ useEffect(() => {+ api.remote().then((s) => (setSt(s), setPort(String(s.port))), toastError);+ }, []);+ if (!st) return null;++ const toggle = async (on: boolean) => {+ try {+ const p = Number(port);+ setSt(await api.setRemote(on, Number.isInteger(p) && p >= 1024 && p <= 65535 ? p : undefined));+ } catch (e) {+ toastError(e);+ }+ };+ const removePassword = async () => {+ if (!(await native.confirm("Remove the password? Access from other devices turns off, and every browser is signed out.", "Remove password"))) return;+ try {+ setSt(await api.removeRemotePassword());+ } catch (e) {+ toastError(e);+ }+ };++ return (+ <>+ <span className="muted">+ Open Kokon in a browser on your phone, tablet or another computer on the same network. Images are made on this computer and saved in its gallery; each device can download+ them.+ </span>+ {!st.password_set ? (+ <PasswordForm status={st} onSaved={setSt} />+ ) : (+ <>+ <div className="field-row">+ <span>Allow access from other devices</span>+ <Switch on={st.enabled} onChange={toggle} />+ </div>+ {st.forced && <span className="muted">Turned on for this run by kokon-service --remote.</span>}+ {st.listening && st.url && (+ <div className="setting-card">+ <div className="setting-card-text">+ <strong>Open this address on the other device</strong>+ <span className="remote-url">{st.url}</span>+ </div>+ <button className="btn" onClick={() => writeText(st.url!).then(() => toastInfo("Address copied"), toastError)}>+ <Copy size={14} /> Copy+ </button>+ </div>+ )}+ {st.listening && !st.url && <span className="muted">On, at port {st.port} of this computer's network address.</span>}+ {st.error && <span className="muted">{st.error}</span>}+ <label className="field-row">+ <span>Port</span>+ <input className="input" type="number" min={1024} max={65535} style={{ width: 100 }} value={port} onChange={(e) => setPort(e.target.value)} onBlur={() => st.enabled && Number(port) !== st.port && toggle(true)} />+ </label>+ <PasswordForm status={st} onSaved={setSt} />+ <div className="field-row">+ <span>Remove the password and turn access off</span>+ <button className="btn" onClick={removePassword}>+ Remove+ </button>+ </div>+ </>+ )}+ <div className="setting-card" style={{ alignItems: "flex-start" }}>+ <div className="setting-card-text">+ <strong>Good to know</strong>+ <span className="muted">+ It works while Kokon is open on this computer. Use it on a network you trust, like your home Wi-Fi: the connection is not encrypted, so avoid public or shared networks. To+ reach Kokon from outside, use a private network such as Tailscale, never port forwarding on your router. The first time, your system may ask to allow Kokon on the+ network: allow it on private networks.+ </span>+ </div>+ <button className="btn" onClick={() => native.openLink(GUIDE_URL).catch(toastError)}>+ <ExternalLink size={14} /> Guide+ </button>+ </div>+ </>+ );+}diff --git a/src/components/Settings.tsx b/src/components/Settings.tsxindex 2979a03..296a4c2 100644--- a/src/components/Settings.tsx+++ b/src/components/Settings.tsx@@ -1,12 +1,14 @@-import { Activity, Copy, Cpu, Download, FolderOpen, HardDrive, Heart, Layers, RefreshCw, RotateCcw, Settings2, Trash2, X } from "lucide-react";+import { Activity, Copy, Cpu, Download, FolderOpen, HardDrive, Heart, Layers, MonitorSmartphone, RefreshCw, RotateCcw, Settings2, Trash2, X } from "lucide-react";import { useEffect, useState } from "react";import { writeText } from "@tauri-apps/plugin-clipboard-manager";import { api } from "../lib/api";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import { getState, openModelSetup, refreshStatus, setState, startTour, toastError, toastInfo, useStore } from "../lib/store";import { formatBytes } from "../lib/logic";import { setThemeChoice, themeChoice, type ThemeChoice } from "../lib/theme";import { LoraSettings } from "./LoraSettings";+import { RemoteAccess } from "./RemoteAccess";import { UpscalerControls } from "./Upscalers";import { WHATS_NEW_VERSION } from "./WhatsNew";import type { AppConfig, Check, ModelProfile, ModelsStatus, SetupReport, TextEncoderPlacement } from "../lib/types";@@ -60,10 +62,19 @@ function GitHubMark() {);}-type Tab = "general" | "models" | "lora" | "performance" | "diagnostics";-const TABS: Tab[] = ["general", "models", "lora", "performance", "diagnostics"];+type Tab = "general" | "models" | "lora" | "performance" | "devices" | "diagnostics";+const TABS: Tab[] = ["general", "models", "lora", "performance", "devices", "diagnostics"];+/** Browser: what the computer running Kokon has set (only its desktop app changes folders and files). */function PathField(props: { label: string; value: string; onChange: (v: string) => void; folder?: boolean; extensions?: string[]; open?: boolean }) {+ if (inBrowser) {+ return (+ <div className="field">+ <span>{props.label}</span>+ <span className="muted">{props.value || "—"} (on the computer running Kokon)</span>+ </div>+ );+ }return (<label className="field"><span>{props.label}</span>@@ -133,9 +144,11 @@ function Diagnostics() {return (<><div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>- <button className="btn" disabled={!text} onClick={async () => (await writeText(text ?? ""), toastInfo("Diagnostics copied"))}>- <Copy size={14} /> Copy- </button>+ {(!inBrowser || window.isSecureContext) && (+ <button className="btn" disabled={!text} onClick={async () => (await (inBrowser ? navigator.clipboard.writeText(text ?? "") : writeText(text ?? "")), toastInfo("Diagnostics copied"))}>+ <Copy size={14} /> Copy+ </button>+ )}<button className="btn" onClick={load}><RefreshCw size={14} /> Refresh</button>@@ -158,9 +171,11 @@ function Diagnostics() {><RotateCcw size={14} /> {busy ? "Restarting…" : "Restart server"}</button>- <button className="btn" onClick={async () => native.openFolder(await native.dataFolder().then((d) => `${d}${d.includes("\\") ? "\\" : "/"}logs`)).catch(toastError)}>- <FolderOpen size={14} /> Logs- </button>+ {!inBrowser && (+ <button className="btn" onClick={async () => native.openFolder(await native.dataFolder().then((d) => `${d}${d.includes("\\") ? "\\" : "/"}logs`)).catch(toastError)}>+ <FolderOpen size={14} /> Logs+ </button>+ )}</div><pre className="diag">{text ?? "Collecting…"}</pre></>@@ -286,6 +301,8 @@ export function Settings() {["models", "Models", <HardDrive size={16} key="m" />],["lora", "LoRA (beta)", <Layers size={16} key="l" />],["performance", "Performance", <Cpu size={16} key="p" />],+ // Only the computer running Kokon decides who else can use it.+ ...(inBrowser ? [] : ([["devices", "Other devices", <MonitorSmartphone size={16} key="o" />]] as [Tab, string, React.ReactNode][])),["diagnostics", "Diagnostics", <Activity size={16} key="d" />],];@@ -299,7 +316,7 @@ export function Settings() {</button>))}<span style={{ flex: 1 }} />- {tab !== "diagnostics" && tab !== "lora" && (+ {tab !== "diagnostics" && tab !== "lora" && tab !== "devices" && (<button className="btn primary" style={{ justifyContent: "center" }} disabled={!dirty} onClick={save}>Save</button>@@ -341,19 +358,30 @@ export function Settings() {<input className="input" type="number" min={0} max={1440} style={{ width: 90 }} value={cfg.idleUnloadMinutes} onChange={(e) => set({ idleUnloadMinutes: Math.max(0, Number(e.target.value) || 0) })} /></label><span className="muted" style={{ marginTop: -10 }}>Applies to MCP and API use without the desktop window. 0 keeps it loaded.</span>- <div className="field-row">- <span>Check for updates once a day</span>- <Switch on={autoCheckEnabled(cfg.ui)} onChange={(v) => set({ ui: { ...cfg.ui, updateCheck: v } })} />- </div>- <span className="muted" style={{ marginTop: -10 }}>- Only asks GitHub for the latest version number; nothing about you or your images is sent. Updates install when you click them.- </span>- <div className="field-row">- <span>You have Kokon {appVersion}</span>- <button className="btn" onClick={() => checkForUpdate(true)}>- Check now- </button>- </div>+ {inBrowser ? (+ <div className="field-row">+ <span>Kokon {appVersion} on the computer running it. It updates there.</span>+ <button className="btn" onClick={() => api.logout().then(() => location.reload(), toastError)}>+ Sign out+ </button>+ </div>+ ) : (+ <>+ <div className="field-row">+ <span>Check for updates once a day</span>+ <Switch on={autoCheckEnabled(cfg.ui)} onChange={(v) => set({ ui: { ...cfg.ui, updateCheck: v } })} />+ </div>+ <span className="muted" style={{ marginTop: -10 }}>+ Only asks GitHub for the latest version number; nothing about you or your images is sent. Updates install when you click them.+ </span>+ <div className="field-row">+ <span>You have Kokon {appVersion}</span>+ <button className="btn" onClick={() => checkForUpdate(true)}>+ Check now+ </button>+ </div>+ </>+ )}<div className="field-row"><span>What's new in Kokon {WHATS_NEW_VERSION}</span><button className="btn" onClick={() => setState({ overlay: "whats-new" })}>@@ -412,6 +440,8 @@ export function Settings() {</>)}+ {tab === "devices" && <RemoteAccess />}+{tab === "models" && (<><div className="setting-card">@@ -475,15 +505,17 @@ export function Settings() {<Download size={15} /> Download…</button>)}- <button- className="btn"- onClick={() => {- if (dirty && !window.confirm("Discard the unsaved changes and choose your own model files?")) return;- openModelSetup("own");- }}- >- <FolderOpen size={15} /> Use my own files…- </button>+ {!inBrowser && (+ <button+ className="btn"+ onClick={() => {+ if (dirty && !window.confirm("Discard the unsaved changes and choose your own model files?")) return;+ openModelSetup("own");+ }}+ >+ <FolderOpen size={15} /> Use my own files…+ </button>+ )}</div></div>) : (diff --git a/src/components/Setup.tsx b/src/components/Setup.tsxindex fa4062b..9bd646f 100644--- a/src/components/Setup.tsx+++ b/src/components/Setup.tsx@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";import { api } from "../lib/api";import { formatBytes, installItemShort, installProgress, installStep, installTimeLeft } from "../lib/logic";import { native } from "../lib/native";+import { inBrowser } from "../lib/platform";import { refreshStatus, setState, toastError, toastInfo, useStore } from "../lib/store";import type { GpuBackend, HardwareReport, InstallItem, InstallStatus, ModelScan, ModelSlot, ModelsStatus, SetupReport } from "../lib/types";import { OwnModels } from "./OwnModels";@@ -53,9 +54,11 @@ function Failure({ it, issuesUrl }: { it: InstallItem; issuesUrl: string }) {<button className="btn" onClick={() => native.openLink(it.page).catch(toastError)}><ExternalLink size={14} /> Download page</button>- <button className="btn" onClick={() => native.openFolder(folder).catch(toastError)}>- <FolderOpen size={14} /> Open folder- </button>+ {!inBrowser && (+ <button className="btn" onClick={() => native.openFolder(folder).catch(toastError)}>+ <FolderOpen size={14} /> Open folder+ </button>+ )}<button className="btn" onClick={() => native.openLink(issuesUrl).catch(toastError)}><Bug size={14} /> Report the problem</button>@@ -325,7 +328,8 @@ export function Setup() {const chosen = hw?.presets.find((p) => p.id === preset) ?? null;const running = inst?.running ?? false;- const own = mode === "own";+ // A browser cannot pick files on the server: the official download only.+ const own = mode === "own" && !inBrowser;// Own files: what their profile needs, once saved and active (until then nothing to install).const ownActive = own && hw?.active_source === "user" && !!hw.user_files;// While (or after) installing this preset, show the live list; otherwise what is on disk.@@ -348,8 +352,10 @@ export function Setup() {const repairOptions: RepairOption[] = [];if (models) {const userActive = models.active.source === "user";- repairOptions.push({ icon: <FolderOpen size={16} />, title: "Find them in another folder", detail: "If you moved your models: Kokon looks for the same files there.", run: searchElsewhere });- repairOptions.push({ icon: <FileSearch size={16} />, title: "Choose other files", detail: "Pick the files yourself, below.", run: showOwn });+ if (!inBrowser) {+ repairOptions.push({ icon: <FolderOpen size={16} />, title: "Find them in another folder", detail: "If you moved your models: Kokon looks for the same files there.", run: searchElsewhere });+ repairOptions.push({ icon: <FileSearch size={16} />, title: "Choose other files", detail: "Pick the files yourself, below.", run: showOwn });+ }if (userActive && models.downloadable.length > 0) {repairOptions.push({ icon: <Download size={16} />, title: "Download the missing files", detail: `The official ${models.downloadable.join(", ")}, saved where the missing file was.`, run: () => download("user") });}@@ -443,8 +449,8 @@ export function Setup() {</div>) : (<>- {/* Where the model comes from: the first choice, so it is seen first. */}- <div className="field">+ {/* Where the model comes from: the first choice, so it is seen first. A browser has only the download. */}+ {!inBrowser && <div className="field"><span>Image model</span><div className="choice-cards" role="radiogroup"><button className={`choice-card ${!own ? "on" : ""}`} role="radio" aria-checked={!own} onClick={() => setMode("official")}>@@ -454,15 +460,17 @@ export function Setup() {<span>Qwen-Image 2.1 Turbo, tested with Kokon{modelBytes ? ` · ${formatBytes(modelBytes)}` : ""}</span></div></button>- <button className={`choice-card ${own ? "on" : ""}`} role="radio" aria-checked={own} onClick={() => setMode("own")}>- <FolderOpen size={20} />- <div>- <strong>Use models I already have</strong>- <span>From ComfyUI or another folder; only the engine is downloaded</span>- </div>- </button>+ {!inBrowser && (+ <button className={`choice-card ${own ? "on" : ""}`} role="radio" aria-checked={own} onClick={() => setMode("own")}>+ <FolderOpen size={20} />+ <div>+ <strong>Use models I already have</strong>+ <span>From ComfyUI or another folder; only the engine is downloaded</span>+ </div>+ </button>+ )}</div>- </div>+ </div>}{own && models && (<div id="own-models"><OwnModels@@ -537,9 +545,11 @@ export function Setup() {<span>Install folder</span><div className="path-row"><input className="input" type="text" value={hw.sdcpp_dir} readOnly spellCheck={false} />- <button className="btn" onClick={chooseFolder}>- Change- </button>+ {!inBrowser && (+ <button className="btn" onClick={chooseFolder}>+ Change+ </button>+ )}</div><span className="muted">{hw.free_bytes != null ? `${formatBytes(hw.free_bytes)} free` : ""}diff --git a/src/components/Stage.tsx b/src/components/Stage.tsxindex e676419..17cb755 100644--- a/src/components/Stage.tsx+++ b/src/components/Stage.tsx@@ -7,7 +7,7 @@ import {compareBase, composerFromRecord, formatDuration, jobLabel, type JobClock, lutInfo, lutLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, arcLayout,upscalerLabel, upscaleTargets, variationRequest, imageName, type LinkKind, type TimelineLink,} from "../lib/logic";-import { native } from "../lib/native";+import { canCopyImage, native } from "../lib/native";import {addAsReference, addResult, cancelJob, focusPrompt, getState, itemSource, removeSessionItem, reusePrompt, selectedItem, selectItem, sessionLabels, sessionLinks, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,} from "../lib/store";@@ -18,7 +18,7 @@ import { PROMPT_FADE_MS, usePromptLeave, useTypewriter, useJobPercent, wordStyleimport { LutBar, LutButton, LutOverlay } from "./Lut";import { IconButton, Popover, useFit } from "./ui";import { Fullscreen, FullscreenButton, isTyping, ZoomImage, type ViewerNav } from "./Viewer";-import { fileManager, shortcut } from "../lib/platform";+import { fileManager, inBrowser, shortcut } from "../lib/platform";export const MODE_ICON: Record<Mode | "lut", React.ReactNode> = {auto: <Wand2 size={11} />,@@ -369,7 +369,7 @@ function MoreMenu({ item, path }: { item: SessionItem; path: string | null }) {<span>Reuse prompt and settings</span></button>)}- {path && (+ {path && !inBrowser && (<button className="opt" onClick={() => (close(), native.reveal(path).catch(toastError))}><span className="check"><FolderOpen size={15} />@@ -433,9 +433,14 @@ function GenActions({ item, g, showOriginal, onLut }: { item: SessionItem; g: Ge<Heart size={17} fill={fav ? "currentColor" : "none"} /></IconButton><IconButton- title={showOriginal ? "Save the original (before upscaling) as…" : "Save as…"}+ title={inBrowser ? (showOriginal ? "Download the original (before upscaling)" : "Download") : showOriginal ? "Save the original (before upscaling) as…" : "Save as…"}onClick={async () => {const name = g.file_path.split(/[\\/]/).pop() ?? "image.png";+ if (inBrowser) {+ // Onto this device, as the file Kokon saved.+ native.download(showOriginal ? urls.genOriginal(g.id) : urls.gen(g.id), showOriginal ? name.replace(/(\.\w+)?$/, "-original.png") : name);+ return;+ }const path = await native.saveAs(showOriginal ? name.replace(/(\.\w+)?$/, "-original.png") : name);if (!path) return;try {@@ -448,19 +453,22 @@ function GenActions({ item, g, showOriginal, onLut }: { item: SessionItem; g: Ge><Download size={17} /></IconButton>- <IconButton- title={showOriginal ? "Copy the original (before upscaling)" : "Copy image"}- onClick={async () => {- try {- await native.copyImage(shownPath);- toastInfo("Image copied");- } catch (e) {- toastError(e);- }- }}- >- <Copy size={17} />- </IconButton>+ {canCopyImage && (+ <IconButton+ title={showOriginal ? "Copy the original (before upscaling)" : "Copy image"}+ onClick={async () => {+ try {+ if (inBrowser) await native.copyImageUrl(showOriginal ? urls.genOriginal(g.id) : urls.gen(g.id));+ else await native.copyImage(shownPath);+ toastInfo("Image copied");+ } catch (e) {+ toastError(e);+ }+ }}+ >+ <Copy size={17} />+ </IconButton>+ )}<Popoverplacement="top-end"trigger={(open, toggle) => (diff --git a/src/components/TitleBar.tsx b/src/components/TitleBar.tsxindex 34acaee..384305a 100644--- a/src/components/TitleBar.tsx+++ b/src/components/TitleBar.tsx@@ -6,11 +6,11 @@import { Copy, Minus, Square, X } from "lucide-react";import { useEffect, useState } from "react";import { native } from "../lib/native";-import { isLinux, isMac } from "../lib/platform";+import { inBrowser, isLinux, isMac } from "../lib/platform";// macOS: room for the traffic lights on the left of the top bar (styles.css). In full screen// macOS hides them, so the room goes too.-if (isMac && typeof document !== "undefined") {+if (isMac && !inBrowser && typeof document !== "undefined") {const root = document.documentElement;root.dataset.platform = "mac";const sync = () =>@@ -25,7 +25,7 @@ if (isMac && typeof document !== "undefined") {export function WindowControls() {const [maximized, setMaximized] = useState(false);useEffect(() => {- if (isMac) return;+ if (isMac || inBrowser) return;let un: (() => void) | undefined;let gone = false;const sync = () => native.isMaximized().then((m) => !gone && setMaximized(m), () => {});@@ -36,7 +36,7 @@ export function WindowControls() {un?.();};}, []);- if (isMac) return null;+ if (isMac || inBrowser) return null;return (<div className={`window-controls ${isLinux ? "linux" : ""}`}><button className="win-btn" title="Minimize" aria-label="Minimize" onClick={() => native.minimize().catch(() => {})}>diff --git a/src/components/Welcome.tsx b/src/components/Welcome.tsxindex e36a7c0..4bd6045 100644--- a/src/components/Welcome.tsx+++ b/src/components/Welcome.tsx@@ -11,7 +11,7 @@ import restyle from "../assets/showcase/restyle.jpg";import text from "../assets/showcase/text.jpg";import { api } from "../lib/api";import { WHATS_NEW_VERSION } from "./WhatsNew";-import { isMac } from "../lib/platform";+import { inBrowser, isMac } from "../lib/platform";import { autoCheckEnabled } from "../lib/updates";import { setState, toastError, useStore } from "../lib/store";@@ -79,10 +79,12 @@ export function Welcome() {</div>))}</div>- <label className="welcome-check">- <input type="checkbox" checked={updateCheck} onChange={(e) => setUpdateCheck(e.target.checked)} />- Check for Kokon updates once a day- </label>+ {!inBrowser && (+ <label className="welcome-check">+ <input type="checkbox" checked={updateCheck} onChange={(e) => setUpdateCheck(e.target.checked)} />+ Check for Kokon updates once a day+ </label>+ )}<button className="btn primary big" onClick={close}>{needsSetup ? "Set up Kokon" : "Start creating"}</button>diff --git a/src/lib/api.test.ts b/src/lib/api.test.tsnew file mode 100644index 0000000..f70cd67--- /dev/null+++ b/src/lib/api.test.ts@@ -0,0 +1,50 @@+// The client as a browser uses it (vitest runs without the Tauri shell, like a browser on+// another device): no token anywhere, the CSRF header on every change, and a sign-in again+// when the session ends.++import { afterEach, describe, expect, it, vi } from "vitest";+import { api, configure, setSignedOutHandler, urls } from "./api";+import { inBrowser } from "./platform";++function reply(status: number, body: unknown) {+ return Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }));+}++afterEach(() => vi.unstubAllGlobals());++describe("api in a browser", () => {+ it("runs as a browser in tests", () => expect(inBrowser).toBe(true));++ it("loads images and events without a token", () => {+ configure("/api/v1", "");+ expect(urls.gen("abc")).toBe("/api/v1/gallery/abc/image");+ expect(urls.inputThumb("x")).toBe("/api/v1/inputs/x/thumb");+ expect(urls.lutPreview("warm", "gen:1", 512)).toBe("/api/v1/luts/warm/preview?source=gen%3A1&max=512");+ });++ it("sends the CSRF header on changes only, never a bearer token", async () => {+ configure("/api/v1", "");+ const fetch = vi.fn(() => reply(200, { ok: true }));+ vi.stubGlobal("fetch", fetch);+ await api.status();+ await api.setFavorite("g1", true);+ const [get, patch] = fetch.mock.calls as unknown as [string, RequestInit][];+ expect(get[0]).toBe("/api/v1/status");+ expect(get[1].headers).not.toHaveProperty("Authorization");+ expect(get[1].headers).not.toHaveProperty("x-kokon-csrf");+ expect(patch[1].headers).toMatchObject({ "x-kokon-csrf": "1", "Content-Type": "application/json" });+ expect(patch[1].headers).not.toHaveProperty("Authorization");+ });++ it("asks to sign in again when the session ends, but not for a wrong password", async () => {+ configure("/api/v1", "");+ const signedOut = vi.fn();+ setSignedOutHandler(signedOut);+ const ended = { error: { code: "login_required", message: "Sign in with the password." } };+ vi.stubGlobal("fetch", vi.fn(() => reply(401, ended)));+ await expect(api.gallery({})).rejects.toThrow("Sign in");+ expect(signedOut).toHaveBeenCalledTimes(1);+ await expect(api.login("wrong one")).rejects.toThrow();+ expect(signedOut).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/lib/api.ts b/src/lib/api.tsindex a9e8583..9ed34c0 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1,6 +1,9 @@// Thin client for the local kokon-service API. Images are referenced by URL (with the// token as a query parameter) so the webview streams them directly — no base64 copies.+// In a browser (another device) there is no token: the session cookie signs requests in, and+// every change carries the CSRF header the service asks for.+import { inBrowser } from "./platform";import type {GpuBackend,AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LoraItem, LutEntry, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,@@ -31,24 +34,50 @@ export function configure(baseUrl: string, tok: string) {export const isConfigured = () => base !== "";+/** Browser: the session ended (new password, signed out elsewhere); the app asks to sign in again. */+let onSignedOut = () => {};+export function setSignedOutHandler(f: () => void) {+ onSignedOut = f;+}++function authHeaders(method: string | undefined): Record<string, string> {+ if (!inBrowser) return { Authorization: `Bearer ${token}` };+ return method && method !== "GET" ? { "x-kokon-csrf": "1" } : {};+}+async function call<T>(path: string, init: RequestInit = {}): Promise<T> {let res: Response;try {res = await fetch(base + path, {...init,- headers: { Authorization: `Bearer ${token}`, ...(init.body && typeof init.body === "string" ? { "Content-Type": "application/json" } : {}), ...(init.headers || {}) },+ headers: { ...authHeaders(init.method), ...(init.body && typeof init.body === "string" ? { "Content-Type": "application/json" } : {}), ...(init.headers || {}) },});} catch (e) {- throw new ApiError({ code: "server_unavailable", message: "The local service is not reachable.", detail: String(e) }, 0);+ throw new ApiError({ code: "server_unavailable", message: inBrowser ? "Kokon is not reachable." : "The local service is not reachable.", detail: String(e) }, 0);}const text = await res.text();const data = text ? JSON.parse(text) : null;if (!res.ok) {+ if (inBrowser && data?.error?.code === "login_required" && !path.startsWith("/auth/")) onSignedOut();throw new ApiError(data?.error ?? { code: "internal", message: `HTTP ${res.status}` }, res.status);}return data as T;}+/** `?token=…` for URLs the browser loads by itself (images, events); nothing in a browser, where the cookie signs in. */+const tq = (sep: "?" | "&") => (token ? `${sep}token=${token}` : "");++export interface RemoteStatus {+ enabled: boolean;+ forced: boolean;+ port: number;+ password_set: boolean;+ listening: boolean;+ url: string | null;+ error: string | null;+ min_password_chars: number;+}+const json = (body: unknown) => JSON.stringify(body);export const api = {@@ -135,19 +164,30 @@ export const api = {applyLut: (name: string, source: string, intensity: number, isPrivate: boolean) =>call<GenerationRecord>(`/luts/${encodeURIComponent(name)}/apply`, { method: "POST", body: json({ source, intensity, private: isPrivate }) }),exportGeneration: (id: string, path: string, original = false) => call<{ path: string }>(`/gallery/${id}/export`, { method: "POST", body: json({ path, overwrite: true, original }) }),+ /** Browser sign-in (see crates/qls-service/src/remote.rs). */+ session: () => call<{ signed_in: boolean; password_set: boolean }>("/auth/session"),+ login: (password: string) => call<{ signed_in: boolean }>("/auth/login", { method: "POST", body: json({ password }) }),+ logout: () => call<{ signed_in: boolean }>("/auth/logout", { method: "POST" }),+ /** Access from other devices (desktop app only). */+ remote: () => call<RemoteStatus>("/remote"),+ setRemote: (enabled: boolean, port?: number) => call<RemoteStatus>("/remote", { method: "POST", body: json({ enabled, port }) }),+ setRemotePassword: (password: string) => call<RemoteStatus>("/remote/password", { method: "POST", body: json({ password }) }),+ removeRemotePassword: () => call<RemoteStatus>("/remote/password", { method: "DELETE" }),+ /** Browser: keeps the service from exiting while this tab is open (the desktop app does it from Rust). */+ heartbeat: (clientId: string) => call<{ ok: boolean }>("/session/heartbeat", { method: "POST", body: json({ client_id: clientId, kind: "web" }) }),};export const urls = {- input: (id: string) => `${base}/inputs/${id}/image?token=${token}`,- inputThumb: (id: string) => `${base}/inputs/${id}/thumb?token=${token}`,- gen: (id: string) => `${base}/gallery/${id}/image?token=${token}`,- genThumb: (id: string) => `${base}/gallery/${id}/thumb?token=${token}`,+ input: (id: string) => `${base}/inputs/${id}/image${tq("?")}`,+ inputThumb: (id: string) => `${base}/inputs/${id}/thumb${tq("?")}`,+ gen: (id: string) => `${base}/gallery/${id}/image${tq("?")}`,+ genThumb: (id: string) => `${base}/gallery/${id}/thumb${tq("?")}`,/** The result before the upscaler enlarged it (`pipeline.original_path`). */- genOriginal: (id: string) => `${base}/gallery/${id}/original?token=${token}`,+ genOriginal: (id: string) => `${base}/gallery/${id}/original${tq("?")}`,/** Full image for a "gen:<id>" / "input:<id>" source. */source: (s: string) => (s.startsWith("gen:") ? urls.gen(s.slice(4)) : urls.input(s.slice(6))),/** A LUT on a "gen:"/"input:" source at full strength, at most `max` px on its long side. */- lutPreview: (name: string, source: string, max: number) => `${base}/luts/${encodeURIComponent(name)}/preview?source=${encodeURIComponent(source)}&max=${max}&token=${token}`,+ lutPreview: (name: string, source: string, max: number) => `${base}/luts/${encodeURIComponent(name)}/preview?source=${encodeURIComponent(source)}&max=${max}${tq("&")}`,sourceThumb: (s: string) => (s.startsWith("gen:") ? urls.genThumb(s.slice(4)) : urls.inputThumb(s.slice(6))),};@@ -157,7 +197,7 @@ export function subscribe(onEvent: (e: ServiceEvent) => void, onState?: (connectlet closed = false;let retry: number | undefined;const open = () => {- es = new EventSource(`${base}/events?token=${token}`);+ es = new EventSource(`${base}/events${tq("?")}`);es.onopen = () => onState?.(true);es.onmessage = (m) => {try {diff --git a/src/lib/native.ts b/src/lib/native.tsindex f12cf4d..64c63ce 100644--- a/src/lib/native.ts+++ b/src/lib/native.ts@@ -1,15 +1,42 @@-// Native integrations through the Tauri shell.+// Native integrations through the Tauri shell. In a browser (the UI served by kokon-service to+// other devices) there is no shell: files come in by upload and go out by download, and what+// needs the computer's own folders is hidden by the components (`inBrowser`).import { invoke } from "@tauri-apps/api/core";import { getCurrentWindow } from "@tauri-apps/api/window";import { ask, open, save } from "@tauri-apps/plugin-dialog";+import { inBrowser } from "./platform";export interface Connection { baseUrl: string; token: string; version: string }+/** Copying images in a browser needs a secure page (https, e.g. through Tailscale, or localhost). */+export const canCopyImage = !inBrowser || (typeof window !== "undefined" && window.isSecureContext && !!navigator.clipboard?.write && typeof ClipboardItem !== "undefined");++/** The browser's clipboard takes PNG only. */+async function asPng(blob: Blob): Promise<Blob> {+ if (blob.type === "image/png") return blob;+ const bmp = await createImageBitmap(blob);+ const canvas = document.createElement("canvas");+ canvas.width = bmp.width;+ canvas.height = bmp.height;+ canvas.getContext("2d")!.drawImage(bmp, 0, 0);+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not copy the image."))), "image/png"));+}+export const native = {- connect: () => invoke<Connection>("connect"),+ /** In a browser the API is on the page's own server, signed in by cookie. */+ connect: () => (inBrowser ? Promise.resolve<Connection>({ baseUrl: "/api/v1", token: "", version: "" }) : invoke<Connection>("connect")),+ /** Desktop: the image file at `path`. */copyImage: (path: string) => invoke<void>("copy_image", { path }),+ /** Browser: the image at `url` (see `canCopyImage`). */+ copyImageUrl: async (url: string) => {+ const res = await fetch(url);+ if (!res.ok) throw new Error("Could not read the image.");+ const png = await asPng(await res.blob());+ await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);+ },readClipboardImage: async (): Promise<Uint8Array | null> => {+ if (inBrowser) return null;const buf = await invoke<ArrayBuffer>("read_clipboard_image");const bytes = new Uint8Array(buf);return bytes.length ? bytes : null;@@ -17,13 +44,28 @@ export const native = {reveal: (path: string) => invoke<void>("reveal", { path }),openFolder: (path: string) => invoke<void>("open_folder", { path }),dataFolder: () => invoke<string>("data_folder"),- /** https links to github.com / huggingface.co only. */- openLink: (url: string) => invoke<void>("open_link", { url }),+ /** https links to github.com / huggingface.co only (desktop). */+ openLink: async (url: string) => {+ if (inBrowser) window.open(url, "_blank", "noopener,noreferrer");+ else await invoke<void>("open_link", { url });+ },+ /** Desktop: paths of the images picked. */pickImages: async (): Promise<string[]> => {const r = await open({ multiple: true, directory: false, filters: [{ name: "Images", extensions: ["png", "jpg", "jpeg", "webp", "bmp", "gif", "tif", "tiff", "heic", "heif"] }] });if (!r) return [];return Array.isArray(r) ? r : [r];},+ /** Browser: the images picked on this device, to upload. */+ pickImageFiles: (): Promise<File[]> =>+ new Promise((resolve) => {+ const input = document.createElement("input");+ input.type = "file";+ input.multiple = true;+ input.accept = "image/*,.heic,.heif";+ input.onchange = () => resolve(Array.from(input.files ?? []));+ input.oncancel = () => resolve([]);+ input.click();+ }),pickFile: async (extensions: string[], defaultPath?: string, kind = "Model"): Promise<string | null> => {const r = await open({ multiple: false, directory: false, defaultPath, filters: [{ name: kind, extensions }] });return typeof r === "string" ? r : null;@@ -32,16 +74,24 @@ export const native = {const r = await open({ multiple: false, directory: true, defaultPath });return typeof r === "string" ? r : null;},- confirm: (message: string, title: string) => ask(message, { title, kind: "warning" }),- isFullscreen: () => getCurrentWindow().isFullscreen(),- setFullscreen: (on: boolean) => getCurrentWindow().setFullscreen(on),- setTheme: async (theme: "light" | "dark" | null) => getCurrentWindow().setTheme(theme),+ confirm: (message: string, title: string) => (inBrowser ? Promise.resolve(window.confirm(message)) : ask(message, { title, kind: "warning" })),+ isFullscreen: async () => (inBrowser ? !!document.fullscreenElement : getCurrentWindow().isFullscreen()),+ setFullscreen: async (on: boolean) => {+ if (!inBrowser) return getCurrentWindow().setFullscreen(on);+ if (on && !document.fullscreenElement) await document.documentElement.requestFullscreen?.();+ else if (!on && document.fullscreenElement) await document.exitFullscreen();+ },+ setTheme: async (theme: "light" | "dark" | null) => (inBrowser ? undefined : getCurrentWindow().setTheme(theme)),// Kokon's own title bar (the system one is off on Windows and Linux).minimize: () => getCurrentWindow().minimize(),toggleMaximize: () => getCurrentWindow().toggleMaximize(),close: () => getCurrentWindow().close(),isMaximized: () => getCurrentWindow().isMaximized(),- onResized: (f: () => void) => getCurrentWindow().onResized(f),+ onResized: async (f: () => void): Promise<() => void> => {+ if (!inBrowser) return getCurrentWindow().onResized(f);+ window.addEventListener("resize", f);+ return () => window.removeEventListener("resize", f);+ },saveAs: (defaultName: string) =>save({defaultPath: defaultName,@@ -51,4 +101,13 @@ export const native = {{ name: "WebP", extensions: ["webp"] },],}),+ /** Browser: saves the file at `url` on this device (the browser's downloads). */+ download: (url: string, name: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.download = name;+ document.body.appendChild(a);+ a.click();+ a.remove();+ },};diff --git a/src/lib/platform.ts b/src/lib/platform.tsindex 868948d..0723438 100644--- a/src/lib/platform.ts+++ b/src/lib/platform.ts@@ -8,3 +8,6 @@ export const shortcut = (key: string) => (isMac ? `⌘${key}` : `Ctrl+${key}`);export const isLinux = typeof navigator !== "undefined" && !isMac && /Linux/i.test(navigator.platform || navigator.userAgent);export const fileManager = isMac ? "Finder" : isLinux ? "the file manager" : "Explorer";++/** The UI runs in a browser, served by kokon-service to another device, not in the desktop app. */+export const inBrowser = typeof window !== "undefined" && !("__TAURI_INTERNALS__" in window);diff --git a/src/lib/updates.ts b/src/lib/updates.tsindex 0d4647a..154afe5 100644--- a/src/lib/updates.ts+++ b/src/lib/updates.ts@@ -6,6 +6,7 @@ import { invoke } from "@tauri-apps/api/core";import { relaunch } from "@tauri-apps/plugin-process";import { type Update, check } from "@tauri-apps/plugin-updater";import { api } from "./api";+import { inBrowser } from "./platform";import { getState, setState, toastError, toastInfo } from "./store";const DAY_MS = 24 * 60 * 60 * 1000;@@ -41,6 +42,8 @@ function writeLastCheck(t: number) {/** Looks for an update. `manual`: from Settings, so report the outcome (and errors). */export async function checkForUpdate(manual = false): Promise<void> {+ // A browser shows the server's Kokon, which updates on that computer (or with a new image).+ if (inBrowser) return;try {const u = await check();writeLastCheck(Date.now());diff --git a/src/styles.css b/src/styles.cssindex 99e90d1..487a8de 100644--- a/src/styles.css+++ b/src/styles.css@@ -286,6 +286,13 @@ svg { display: block; flex: none; }.popover .opt:disabled { opacity: 0.5; cursor: default; }.failed { display: flex; flex-direction: column; align-items: center; gap: 10px; max-width: 460px; text-align: center; color: var(--text-2); }.failed strong { color: var(--text); font-weight: 600; }+/* Sign-in in a browser on another device (Login.tsx). */+.login { display: flex; flex-direction: column; align-items: center; gap: 12px; width: min(340px, calc(100vw - 32px)); text-align: center; color: var(--text-2); }+.login strong { color: var(--text); font-size: 17px; font-weight: 600; }+.login .input { width: 100%; box-sizing: border-box; }+.login .btn { width: 100%; justify-content: center; }+.login-error { color: var(--text); font-weight: 500; }+.remote-url { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 15px; color: var(--text); user-select: all; }/* version timeline: a line per image and the versions made from it; arcs join versions madefrom earlier ones or from several */