| 1 | import React, { |
| 2 | createContext, |
| 3 | useContext, |
| 4 | useEffect, |
| 5 | useId, |
| 6 | useRef, |
| 7 | useState, |
| 8 | } from "react"; |
| 9 | import { |
| 10 | Camera, |
| 11 | Check, |
| 12 | ChevronDown, |
| 13 | Eye, |
| 14 | EyeOff, |
| 15 | Fingerprint, |
| 16 | LockKeyhole, |
| 17 | LogOut, |
| 18 | Settings, |
| 19 | } from "lucide-react"; |
| 20 | import { api, native, nativeAvailable } from "./api"; |
| 21 | import { getClientContext, isRemoteClient } from "./client-context.mjs"; |
| 22 | import logo from "./logo.png"; |
| 23 | import "./account.css"; |
| 24 | |
| 25 | const AccountContext = createContext(null); |
| 26 | export const useAccount = () => useContext(AccountContext); |
| 27 | const localDesktop = () => getClientContext().desktop_gateway && !isRemoteClient(); |
| 28 | const trustedLogin = (action, password) => api("/client/trusted-login", { |
| 29 | action, password, connection_id: getClientContext().connection_id, |
| 30 | }); |
| 31 | const credentialPresent = (status) => status === "available" || status === "authentication_required"; |
| 32 | |
| 33 | export function AccountProvider({ children }) { |
| 34 | const [account, setAccount] = useState(null); |
| 35 | const [error, setError] = useState(""); |
| 36 | const [deviceCheck, setDeviceCheck] = useState(null); |
| 37 | const deviceKey = JSON.stringify([account?.device_binding, account?.devices?.automatic, account?.devices?.biometric]); |
| 38 | const deviceSupport = deviceCheck?.key === deviceKey ? deviceCheck.value : null; |
| 39 | const [deviceNotice, setDeviceNotice] = useState(""); |
| 40 | const sequence = useRef(0); |
| 41 | const refresh = async () => { |
| 42 | const current = ++sequence.current; |
| 43 | try { |
| 44 | const value = await api("/account"); |
| 45 | if (sequence.current === current) { |
| 46 | setAccount(value); |
| 47 | setError(""); |
| 48 | } |
| 49 | return value; |
| 50 | } catch (e) { |
| 51 | if (sequence.current === current) setError(e.message); |
| 52 | throw e; |
| 53 | } |
| 54 | }; |
| 55 | const act = async (action, input = {}) => { |
| 56 | const current = ++sequence.current; |
| 57 | const value = await api(`/account/${action}`, input); |
| 58 | if (action !== "logout" && sequence.current === current) setAccount(value); |
| 59 | return value; |
| 60 | }; |
| 61 | useEffect(() => { |
| 62 | if (!account || deviceSupport !== null) return; |
| 63 | if (!nativeAvailable()) { setDeviceCheck({ key: deviceKey, value: { supported: false } }); return; } |
| 64 | let live = true; |
| 65 | native("accountDevice", { operation: "status" }) |
| 66 | .then((value) => { if (live) setDeviceCheck({ key: deviceKey, value: value || { supported: false } }); }) |
| 67 | .catch(() => { if (live) setDeviceCheck({ key: deviceKey, value: { supported: false } }); }); |
| 68 | return () => { live = false; }; |
| 69 | }, [Boolean(account), deviceKey, deviceSupport]); |
| 70 | const deviceAction = async (operation, kind) => { |
| 71 | if (!deviceSupport?.device_status) throw new Error("当前应用启动器需要更新,请重新安装完整的 Cage 应用后再设置快捷登录。"); |
| 72 | try { |
| 73 | await native("accountDevice", { operation, kind }); |
| 74 | } finally { |
| 75 | |
| 76 | |
| 77 | await refresh(); |
| 78 | setDeviceCheck(null); |
| 79 | } |
| 80 | }; |
| 81 | useEffect(() => { |
| 82 | let live = true, |
| 83 | timer; |
| 84 | const poll = async () => { |
| 85 | try { |
| 86 | await refresh(); |
| 87 | } catch { |
| 88 | |
| 89 | } |
| 90 | if (live) timer = setTimeout(poll, document.hidden ? 10000 : 2500); |
| 91 | }; |
| 92 | const start = async () => { |
| 93 | try { |
| 94 | if (location.hash) { |
| 95 | await api("/session", { token: location.hash.slice(1) }); |
| 96 | history.replaceState(null, "", location.pathname); |
| 97 | } |
| 98 | window.dispatchEvent(new Event("cage-session-ready")); |
| 99 | if (live) await poll(); |
| 100 | } catch (e) { |
| 101 | if (live) setError(e.message); |
| 102 | } |
| 103 | }; |
| 104 | const locked = () => { |
| 105 | |
| 106 | |
| 107 | setDeviceCheck(null); |
| 108 | setAccount((previous) => |
| 109 | previous ? { ...previous, unlocked: false } : previous, |
| 110 | ); |
| 111 | refresh().catch(() => {}); |
| 112 | }; |
| 113 | start(); |
| 114 | window.addEventListener("cage-account-locked", locked); |
| 115 | return () => { |
| 116 | live = false; |
| 117 | sequence.current++; |
| 118 | clearTimeout(timer); |
| 119 | window.removeEventListener("cage-account-locked", locked); |
| 120 | }; |
| 121 | }, []); |
| 122 | return ( |
| 123 | <AccountContext.Provider value={{ account, error, refresh, act, deviceSupport, deviceAction, deviceNotice, setDeviceNotice, recheckDevices: () => setDeviceCheck(null) }}> |
| 124 | {children} |
| 125 | </AccountContext.Provider> |
| 126 | ); |
| 127 | } |
| 128 | |
| 129 | export function AccountAvatar({ account, large = false }) { |
| 130 | const initial = Array.from( |
| 131 | account?.username?.trim() || "C", |
| 132 | )[0].toLocaleUpperCase(); |
| 133 | return ( |
| 134 | <span |
| 135 | className={`account-avatar ${large ? "large" : ""}`} |
| 136 | aria-hidden="true" |
| 137 | > |
| 138 | {account?.avatar ? <img src={account.avatar} alt="" /> : initial} |
| 139 | </span> |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | export function MacOSAccountGate({ children }) { |
| 144 | const { account, act } = useAccount(); |
| 145 | const [name, setName] = useState(account?.macos_guest_user || account?.username || ""); |
| 146 | const [password, setPassword] = useState(""); |
| 147 | const [confirmation, setConfirmation] = useState(""); |
| 148 | const [busy, setBusy] = useState(false); |
| 149 | const [error, setError] = useState(""); |
| 150 | if (!account?.macos_account_host || account.macos_credentials_ready) return children; |
| 151 | async function submit(event) { |
| 152 | event.preventDefault(); |
| 153 | if (busy) return; |
| 154 | if (password !== confirmation) { setError("两次密码不一致"); return; } |
| 155 | setBusy(true); setError(""); |
| 156 | try { await act("prepare-macos", { username:name, password, confirm_password:confirmation }); setPassword(""); setConfirmation(""); } |
| 157 | catch (e) { setError(e.message); } |
| 158 | finally { setBusy(false); } |
| 159 | } |
| 160 | return <main className="account-gate"><div className="account-brand"><img src={logo} alt="" />Cage</div><section className="account-entry"> |
| 161 | <h1>设置 Cage 与 macOS 共用账密</h1> |
| 162 | <p className="account-entry-intro">{account.trusted_local ? "先设置 Cage 用户名和密码,再继续客机安装。已有账户、文件和登录状态会保留。" : "输入当前 Cage 密码,确认用于 macOS 客机。已有客机保留用户名和用户目录。"}</p> |
| 163 | <form onSubmit={submit}><fieldset disabled={busy}> |
| 164 | <label className="account-field">用户名<input required value={name} onChange={event => setName(event.target.value)} maxLength={31} pattern="[a-z][a-z0-9_]{0,30}" readOnly={Boolean(account.macos_guest_user)} autoComplete="username" /></label> |
| 165 | <p className="field-help">小写字母开头,1–31 个小写字母、数字或下划线。密码使用 8–256 个英文键盘可输入的字符。</p> |
| 166 | <PasswordField label={account.trusted_local ? "设置密码" : "当前 Cage 密码"} value={password} onChange={setPassword} autoComplete={account.trusted_local ? "new-password" : "current-password"} /> |
| 167 | <PasswordField label="确认密码" value={confirmation} onChange={setConfirmation} autoComplete={account.trusted_local ? "new-password" : "current-password"} /> |
| 168 | {error && <p role="alert" className="account-error">{error}</p>} |
| 169 | <button className="primary account-submit" disabled={busy}>{busy ? "正在保存…" : "保存账密并继续"}</button> |
| 170 | </fieldset></form> |
| 171 | </section></main>; |
| 172 | } |
| 173 | |
| 174 | function PasswordField({ |
| 175 | label, |
| 176 | value, |
| 177 | onChange, |
| 178 | autoComplete = "current-password", |
| 179 | }) { |
| 180 | const [visible, setVisible] = useState(false); |
| 181 | const id = useId(); |
| 182 | return ( |
| 183 | <div className="account-field"> |
| 184 | <label htmlFor={id}>{label}</label> |
| 185 | <span className="password-input"> |
| 186 | <input |
| 187 | id={id} |
| 188 | type={visible ? "text" : "password"} |
| 189 | value={value} |
| 190 | onChange={(e) => onChange(e.target.value)} |
| 191 | autoComplete={autoComplete} |
| 192 | required |
| 193 | maxLength={1024} |
| 194 | /> |
| 195 | <button |
| 196 | type="button" |
| 197 | className="icon-button" |
| 198 | aria-label={`${visible ? "隐藏" : "显示"}${label}`} |
| 199 | onClick={() => setVisible(!visible)} |
| 200 | > |
| 201 | {visible ? <EyeOff size={16} /> : <Eye size={16} />} |
| 202 | </button> |
| 203 | </span> |
| 204 | </div> |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | export function AccountGate({ children }) { |
| 209 | const { account, error: connectionError, refresh, act, deviceSupport, deviceAction, setDeviceNotice } = useAccount(); |
| 210 | const [username, setUsername] = useState(""); |
| 211 | const [password, setPassword] = useState(""); |
| 212 | const [confirmation, setConfirmation] = useState(""); |
| 213 | const [rememberLogin, setRememberLogin] = useState(null); |
| 214 | const [busy, setBusy] = useState(false); |
| 215 | const [error, setError] = useState(""); |
| 216 | const automaticAttempt = useRef(""); |
| 217 | const gateAcknowledged = useRef(false); |
| 218 | const trustedAttempt = useRef(false); |
| 219 | const enterTrusted = async (action) => { |
| 220 | setBusy(true); setError(""); |
| 221 | try { await trustedLogin(action); await refresh(); } |
| 222 | catch (e) { setError(e.message); } |
| 223 | finally { setBusy(false); } |
| 224 | }; |
| 225 | useEffect(() => { |
| 226 | if (account?.unlocked) { trustedAttempt.current = false; setRememberLogin(null); return; } |
| 227 | if (!account || !localDesktop() || trustedAttempt.current || account.require_authentication) return; |
| 228 | if (!(account.trusted_local || account.trusted_login)) return; |
| 229 | trustedAttempt.current = true; |
| 230 | void enterTrusted("resume"); |
| 231 | }, [account?.unlocked, account?.exists, account?.guest_system, account?.trusted_local, account?.trusted_login, account?.require_authentication]); |
| 232 | useEffect(() => { |
| 233 | if (!account || account.unlocked || connectionError || gateAcknowledged.current || !nativeAvailable()) return; |
| 234 | |
| 235 | |
| 236 | native("workbenchReady").then((accepted) => { |
| 237 | if (accepted === true) gateAcknowledged.current = true; |
| 238 | }).catch(() => {}); |
| 239 | }, [Boolean(account), account?.unlocked, connectionError]); |
| 240 | useEffect(() => { |
| 241 | const id = account?.devices?.automatic; |
| 242 | if ((account?.trusted_login && localDesktop()) || !id || account.unlocked || account.require_authentication || !deviceSupport?.supported || deviceSupport.device_status?.automatic !== "available" || automaticAttempt.current === id) return; |
| 243 | automaticAttempt.current = id; |
| 244 | setBusy(true); |
| 245 | deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false)); |
| 246 | }, [account?.unlocked, account?.devices?.automatic, account?.require_authentication, deviceSupport]); |
| 247 | if (account?.unlocked) return children; |
| 248 | const creating = account && !account.exists; |
| 249 | const rememberThisDevice = rememberLogin ?? Boolean(creating || account?.trusted_login || account?.devices?.automatic); |
| 250 | const submit = async (event) => { |
| 251 | event.preventDefault(); |
| 252 | if (busy) return; |
| 253 | if (creating && password !== confirmation) { |
| 254 | setError("两次密码不一致"); |
| 255 | return; |
| 256 | } |
| 257 | setBusy(true); |
| 258 | setError(""); |
| 259 | try { |
| 260 | await act( |
| 261 | creating ? "create" : "unlock", |
| 262 | creating |
| 263 | ? { username, password, confirm_password: confirmation } |
| 264 | : { password }, |
| 265 | ); |
| 266 | if (localDesktop()) { |
| 267 | try { |
| 268 | await trustedLogin(rememberThisDevice ? "enable" : "disable", password); |
| 269 | await refresh(); |
| 270 | } catch (e) { |
| 271 | setDeviceNotice(`已登录,${rememberThisDevice ? "记住我未能开启" : "记住我未能关闭"}:${e.message}。可在「设置 → 账户」中重试。`); |
| 272 | } |
| 273 | } else if (creating && rememberThisDevice && deviceSupport?.supported && deviceSupport.device_status) { |
| 274 | try { await deviceAction("enable", "automatic"); } |
| 275 | catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在「设置 → 账户」中重试。`); } |
| 276 | } |
| 277 | setPassword(""); |
| 278 | setConfirmation(""); |
| 279 | } catch (e) { |
| 280 | setError(e.message); |
| 281 | } finally { |
| 282 | setBusy(false); |
| 283 | } |
| 284 | }; |
| 285 | return ( |
| 286 | <main className="account-gate"> |
| 287 | <div className="account-brand"> |
| 288 | <img src={logo} alt="" /> |
| 289 | Cage |
| 290 | </div> |
| 291 | <section |
| 292 | className="account-entry" |
| 293 | aria-label={creating ? isRemoteClient() ? "创建云端账户" : "创建本地账户" : "解锁 Cage"} |
| 294 | > |
| 295 | {creating ? ( |
| 296 | <img className="account-welcome-logo" src={logo} alt="" /> |
| 297 | ) : ( |
| 298 | account && <AccountAvatar account={account} large /> |
| 299 | )} |
| 300 | <h1> |
| 301 | {creating |
| 302 | ? "注册 Cage 账户" |
| 303 | : account |
| 304 | ? `欢迎回来,${account.username}` |
| 305 | : "正在连接 Cage"} |
| 306 | </h1> |
| 307 | <p className="account-entry-intro"> |
| 308 | {creating |
| 309 | ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : "先注册用户名和密码,再选择客机系统并安装环境。macOS 客机会使用同一套账密。" |
| 310 | : account |
| 311 | ? account.trusted_local ? "本机工作区" : "输入密码,继续你的工作。" |
| 312 | : isRemoteClient() ? "正在读取云端账户…" : "正在读取本机账户…"} |
| 313 | </p> |
| 314 | {account?.background_running && ( |
| 315 | <div className="account-background"> |
| 316 | <i /> |
| 317 | 后台环境仍在运行,任务没有停止 |
| 318 | </div> |
| 319 | )} |
| 320 | {account?.trusted_local && <div className="account-trust-choice"> |
| 321 | <p>{localDesktop() ? "使用当前系统用户的本机信任凭据进入工作区。" : "请回到受信任的桌面设置账户密码,再从此处登录。"}</p> |
| 322 | {localDesktop() && <button className="quiet-button" disabled={busy} onClick={() => enterTrusted("resume")}>{busy ? "正在进入…" : "重新进入本机工作区"}</button>} |
| 323 | </div>} |
| 324 | {account?.trusted_local && error && <p className="account-error" role="alert">{error}</p>} |
| 325 | {account && !account.trusted_local && ( |
| 326 | <form onSubmit={submit}> |
| 327 | <fieldset disabled={busy}> |
| 328 | {creating && ( |
| 329 | <><label className="account-field"> |
| 330 | 用户名 |
| 331 | <input |
| 332 | autoFocus |
| 333 | autoComplete="username" |
| 334 | maxLength={account.macos_account_host ? 31 : 40} |
| 335 | pattern={account.macos_account_host ? "[a-z][a-z0-9_]{0,30}" : undefined} |
| 336 | required |
| 337 | value={username} |
| 338 | onChange={(e) => setUsername(e.target.value)} |
| 339 | placeholder={account.macos_account_host ? "例如:shihao" : "你希望怎样被称呼"} |
| 340 | /> |
| 341 | </label> |
| 342 | {account.macos_account_host && <p className="field-help">与 macOS 客机共用:小写字母开头,1–31 个小写字母、数字或下划线。</p>}</> |
| 343 | )} |
| 344 | <PasswordField |
| 345 | label={creating ? "设置密码" : "账户密码"} |
| 346 | value={password} |
| 347 | onChange={setPassword} |
| 348 | autoComplete={creating ? "new-password" : "current-password"} |
| 349 | /> |
| 350 | {creating && ( |
| 351 | <PasswordField |
| 352 | label="确认密码" |
| 353 | value={confirmation} |
| 354 | onChange={setConfirmation} |
| 355 | autoComplete="new-password" |
| 356 | /> |
| 357 | )} |
| 358 | {creating && account.macos_account_host && <p className="field-help">密码使用 8–256 个英文键盘可输入的字母、数字、空格或符号。安装中断后继续使用这套账密。</p>} |
| 359 | {(error || connectionError) && ( |
| 360 | <p className="account-error" role="alert"> |
| 361 | {error || connectionError} |
| 362 | </p> |
| 363 | )} |
| 364 | {!creating && Object.values(deviceSupport?.device_status || {}).includes("missing") && ( |
| 365 | <p className="field-help" role="status">当前目录的快捷登录凭据缺失或已失效。请用密码解锁,再到「设置 → 账户 → 登录与解锁」重新开启。</p> |
| 366 | )} |
| 367 | {!creating && Object.values(deviceSupport?.device_status || {}).includes("unavailable") && ( |
| 368 | <p className="field-help" role="status">暂时无法检查系统钥匙串,请先用密码解锁。快捷登录授权记录已保留。</p> |
| 369 | )} |
| 370 | {deviceSupport?.supported && !deviceSupport.device_status && ( |
| 371 | <p className="field-help" role="status">当前应用启动器需要更新,暂时无法检查快捷登录状态。请先用密码进入,并重新安装完整的 Cage 应用。</p> |
| 372 | )} |
| 373 | {(localDesktop() || (creating && deviceSupport?.supported && deviceSupport.device_status)) && ( |
| 374 | <label className="account-device-option check-line"> |
| 375 | <input type="checkbox" checked={rememberThisDevice} onChange={(e) => setRememberLogin(e.target.checked)} /> |
| 376 | <span><strong>{localDesktop() ? "记住我" : "记住登录"}</strong><small>{localDesktop() ? "信任此电脑,下次用当前系统用户打开时直接进入。手动锁定仍需验证。" : "下次打开直接进入。手动锁定后仍需验证。"}</small></span> |
| 377 | </label> |
| 378 | )} |
| 379 | {!creating && deviceSupport?.supported && credentialPresent(deviceSupport.device_status?.biometric) && account.devices?.biometric && ( |
| 380 | <button type="button" className="quiet-button account-submit" disabled={busy} |
| 381 | onClick={async () => { |
| 382 | setBusy(true); setError(""); |
| 383 | try { await deviceAction("unlock", "biometric"); } |
| 384 | catch (e) { setError(e.message); } |
| 385 | finally { setBusy(false); } |
| 386 | }}> |
| 387 | <Fingerprint size={18} />使用 Touch ID 解锁 |
| 388 | </button> |
| 389 | )} |
| 390 | <button |
| 391 | className="primary account-submit" |
| 392 | disabled={busy || !password || (creating && (!username.trim() || (!localDesktop() && nativeAvailable() && deviceSupport === null)))} |
| 393 | > |
| 394 | {busy ? "正在解锁…" : creating ? isRemoteClient() ? "创建云端账户" : "创建本地账户" : "解锁 Cage"} |
| 395 | </button> |
| 396 | </fieldset> |
| 397 | </form> |
| 398 | )} |
| 399 | {!account && connectionError && ( |
| 400 | <> |
| 401 | <p role="alert" className="account-error"> |
| 402 | {connectionError} |
| 403 | </p> |
| 404 | <button onClick={() => refresh().catch(() => {})}>重新连接</button> |
| 405 | </> |
| 406 | )} |
| 407 | <p className="account-local-note"> |
| 408 | <LockKeyhole size={14} /> |
| 409 | {isRemoteClient() ? "账户资料保存在当前云端主机" : "账户资料仅保存在这台设备上"} |
| 410 | </p> |
| 411 | {!account?.trusted_local && <p className="account-recovery-note"> |
| 412 | {creating |
| 413 | ? "密码至少 8 个字符,用于保护应用登录凭据。请妥善保存,当前不支持在线找回。" |
| 414 | : isRemoteClient() ? "请输入云端 Cage 账户密码;当前不支持在线找回。" : "请输入本地账户密码;当前不支持在线找回。"} |
| 415 | </p>} |
| 416 | </section> |
| 417 | {nativeAvailable() && ( |
| 418 | <button |
| 419 | className="text-button account-exit-app" |
| 420 | onClick={() => native("quitNow").catch((e) => setError(e.message))} |
| 421 | > |
| 422 | {account?.background_running ? "退出应用,后台继续运行" : "退出 Cage"} |
| 423 | </button> |
| 424 | )} |
| 425 | </main> |
| 426 | ); |
| 427 | } |
| 428 | |
| 429 | export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { |
| 430 | const { account, act, deviceNotice, setDeviceNotice } = useAccount(); |
| 431 | useEffect(() => { |
| 432 | if (deviceNotice) { onStatus(deviceNotice); setDeviceNotice(""); } |
| 433 | }, [deviceNotice]); |
| 434 | const [open, setOpen] = useState(false); |
| 435 | const root = useRef(); |
| 436 | useEffect(() => { |
| 437 | if (!open) return; |
| 438 | root.current.querySelector('[role="menuitem"]').focus(); |
| 439 | const dismiss = (event) => { |
| 440 | if ( |
| 441 | event.key === "Escape" || |
| 442 | (event.type === "click" && !root.current?.contains(event.target)) |
| 443 | ) { |
| 444 | if (event.key === "Escape") root.current?.querySelector(".account-trigger")?.focus(); |
| 445 | setOpen(false); |
| 446 | } |
| 447 | }; |
| 448 | window.addEventListener("click", dismiss); |
| 449 | window.addEventListener("keydown", dismiss); |
| 450 | return () => { |
| 451 | window.removeEventListener("click", dismiss); |
| 452 | window.removeEventListener("keydown", dismiss); |
| 453 | }; |
| 454 | }, [open]); |
| 455 | const perform = async (action) => { |
| 456 | setOpen(false); |
| 457 | if ( |
| 458 | action === "logout" && |
| 459 | !(await onConfirm({ |
| 460 | title: isRemoteClient() ? "退出云端账户?" : "退出本地账户?", |
| 461 | body: "这会停止 Cage 环境与后台任务,并锁定登录凭据。请先保存文件。", |
| 462 | confirm: "停止环境并退出账户", |
| 463 | })) |
| 464 | ) |
| 465 | return; |
| 466 | try { |
| 467 | await act(action); |
| 468 | } catch (e) { |
| 469 | onStatus(e.message); |
| 470 | } |
| 471 | }; |
| 472 | return ( |
| 473 | <div className="account-menu-root" ref={root}> |
| 474 | <button |
| 475 | className="account-trigger" |
| 476 | aria-label={`账户菜单,${account.username}`} |
| 477 | aria-expanded={open} |
| 478 | aria-haspopup="menu" |
| 479 | onClick={() => setOpen(!open)} |
| 480 | > |
| 481 | <AccountAvatar account={account} /> |
| 482 | <span className="account-trigger-name"> |
| 483 | <strong>{account.username}</strong> |
| 484 | <small>{account.trusted_local ? "受信任的本机" : isRemoteClient() ? "云端账户" : "本地账户"}</small> |
| 485 | </span> |
| 486 | <ChevronDown size={15} /> |
| 487 | </button> |
| 488 | {open && ( |
| 489 | <div className="account-menu" role="menu" aria-label={isRemoteClient() ? "云端账户菜单" : "本地账户菜单"} |
| 490 | onKeyDown={(event) => { |
| 491 | if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; |
| 492 | event.preventDefault(); |
| 493 | const items = [...event.currentTarget.querySelectorAll("button:enabled")]; |
| 494 | const step = event.key === "ArrowDown" ? 1 : -1; |
| 495 | items[(items.indexOf(event.target) + step + items.length) % items.length].focus(); |
| 496 | }} |
| 497 | > |
| 498 | <div className="account-menu-label">你的 Cage</div> |
| 499 | <button |
| 500 | role="menuitem" |
| 501 | onClick={() => { |
| 502 | setOpen(false); |
| 503 | onSettings("account"); |
| 504 | }} |
| 505 | > |
| 506 | <Settings size={16} /> |
| 507 | 设置 |
| 508 | </button> |
| 509 | {account.trusted_local ? <button role="menuitem" onClick={() => { setOpen(false); onSettings("account"); }}> |
| 510 | <LockKeyhole size={16} /> 设置账户密码 |
| 511 | </button> : <> |
| 512 | <div className="account-menu-divider" /> |
| 513 | <button role="menuitem" onClick={() => perform("lock")}> |
| 514 | <LockKeyhole size={16} /> |
| 515 | 锁定 Cage<small>任务继续运行</small> |
| 516 | </button> |
| 517 | <button |
| 518 | role="menuitem" |
| 519 | disabled={busy} |
| 520 | onClick={() => perform("logout")} |
| 521 | > |
| 522 | <LogOut size={16} /> |
| 523 | 退出账户 |
| 524 | </button></>} |
| 525 | </div> |
| 526 | )} |
| 527 | </div> |
| 528 | ); |
| 529 | } |
| 530 | |
| 531 | export function AccountSettings({ busy: environmentBusy, onDirty }) { |
| 532 | const { account, act, refresh } = useAccount(); |
| 533 | const [name, setName] = useState(account.username), |
| 534 | [avatar, setAvatar] = useState(account.avatar || ""); |
| 535 | const [oldPassword, setOldPassword] = useState(""), |
| 536 | [password, setPassword] = useState(""), |
| 537 | [confirmation, setConfirmation] = useState(""); |
| 538 | const [busy, setBusy] = useState(false), |
| 539 | [error, setError] = useState(""), |
| 540 | [message, setMessage] = useState(""); |
| 541 | const [feedbackTarget, setFeedbackTarget] = useState("profile"); |
| 542 | const file = useRef(); |
| 543 | const changed = |
| 544 | name !== account.username || avatar !== (account.avatar || ""); |
| 545 | useEffect(() => { |
| 546 | onDirty?.(changed || Boolean(oldPassword || password || confirmation)); |
| 547 | }, [changed, oldPassword, password, confirmation]); |
| 548 | useEffect(() => () => onDirty?.(false), []); |
| 549 | const upload = async (event) => { |
| 550 | setFeedbackTarget("profile"); |
| 551 | const selected = event.target.files?.[0]; |
| 552 | event.target.value = ""; |
| 553 | if (!selected) return; |
| 554 | if ( |
| 555 | selected.size > 2 * 1024 * 1024 || |
| 556 | !["image/png", "image/jpeg"].includes(selected.type) |
| 557 | ) { |
| 558 | setError("请选择不超过 2 MB 的 PNG 或 JPEG 图片"); |
| 559 | return; |
| 560 | } |
| 561 | const reader = new FileReader(); |
| 562 | reader.onload = () => { |
| 563 | setAvatar(reader.result); |
| 564 | setError(""); |
| 565 | setMessage(""); |
| 566 | }; |
| 567 | reader.readAsDataURL(selected); |
| 568 | }; |
| 569 | const save = async (event, changingPassword = false) => { |
| 570 | event.preventDefault(); |
| 571 | if (busy) return; |
| 572 | setFeedbackTarget(changingPassword ? "password" : "profile"); |
| 573 | if (changingPassword && password !== confirmation) { |
| 574 | setError("两次密码不一致"); |
| 575 | return; |
| 576 | } |
| 577 | setBusy(true); |
| 578 | setError(""); |
| 579 | setMessage(""); |
| 580 | try { |
| 581 | if (changingPassword && account.trusted_local) { |
| 582 | await trustedLogin("protect", password); |
| 583 | await refresh(); |
| 584 | setPassword(""); setConfirmation(""); |
| 585 | setMessage("已设置密码,下次打开 Cage 时使用密码登录。"); |
| 586 | return; |
| 587 | } |
| 588 | const value = await act( |
| 589 | changingPassword ? "password" : "profile", |
| 590 | changingPassword |
| 591 | ? { |
| 592 | old_password: oldPassword, |
| 593 | password, |
| 594 | confirm_password: confirmation, |
| 595 | } |
| 596 | : { username: name, avatar }, |
| 597 | ); |
| 598 | if (changingPassword) { |
| 599 | setOldPassword(""); |
| 600 | setPassword(""); |
| 601 | setConfirmation(""); |
| 602 | setMessage(value.macos_password_pending ? "Cage 密码已修改。客机密码待同步,下次启动时自动重试;同步完成前客机可能仍需原密码。" : "密码已修改,应用登录状态保持不变"); |
| 603 | } else { |
| 604 | setName(value.username); |
| 605 | setAvatar(value.avatar || ""); |
| 606 | setMessage("账户资料已保存"); |
| 607 | } |
| 608 | } catch (e) { |
| 609 | setError(e.message); |
| 610 | } finally { |
| 611 | setBusy(false); |
| 612 | } |
| 613 | }; |
| 614 | const feedback = ( |
| 615 | <> |
| 616 | {error && ( |
| 617 | <p className="account-error" role="alert"> |
| 618 | {error} |
| 619 | </p> |
| 620 | )} |
| 621 | {message && ( |
| 622 | <p className="account-saved" role="status"> |
| 623 | <Check size={15} /> |
| 624 | {message} |
| 625 | </p> |
| 626 | )} |
| 627 | </> |
| 628 | ); |
| 629 | if (account.macos_account_host && account.guest_system === "macos" && !account.macos_credentials_ready) return <MacOSAccountGate />; |
| 630 | return ( |
| 631 | <div className="account-settings"> |
| 632 | <div className="section-title"> |
| 633 | <h3>账户</h3> |
| 634 | <p>给工作空间一点你的样子。</p> |
| 635 | </div> |
| 636 | <form onSubmit={(event) => save(event)}> |
| 637 | <fieldset disabled={busy || environmentBusy}> |
| 638 | <div className="account-profile-heading"> |
| 639 | <AccountAvatar account={{ username: name, avatar }} large /> |
| 640 | <div> |
| 641 | <button |
| 642 | type="button" |
| 643 | className="quiet-button" |
| 644 | onClick={() => file.current.click()} |
| 645 | > |
| 646 | <Camera size={16} /> |
| 647 | 更换头像 |
| 648 | </button> |
| 649 | {avatar && ( |
| 650 | <button |
| 651 | type="button" |
| 652 | className="text-button" |
| 653 | onClick={() => setAvatar("")} |
| 654 | > |
| 655 | 恢复默认 |
| 656 | </button> |
| 657 | )} |
| 658 | <p className="field-help"> |
| 659 | PNG 或 JPEG,最多 2 MB,自动居中裁切。 |
| 660 | </p> |
| 661 | </div> |
| 662 | </div> |
| 663 | <input |
| 664 | ref={file} |
| 665 | type="file" |
| 666 | accept="image/png,image/jpeg" |
| 667 | hidden |
| 668 | onChange={upload} |
| 669 | aria-label="选择头像图片" |
| 670 | /> |
| 671 | <label className="account-field"> |
| 672 | 用户名 |
| 673 | <input |
| 674 | value={name} |
| 675 | maxLength={40} |
| 676 | autoComplete="username" |
| 677 | onChange={(e) => setName(e.target.value)} |
| 678 | required |
| 679 | readOnly={account.macos_username_bound} |
| 680 | /> |
| 681 | </label> |
| 682 | {account.macos_username_bound && <p className="field-help">用户名已用于 macOS 客机,保留该名称以继续使用原账户和文件。</p>} |
| 683 | <button |
| 684 | className="primary" |
| 685 | disabled={!changed || !name.trim() || busy} |
| 686 | > |
| 687 | <Check size={16} /> |
| 688 | 保存资料 |
| 689 | </button> |
| 690 | </fieldset> |
| 691 | </form> |
| 692 | {feedbackTarget === "profile" && feedback} |
| 693 | <div className="account-section-divider" /> |
| 694 | <form onSubmit={(event) => save(event, true)}> |
| 695 | <fieldset disabled={busy || environmentBusy}> |
| 696 | <h4>账户密码</h4> |
| 697 | <p className="field-help"> |
| 698 | 修改密码不会清除 Claude 的登录状态。{account.macos_credentials_ready ? "Cage 与 macOS 客机共用密码;客机关闭时会在下次启动后同步。" : isRemoteClient() ? "密码用于解锁当前云端 Cage,没有在线找回。" : "密码用于本机解锁,没有在线找回。"} |
| 699 | </p> |
| 700 | {!account.trusted_local && <PasswordField |
| 701 | label="当前密码" |
| 702 | value={oldPassword} |
| 703 | onChange={setOldPassword} |
| 704 | />} |
| 705 | <PasswordField |
| 706 | label="新密码" |
| 707 | value={password} |
| 708 | onChange={setPassword} |
| 709 | autoComplete="new-password" |
| 710 | /> |
| 711 | <PasswordField |
| 712 | label="确认新密码" |
| 713 | value={confirmation} |
| 714 | onChange={setConfirmation} |
| 715 | autoComplete="new-password" |
| 716 | /> |
| 717 | <button |
| 718 | className="quiet-button" |
| 719 | disabled={busy || (!account.trusted_local && !oldPassword) || !password || !confirmation} |
| 720 | > |
| 721 | {account.trusted_local ? "设置密码并关闭免账号登录" : "修改密码"} |
| 722 | </button> |
| 723 | </fieldset> |
| 724 | </form> |
| 725 | |
| 726 | {feedbackTarget === "password" && feedback} |
| 727 | {localDesktop() && !account.trusted_local && <TrustedDeviceSettings />} |
| 728 | {!account.trusted_local && <AccountDeviceSettings />} |
| 729 | <p className="account-settings-note"> |
| 730 | <LockKeyhole size={15} /> |
| 731 | {isRemoteClient() ? "账户、应用资料与登录凭据保存在当前云端主机。" : "一个本地账户,一个持久工作环境。资料与凭据不上传到 Cage 服务器。"} |
| 732 | </p> |
| 733 | </div> |
| 734 | ); |
| 735 | } |
| 736 | |
| 737 | function TrustedDeviceSettings() { |
| 738 | const { account, refresh } = useAccount(); |
| 739 | const enabled = Boolean(account.trusted_login || account.devices?.automatic); |
| 740 | const [password, setPassword] = useState(""); |
| 741 | const [message, setMessage] = useState(""); |
| 742 | const [busy, setBusy] = useState(false); |
| 743 | const update = async (event) => { |
| 744 | event.preventDefault(); |
| 745 | setBusy(true); setMessage(""); |
| 746 | try { |
| 747 | await trustedLogin(enabled ? "disable" : "enable", password); |
| 748 | setPassword(""); |
| 749 | await refresh(); |
| 750 | } catch (error) { setMessage(error.message); } |
| 751 | finally { setBusy(false); } |
| 752 | }; |
| 753 | return <form onSubmit={update}> |
| 754 | <fieldset disabled={busy}> |
| 755 | <h4>记住我</h4> |
| 756 | <p className="field-help">{enabled ? "已信任此电脑,下次用当前系统用户打开时自动进入。手动锁定仍需验证,退出账户会撤销信任。" : "验证一次账户密码,信任此电脑,下次用当前系统用户打开时自动进入。"}</p> |
| 757 | {!enabled && <PasswordField label="验证账户密码" value={password} onChange={setPassword} autoComplete="current-password" />} |
| 758 | <button className="quiet-button" disabled={!enabled && !password}>{enabled ? "关闭记住我" : "信任此电脑"}</button> |
| 759 | {message && <p className="account-error" role="alert">{message}</p>} |
| 760 | </fieldset> |
| 761 | </form>; |
| 762 | } |
| 763 | |
| 764 | function AccountDeviceSettings() { |
| 765 | const { account, deviceSupport, deviceAction, recheckDevices } = useAccount(); |
| 766 | const [busy, setBusy] = useState(false); |
| 767 | const [error, setError] = useState(""); |
| 768 | const [message, setMessage] = useState(""); |
| 769 | if (!deviceSupport?.supported) return null; |
| 770 | if (!deviceSupport.device_status) return <section className="account-device-settings" aria-label="登录与解锁"> |
| 771 | <h4>登录与解锁</h4> |
| 772 | <p className="field-help" role="status">当前应用启动器需要更新,无法检查快捷登录状态。请重新安装完整的 Cage 应用后再设置;现有授权已保留。</p> |
| 773 | </section>; |
| 774 | const states = deviceSupport.device_status || {}; |
| 775 | const description = (kind, fallback) => states[kind] === "missing" |
| 776 | ? "当前目录的凭据缺失或已失效,请重新开启。" |
| 777 | : states[kind] === "unavailable" |
| 778 | ? "暂时无法检查系统钥匙串,授权记录已保留。请稍后重新检查。" |
| 779 | : states[kind] === "authentication_required" |
| 780 | ? "凭据需要通过 Touch ID 验证,解锁时会请求指纹。" |
| 781 | : fallback; |
| 782 | const change = async (kind, enabled) => { |
| 783 | setBusy(true); setError(""); setMessage(""); |
| 784 | try { |
| 785 | await deviceAction(enabled ? "enable" : "disable", kind); |
| 786 | setMessage(enabled ? "已开启,解锁凭据保存在这台 Mac 的系统钥匙串中" : "已关闭快捷登录授权"); |
| 787 | } catch (e) { setError(e.message); } |
| 788 | finally { setBusy(false); } |
| 789 | }; |
| 790 | return <section className="account-device-settings" aria-label="登录与解锁"> |
| 791 | <h4>登录与解锁</h4> |
| 792 | {!localDesktop() && <label className="account-device-option check-line"> |
| 793 | <input type="checkbox" checked={Boolean(account.devices?.automatic) && states.automatic === "available"} disabled={busy || states.automatic === "unavailable"} |
| 794 | onChange={(event) => change("automatic", event.target.checked)} /> |
| 795 | <span><strong>记住登录</strong><small>{description("automatic", "重新打开直接进入。手动锁定后仍需指纹或密码。")}</small></span> |
| 796 | </label>} |
| 797 | <label className="account-device-option check-line"> |
| 798 | <input type="checkbox" checked={Boolean(account.devices?.biometric) && credentialPresent(states.biometric)} disabled={busy || states.biometric === "unavailable" || (!deviceSupport.biometric_available && !credentialPresent(states.biometric))} |
| 799 | onChange={(event) => change("biometric", event.target.checked)} /> |
| 800 | <span><strong>使用 Touch ID 解锁</strong><small>{description("biometric", deviceSupport.biometric_available ? "手动锁定后,通过系统指纹验证进入。" : "请先在 macOS 系统设置中设置 Touch ID。")}</small></span> |
| 801 | </label> |
| 802 | {Object.values(states).includes("unavailable") && <button type="button" className="quiet-button" disabled={busy} onClick={recheckDevices}>重新检查快捷登录</button>} |
| 803 | <p className="field-help">退出账户会撤销本机快捷登录授权。密码始终可以用于解锁。</p> |
| 804 | {error && <p className="account-error" role="alert">{error}</p>} |
| 805 | {message && <p className="account-saved" role="status">{message}</p>} |
| 806 | </section>; |
| 807 | } |