diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs
index df13e72..f1ce750 100644
--- a/src-tauri/src/api.rs
+++ b/src-tauri/src/api.rs
@@ -197,7 +197,7 @@ pub async fn app_boot(state: State<'_, Api>) -> Result {
/// 切换严格安全模式(关闭后回退到兼容清洗与网络守卫模式,立即生效并落盘)。
#[tauri::command]
pub async fn security_set(strict: bool) -> Result {
- crate::network_policy::set_strict_security(strict);
+ crate::network_policy::set_strict_security(strict)?;
crate::net::refresh_client();
Ok(crate::network_policy::strict_security())
}
diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs
index 98ff37b..eb4a2df 100644
--- a/src-tauri/src/network_policy.rs
+++ b/src-tauri/src/network_policy.rs
@@ -69,11 +69,15 @@ pub fn bind_security(dir: &Path) {
}
/// 切换严格安全模式并落盘。
-pub fn set_strict_security(strict: bool) {
+pub fn set_strict_security(strict: bool) -> Result<(), String> {
+ let file = SECURITY_FILE.write().map_err(|_| "安全设置锁失败")?;
+ let path = file.as_ref().ok_or("安全设置尚未初始化")?;
+ let temp = path.with_extension("json.tmp");
+ std::fs::write(&temp, json!({ "strict": strict }).to_string())
+ .and_then(|_| std::fs::rename(&temp, path))
+ .map_err(|_| "无法保存安全设置,请检查应用数据目录")?;
STRICT.store(strict, Ordering::Relaxed);
- if let Some(path) = SECURITY_FILE.read().ok().and_then(|p| p.clone()) {
- let _ = std::fs::write(path, json!({ "strict": strict }).to_string());
- }
+ Ok(())
}
fn is_internal_webview_host(name: &str) -> bool {
@@ -221,6 +225,28 @@ pub fn redirect_target_with_mode(
mod tests {
use super::*;
+ #[test]
+ fn failed_security_save_keeps_the_effective_mode() {
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let dir =
+ std::env::temp_dir().join(format!("hghub-security-{}-{unique}", std::process::id()));
+ std::fs::create_dir(&dir).unwrap();
+ let path = dir.join("security.json");
+ let previous = SECURITY_FILE.write().unwrap().replace(path.clone());
+ let before = strict_security();
+ set_strict_security(before).unwrap();
+ let saved: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
+ assert_eq!(saved["strict"], before);
+ *SECURITY_FILE.write().unwrap() = Some(dir.join("missing/security.json"));
+ assert!(set_strict_security(!before).is_err());
+ assert_eq!(strict_security(), before);
+ *SECURITY_FILE.write().unwrap() = previous;
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
#[test]
fn public_and_fakeip_are_allowed() {
for ip in [
diff --git a/src/components/ui.tsx b/src/components/ui.tsx
index 913d61c..714e62a 100644
--- a/src/components/ui.tsx
+++ b/src/components/ui.tsx
@@ -60,10 +60,10 @@ export function Modal({ open, onClose, children, width = 340 }: { open: boolean;
}
/* ——— 开关 ——— */
-export function Toggle({ on, onChange, label }: { on: boolean; onChange: (b: boolean) => void; label?: string }) {
+export function Toggle({ on, onChange, label, disabled = false }: { on: boolean; onChange: (b: boolean) => void; label?: string; disabled?: boolean }) {
return (
-
'} onClose={() => {}} />; }
+function deferred() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+}
+const checks: string[] = [];
+function assert(ok: unknown, label: string) { if (!ok) throw new Error(label); checks.push(label); }
+const originalBoot = api.boot, originalSave = api.securitySet;
+const previousLocal = localStorage.getItem("hghub_strict_security");
+const root = createRoot(document.querySelector("#fixture")!);
+try {
+ localStorage.setItem("hghub_strict_security", "0");
+ setStrictSecurity(true);
+ const boot = deferred>>();
+ api.boot = () => boot.promise;
+ await act(async () => { root.render(); });
+ assert(store!.strictSecurity && !store!.strictSecurityReady, "startup defaults strict until backend responds");
+ await act(async () => boot.resolve({ user: null, logged_in: false, base: "https://huangguoai.com", strict_security: false }));
+ assert(!store!.strictSecurity && store!.strictSecurityReady && !isStrictSecurity(), "backend boot controls effective mode");
+ assert(document.querySelector(".article-body p")?.hasAttribute("style"), "open article uses compatible mode");
+ const save = deferred();
+ api.securitySet = () => save.promise;
+ let saving!: Promise;
+ await act(async () => { saving = store!.setStrictSecurity(true); });
+ assert(store!.securityPending && !store!.strictSecurity && !isStrictSecurity(), "pending write does not optimistically change mode");
+ await act(async () => { save.resolve(true); await saving; });
+ assert(store!.strictSecurity && isStrictSecurity() && !store!.securityPending, "successful backend write updates effective mode");
+ assert(!document.querySelector(".article-body p")?.hasAttribute("style"), "already open article rerenders on mode change");
+ api.securitySet = async () => { throw new Error("disk unavailable"); };
+ let failed = false;
+ await act(async () => { try { await store!.setStrictSecurity(false); } catch { failed = true; } });
+ assert(failed && store!.strictSecurity && isStrictSecurity() && !store!.securityPending, "failed save keeps backend-confirmed mode and reports failure");
+ assert(localStorage.getItem("hghub_strict_security") === "0", "mode changes do not write a second persisted source");
+ document.querySelector("#results")!.textContent = JSON.stringify({ passed: checks.length, failed: 0, checks });
+} catch (error) {
+ document.querySelector("#results")!.textContent = JSON.stringify({ passed: checks.length, failed: 1, error: String(error), checks });
+} finally {
+ await act(async () => root.unmount());
+ api.boot = originalBoot; api.securitySet = originalSave;
+ setStrictSecurity(true);
+ if (previousLocal === null) localStorage.removeItem("hghub_strict_security");
+ else localStorage.setItem("hghub_strict_security", previousLocal);
+}