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
fix: harden local extension connection cors
nash_su9a1755259db8
diff --git a/extension/manifest.json b/extension/manifest.jsonindex b0bb891b..614297e6 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -4,7 +4,10 @@"version": "0.1.0","description": "Clip web pages to your LLM Wiki knowledge base","permissions": ["activeTab", "scripting"],- "host_permissions": ["http://127.0.0.1:19827/*"],+ "host_permissions": [+ "http://127.0.0.1:19827/*",+ "http://localhost:19827/*"+ ],"action": {"default_popup": "popup.html","default_icon": {diff --git a/extension/popup.js b/extension/popup.jsindex 4d824522..4201ec63 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -1,4 +1,4 @@-const API_URL = "http://127.0.0.1:19827";+const API_URLS = ["http://127.0.0.1:19827", "http://localhost:19827"];const statusBar = document.getElementById("statusBar");const titleInput = document.getElementById("titleInput");@@ -9,10 +9,34 @@ const projectSelect = document.getElementById("projectSelect");let extractedContent = "";let pageUrl = "";+let apiUrl = API_URLS[0];++async function clipFetch(path, options) {+ const method = String(options?.method || "GET").toUpperCase();+ // Only retry idempotent reads across host aliases. Retrying POST /clip can+ // duplicate a clip if the server handled the first request but the response+ // failed before the extension received it.+ const urls = method === "GET"+ ? [apiUrl, ...API_URLS.filter((url) => url !== apiUrl)]+ : [apiUrl];+ let lastError;++ for (const baseUrl of urls) {+ try {+ const res = await fetch(`${baseUrl}${path}`, options);+ apiUrl = baseUrl;+ return res;+ } catch (err) {+ lastError = err;+ }+ }++ throw lastError || new Error("Unable to connect to LLM Wiki");+}async function checkConnection() {try {- const res = await fetch(`${API_URL}/status`, { method: "GET" });+ const res = await clipFetch("/status", { method: "GET" });const data = await res.json();if (data.ok) {statusBar.className = "status connected";@@ -30,7 +54,7 @@ async function checkConnection() {async function loadProjects() {try {- const res = await fetch(`${API_URL}/projects`, { method: "GET" });+ const res = await clipFetch("/projects", { method: "GET" });const data = await res.json();if (data.ok && data.projects?.length > 0) {projectSelect.innerHTML = "";@@ -46,7 +70,7 @@ async function loadProjects() {} catch {}// Fallback to current projecttry {- const res = await fetch(`${API_URL}/project`, { method: "GET" });+ const res = await clipFetch("/project", { method: "GET" });const data = await res.json();if (data.ok && data.path) {const name = data.path.replace(/\\/g, "/").split("/").pop() || data.path;@@ -212,7 +236,7 @@ async function sendClip() {statusBar.textContent = "⏳ Sending to LLM Wiki...";try {- const res = await fetch(`${API_URL}/clip`, {+ const res = await clipFetch("/clip", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex c9a0e585..227dafca 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -13,6 +13,7 @@ use tauri::{AppHandle, Manager};use tiny_http::{Header, Method, Response, Server, StatusCode};use walkdir::WalkDir;+use crate::cors::{local_cors_headers, request_origin};use crate::{clip_server, commands};const PORT: u16 = 19828;@@ -78,12 +79,13 @@ pub fn start_api_server(app: AppHandle) {for request in server.incoming_requests() {let method = request.method().clone();let url = request.url().to_string();+ let origin = request_origin(&request);if should_rate_limit(&method, &url) && !allow_request() {- respond_error(request, 429, "Too many requests");+ respond_error(request, 429, "Too many requests", origin.as_deref());continue;}let Some(slot) = try_acquire_request_slot() else {- respond_error(request, 503, "API server is busy");+ respond_error(request, 503, "API server is busy", origin.as_deref());continue;};let app = app.clone();@@ -150,8 +152,9 @@ fn try_acquire_request_slot() -> Option<RequestSlot> {fn process_request(app: AppHandle, mut request: tiny_http::Request) {let method = request.method().clone();let url = request.url().to_string();+ let origin = request_origin(&request);if method == Method::Options {- respond_options(request);+ respond_options(request, origin.as_deref());return;}@@ -169,7 +172,7 @@ fn process_request(app: AppHandle, mut request: tiny_http::Request) {let body = match read_body(&mut request) {Ok(body) => body,Err(err) => {- respond_error(request, 400, &err);+ respond_error(request, 400, &err, origin.as_deref());return;}};@@ -181,7 +184,7 @@ fn process_request(app: AppHandle, mut request: tiny_http::Request) {eprintln!("[API Server] request panicked: {payload:?}");err(500, "Internal API server error")});- respond_json(request, response.status, response.body);+ respond_json(request, response.status, response.body, origin.as_deref());}struct ApiResponse {@@ -316,38 +319,34 @@ fn read_body(request: &mut tiny_http::Request) -> Result<String, String> {String::from_utf8(bytes).map_err(|_| "Request body must be UTF-8".to_string())}-fn respond_error(request: tiny_http::Request, status: u16, message: &str) {- respond_json(request, status, json!({ "ok": false, "error": message }));+fn respond_error(request: tiny_http::Request, status: u16, message: &str, origin: Option<&str>) {+ respond_json(+ request,+ status,+ json!({ "ok": false, "error": message }),+ origin,+ );}-fn respond_options(request: tiny_http::Request) {+fn respond_options(request: tiny_http::Request, origin: Option<&str>) {let mut response = Response::empty(StatusCode(204));- for header in cors_headers() {+ for header in cors_headers(origin) {response.add_header(header);}response.add_header(Header::from_bytes("Access-Control-Max-Age", "600").unwrap());let _ = request.respond(response);}-fn respond_json(request: tiny_http::Request, status: u16, body: Value) {+fn respond_json(request: tiny_http::Request, status: u16, body: Value, origin: Option<&str>) {let mut response = Response::from_string(body.to_string()).with_status_code(StatusCode(status));- for header in cors_headers() {+ for header in cors_headers(origin) {response.add_header(header);}let _ = request.respond(response);}-fn cors_headers() -> Vec<Header> {- vec![- Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap(),- Header::from_bytes("Access-Control-Allow-Methods", "GET, POST, PATCH, OPTIONS").unwrap(),- Header::from_bytes(- "Access-Control-Allow-Headers",- "Content-Type, Authorization, X-LLM-Wiki-Token",- )- .unwrap(),- Header::from_bytes("Content-Type", "application/json").unwrap(),- ]+fn cors_headers(origin: Option<&str>) -> Vec<Header> {+ local_cors_headers(origin, "Content-Type, Authorization, X-LLM-Wiki-Token")}fn split_url(url: &str) -> (String, &str) {diff --git a/src-tauri/src/clip_server.rs b/src-tauri/src/clip_server.rsindex b68402f0..17a9ceab 100644--- a/src-tauri/src/clip_server.rs+++ b/src-tauri/src/clip_server.rs@@ -3,6 +3,8 @@ use std::sync::Mutex;use std::thread;use tiny_http::{Header, Method, Response, Server};+use crate::cors::{local_cors_headers, request_origin};+static CURRENT_PROJECT: Mutex<String> = Mutex::new(String::new());static ALL_PROJECTS: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new()); // (name, path)static PENDING_CLIPS: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new()); // (projectPath, filePath)@@ -87,13 +89,8 @@ pub fn start_clip_server() {println!("[Clip Server] Listening on http://127.0.0.1:{}", PORT);for mut request in server.incoming_requests() {- let cors_headers = vec![- Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap(),- Header::from_bytes("Access-Control-Allow-Methods", "GET, POST, OPTIONS")- .unwrap(),- Header::from_bytes("Access-Control-Allow-Headers", "Content-Type").unwrap(),- Header::from_bytes("Content-Type", "application/json").unwrap(),- ];+ let origin = request_origin(&request);+ let cors_headers = cors_headers(origin.as_deref());// Handle CORS preflightif request.method() == &Method::Options {@@ -101,6 +98,8 @@ pub fn start_clip_server() {for h in &cors_headers {response.add_header(h.clone());}+ response+ .add_header(Header::from_bytes("Access-Control-Max-Age", "600").unwrap());let _ = request.respond(response);continue;}@@ -292,6 +291,10 @@ pub fn start_clip_server() {});}+fn cors_headers(origin: Option<&str>) -> Vec<Header> {+ local_cors_headers(origin, "Content-Type")+}+fn handle_set_project(body: &str) -> String {let parsed: serde_json::Value = match serde_json::from_str(body) {Ok(v) => v,diff --git a/src-tauri/src/cors.rs b/src-tauri/src/cors.rsnew file mode 100644index 00000000..309da781--- /dev/null+++ b/src-tauri/src/cors.rs@@ -0,0 +1,108 @@+use tiny_http::Header;++pub fn request_origin(request: &tiny_http::Request) -> Option<String> {+ request+ .headers()+ .iter()+ .find(|header| header.field.equiv("Origin"))+ .map(|header| header.value.as_str().to_string())+}++pub fn is_allowed_browser_origin(origin: &str) -> bool {+ origin.starts_with("chrome-extension://")+ || origin.starts_with("moz-extension://")+ || origin == "http://localhost"+ || origin.starts_with("http://localhost:")+ || origin == "http://127.0.0.1"+ || origin.starts_with("http://127.0.0.1:")+ || origin == "http://[::1]"+ || origin.starts_with("http://[::1]:")+ || origin == "tauri://localhost"+ || origin == "http://tauri.localhost"+ || origin == "https://tauri.localhost"+}++pub fn local_cors_headers(origin: Option<&str>, allow_headers: &str) -> Vec<Header> {+ let mut headers = vec![+ Header::from_bytes("Access-Control-Allow-Methods", "GET, POST, PATCH, OPTIONS").unwrap(),+ Header::from_bytes("Access-Control-Allow-Headers", allow_headers).unwrap(),+ Header::from_bytes("Content-Type", "application/json").unwrap(),+ ];+ if let Some(origin) = origin.filter(|origin| is_allowed_browser_origin(origin)) {+ headers.push(Header::from_bytes("Access-Control-Allow-Origin", origin).unwrap());+ headers.push(Header::from_bytes("Vary", "Origin").unwrap());+ headers.push(Header::from_bytes("Access-Control-Allow-Private-Network", "true").unwrap());+ }+ headers+}++#[cfg(test)]+mod tests {+ use super::*;++ fn header_value(headers: &[Header], name: &str) -> Option<String> {+ headers+ .iter()+ .find(|header| header.field.as_str().to_string().eq_ignore_ascii_case(name))+ .map(|header| header.value.as_str().to_string())+ }++ #[test]+ fn allowed_browser_origins_are_narrowly_scoped() {+ for origin in [+ "chrome-extension://abc",+ "moz-extension://abc",+ "http://localhost",+ "http://localhost:19827",+ "http://127.0.0.1:5500",+ "http://[::1]:3000",+ "tauri://localhost",+ "http://tauri.localhost",+ "https://tauri.localhost",+ ] {+ assert!(is_allowed_browser_origin(origin), "{origin}");+ }++ for origin in [+ "",+ "HTTP://LOCALHOST",+ "http://localhost.evil.com",+ "http://127.0.0.1.evil.com",+ "https://localhost",+ "http://evil.com",+ "https://evil.com",+ ] {+ assert!(!is_allowed_browser_origin(origin), "{origin}");+ }+ }++ #[test]+ fn cors_headers_reflect_allowed_origin_only() {+ let allowed = local_cors_headers(Some("chrome-extension://abc"), "Content-Type");+ assert_eq!(+ header_value(&allowed, "Access-Control-Allow-Origin").as_deref(),+ Some("chrome-extension://abc")+ );+ assert_eq!(+ header_value(&allowed, "Access-Control-Allow-Private-Network").as_deref(),+ Some("true")+ );+ assert_eq!(+ header_value(&allowed, "Access-Control-Allow-Methods").as_deref(),+ Some("GET, POST, PATCH, OPTIONS")+ );+ assert_eq!(+ header_value(&allowed, "Access-Control-Allow-Headers").as_deref(),+ Some("Content-Type")+ );+ assert_eq!(header_value(&allowed, "Vary").as_deref(), Some("Origin"));++ let denied = local_cors_headers(Some("https://evil.com"), "Content-Type");+ assert!(header_value(&denied, "Access-Control-Allow-Origin").is_none());+ assert!(header_value(&denied, "Access-Control-Allow-Private-Network").is_none());+ assert!(header_value(&denied, "Vary").is_none());++ let missing = local_cors_headers(None, "Content-Type");+ assert!(header_value(&missing, "Access-Control-Allow-Origin").is_none());+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 740399ba..112d99ac 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,6 +1,7 @@mod api_server;mod clip_server;mod commands;+mod cors;mod panic_guard;mod proxy;mod tray;