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: allow secure LAN clipper connections
nash_su3f0491c84df3
diff --git a/extension/manifest.json b/extension/manifest.jsonindex 614297e6..3829f2d0 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -3,11 +3,15 @@"name": "LLM Wiki Clipper","version": "0.1.0","description": "Clip web pages to your LLM Wiki knowledge base",- "permissions": ["activeTab", "scripting"],+ "permissions": ["activeTab", "scripting", "storage"],"host_permissions": ["http://127.0.0.1:19827/*","http://localhost:19827/*"],+ "optional_host_permissions": [+ "http://*/*",+ "https://*/*"+ ],"action": {"default_popup": "popup.html","default_icon": {diff --git a/extension/popup.html b/extension/popup.htmlindex cd87543b..61402bfb 100644--- a/extension/popup.html+++ b/extension/popup.html@@ -60,6 +60,22 @@box-shadow: 0 0 0 2px rgba(99,102,241,0.1);}.field select { cursor: pointer; }+ .connection-settings {+ margin-bottom: 10px;+ border: 1px solid #e5e7eb;+ border-radius: 6px;+ background: white;+ }+ .connection-settings summary {+ padding: 7px 10px;+ cursor: pointer;+ font-size: 11px;+ font-weight: 600;+ color: #4b5563;+ }+ .connection-settings-body { padding: 0 10px 9px; }+ .btn-secondary { margin-top: 2px; padding: 7px; background: #e5e7eb; color: #374151; }+ .btn-secondary:hover { background: #d1d5db; }.url-preview {padding: 4px 8px;background: #f3f4f6;@@ -119,6 +135,21 @@<div class="content"><div id="statusBar" class="status disconnected">Checking connection...</div>+ <details class="connection-settings" id="connectionSettings">+ <summary>Connection settings</summary>+ <div class="connection-settings-body">+ <div class="field">+ <label for="serverUrlInput">Server address</label>+ <input type="text" id="serverUrlInput" placeholder="http://192.168.1.50:19827">+ </div>+ <div class="field">+ <label for="accessTokenInput">Access token</label>+ <input type="password" id="accessTokenInput" placeholder="Required for LAN access">+ </div>+ <button class="btn btn-secondary" id="saveConnectionBtn" type="button">Save and reconnect</button>+ </div>+ </details>+<div class="field"><label>Save to Project</label><select id="projectSelect">diff --git a/extension/popup.js b/extension/popup.jsindex 4201ec63..3f4e0208 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -6,24 +6,64 @@ const urlPreview = document.getElementById("urlPreview");const contentPreview = document.getElementById("contentPreview");const clipBtn = document.getElementById("clipBtn");const projectSelect = document.getElementById("projectSelect");+const serverUrlInput = document.getElementById("serverUrlInput");+const accessTokenInput = document.getElementById("accessTokenInput");+const saveConnectionBtn = document.getElementById("saveConnectionBtn");+const connectionSettings = document.getElementById("connectionSettings");let extractedContent = "";let pageUrl = "";let apiUrl = API_URLS[0];+let accessToken = "";++function normalizeServerUrl(value) {+ let candidate = String(value || "").trim();+ if (!candidate) return API_URLS[0];+ if (!/^https?:\/\//i.test(candidate)) candidate = `http://${candidate}`;+ const parsed = new URL(candidate);+ if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password) {+ throw new Error("Use an http(s) address without embedded credentials");+ }+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) {+ throw new Error("Enter only the server origin, without a path, query, or fragment");+ }+ if (!parsed.port) parsed.port = "19827";+ return parsed.origin;+}++async function loadConnectionSettings() {+ const saved = await chrome.storage.local.get(["serverUrl", "accessToken"]);+ try {+ apiUrl = normalizeServerUrl(saved.serverUrl || API_URLS[0]);+ } catch {+ apiUrl = API_URLS[0];+ connectionSettings.open = true;+ }+ accessToken = String(saved.accessToken || "");+ serverUrlInput.value = apiUrl;+ accessTokenInput.value = accessToken;+}++function requestHeaders(options) {+ const headers = new Headers(options?.headers || {});+ if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);+ return headers;+}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"+ const isDefaultLocalAddress = API_URLS.includes(apiUrl);+ const urls = method === "GET" && isDefaultLocalAddress? [apiUrl, ...API_URLS.filter((url) => url !== apiUrl)]: [apiUrl];let lastError;for (const baseUrl of urls) {try {- const res = await fetch(`${baseUrl}${path}`, options);+ const res = await fetch(`${baseUrl}${path}`, { ...options, headers: requestHeaders(options) });apiUrl = baseUrl;return res;} catch (err) {@@ -35,18 +75,25 @@ async function clipFetch(path, options) {}async function checkConnection() {+ let connectionError = "";try {const res = await clipFetch("/status", { method: "GET" });const data = await res.json();+ if (res.status === 401) throw new Error("Access token required or invalid");if (data.ok) {statusBar.className = "status connected";statusBar.textContent = "✓ Connected to LLM Wiki";await loadProjects();return true;}- } catch {}+ } catch (err) {+ connectionError = err?.message || "";+ }statusBar.className = "status disconnected";- statusBar.textContent = "✗ LLM Wiki app is not running";+ statusBar.textContent = connectionError.includes("token")+ ? "✗ Access token required or invalid"+ : "✗ Cannot connect to LLM Wiki"+ statusBar.title = connectionError;clipBtn.disabled = true;projectSelect.innerHTML = '<option value="">App not running</option>';return false;@@ -268,6 +315,25 @@ async function sendClip() {clipBtn.addEventListener("click", sendClip);+saveConnectionBtn.addEventListener("click", async () => {+ try {+ const nextUrl = normalizeServerUrl(serverUrlInput.value);+ const originPattern = `${new URL(nextUrl).origin}/*`;+ const granted = await chrome.permissions.request({ origins: [originPattern] });+ if (!granted) throw new Error("Host permission was not granted");+ apiUrl = nextUrl;+ accessToken = accessTokenInput.value.trim();+ await chrome.storage.local.set({ serverUrl: apiUrl, accessToken });+ connectionSettings.open = false;+ clipBtn.disabled = true;+ await checkConnection();+ } catch (err) {+ connectionSettings.open = true;+ statusBar.className = "status error";+ statusBar.textContent = `✗ ${err.message}`;+ }+});+// Resize content preview to fill available space without causing popup scrollfunction resizePreview() {const totalHeight = 500; // matches html/body height@@ -282,6 +348,7 @@ function resizePreview() {}(async () => {+ await loadConnectionSettings();const connected = await checkConnection();// Always extract content so user can preview, even if app not runningawait extractContent();diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 2a7d1bba..37665d38 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -431,7 +431,11 @@ fn is_authorized(app: &AppHandle, query: &str, headers: &[(String, String)]) ->is_token_authorized(app, query, headers)}-fn is_token_authorized(app: &AppHandle, query: &str, headers: &[(String, String)]) -> bool {+pub(crate) fn is_token_authorized(+ app: &AppHandle,+ query: &str,+ headers: &[(String, String)],+) -> bool {let Some(token) = api_token(app) else {return false;};diff --git a/src-tauri/src/clip_server.rs b/src-tauri/src/clip_server.rsindex 752ee716..bbc72571 100644--- a/src-tauri/src/clip_server.rs+++ b/src-tauri/src/clip_server.rs@@ -108,6 +108,23 @@ pub fn start_clip_server(app: AppHandle) {continue;}+ // Loopback callers preserve the pre-LAN behavior used by the+ // desktop app and older extensions. Any LAN client must use+ // the same API token as port 19828; exposing clip/project+ // endpoints without authentication would leak project paths+ // and permit writes from every device on the network.+ if !request_is_loopback(&request) && !request_is_authorized(&app, &request) {+ let mut response = Response::from_string(+ r#"{"ok":false,"error":"Missing or invalid API token"}"#,+ )+ .with_status_code(401);+ for h in &cors_headers {+ response.add_header(h.clone());+ }+ let _ = request.respond(response);+ continue;+ }+let url = request.url().to_string();match (request.method(), url.as_str()) {@@ -296,7 +313,48 @@ pub fn start_clip_server(app: AppHandle) {}fn cors_headers(origin: Option<&str>) -> Vec<Header> {- local_cors_headers(origin, "Content-Type")+ local_cors_headers(origin, "Content-Type, Authorization, X-LLM-Wiki-Token")+}++fn request_is_loopback(request: &tiny_http::Request) -> bool {+ address_is_loopback(request.remote_addr())+}++fn address_is_loopback(address: Option<&std::net::SocketAddr>) -> bool {+ address+ .map(|value| value.ip().is_loopback())+ .unwrap_or(false)+}++fn request_is_authorized(app: &AppHandle, request: &tiny_http::Request) -> bool {+ let headers = request+ .headers()+ .iter()+ .map(|header| {+ (+ header.field.as_str().to_string().to_ascii_lowercase(),+ header.value.as_str().to_string(),+ )+ })+ .collect::<Vec<_>>();+ crate::api_server::is_token_authorized(app, "", &headers)+}++#[cfg(test)]+mod lan_auth_tests {+ use super::address_is_loopback;+ use std::net::SocketAddr;++ #[test]+ fn only_ipv4_and_ipv6_loopback_addresses_bypass_clip_auth() {+ let ipv4: SocketAddr = "127.0.0.1:50000".parse().unwrap();+ let ipv6: SocketAddr = "[::1]:50000".parse().unwrap();+ let lan: SocketAddr = "192.168.1.20:50000".parse().unwrap();+ assert!(address_is_loopback(Some(&ipv4)));+ assert!(address_is_loopback(Some(&ipv6)));+ assert!(!address_is_loopback(Some(&lan)));+ assert!(!address_is_loopback(None));+ }}fn handle_set_project(body: &str) -> String {