Repository Public
1// Security Center: local analysis (weak, reused, duplicates, insecure URLs, expiry, rotation) + opt-in breach check.2import { useEffect, useMemo, useRef, useState } from "react";3import { analyze, type Finding } from "../../../../packages/protocol/src/index.ts";4import type { ItemView } from "../core/engine.ts";5import { engine, errText } from "../state.ts";6import { Badge, Btn, Callout, Empty, ErrorText, Icon, type IconName, Monogram, PageHead } from "./common.tsx";7import { keyOf, subtitle } from "./itemmeta.ts";89const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));1011export function SecurityCenter({ items, onOpen, onBack }: { items: ItemView[]; onOpen: (key: string) => void; onBack: () => void }) {12 const byKey = useMemo(() => new Map(items.map((v) => [keyOf(v), v])), [items]);13 const findings = useMemo(() => analyze(items.map((v) => ({ id: keyOf(v), item: v.item }))), [items]);14 const [breached, setBreached] = useState<Map<string, number> | null>(null); // memory only, never persisted15 const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);16 const [breachError, setBreachError] = useState("");17 const cancel = useRef(false);18 useEffect(() => () => { cancel.current = true; }, []);1920 const of = <K extends Finding["kind"]>(k: K) => findings.filter((f): f is Extract<Finding, { kind: K }> => f.kind === k);21 const weak = of("weak"), reused = of("reused"), dup = of("duplicate"), insecure = of("insecure-url"), expiring = of("expiring"), rotation = of("rotation-due");22 const live = items.filter((v) => !v.item.trashedAt);23 const withPw = live.filter((v) => v.item.type === "login" && v.item.fields.password);24 const breachedList = breached ? [...breached].filter(([k, n]) => n > 0 && byKey.has(k)) : [];2526 const reusedCount = reused.reduce((n, f) => n + f.ids.length, 0);27 const penalty = weak.length * 6 + reusedCount * 5 + insecure.length * 3 + expiring.filter((e) => e.expired).length * 4 + rotation.length * 2 + dup.length + breachedList.length * 10;28 const score = live.length === 0 ? null : Math.max(0, Math.min(100, Math.round(100 - (penalty * 100) / Math.max(40, live.length * 8))));29 const grade = score === null ? "—" : score >= 90 ? "Excellent" : score >= 70 ? "Good" : score >= 45 ? "Needs attention" : "At risk";3031 const runBreach = async () => {32 cancel.current = false; setBreachError(""); setProgress({ done: 0, total: withPw.length });33 const out = new Map<string, number>(), cache = new Map<string, number>();34 try {35 for (let i = 0; i < withPw.length && !cancel.current; i++) {36 const v = withPw[i]!, pw = v.item.fields.password!;37 if (!cache.has(pw)) { cache.set(pw, await engine.breachCheck(pw)); await sleep(200); } // ≈ 5 lookups per second38 out.set(keyOf(v), cache.get(pw)!);39 setProgress({ done: i + 1, total: withPw.length });40 }41 if (!cancel.current) setBreached(out);42 } catch (e) { setBreachError(errText(e)); }43 finally { setProgress(null); }44 };4546 const ItemLink = ({ id, note }: { id: string; note?: React.ReactNode }) => {47 const v = byKey.get(id);48 if (!v) return null;49 return (50 <li><button type="button" className="finding-row" onClick={() => onOpen(id)} data-testid="finding-item">51 <Monogram title={v.item.title || "?"} size={28} />52 <span className="item-text"><span className="item-title ellipsis">{v.item.title || "Untitled"}</span><span className="item-sub ellipsis">{subtitle(v.item)}</span></span>53 {note}<Icon name="chevron" size={15} />54 </button></li>55 );56 };57 const Card = ({ id, icon, title, count, tone, children, blurb }: { id: string; icon: IconName; title: string; count: number; tone: "danger" | "brass" | "ok"; children?: React.ReactNode; blurb: string }) => (58 <section className={`finding-card ${count ? tone : "ok"}`} data-testid={`sec-${id}`} data-count={count} aria-label={title}>59 <header><span className="finding-icon"><Icon name={count ? icon : "check"} /></span><h2>{title}</h2><span className="finding-count mono">{count}</span></header>60 <p className="muted small">{count ? blurb : "Nothing found."}</p>61 {count > 0 && children}62 </section>63 );6465 return (66 <div className="page" data-testid="security-center">67 <PageHead title="Security Center" sub="Computed in this browser from your decrypted items. Nothing about your passwords is sent anywhere unless you start the breach check below." onBack={onBack} />68 {live.length === 0 ? <Empty icon="shield" title="Nothing to analyse yet">Add a few items and their health will be summarised here.</Empty> : (69 <>70 <div className="score-card" data-testid="score">71 <div className="score-dial" style={{ "--score": score ?? 0 } as React.CSSProperties} role="img" aria-label={`Overall score ${score} out of 100: ${grade}`}>72 <svg viewBox="0 0 120 120" aria-hidden="true"><circle className="ring-bg" cx="60" cy="60" r="52" fill="none" strokeWidth="9" /><circle className="ring-fg" cx="60" cy="60" r="52" fill="none" strokeWidth="9" strokeLinecap="round" pathLength={100} strokeDasharray="100" strokeDashoffset={100 - (score ?? 0)} transform="rotate(-90 60 60)" /></svg>73 <span className="score-num serif">{score}</span>74 </div>75 <div className="score-text">76 <h2 className="serif">{grade}</h2>77 <p className="muted">{live.length} items · {withPw.length} login passwords · {weak.length} weak · {reusedCount} reused{breached ? ` · ${breachedList.length} in known breaches` : ""}</p>78 <p className="fine">The score is a simple local heuristic to rank what to fix first, not a guarantee.</p>79 </div>80 </div>8182 <div className="finding-grid">83 <Card id="weak" icon="alert" title="Weak passwords" count={weak.length} tone="danger" blurb="Estimated below 50 bits: guessable offline if a site leaks its hashes.">84 <ul className="finding-list">{weak.map((f) => <ItemLink key={f.id} id={f.id} note={<Badge kind="danger">≈ {f.bits} bits</Badge>} />)}</ul>85 </Card>86 <Card id="reused" icon="copy" title="Reused passwords" count={reusedCount} tone="danger" blurb="One leak exposes every account sharing the password.">87 {reused.map((f, i) => <div key={i} className="finding-group"><span className="eyebrow">Same password · {f.ids.length} items</span><ul className="finding-list">{f.ids.map((id) => <ItemLink key={id} id={id} />)}</ul></div>)}88 </Card>89 <Card id="breached" icon="alert" title="Found in known breaches" count={breachedList.length} tone="danger" blurb="These passwords appear in public breach corpora. Change them.">90 <ul className="finding-list">{breachedList.map(([id, n]) => <ItemLink key={id} id={id} note={<Badge kind="danger">seen {n.toLocaleString()}×</Badge>} />)}</ul>91 </Card>92 <Card id="duplicate" icon="copy" title="Duplicate logins" count={dup.length} tone="brass" blurb="Several items for the same site and username.">93 {dup.map((f, i) => <div key={i} className="finding-group"><ul className="finding-list">{f.ids.map((id) => <ItemLink key={id} id={id} />)}</ul></div>)}94 </Card>95 <Card id="insecure" icon="link" title="Insecure addresses" count={insecure.length} tone="brass" blurb="Saved with http:// — credentials would travel unencrypted.">96 <ul className="finding-list">{insecure.map((f) => <ItemLink key={f.id} id={f.id} />)}</ul>97 </Card>98 <Card id="expiring" icon="clock" title="Expiring or expired" count={expiring.length} tone="brass" blurb="Expired, or expiring within 30 days.">99 <ul className="finding-list">{expiring.map((f) => <ItemLink key={f.id} id={f.id} note={<Badge kind={f.expired ? "danger" : "brass"}>{f.expired ? "expired" : f.expiresAt.slice(0, 10)}</Badge>} />)}</ul>100 </Card>101 <Card id="rotation" icon="refresh" title="Rotation due" count={rotation.length} tone="brass" blurb="Past their rotation schedule.">102 <ul className="finding-list">{rotation.map((f) => <ItemLink key={f.id} id={f.id} note={<Badge kind="brass">due {f.dueAt.slice(0, 10)}</Badge>} />)}</ul>103 </Card>104 </div>105106 <section className="section breach" aria-label="Breach check">107 <div className="section-head"><h2>Check for known breaches</h2></div>108 <p>Optional. For each login password, this browser computes a SHA-1 hash and sends <strong>only its first 5 hexadecimal characters</strong> to this server, which relays them to Have I Been Pwned. The reply lists hundreds of unrelated hash endings; the comparison happens here. <strong>The password and its full hash never leave the browser</strong> (k-anonymity), and Have I Been Pwned never sees your address.</p>109 <p className="muted small">The server learns that a check ran and which prefixes were asked — about a million passwords share each prefix. Results stay in memory and disappear when you lock.</p>110 <ErrorText text={breachError} />111 {progress ? (112 <div className="progress-row" role="status"><span>Checking {progress.done} of {progress.total}…</span><progress max={progress.total || 1} value={progress.done} aria-label="Breach check progress" /><Btn small onClick={() => { cancel.current = true; }}>Stop</Btn></div>113 ) : (114 <div className="row wrap">115 <Btn variant="primary" icon="shield" onClick={runBreach} disabled={withPw.length === 0} data-testid="breach-run">{breached ? "Check again" : `Check ${withPw.length} password${withPw.length === 1 ? "" : "s"}`}</Btn>116 {breached && <span className="muted" data-testid="breach-result">{breachedList.length === 0 ? "None of your login passwords appear in the corpus." : `${breachedList.length} password${breachedList.length === 1 ? "" : "s"} found in the corpus — see the card above.`}</span>}117 </div>118 )}119 </section>120 {findings.length === 0 && !breachedList.length && <Callout kind="ok" title="No findings"><p>No weak, reused, duplicate, insecure or expiring item was detected.</p></Callout>}121 </>122 )}123 </div>124 );125}126