| 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | import { KeyRound, Plus, Search, ShieldCheck } from "lucide-react"; |
| 3 | import { api, writeClipboard } from "./api"; |
| 4 | import "./password-vault.css"; |
| 5 | |
| 6 | const emptyBrowser = { available: false, entries: [], candidates: [] }; |
| 7 | export function usePasswordVault(ready, tab) { |
| 8 | const [state, setState] = useState(emptyBrowser); |
| 9 | const refresh = useRef(null), mutation = useRef(0); |
| 10 | useEffect(() => { |
| 11 | let cancelled = false, timer, running = false; |
| 12 | setState(emptyBrowser); |
| 13 | const poll = async () => { |
| 14 | if (running || cancelled || !ready) return; |
| 15 | running = true; |
| 16 | const revision = mutation.current; |
| 17 | clearTimeout(timer); |
| 18 | try { |
| 19 | const value = await api("/vault/browser", { action: "status", tab }); |
| 20 | if (!cancelled && revision === mutation.current) setState({ ...emptyBrowser, ...value, tab }); |
| 21 | } catch (error) { |
| 22 | if (!cancelled) setState({ ...emptyBrowser, message: error.message }); |
| 23 | } finally { |
| 24 | running = false; |
| 25 | if (!cancelled && ready) timer = setTimeout(poll, 2000); |
| 26 | } |
| 27 | }; |
| 28 | refresh.current = poll; |
| 29 | void poll(); |
| 30 | return () => { cancelled = true; clearTimeout(timer); refresh.current = null; }; |
| 31 | }, [ready, tab]); |
| 32 | const act = async input => { |
| 33 | await api("/vault/browser", input); |
| 34 | mutation.current++; |
| 35 | if (input.candidate) setState(previous => ({ ...previous, candidates: previous.candidates.filter(value => value.id !== input.candidate) })); |
| 36 | await refresh.current?.(); |
| 37 | }; |
| 38 | return { state, act }; |
| 39 | } |
| 40 | |
| 41 | export function BrowserVaultBar({ tab, vault, onManage, ready, menu = false }) { |
| 42 | const [open, setOpen] = useState(false), [busy, setBusy] = useState(false), [message, setMessage] = useState(""); |
| 43 | const { state, act } = vault; |
| 44 | const entries = state.tab === tab.id ? state.entries : []; |
| 45 | const candidate = state.candidates.find(value => value.tab === tab.id); |
| 46 | useEffect(() => { setOpen(false); setMessage(""); }, [tab.id, tab.url]); |
| 47 | const run = async (input, success) => { |
| 48 | setBusy(true); setMessage(""); |
| 49 | try { await act(input); setMessage(success); } |
| 50 | catch (error) { setMessage(error.message); } |
| 51 | finally { setBusy(false); } |
| 52 | }; |
| 53 | return <div className="vault-browser" onKeyDown={event => { |
| 54 | if (event.key === "Escape" && open) { event.stopPropagation(); setOpen(false); event.currentTarget.querySelector("button").focus(); } |
| 55 | }}> |
| 56 | <div className="vault-browser-heading"> |
| 57 | <button className={menu ? "browser-menu-item" : "text-button"} role={menu ? "menuitem" : undefined} |
| 58 | aria-expanded={open} onClick={() => setOpen(!open)}> |
| 59 | <KeyRound size={16} /><span>密码{entries.length ? ` · ${entries.length} 个账号` : ""}</span> |
| 60 | </button> |
| 61 | {message && <span role="status">{message}</span>} |
| 62 | </div> |
| 63 | {candidate && <div className="vault-save" role="region" aria-label="保存网站密码"> |
| 64 | <div><strong>{candidate.update ? "更新此账号的密码?" : "保存此账号密码?"}</strong> |
| 65 | <span>{candidate.origin} · {candidate.username || "未填写用户名"}</span> |
| 66 | <small>请确认网站登录成功后保存。</small></div> |
| 67 | <div className="vault-actions"> |
| 68 | <button className="primary" disabled={busy} onClick={() => run({ action: "save", candidate: candidate.id }, "密码已保存")}>{candidate.update ? "更新密码" : "保存密码"}</button> |
| 69 | <button disabled={busy} onClick={() => run({ action: "dismiss", candidate: candidate.id }, "")}>暂不保存</button> |
| 70 | <button className="text-button" disabled={busy} onClick={() => run({ action: "never", candidate: candidate.id }, "此网站不再提示保存")}>此网站不再提示</button> |
| 71 | </div> |
| 72 | </div>} |
| 73 | {open && <div className="vault-picker" role="region" aria-label="当前网站的密码"> |
| 74 | <p>{state.origin && state.tab === tab.id ? state.origin : "在 HTTPS 网站的登录页选择账号填充"}</p> |
| 75 | {!ready ? <p>启动环境后可填写网站密码。</p> : !state.available ? <p>{state.message || "正在连接浏览器密码功能…"}</p> : |
| 76 | entries.length ? entries.map(entry => <button className="vault-account-choice" key={entry.id} disabled={busy} |
| 77 | onClick={() => run({ action: "fill", tab: tab.id, id: entry.id, document: state.document }, "已填写,请在网页中提交登录")}> |
| 78 | <span>{entry.username || "未填写用户名"}</span><span>填入账号密码</span> |
| 79 | </button>) : <p>此网站尚未保存账号密码。</p>} |
| 80 | <button className="text-button" onClick={onManage}>管理密码保险箱</button> |
| 81 | </div>} |
| 82 | </div>; |
| 83 | } |
| 84 | |
| 85 | const newEntry = () => ({ origin: "", username: "", password: "" }); |
| 86 | export function PasswordVaultSettings({ onConfirm, onDirty }) { |
| 87 | const [store, setStore] = useState({ entries: [], blocked: [] }); |
| 88 | const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false); |
| 89 | const [search, setSearch] = useState(""), [draft, setDraft] = useState(null); |
| 90 | const [verify, setVerify] = useState(null), [accountPassword, setAccountPassword] = useState(""); |
| 91 | const [revealed, setRevealed] = useState(null), [error, setError] = useState(""), [message, setMessage] = useState(""); |
| 92 | const alive = useRef(true); |
| 93 | const refresh = async () => { |
| 94 | const data = await api("/vault"); |
| 95 | if (alive.current) setStore(data); |
| 96 | }; |
| 97 | useEffect(() => { |
| 98 | alive.current = true; |
| 99 | refresh().catch(error => { if (alive.current) setError(error.message); }).finally(() => { if (alive.current) setLoading(false); }); |
| 100 | const clear = () => { setRevealed(null); setAccountPassword(""); }; |
| 101 | window.addEventListener("blur", clear); |
| 102 | document.addEventListener("visibilitychange", clear); |
| 103 | return () => { alive.current = false; window.removeEventListener("blur", clear); document.removeEventListener("visibilitychange", clear); }; |
| 104 | }, []); |
| 105 | useEffect(() => { onDirty(Boolean(draft)); return () => onDirty(false); }, [draft, onDirty]); |
| 106 | useEffect(() => { |
| 107 | if (!revealed) return; |
| 108 | const timer = setTimeout(() => setRevealed(null), 30000); |
| 109 | return () => clearTimeout(timer); |
| 110 | }, [revealed]); |
| 111 | const run = async (input, success) => { |
| 112 | setBusy(true); setError(""); setMessage(""); |
| 113 | try { |
| 114 | const result = await api("/vault", input); |
| 115 | if (!alive.current) return; |
| 116 | if (input.action === "reveal") { |
| 117 | if (verify.mode === "copy") { await writeClipboard(result.password); setMessage("密码已复制到本机剪贴板"); } |
| 118 | else setRevealed({ id: input.id, password: result.password }); |
| 119 | setVerify(null); |
| 120 | } else { setDraft(null); setRevealed(null); await refresh(); setMessage(success); } |
| 121 | } catch (error) { if (alive.current) setError(error.message); } |
| 122 | finally { if (alive.current) { setBusy(false); setAccountPassword(""); } } |
| 123 | }; |
| 124 | const askReveal = (entry, mode) => { setRevealed(null); setAccountPassword(""); setVerify({ entry, mode }); setError(""); }; |
| 125 | const entries = store.entries.filter(entry => `${entry.origin} ${entry.username}`.toLowerCase().includes(search.toLowerCase())); |
| 126 | return <section className="vault-settings"> |
| 127 | <div className="section-title"><h3>密码保险箱</h3><p>账号密码加密保存在这台设备,随 Cage 一起解锁和锁定。</p></div> |
| 128 | <div className="vault-note"><ShieldCheck size={17} /><span>查看或复制密码需要再次验证 Cage 账户密码。填充后由你提交登录。</span></div> |
| 129 | {error && <p className="account-error" role="alert">{error}</p>} |
| 130 | {message && <p role="status">{message}</p>} |
| 131 | <div className="vault-toolbar"><label className="vault-search"><span><Search size={14} />搜索网站或账号</span> |
| 132 | <input type="search" value={search} onChange={event => setSearch(event.target.value)} /></label> |
| 133 | <button disabled={busy || Boolean(draft) || loading || Boolean(error && !store.entries.length)} onClick={() => { setDraft(newEntry()); setVerify(null); setRevealed(null); }}><Plus size={15} />添加密码</button></div> |
| 134 | {draft && <form className="vault-editor" onSubmit={event => { event.preventDefault(); void run({ action: "save", entry: draft }, "密码记录已保存"); }}> |
| 135 | <h4>{draft.id ? "编辑密码" : "添加密码"}</h4> |
| 136 | <fieldset disabled={busy}> |
| 137 | <label>网站地址<input type="url" required autoFocus placeholder="https://mail.example.com" value={draft.origin} onChange={event => setDraft({ ...draft, origin: event.target.value })} /></label> |
| 138 | <label>账号或邮箱<input autoComplete="off" maxLength={1024} value={draft.username} onChange={event => setDraft({ ...draft, username: event.target.value })} /></label> |
| 139 | <label>{draft.id ? "新密码(留空保留原密码)" : "网站密码"}<input type="password" autoComplete="new-password" required={!draft.id} maxLength={8192} value={draft.password || ""} onChange={event => setDraft({ ...draft, password: event.target.value })} /></label> |
| 140 | <div className="vault-actions"><button className="primary" type="submit">保存记录</button><button type="button" onClick={() => setDraft(null)}>取消</button></div> |
| 141 | </fieldset> |
| 142 | </form>} |
| 143 | {verify && <form className="vault-editor" onSubmit={event => { event.preventDefault(); void run({ action: "reveal", id: verify.entry.id, account_password: accountPassword }); }}> |
| 144 | <h4>{verify.mode === "copy" ? "验证后复制密码" : "验证后查看密码"}</h4><p>{verify.entry.origin} · {verify.entry.username}</p> |
| 145 | <label>Cage 账户密码<input type="password" autoComplete="off" autoFocus required maxLength={1024} value={accountPassword} onChange={event => setAccountPassword(event.target.value)} /></label> |
| 146 | <div className="vault-actions"><button className="primary" disabled={busy} type="submit">验证并{verify.mode === "copy" ? "复制" : "查看"}</button> |
| 147 | <button type="button" disabled={busy} onClick={() => { setVerify(null); setAccountPassword(""); }}>取消验证</button></div> |
| 148 | </form>} |
| 149 | {loading ? <p>正在读取密码保险箱…</p> : !entries.length ? <div className="vault-empty"><KeyRound size={24} /><p>{search ? "没有找到匹配的账号" : "还没有保存密码"}</p><small>网页登录后可以确认保存,也可以手动添加。</small></div> : |
| 150 | <div className="vault-list">{entries.map(entry => <article className="vault-entry" key={entry.id}> |
| 151 | <div><strong>{entry.origin}</strong><span>{entry.username || "未填写用户名"}</span></div> |
| 152 | {revealed?.id === entry.id && <div className="vault-revealed"><output aria-label="已保存的网站密码">{revealed.password}</output><button onClick={() => setRevealed(null)}>隐藏密码</button></div>} |
| 153 | <div className="vault-actions"> |
| 154 | <button disabled={busy || Boolean(draft)} onClick={() => askReveal(entry, "view")}>查看密码</button> |
| 155 | <button disabled={busy || Boolean(draft)} onClick={() => askReveal(entry, "copy")}>复制密码</button> |
| 156 | <button disabled={busy || Boolean(draft)} onClick={() => { setDraft({ ...entry, password: "" }); setVerify(null); setRevealed(null); }}>编辑</button> |
| 157 | <button disabled={busy || Boolean(draft)} onClick={async () => { if (await onConfirm({ title: "删除此密码?", body: `${entry.origin} · ${entry.username || "未填写用户名"}。删除后无法恢复。`, confirm: "删除密码" })) await run({ action: "delete", id: entry.id }, "密码记录已删除"); }}>删除</button> |
| 158 | </div> |
| 159 | </article>)}</div>} |
| 160 | {store.blocked.length > 0 && <section className="vault-blocked"><h4>不再提示保存的网站</h4>{store.blocked.map(origin => <div key={origin}><span>{origin}</span><button disabled={busy} onClick={() => run({ action: "unblock", origin }, "已恢复此网站的保存提示")}>恢复提示</button></div>)}</section>} |
| 161 | <p className="footnote">目前支持 HTTPS 顶层网页的常见登录表单。密码不会同步到其他设备;备份时需同时保留本地账户文件与密码库。</p> |
| 162 | </section>; |
| 163 | } |