fix(P2-4): use persisted backend security mode as authority
This commit is contained in:
@@ -197,7 +197,7 @@ pub async fn app_boot(state: State<'_, Api>) -> Result<Value, String> {
|
||||
/// 切换严格安全模式(关闭后回退到兼容清洗与网络守卫模式,立即生效并落盘)。
|
||||
#[tauri::command]
|
||||
pub async fn security_set(strict: bool) -> Result<bool, String> {
|
||||
crate::network_policy::set_strict_security(strict);
|
||||
crate::network_policy::set_strict_security(strict)?;
|
||||
crate::net::refresh_client();
|
||||
Ok(crate::network_policy::strict_security())
|
||||
}
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -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 (
|
||||
<button onClick={() => onChange(!on)} aria-pressed={on} aria-label={label}
|
||||
className={`relative w-[46px] h-[26px] rounded-full transition-colors duration-200 ${on ? "bg-primary" : "bg-s4"}`}>
|
||||
<button disabled={disabled} onClick={() => onChange(!on)} aria-pressed={on} aria-label={label}
|
||||
className={`relative w-[46px] h-[26px] rounded-full transition-colors duration-200 disabled:opacity-50 disabled:cursor-wait ${on ? "bg-primary" : "bg-s4"}`}>
|
||||
<span className={`absolute top-[3px] w-5 h-5 rounded-full elev-1 transition-all duration-200 ${on ? "left-[23px] bg-on-primary" : "left-[3px] bg-mut"}`} />
|
||||
</button>
|
||||
);
|
||||
|
||||
+3
-14
@@ -3,17 +3,8 @@ import DOMPurify from "dompurify";
|
||||
|
||||
/** 站点根地址:正文里的相对路径要补全 */
|
||||
const SITE = "https://huangguoai.com";
|
||||
const STRICT_LS = "hghub_strict_security";
|
||||
|
||||
function readStrictSecurity(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(STRICT_LS) !== "0";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
let strictSecurity = readStrictSecurity();
|
||||
// 启动前默认严格;有效状态只由 Rust app_boot / security_set 返回值更新。
|
||||
let strictSecurity = true;
|
||||
|
||||
/** 当前是否启用严格安全模式(默认开启)。 */
|
||||
export function isStrictSecurity(): boolean {
|
||||
@@ -23,9 +14,7 @@ export function isStrictSecurity(): boolean {
|
||||
/** 切换严格安全模式(关闭后回退为兼容清洗与链接策略)。 */
|
||||
export function setStrictSecurity(strict: boolean): void {
|
||||
strictSecurity = strict;
|
||||
try {
|
||||
localStorage.setItem(STRICT_LS, strict ? "1" : "0");
|
||||
} catch { /* ignore */ }
|
||||
|
||||
}
|
||||
|
||||
function isInternalWebviewHost(host: string): boolean {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, ILockF, IMoon, IRe
|
||||
/* 独立设置页:线路 / 外观 / 本地数据 / 清理缓存 / 网络诊断 / 关于
|
||||
入口:Windows 侧栏「设置」、Android「我的」右上角齿轮 */
|
||||
export default function Settings({ onBack, wide }: { onBack: () => void; wide: boolean }) {
|
||||
const { theme, setTheme, favs, history, strictSecurity, cliRelaxed, setStrictSecurity, toast } = useStore();
|
||||
const { theme, setTheme, favs, history, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity, toast } = useStore();
|
||||
const [about, setAbout] = useState(false);
|
||||
const [clearOpen, setClearOpen] = useState(false);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
@@ -112,9 +112,11 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
|
||||
</div>
|
||||
<Toggle
|
||||
on={strictSecurity}
|
||||
disabled={!strictSecurityReady || securityPending}
|
||||
onChange={(on) => {
|
||||
void setStrictSecurity(on);
|
||||
toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info");
|
||||
void setStrictSecurity(on).then(() => {
|
||||
toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info");
|
||||
}).catch(() => toast("安全设置保存失败,已保持原模式", "info"));
|
||||
}}
|
||||
label="严格安全模式"
|
||||
/>
|
||||
|
||||
+13
-8
@@ -120,7 +120,7 @@ type Store = {
|
||||
muted: boolean; setMuted: (v: boolean | ((p: boolean) => boolean)) => void;
|
||||
volume: number; setVolume: (v: number) => void;
|
||||
searchHist: string[]; addSearch: (q: string) => void; clearSearchHist: () => void;
|
||||
strictSecurity: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise<void>;
|
||||
strictSecurity: boolean; strictSecurityReady: boolean; securityPending: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise<void>;
|
||||
toasts: Toast[]; toast: (msg: string, icon?: Toast["icon"]) => void;
|
||||
};
|
||||
|
||||
@@ -140,6 +140,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
const [fs, setFsState] = useState(false);
|
||||
const [strictSecurity, setStrictSecurityState] = useState<boolean>(isStrictSecurity);
|
||||
const [cliRelaxed, setCliRelaxed] = useState(false);
|
||||
const [strictSecurityReady, setStrictSecurityReady] = useState(false);
|
||||
const [securityPending, setSecurityPending] = useState(false);
|
||||
const toastSeq = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -158,6 +160,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
if (typeof r.strict_security === "boolean") {
|
||||
setStrictSecurityState(r.strict_security);
|
||||
setHtmlStrictSecurity(r.strict_security);
|
||||
setStrictSecurityReady(true);
|
||||
}
|
||||
setCliRelaxed(!!r.cli_relaxed);
|
||||
})
|
||||
@@ -165,14 +168,16 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
}, []);
|
||||
|
||||
const setStrictSecurity = useCallback(async (on: boolean) => {
|
||||
setStrictSecurityState(on);
|
||||
setHtmlStrictSecurity(on);
|
||||
if (!strictSecurityReady) throw new Error("安全设置尚未读取,请重新启动应用");
|
||||
setSecurityPending(true);
|
||||
try {
|
||||
const saved = await api.securitySet(on);
|
||||
setStrictSecurityState(saved);
|
||||
setHtmlStrictSecurity(saved);
|
||||
} catch { /* ignore */ }
|
||||
}, []);
|
||||
setStrictSecurityState(saved);
|
||||
} finally {
|
||||
setSecurityPending(false);
|
||||
}
|
||||
}, [strictSecurityReady]);
|
||||
|
||||
const toast = useCallback((msg: string, icon?: Toast["icon"]) => {
|
||||
const id = ++toastSeq.current;
|
||||
@@ -266,11 +271,11 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory,
|
||||
muted: p.muted, setMuted, volume: p.volume, setVolume, theater, setTheater, fs, setFs,
|
||||
searchHist: p.searchHist, addSearch, clearSearchHist,
|
||||
strictSecurity, cliRelaxed, setStrictSecurity,
|
||||
strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity,
|
||||
toasts, toast,
|
||||
}), [theme, tab, setTab, stack, push, pop, user, loginOpen, logout,
|
||||
p, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory,
|
||||
setMuted, setVolume, addSearch, clearSearchHist, strictSecurity, cliRelaxed, setStrictSecurity,
|
||||
setMuted, setVolume, addSearch, clearSearchHist, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity,
|
||||
toasts, toast, theater, setTheater, fs, setFs]);
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<!doctype html><meta charset="utf-8"><div id="fixture"></div><pre id="results"></pre>
|
||||
<script type="module" src="/tests/security-settings.tsx"></script>
|
||||
@@ -0,0 +1,53 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { api } from "../src/api";
|
||||
import { AppProvider, useStore } from "../src/store";
|
||||
import { ArticlePanel } from "../src/components/Panels";
|
||||
import { isStrictSecurity, setStrictSecurity } from "../src/html";
|
||||
|
||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let store: ReturnType<typeof useStore>;
|
||||
function Probe() { store = useStore(); return <ArticlePanel title="test" html={'<p style="color:red">article</p>'} onClose={() => {}} />; }
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((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<Awaited<ReturnType<typeof api.boot>>>();
|
||||
api.boot = () => boot.promise;
|
||||
await act(async () => { root.render(<AppProvider><Probe /></AppProvider>); });
|
||||
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<boolean>();
|
||||
api.securitySet = () => save.promise;
|
||||
let saving!: Promise<void>;
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user