LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: add LAN access setting for local servers
nash_su21dd78d51cbe
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 05268610..8b257cc6 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -64,8 +64,8 @@ pub fn invalidate_config_cache() {pub fn start_api_server(app: AppHandle) {thread::spawn(move || loop {API_STATUS.store(0, Ordering::Relaxed);- let server = match bind_server_with_retry() {- Some(server) => server,+ let (server, addr) = match bind_server_with_retry(&app) {+ Some(bound) => bound,None => {API_STATUS.store(2, Ordering::Relaxed);thread::sleep(Duration::from_secs(BIND_RETRY_DELAY_SECS));@@ -74,7 +74,6 @@ pub fn start_api_server(app: AppHandle) {};API_STATUS.store(1, Ordering::Relaxed);- let addr = server_bind::bind_addr(&server_bind::configured_bind_host(), PORT);eprintln!("[API Server] Listening on http://{addr}{API_PREFIX}");for request in server.incoming_requests() {@@ -107,12 +106,12 @@ pub fn start_api_server(app: AppHandle) {});}-fn bind_server_with_retry() -> Option<Server> {- let host = server_bind::configured_bind_host();+fn bind_server_with_retry(app: &AppHandle) -> Option<(Server, String)> {+ let host = server_bind::configured_bind_host(app);let addr = server_bind::bind_addr(&host, PORT);for attempt in 1..=MAX_BIND_RETRIES {match Server::http(&addr) {- Ok(server) => return Some(server),+ Ok(server) => return Some((server, addr)),Err(err) => {eprintln!("[API Server] Failed to bind {addr} (attempt {attempt}/{MAX_BIND_RETRIES}): {err}"@@ -230,6 +229,7 @@ fn handle_request("enabled": api_enabled(app),"mcpEnabled": api_mcp_enabled(app),"allowUnauthenticated": api_allow_unauthenticated(app),+ "allowLanAccess": api_allow_lan_access(app),}));}if !path.starts_with(API_PREFIX) {@@ -468,6 +468,17 @@ fn api_allow_unauthenticated(app: &AppHandle) -> bool {.unwrap_or(false)}+fn api_allow_lan_access(app: &AppHandle) -> bool {+ let Some(parsed) = load_app_state(app) else {+ return false;+ };+ parsed+ .get("apiConfig")+ .and_then(|v| v.get("allowLanAccess"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}+/// Whether the API server should accept non-/health requests.////// Defaults to `true` when no config has been written yet — keeps@@ -2428,6 +2439,7 @@ mod tests {"apiConfig": {"enabled": false,"allowUnauthenticated": true,+ "allowLanAccess": true,"mcpEnabled": true,"token": "abc"}@@ -2444,6 +2456,12 @@ mod tests {.and_then(Value::as_bool).unwrap_or(false);assert!(allow_unauthenticated);+ let allow_lan_access = payload+ .get("apiConfig")+ .and_then(|v| v.get("allowLanAccess"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ assert!(allow_lan_access);let mcp_enabled = payload.get("apiConfig").and_then(|v| v.get("mcpEnabled"))@@ -2473,5 +2491,11 @@ mod tests {.and_then(Value::as_bool).unwrap_or(false);assert!(!mcp_enabled_missing);+ let allow_lan_access_missing = missing+ .get("apiConfig")+ .and_then(|v| v.get("allowLanAccess"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ assert!(!allow_lan_access_missing);}}diff --git a/src-tauri/src/clip_server.rs b/src-tauri/src/clip_server.rsindex 9a861dec..752ee716 100644--- a/src-tauri/src/clip_server.rs+++ b/src-tauri/src/clip_server.rs@@ -1,6 +1,7 @@use std::sync::atomic::{AtomicU8, Ordering};use std::sync::Mutex;use std::thread;+use tauri::AppHandle;use tiny_http::{Header, Method, Response, Server};use crate::cors::{local_cors_headers, request_origin};@@ -43,14 +44,14 @@ pub fn all_projects() -> Vec<(String, String)> {.unwrap_or_default()}-pub fn start_clip_server() {- thread::spawn(|| {+pub fn start_clip_server(app: AppHandle) {+ thread::spawn(move || {let mut restart_count: u32 = 0;loop {// Try to bind the port with retries- let server = {- let host = server_bind::configured_bind_host();+ let (server, addr) = {+ let host = server_bind::configured_bind_host(&app);let addr = server_bind::bind_addr(&host, PORT);let mut last_err = String::new();let mut bound = None;@@ -75,7 +76,7 @@ pub fn start_clip_server() {}}match bound {- Some(s) => s,+ Some(s) => (s, addr),None => {eprintln!("[Clip Server] Address {} unavailable after {} attempts: {}",@@ -89,7 +90,6 @@ pub fn start_clip_server() {DAEMON_STATUS.store(1, Ordering::Relaxed); // runningrestart_count = 0; // Reset on successful bind- let addr = server_bind::bind_addr(&server_bind::configured_bind_host(), PORT);println!("[Clip Server] Listening on http://{}", addr);for mut request in server.incoming_requests() {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex eae28351..04a5702d 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -136,8 +136,6 @@ fn tray_available<R: tauri::Runtime>(window: &tauri::Window<R>) -> bool {#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {- clip_server::start_clip_server();-tauri::Builder::default().plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_dialog::init())@@ -186,6 +184,7 @@ pub fn run() {app.manage(TrayAvailabilityState(Mutex::new(false)));// Start the API before optional desktop integrations so the// backend is reachable if tray setup or another integration fails.+ clip_server::start_clip_server(app.handle().clone());api_server::start_api_server(app.handle().clone());let tray_available = match tray::create_tray(app.handle()) {Ok(()) => true,diff --git a/src-tauri/src/server_bind.rs b/src-tauri/src/server_bind.rsindex 7fab7df7..831742f9 100644--- a/src-tauri/src/server_bind.rs+++ b/src-tauri/src/server_bind.rs@@ -1,11 +1,33 @@+use std::fs;++use serde_json::Value;+use tauri::{AppHandle, Manager};+const DEFAULT_BIND_HOST: &str = "127.0.0.1";+const PUBLIC_BIND_HOST: &str = "0.0.0.0";const BIND_HOST_ENV: &str = "LLM_WIKI_BIND_HOST";-pub fn configured_bind_host() -> String {+pub fn configured_bind_host(app: &AppHandle) -> String {+ configured_env_bind_host()+ .or_else(|| configured_store_bind_host(app))+ .unwrap_or_else(|| DEFAULT_BIND_HOST.to_string())+}++fn configured_env_bind_host() -> Option<String> {std::env::var(BIND_HOST_ENV).ok().and_then(|value| sanitize_bind_host(&value))- .unwrap_or_else(|| DEFAULT_BIND_HOST.to_string())+}++fn configured_store_bind_host(app: &AppHandle) -> Option<String> {+ let path = app.path().app_data_dir().ok()?.join("app-state.json");+ let raw = fs::read_to_string(path).ok()?;+ let parsed: Value = serde_json::from_str(&raw).ok()?;+ if allow_lan_access_from_state(&parsed) {+ Some(PUBLIC_BIND_HOST.to_string())+ } else {+ None+ }}pub fn bind_addr(host: &str, port: u16) -> String {@@ -31,9 +53,19 @@ fn sanitize_bind_host(value: &str) -> Option<String> {}}+fn allow_lan_access_from_state(value: &Value) -> bool {+ value+ .get("apiConfig")+ .and_then(|config| config.get("allowLanAccess"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}+#[cfg(test)]mod tests {- use super::{bind_addr, sanitize_bind_host};+ use serde_json::json;++ use super::{allow_lan_access_from_state, bind_addr, sanitize_bind_host};#[test]fn sanitize_bind_host_accepts_common_lan_hosts() {@@ -60,4 +92,15 @@ mod tests {assert_eq!(bind_addr("::1", 19828), "[::1]:19828");assert_eq!(bind_addr("[::]", 19828), "[::]:19828");}++ #[test]+ fn allow_lan_access_reads_api_config_flag() {+ assert!(allow_lan_access_from_state(&json!({+ "apiConfig": { "allowLanAccess": true }+ })));+ assert!(!allow_lan_access_from_state(&json!({+ "apiConfig": { "allowLanAccess": false }+ })));+ assert!(!allow_lan_access_from_state(&json!({})));+ }}diff --git a/src/App.tsx b/src/App.tsxindex 892ebc6a..ad399178 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -317,7 +317,7 @@ function App() {}// Local HTTP API server config — global (single token + enable// flag for the whole install, not per-project). The Rust side- // reads `apiConfig.{enabled,token,mcpEnabled}` from `app-state.json`+ // reads `apiConfig.{enabled,token,mcpEnabled,allowLanAccess}` from `app-state.json`// directly; this only hydrates the Zustand store so the// Settings UI reflects the persisted values.const savedApi = await loadApiConfig()@@ -328,6 +328,8 @@ function App() {typeof savedApi.allowUnauthenticated === "boolean"? savedApi.allowUnauthenticated: false,+ allowLanAccess:+ typeof savedApi.allowLanAccess === "boolean" ? savedApi.allowLanAccess : false,mcpEnabled:typeof savedApi.mcpEnabled === "boolean"? savedApi.mcpEnableddiff --git a/src/components/settings/sections/api-server-section.tsx b/src/components/settings/sections/api-server-section.tsxindex d9d21182..be8d2ebb 100644--- a/src/components/settings/sections/api-server-section.tsx+++ b/src/components/settings/sections/api-server-section.tsx@@ -32,6 +32,7 @@ interface ApiHealth {authRequired?: booleanauthConfigured?: booleanallowUnauthenticated?: boolean+ allowLanAccess?: booleantokenSource?: "env" | "store" | "none"}@@ -148,6 +149,7 @@ export function ApiServerSection({ draft, setDraft }: Props) {const hasUnsavedApiConfig =persistedApiConfig.enabled !== draft.apiEnabled ||persistedApiConfig.allowUnauthenticated !== draft.apiAllowUnauthenticated ||+ persistedApiConfig.allowLanAccess !== draft.apiAllowLanAccess ||persistedApiConfig.mcpEnabled !== draft.apiMcpEnabled ||persistedApiConfig.token !== draft.apiToken.trim()@@ -288,6 +290,28 @@ export function ApiServerSection({ draft, setDraft }: Props) {</div></label>+ <label className="flex items-start gap-3 rounded-md border border-border/60 bg-background/40 px-3 py-2">+ <input+ type="checkbox"+ checked={draft.apiAllowLanAccess}+ onChange={(event) => setDraft("apiAllowLanAccess", event.target.checked)}+ className="mt-1 h-4 w-4"+ />+ <div className="space-y-1">+ <div className="text-sm font-semibold">+ {t("settings.sections.apiServer.allowLanAccess", {+ defaultValue: "Allow API and Clip server access from the local network",+ })}+ </div>+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("settings.sections.apiServer.allowLanAccessHint", {+ defaultValue:+ "After restarting the app, the API and Clip server listen on 0.0.0.0 instead of 127.0.0.1. Use only on trusted networks, and keep token auth enabled unless you fully trust the LAN.",+ })}+ </p>+ </div>+ </label>+<div className="grid grid-cols-1 gap-3 rounded-md border border-border/60 bg-background/40 p-3 text-sm sm:grid-cols-2"><div className="space-y-0.5"><div className="text-[11px] uppercase tracking-wide text-muted-foreground">diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.tsindex 25d9fafc..dc35229d 100644--- a/src/components/settings/settings-types.ts+++ b/src/components/settings/settings-types.ts@@ -84,6 +84,7 @@ export interface SettingsDraft {// Local HTTP API serverapiEnabled: booleanapiAllowUnauthenticated: boolean+ apiAllowLanAccess: booleanapiMcpEnabled: booleanapiToken: string}diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex f7290c54..786c6ece 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -162,6 +162,7 @@ function initialDraft(mineruModelVersion: mineru.modelVersion,apiEnabled: apiConfig.enabled,apiAllowUnauthenticated: apiConfig.allowUnauthenticated,+ apiAllowLanAccess: apiConfig.allowLanAccess,apiMcpEnabled: apiConfig.mcpEnabled,apiToken: apiConfig.token,autostart: generalConfig.autostart,@@ -400,6 +401,7 @@ export function SettingsView() {const newApiConfig = {enabled: draft.apiEnabled,allowUnauthenticated: draft.apiAllowUnauthenticated,+ allowLanAccess: draft.apiAllowLanAccess,mcpEnabled: draft.apiMcpEnabled,token: draft.apiToken.trim(),}@@ -467,9 +469,10 @@ export function SettingsView() {await saveMineruConfig(newMineruConfig)- // The Rust side reads `apiConfig.{enabled,token,mcpEnabled}` from this+ // The Rust side reads `apiConfig.{enabled,token,mcpEnabled,allowLanAccess}` from this// same `app-state.json` via a 5s cache, so saved changes propagate within- // that window without any IPC round-trip.+ // that window without any IPC round-trip. Bind-address changes still+ // require an app restart because the server sockets are already open.await saveApiConfig(newApiConfig)try {await invoke<string>("api_server_reload_config")diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex a94867c0..27cff953 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -528,6 +528,8 @@"openHealthHint": "Opens in your system browser. /health is the only unauthenticated endpoint.","allowUnauthenticated": "Allow access without a token","allowUnauthenticatedHint": "Use only for trusted local agents. Any process or browser page on this machine can call the API while this is enabled.",+ "allowLanAccess": "Allow API and Clip server access from the local network",+ "allowLanAccessHint": "After restarting the app, the API and Clip server listen on 0.0.0.0 instead of 127.0.0.1. Use only on trusted networks, and keep token auth enabled unless you fully trust the LAN.","mcpEnable": "Enable MCP access","mcpEnableHint": "MCP uses the local API and the same token rules. Keep the HTTP API enabled, then connect an MCP client to the bundled Node server.","mcpUsage": "MCP usage",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 80779c22..737ebebc 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -528,6 +528,8 @@"openHealthHint": "在系统浏览器中打开。/health 是唯一不需要 token 的接口。","allowUnauthenticated": "允许无 token 访问","allowUnauthenticatedHint": "仅用于可信的本地智能体。启用后,这台机器上的任何进程或浏览器页面都可以调用 API。",+ "allowLanAccess": "允许 API 和 Clip server 局域网访问",+ "allowLanAccessHint": "重启应用后,API 和 Clip server 会监听 0.0.0.0,而不是 127.0.0.1。仅在可信网络中使用,除非完全信任局域网,否则请保留 token 鉴权。","mcpEnable": "启用 MCP 访问","mcpEnableHint": "MCP 复用本地 API 和同一套 token 规则。保持 HTTP API 启用后,将 MCP 客户端连接到内置 Node 服务即可。","mcpUsage": "MCP 使用说明",diff --git a/src/lib/api-server.real-llm.test.ts b/src/lib/api-server.real-llm.test.tsindex 7759a231..203d6429 100644--- a/src/lib/api-server.real-llm.test.ts+++ b/src/lib/api-server.real-llm.test.ts@@ -46,6 +46,7 @@ interface ApiHealth extends ApiEnvelope {authRequired?: booleanauthConfigured?: booleanallowUnauthenticated?: boolean+ allowLanAccess?: booleantokenSource?: "env" | "store" | "none"}@@ -259,10 +260,11 @@ async function readAppState(): Promise<Record<string, unknown>> {async function writeApiConfig(config: {enabled: booleanallowUnauthenticated: boolean+ allowLanAccess?: booleantoken: string}): Promise<void> {const state = await readAppState()- state.apiConfig = config+ state.apiConfig = { allowLanAccess: false, ...config }await fs.writeFile(appStatePath!, `${JSON.stringify(state, null, 2)}\n`, "utf8")appStateMutated = true}diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex b3cf788f..d474751b 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -197,6 +197,8 @@ interface ScheduledImportConfig {* env-token-only setup keeps working after the toggle is added.* - `allowUnauthenticated` lets local agents call the API without a* token. It is explicit and default-off.+ * - `allowLanAccess` binds the API and clip server to 0.0.0.0 on+ * app startup so trusted LAN devices can reach them. Default-off.* - `mcpEnabled` allows the optional MCP stdio server to use this* API. It is separate from the HTTP API kill-switch so users can* expose scripts while keeping MCP disabled.@@ -207,6 +209,7 @@ interface ScheduledImportConfig {interface ApiConfig {enabled: booleanallowUnauthenticated: boolean+ allowLanAccess: booleanmcpEnabled: booleantoken: string}@@ -529,6 +532,7 @@ export const useWikiStore = create<WikiState>((set) => ({apiConfig: {enabled: true,allowUnauthenticated: false,+ allowLanAccess: false,mcpEnabled: false,token: "",},