1import { createMemo, createSignal, For, onMount, Show } from "solid-js";2import { default as zxcvbn } from "zxcvbn";3import type { AdvancedHealthReport, VaultEntry } from "../../shared/types";4import { getDisplayDomain } from "../../shared/domain";5import { sendMessage } from "../App";6import { VaultView } from "./Vault";78function sha256(plain: string): Promise<string> {9 const encoder = new TextEncoder();10 const data = encoder.encode(plain);11 return crypto.subtle.digest("SHA-256", data).then((buf) => {12 return Array.from(new Uint8Array(buf))13 .map((b) => b.toString(16).padStart(2, "0"))14 .join("");15 });16}1718interface ReusedGroup {19 hash: string;20 entries: VaultEntry[];21}2223interface HealthProps {24 entries: VaultEntry[];25 isPro?: boolean;26 onFixEntry: (entry: VaultEntry) => void;27 onBack: () => void;28 onRefresh: () => void;29}3031function formatExposure(count: number): string {32 if (count >= 1000) return `${(count / 1000).toFixed(count % 1000 === 0 ? 0 : 1)}k exposures`;33 return `${count.toLocaleString()} ${count === 1 ? "exposure" : "exposures"}`;34}3536function formatRelativeTime(ms: number): string {37 const seconds = Math.floor(ms / 1000);38 if (seconds < 60) return "just now";39 const minutes = Math.floor(seconds / 60);40 if (minutes < 60) return `${minutes} minute${minutes !== 1 ? "s" : ""} ago`;41 const hours = Math.floor(minutes / 60);42 if (hours < 24) return `${hours} hour${hours !== 1 ? "s" : ""} ago`;43 const days = Math.floor(hours / 24);44 if (days < 30) return `${days} day${days !== 1 ? "s" : ""} ago`;45 const months = Math.floor(days / 30);46 if (months < 12) return `${months} month${months !== 1 ? "s" : ""} ago`;47 const years = Math.floor(months / 12);48 return `${years} year${years !== 1 ? "s" : ""} ago`;49}5051function scoreLabel(score: number): string {52 const labels = ["very weak", "weak", "fair", "good", "strong"];53 return labels[score] ?? "unknown";54}5556export function HealthView(props: HealthProps) {57 const [checkingBreaches, setCheckingBreaches] = createSignal(false);58 const [reusedGroups, setReusedGroups] = createSignal<ReusedGroup[]>([]);59 const [reusedLoading, setReusedLoading] = createSignal(true);60 const [expandedSections, setExpandedSections] = createSignal<Record<string, boolean>>({61 breached: true,62 reused: true,63 weak: true,64 old: true,65 passkeys: true,66 });67 const [viewingReusedGroup, setViewingReusedGroup] = createSignal<VaultEntry[] | null>(null);68 const [advancedReport, setAdvancedReport] = createSignal<AdvancedHealthReport | null>(null);69 const [advancedLoading, setAdvancedLoading] = createSignal<boolean>(false);70 const [smartChangingId, setSmartChangingId] = createSignal<string | null>(null);7172 onMount(async () => {73 if (!props.isPro) return;74 setAdvancedLoading(true);75 try {76 const res = await sendMessage({ type: "GET_ADVANCED_HEALTH_REPORT" });77 if ((res as { ok: boolean }).ok) {78 setAdvancedReport((res as { ok: boolean; data?: AdvancedHealthReport }).data ?? null);79 }80 } finally {81 setAdvancedLoading(false);82 }83 });8485 async function handleSmartChange(entryId: string) {86 setSmartChangingId(entryId);87 const res = await sendMessage({88 type: "INITIATE_PASSWORD_CHANGE",89 payload: { id: entryId },90 });91 setSmartChangingId(null);92 if ((res as { ok: boolean }).ok) {93 94 95 96 window.close();97 }98 }99100 const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;101102 const breachedEntries = createMemo(() =>103 props.entries104 .filter((e) => (e.breach ?? 0) > 0)105 .sort((a, b) => (b.breach ?? 0) - (a.breach ?? 0))106 );107108 const weakEntries = createMemo(() => {109 110 const scored = props.entries111 .filter((e) => e.type !== "note" && e.password)112 .map((entry) => ({ entry, score: zxcvbn(entry.password!).score }))113 .filter(({ score }) => score <= 1);114 scored.sort((a, b) => a.score - b.score);115 return scored;116 });117118 const oldEntries = createMemo(() =>119 props.entries120 .filter((e) => e.type === "login" && e.modifiedAt < Date.now() - ONE_YEAR_MS)121 .sort((a, b) => a.modifiedAt - b.modifiedAt)122 );123124 const stalePasskeys = createMemo(() =>125 props.entries126 .filter((e) => e.passkey !== undefined)127 .map((entry) => {128 const passkey = entry.passkey!;129 const lastActivity = passkey.lastUsedAt ?? passkey.createdAt ?? entry.createdAt;130 const ageMs = Date.now() - lastActivity;131 const status =132 passkey.signCount === 0 && ageMs >= 30 * 24 * 60 * 60 * 1000133 ? "Unused"134 : ageMs >= ONE_YEAR_MS135 ? "Old"136 : null;137 return { entry, lastActivity, status };138 })139 .filter((item) => item.status !== null)140 .sort((a, b) => a.lastActivity - b.lastActivity)141 );142143 async function computeReused() {144 const loginEntries = props.entries.filter((e) => e.type !== "note" && e.password);145 if (loginEntries.length === 0) {146 setReusedGroups([]);147 setReusedLoading(false);148 return;149 }150 const hashes = await Promise.all(151 loginEntries.map(async (e) => ({ entry: e, hash: await sha256(e.password!) }))152 );153 const map = new Map<string, VaultEntry[]>();154 for (const { entry, hash } of hashes) {155 const group = map.get(hash) ?? [];156 group.push(entry);157 map.set(hash, group);158 }159 const groups: ReusedGroup[] = [];160 map.forEach((entries, hash) => {161 if (entries.length >= 2) {162 groups.push({ hash, entries });163 }164 });165 groups.sort((a, b) => b.entries.length - a.entries.length);166 setReusedGroups(groups);167 setReusedLoading(false);168 }169170 computeReused();171172 function toggleSection(key: string) {173 setExpandedSections((prev) => ({ ...prev, [key]: !prev[key] }));174 }175176 async function handleCheckAllBreaches() {177 setCheckingBreaches(true);178 const res = await sendMessage({ type: "CHECK_ALL_BREACHES" });179 setCheckingBreaches(false);180 if ((res as { ok: boolean }).ok) {181 props.onRefresh();182 }183 }184185 const totalNeedsAttention = createMemo(186 () =>187 breachedEntries().length +188 reusedGroups().length +189 weakEntries().length + 190 oldEntries().length +191 stalePasskeys().length192 );193194 return (195 <>196 <div class="peach-overlay-view ov-enter-right" style="display:flex">197 <div class="peach-overlay-header">198 <button199 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"200 onClick={props.onBack}201 aria-label="Back"202 >203 <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">204 <path d="M6 1L1 6L6 11" />205 </svg>206 </button>207 <span class="peach-overlay-title">vault health</span>208 <div class="peach-overlay-spacer"></div>209 </div>210211 <div class="peach-health-body">212 <Show when={props.isPro && advancedLoading()}>213 <div class="peach-health-loading-screen" aria-busy="true" aria-live="polite">214 <div class="peach-health-loading-glyph" aria-hidden="true">215 <svg width="32" height="32" viewBox="0 0 32 32" fill="none">216 <circle cx="16" cy="16" r="13" stroke="currentColor" stroke-width="1.2" opacity="0.18" />217 <path d="M16 3a13 13 0 0 1 13 13" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">218 <animateTransform attributeName="transform" type="rotate" from="0 16 16" to="360 16 16" dur="1.2s" repeatCount="indefinite" />219 </path>220 </svg>221 </div>222 <h2 class="peach-health-loading-title">Checking your vault's health</h2>223 <p class="peach-health-loading-copy">224 Scanning for reused, breached, weak, and aging credentials.225 Just a moment…226 </p>227 <div class="peach-health-loading-track" aria-hidden="true">228 <div class="peach-health-loading-fill"></div>229 </div>230 </div>231 </Show>232 <Show when={props.isPro && !advancedLoading() && advancedReport() && advancedReport()!.remediation.length > 0}>233 <div class="peach-health-pro-queue">234 <div class="peach-health-pro-queue-head">235 <span class="peach-health-pro-queue-title">Remediation queue</span>236 <span class="peach-health-pro-queue-score">237 Vault score {advancedReport()!.vaultScore}/100238 </span>239 </div>240 <For each={advancedReport()!.remediation.slice(0, 8)}>241 {(item) => (242 <div class="peach-health-pro-row">243 <div class="peach-health-pro-row-info">244 <span class="peach-health-pro-row-name">{item.title}</span>245 <span class="peach-health-pro-row-meta">246 {item.reasons.join(" · ")}247 </span>248 <div class="peach-health-pro-bar" aria-hidden="true">249 <div250 class="peach-health-pro-bar-fill"251 style={{ width: `${Math.min(item.score, 100)}%` }}252 ></div>253 </div>254 </div>255 <button256 class="peach-btn peach-btn--accent peach-btn--sm"257 onClick={() => void handleSmartChange(item.id)}258 disabled={smartChangingId() === item.id}259 >260 {smartChangingId() === item.id ? "opening…" : "Change this password"}261 </button>262 </div>263 )}264 </For>265 </div>266 </Show>267268 <div class="peach-health-summary">269 <Show270 when={totalNeedsAttention() > 0}271 fallback={<span class="peach-health-summary-ok">Your vault looks healthy.</span>}272 >273 <span class="peach-health-summary-warn">274 {totalNeedsAttention()} {totalNeedsAttention() === 1 ? "entry needs" : "entries need"} attention275 </span>276 </Show>277 </div>278279 <div class="peach-health-check-row">280 <button281 class="peach-btn peach-btn--accent peach-btn--sm peach-health-check-btn"282 onClick={() => void handleCheckAllBreaches()}283 disabled={checkingBreaches()}284 >285 <svg width="10" height="12" viewBox="0 0 10 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-right:5px;">286 <path d="M9 6L5 10L1 6" />287 <path d="M5 10V2" />288 </svg>289 {checkingBreaches() ? "checking..." : "Check all breaches now"}290 </button>291 </div>292293 <div class="peach-health-sections">294 <HealthSection295 title="Breached"296 count={breachedEntries().length}297 expanded={expandedSections().breached}298 onToggle={() => toggleSection("breached")}299 emptyMessage="No breached entries"300 >301 <For each={breachedEntries()}>302 {(entry) => (303 <div class="peach-health-row">304 <div class="peach-health-row-info">305 <span class="peach-health-row-name">{entry.title}</span>306 <span class="peach-health-row-meta" style="color:var(--peach-breach);">307 {formatExposure(entry.breach ?? 0)}308 </span>309 </div>310 <button311 class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"312 onClick={() => props.onFixEntry(entry)}313 >314 Fix315 <svg width="6" height="10" viewBox="0 0 6 10" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-left:4px;">316 <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />317 </svg>318 </button>319 </div>320 )}321 </For>322 </HealthSection>323324 <HealthSection325 title="Reused"326 count={reusedGroups().length}327 expanded={expandedSections().reused}328 onToggle={() => toggleSection("reused")}329 loading={reusedLoading()}330 emptyMessage="No reused passwords"331 >332 <Show when={!reusedLoading()} fallback={<div class="peach-health-loading">Computing...</div>}>333 <For each={reusedGroups()}>334 {(group) => (335 <div class="peach-health-row">336 <div class="peach-health-row-info">337 <span class="peach-health-row-name">338 Used in {group.entries.length} places339 </span>340 <span class="peach-health-row-meta">341 {group.entries.map((e) => e.title).join(", ")}342 </span>343 </div>344 <button345 class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"346 onClick={() => setViewingReusedGroup(group.entries)}347 >348 View349 <svg width="6" height="10" viewBox="0 0 6 10" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-left:4px;">350 <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />351 </svg>352 </button>353 </div>354 )}355 </For>356 </Show>357 </HealthSection>358359 <HealthSection360 title="Weak"361 count={weakEntries().length}362 expanded={expandedSections().weak}363 onToggle={() => toggleSection("weak")}364 emptyMessage="No weak passwords"365 >366 <For each={weakEntries()}>367 {({ entry, score }) => (368 <div class="peach-health-row">369 <div class="peach-health-row-info">370 <span class="peach-health-row-name">371 {entry.url ? getDisplayDomain(entry.url) : entry.title}372 </span>373 <span class="peach-health-row-meta">374 score: {score} ({scoreLabel(score)})375 </span>376 </div>377 <button378 class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"379 onClick={() => props.onFixEntry(entry)}380 >381 Fix382 <svg width="6" height="10" viewBox="0 0 6 10" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-left:4px;">383 <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />384 </svg>385 </button>386 </div>387 )}388 </For>389 </HealthSection>390391 <HealthSection392 title="Old"393 count={oldEntries().length}394 expanded={expandedSections().old}395 onToggle={() => toggleSection("old")}396 emptyMessage="No old entries"397 >398 <For each={oldEntries()}>399 {(entry) => {400 const age = Date.now() - entry.modifiedAt;401 return (402 <div class="peach-health-row">403 <div class="peach-health-row-info">404 <span class="peach-health-row-name">405 {entry.url ? getDisplayDomain(entry.url) : entry.title}406 </span>407 <span class="peach-health-row-meta">408 last changed {formatRelativeTime(age)}409 </span>410 </div>411 <button412 class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"413 onClick={() => props.onFixEntry(entry)}414 >415 Fix416 <svg width="6" height="10" viewBox="0 0 6 10" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-left:4px;">417 <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />418 </svg>419 </button>420 </div>421 );422 }}423 </For>424 </HealthSection>425426 <HealthSection427 title="Passkeys"428 count={stalePasskeys().length}429 expanded={expandedSections().passkeys}430 onToggle={() => toggleSection("passkeys")}431 emptyMessage="No stale passkeys"432 >433 <For each={stalePasskeys()}>434 {(item) => (435 <div class="peach-health-row">436 <div class="peach-health-row-info">437 <span class="peach-health-row-name">{item.entry.title}</span>438 <span class="peach-health-row-meta">439 {item.status} • {item.entry.rpId} • {formatRelativeTime(Date.now() - item.lastActivity)}440 </span>441 </div>442 <button443 class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"444 onClick={() => props.onFixEntry(item.entry)}445 >446 View447 <svg width="6" height="10" viewBox="0 0 6 10" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-left:4px;">448 <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />449 </svg>450 </button>451 </div>452 )}453 </For>454 </HealthSection>455 </div>456 </div>457 </div>458459 <Show when={viewingReusedGroup()}>460 <VaultView461 entries={viewingReusedGroup()!}462 selectedEntryId={undefined}463 sortOrder="az"464 onSortOrderChange={() => {}}465 onSelectEntry={(entry) => {466 setViewingReusedGroup(null);467 props.onFixEntry(entry);468 }}469 onAdd={() => {}}470 onClose={() => setViewingReusedGroup(null)}471 />472 </Show>473 </>474 );475}476477interface HealthSectionProps {478 title: string;479 count: number;480 expanded: boolean;481 onToggle: () => void;482 loading?: boolean;483 emptyMessage: string;484 children: any;485}486487function HealthSection(props: HealthSectionProps) {488 return (489 <div class="peach-health-section">490 <button class="peach-health-section-header" onClick={props.onToggle}>491 <div class="peach-health-section-title-row">492 <span class="peach-health-count-badge">{props.count}</span>493 <span class="peach-health-section-title">{props.title}</span>494 </div>495 <svg496 class="peach-health-chevron"497 classList={{ "is-expanded": props.expanded }}498 width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"499 >500 <path d="M1 1L5 5L9 1" />501 </svg>502 </button>503 <Show when={props.expanded}>504 <div class="peach-health-section-body">505 <Show506 when={!props.loading && props.count > 0}507 fallback={508 <Show when={!props.loading}>509 <div class="peach-health-empty">{props.emptyMessage}</div>510 </Show>511 }512 >513 {props.children}514 </Show>515 </div>516 </Show>517 </div>518 );519}