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 trusted proxies with invalid TLS certs
nash_sua54ec4165af3
diff --git a/src-tauri/src/agent/provider.rs b/src-tauri/src/agent/provider.rsindex b186a5a8..c8f8e6e9 100644--- a/src-tauri/src/agent/provider.rs+++ b/src-tauri/src/agent/provider.rs@@ -138,7 +138,7 @@ impl AgentLlmProvider for LlmClient {impl LlmClient {pub fn new(config: LlmConfig) -> Result<Self, String> {- let client = reqwest::Client::builder()+ let client = crate::proxy::configure_http_client(reqwest::Client::builder()).timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS)).build().map_err(|err| format!("Failed to build LLM HTTP client: {err}"))?;diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rsindex 4d41f46e..202b3e19 100644--- a/src-tauri/src/agent/tools.rs+++ b/src-tauri/src/agent/tools.rs@@ -1181,7 +1181,7 @@ pub async fn run_web_search(return Err("Web search provider is not configured.".to_string());}let max_results = web_search_result_limit(&provider, top_k);- let client = reqwest::Client::builder()+ let client = crate::proxy::configure_http_client(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(WEB_SEARCH_TIMEOUT_SECS)).build().map_err(|err| format!("Failed to build web search client: {err}"))?;@@ -1242,7 +1242,7 @@ pub async fn run_anytxt_search(.filter_ext.filter(|value| !value.trim().is_empty()).unwrap_or_else(|| "*".to_string());- let client = reqwest::Client::builder()+ let client = crate::proxy::configure_http_client(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(WEB_SEARCH_TIMEOUT_SECS)).build().map_err(|err| format!("Failed to build AnyTXT client: {err}"))?;diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 654bf3b0..47a1de39 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -1107,7 +1107,7 @@ async fn fetch_embedding_batch(}let endpoint = volcengine_embedding_endpoint(cfg);- let mut req = reqwest::Client::builder()+ let mut req = crate::proxy::configure_http_client(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(SEARCH_EMBEDDING_TIMEOUT_SECS,))@@ -1236,7 +1236,7 @@ async fn fetch_embedding_once(} else {volcengine_embedding_endpoint(cfg)};- let mut req = reqwest::Client::builder()+ let mut req = crate::proxy::configure_http_client(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(SEARCH_EMBEDDING_TIMEOUT_SECS,))diff --git a/src-tauri/src/proxy.rs b/src-tauri/src/proxy.rsindex fb3c0d81..253474ed 100644--- a/src-tauri/src/proxy.rs+++ b/src-tauri/src/proxy.rs@@ -13,12 +13,16 @@//! Cost is one duplicated key name (`proxyConfig`) — see//! src/lib/project-store.ts for the matching write site.-use std::path::Path;+use std::{+ path::Path,+ sync::atomic::{AtomicBool, Ordering},+};use serde::{Deserialize, Serialize};const DEFAULT_BYPASS_LIST: &str ="localhost,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.local";+static ACCEPT_INVALID_CERTS: AtomicBool = AtomicBool::new(false);#[derive(Debug, Serialize, Deserialize)]pub struct ProxyConfig {@@ -28,6 +32,8 @@ pub struct ProxyConfig {pub url: String,#[serde(default = "default_true", rename = "bypassLocal")]pub bypass_local: bool,+ #[serde(default, rename = "acceptInvalidCerts")]+ pub accept_invalid_certs: bool,}// Hand-written Default impl so its `bypass_local` matches what@@ -43,6 +49,7 @@ impl Default for ProxyConfig {enabled: false,url: String::new(),bypass_local: true,+ accept_invalid_certs: false,}}}@@ -89,7 +96,13 @@ pub fn apply_proxy_env(config: &ProxyConfig) -> String {let url = config.url.trim();let invalid_scheme = !url.starts_with("http://") && !url.starts_with("https://");- if !config.enabled || url.is_empty() || invalid_scheme {+ let proxy_active = config.enabled && !url.is_empty() && !invalid_scheme;+ ACCEPT_INVALID_CERTS.store(+ proxy_active && config.accept_invalid_certs,+ Ordering::Relaxed,+ );++ if !proxy_active {clear_proxy_env();return if !config.enabled {"disabled".to_string()@@ -112,12 +125,19 @@ pub fn apply_proxy_env(config: &ProxyConfig) -> String {std::env::remove_var("NO_PROXY");}format!(- "enabled ({}, bypass_local={})",+ "enabled ({}, bypass_local={}, accept_invalid_certs={})",redact_url(url),- config.bypass_local+ config.bypass_local,+ config.accept_invalid_certs,)}+/// Apply the process-wide TLS policy to native reqwest clients. This mirrors+/// the `danger.acceptInvalidCerts` option injected into tauri-plugin-http.+pub fn configure_http_client(builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {+ builder.danger_accept_invalid_certs(ACCEPT_INVALID_CERTS.load(Ordering::Relaxed))+}+/// Strip embedded basic-auth credentials from a URL before logging./// `http://user:pass@host:port` → `http://***@host:port`. URLs/// without credentials pass through untouched. Used so stderr /@@ -210,6 +230,7 @@ mod tests {enabled: false,url: "http://x:1".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(s.contains("disabled"));assert!(std::env::var("HTTP_PROXY").is_err());@@ -224,6 +245,7 @@ mod tests {enabled: true,url: "http://127.0.0.1:7890".into(),bypass_local: true,+ accept_invalid_certs: false,});assert_eq!(std::env::var("HTTP_PROXY").unwrap(),@@ -240,6 +262,27 @@ mod tests {});}+ #[test]+ fn invalid_certificates_are_accepted_only_for_an_active_proxy() {+ isolated(|| {+ apply_proxy_env(&ProxyConfig {+ enabled: true,+ url: "http://127.0.0.1:7890".into(),+ bypass_local: true,+ accept_invalid_certs: true,+ });+ assert!(ACCEPT_INVALID_CERTS.load(Ordering::Relaxed));++ apply_proxy_env(&ProxyConfig {+ enabled: false,+ url: "http://127.0.0.1:7890".into(),+ bypass_local: true,+ accept_invalid_certs: true,+ });+ assert!(!ACCEPT_INVALID_CERTS.load(Ordering::Relaxed));+ });+ }+#[test]fn bypass_local_off_clears_no_proxy() {isolated(|| {@@ -248,6 +291,7 @@ mod tests {enabled: true,url: "http://x:1".into(),bypass_local: false,+ accept_invalid_certs: false,});// The stale value must be cleared so the user's intent// (everything goes through the proxy) is honored.@@ -262,6 +306,7 @@ mod tests {enabled: true,url: "socks5://x:1".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(std::env::var("HTTP_PROXY").is_err());});@@ -274,6 +319,7 @@ mod tests {enabled: true,url: " ".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(std::env::var("HTTP_PROXY").is_err());});@@ -291,6 +337,7 @@ mod tests {enabled: true,url: "http://127.0.0.1:7890".into(),bypass_local: true,+ accept_invalid_certs: false,});assert_eq!(std::env::var("HTTP_PROXY").unwrap(),@@ -301,6 +348,7 @@ mod tests {enabled: false,url: "http://127.0.0.1:7890".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(std::env::var("HTTP_PROXY").is_err());assert!(std::env::var("HTTPS_PROXY").is_err());@@ -319,11 +367,13 @@ mod tests {enabled: true,url: "http://127.0.0.1:7890".into(),bypass_local: true,+ accept_invalid_certs: false,});apply_proxy_env(&ProxyConfig {enabled: true,url: "socks5://x:1".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(std::env::var("HTTP_PROXY").is_err());});@@ -336,6 +386,7 @@ mod tests {enabled: true,url: "https://proxy.corp:443".into(),bypass_local: false,+ accept_invalid_certs: false,});assert_eq!(std::env::var("HTTPS_PROXY").unwrap(),@@ -376,6 +427,7 @@ mod tests {enabled: true,url: "http://secretuser:[email protected]:8080".into(),bypass_local: true,+ accept_invalid_certs: false,});assert!(!summary.contains("secretpass"));assert!(!summary.contains("secretuser"));diff --git a/src/components/settings/sections/network-section.tsx b/src/components/settings/sections/network-section.tsxindex 7121e785..a29264c4 100644--- a/src/components/settings/sections/network-section.tsx+++ b/src/components/settings/sections/network-section.tsx@@ -97,6 +97,29 @@ export function NetworkSection({ draft, setDraft }: Props) {</div></label>+ <label className="flex items-start gap-2">+ <input+ type="checkbox"+ checked={draft.proxyAcceptInvalidCerts}+ onChange={(e) => setDraft("proxyAcceptInvalidCerts", e.target.checked)}+ disabled={!draft.proxyEnabled}+ className="mt-0.5 h-4 w-4"+ />+ <div className="space-y-1">+ <span className="text-sm">+ {t("settings.sections.network.acceptInvalidCerts", {+ defaultValue: "Ignore TLS certificate errors",+ })}+ </span>+ <p className="text-xs text-destructive">+ {t("settings.sections.network.acceptInvalidCertsHelp", {+ defaultValue:+ "Use only with a trusted corporate proxy. This disables certificate verification for outbound requests and can expose encrypted traffic to interception.",+ })}+ </p>+ </div>+ </label>+</div>)}diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.tsindex 043dc4c2..4712f575 100644--- a/src/components/settings/settings-types.ts+++ b/src/components/settings/settings-types.ts@@ -62,6 +62,7 @@ export interface SettingsDraft {proxyEnabled: booleanproxyUrl: stringproxyBypassLocal: boolean+ proxyAcceptInvalidCerts: boolean// Scheduled ImportscheduledImportEnabled: booleandiff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex 93ad1eca..af7bb11c 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -155,6 +155,7 @@ function initialDraft(proxyEnabled: proxy.enabled,proxyUrl: proxy.url,proxyBypassLocal: proxy.bypassLocal,+ proxyAcceptInvalidCerts: proxy.acceptInvalidCerts === true,scheduledImportEnabled: scheduledImport.enabled,scheduledImportPath: displayPath,scheduledImportInterval: scheduledImport.interval,@@ -401,6 +402,7 @@ export function SettingsView() {enabled: draft.proxyEnabled,url: draft.proxyUrl.trim(),bypassLocal: draft.proxyBypassLocal,+ acceptInvalidCerts: draft.proxyAcceptInvalidCerts,}const newSourceWatch = normalizeSourceWatchConfig(draft.sourceWatchConfig)const newScheduledImport = {diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 2d722aa9..6e2a5de4 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -710,7 +710,9 @@"url": "Proxy URL","urlHelp": "Full URL with scheme. Supported: http://, https://. (SOCKS5 not supported in this version.)","bypassLocal": "Bypass proxy for local addresses (recommended)",- "bypassLocalHelp": "Requests to localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and *.local don't go through the proxy. Keep this on if you use Ollama / LM Studio / other local or LAN-deployed LLMs."+ "bypassLocalHelp": "Requests to localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and *.local don't go through the proxy. Keep this on if you use Ollama / LM Studio / other local or LAN-deployed LLMs.",+ "acceptInvalidCerts": "Ignore TLS certificate errors",+ "acceptInvalidCertsHelp": "Use only with a trusted corporate proxy. This disables certificate verification for outbound requests and can expose encrypted traffic to interception."},"sourceWatch": {"title": "Source Folder Auto Watch",diff --git a/src/i18n/it.json b/src/i18n/it.jsonindex 765ba4dd..113dedbd 100644--- a/src/i18n/it.json+++ b/src/i18n/it.json@@ -710,7 +710,9 @@"url": "URL del proxy","urlHelp": "URL completo di schema. Supportati: http://, https://. (SOCKS5 non è supportato in questa versione.)","bypassLocal": "Escludi dal proxy gli indirizzi locali (consigliato)",- "bypassLocalHelp": "Le richieste verso localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 e *.local non passano dal proxy. Tienilo attivo se usi Ollama / LM Studio o altri LLM locali o in rete locale."+ "bypassLocalHelp": "Le richieste verso localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 e *.local non passano dal proxy. Tienilo attivo se usi Ollama / LM Studio o altri LLM locali o in rete locale.",+ "acceptInvalidCerts": "Ignora gli errori del certificato TLS",+ "acceptInvalidCertsHelp": "Usa questa opzione solo con un proxy aziendale attendibile. Disabilita la verifica dei certificati per le richieste in uscita e può esporre il traffico cifrato a intercettazioni."},"sourceWatch": {"title": "Monitoraggio automatico della cartella fonti",diff --git a/src/i18n/ru.json b/src/i18n/ru.jsonindex 98483e7c..5d908c04 100644--- a/src/i18n/ru.json+++ b/src/i18n/ru.json@@ -710,7 +710,9 @@"url": "URL прокси","urlHelp": "Полный URL со схемой. Поддерживается: http://, https://. (SOCKS5 в этой версии не поддерживается.)","bypassLocal": "Не использовать прокси для локальных адресов (рекомендуется)",- "bypassLocalHelp": "Запросы к localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 и *.local не идут через прокси. Оставляйте включённым, если используете Ollama / LM Studio / другие локальные или LAN-развёрнутые LLM."+ "bypassLocalHelp": "Запросы к localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 и *.local не идут через прокси. Оставляйте включённым, если используете Ollama / LM Studio / другие локальные или LAN-развёрнутые LLM.",+ "acceptInvalidCerts": "Игнорировать ошибки сертификата TLS",+ "acceptInvalidCertsHelp": "Используйте только с доверенным корпоративным прокси. Параметр отключает проверку сертификатов для исходящих запросов и может сделать зашифрованный трафик уязвимым для перехвата."},"sourceWatch": {"title": "Автоматический мониторинг папки источников",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 9a522f9a..7ba8a799 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -710,7 +710,9 @@"url": "代理地址","urlHelp": "完整 URL,必须带协议头。支持:http://、https://(当前版本不支持 SOCKS5)。","bypassLocal": "本地地址不走代理(推荐)",- "bypassLocalHelp": "对 localhost、127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 以及 *.local 的请求会绕过代理。如果你用 Ollama / LM Studio 或局域网内的 LLM 服务,请保持开启。"+ "bypassLocalHelp": "对 localhost、127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 以及 *.local 的请求会绕过代理。如果你用 Ollama / LM Studio 或局域网内的 LLM 服务,请保持开启。",+ "acceptInvalidCerts": "忽略 TLS 证书错误",+ "acceptInvalidCertsHelp": "仅用于可信的企业代理。此选项会关闭外部请求的证书校验,可能使加密流量面临被拦截的风险。"},"sourceWatch": {"title": "资料文件夹自动监控",diff --git a/src/lib/proxy-config.ts b/src/lib/proxy-config.tsindex abebb2b1..69ef0e49 100644--- a/src/lib/proxy-config.ts+++ b/src/lib/proxy-config.ts@@ -31,12 +31,15 @@ export interface ProxyConfig {* get sent to the external proxy and fail.*/bypassLocal: boolean+ /** Accept invalid TLS certificates for proxied requests. Unsafe by default. */+ acceptInvalidCerts?: boolean}export const DEFAULT_PROXY_CONFIG: ProxyConfig = {enabled: false,url: "",bypassLocal: true,+ acceptInvalidCerts: false,}/**diff --git a/src/lib/tauri-fetch.test.ts b/src/lib/tauri-fetch.test.tsindex 330188be..f7027edb 100644--- a/src/lib/tauri-fetch.test.ts+++ b/src/lib/tauri-fetch.test.ts@@ -14,7 +14,59 @@* run crash with "window is not defined").*/import { describe, it, expect } from "vitest"-import { getHttpFetch, isFetchNetworkError } from "./tauri-fetch"+import { getHttpFetch, isFetchNetworkError, withProxyTlsSettings } from "./tauri-fetch"++describe("withProxyTlsSettings", () => {+ it("enables invalid-certificate acceptance only for an active proxy", () => {+ const init = withProxyTlsSettings(+ { method: "POST" },+ {+ enabled: true,+ url: "http://proxy.corp:8080",+ bypassLocal: true,+ acceptInvalidCerts: true,+ },+ )+ expect(init).toMatchObject({+ method: "POST",+ danger: { acceptInvalidCerts: true },+ })+ })++ it("does not weaken TLS when the proxy is disabled or invalid", () => {+ const original = { method: "GET" } as const+ expect(withProxyTlsSettings(original, {+ enabled: false,+ url: "http://proxy.corp:8080",+ bypassLocal: true,+ acceptInvalidCerts: true,+ })).toBe(original)+ expect(withProxyTlsSettings(original, {+ enabled: true,+ url: "not-a-url",+ bypassLocal: true,+ acceptInvalidCerts: true,+ })).toBe(original)+ })++ it("preserves other plugin danger settings", () => {+ const init = withProxyTlsSettings(+ {+ danger: { acceptInvalidHostnames: true },+ } as RequestInit & { danger: { acceptInvalidHostnames: boolean } },+ {+ enabled: true,+ url: "https://proxy.corp:443",+ bypassLocal: false,+ acceptInvalidCerts: true,+ },+ )+ expect(init?.danger).toEqual({+ acceptInvalidHostnames: true,+ acceptInvalidCerts: true,+ })+ })+})describe("getHttpFetch — Node fallback", () => {it("returns a callable function under Node (typeof window === undefined)", async () => {diff --git a/src/lib/tauri-fetch.ts b/src/lib/tauri-fetch.tsindex cd011315..127ec39a 100644--- a/src/lib/tauri-fetch.ts+++ b/src/lib/tauri-fetch.ts@@ -17,6 +17,9 @@* from any environment without crashing at module load.*/+import { useWikiStore } from "@/stores/wiki-store"+import { isProxyActive, type ProxyConfig } from "@/lib/proxy-config"+let pluginFetchPromise: Promise<typeof globalThis.fetch> | null = null/**@@ -28,6 +31,28 @@ let pluginFetchPromise: Promise<typeof globalThis.fetch> | null = null*/const isNodeEnv = typeof window === "undefined"+type PluginRequestInit = RequestInit & {+ danger?: {+ acceptInvalidCerts?: boolean+ acceptInvalidHostnames?: boolean+ }+}++export function withProxyTlsSettings(+ init: RequestInit | undefined,+ proxy: ProxyConfig,+): PluginRequestInit | undefined {+ if (!isProxyActive(proxy) || proxy.acceptInvalidCerts !== true) return init+ const pluginInit = init as PluginRequestInit | undefined+ return {+ ...pluginInit,+ danger: {+ ...pluginInit?.danger,+ acceptInvalidCerts: true,+ },+ }+}+/*** Returns a fetch function that routes through Tauri's HTTP plugin in* production, falling back to the platform's native fetch in non-Tauri@@ -45,7 +70,18 @@ export function getHttpFetch(): Promise<typeof globalThis.fetch> {pluginFetchPromise = Promise.resolve(globalThis.fetch.bind(globalThis))} else {pluginFetchPromise = import("@tauri-apps/plugin-http")- .then((m) => m.fetch as unknown as typeof globalThis.fetch)+ .then((m) => {+ const pluginFetch = m.fetch+ const configuredFetch: typeof globalThis.fetch = (input, init) => {+ // Read at request time so changing Network settings takes effect+ // immediately. The option is deliberately scoped to the proxy+ // toggle; disabling the proxy restores normal TLS verification.+ const proxy = useWikiStore.getState().proxyConfig+ const requestInit = withProxyTlsSettings(init, proxy)+ return pluginFetch(input, requestInit)+ }+ return configuredFetch+ }).catch(() => globalThis.fetch.bind(globalThis))}}diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex 192c5c48..b709dbd0 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -191,6 +191,7 @@ interface ProxyConfig {enabled: booleanurl: stringbypassLocal: boolean+ acceptInvalidCerts?: boolean}interface ScheduledImportConfig {@@ -607,6 +608,7 @@ export const useWikiStore = create<WikiState>((set) => ({enabled: false,url: "",bypassLocal: true,+ acceptInvalidCerts: false,},scheduledImportConfig: {