Health.tsx

21.2 KB · raw

1import { createMemo, createSignal, For, onMount, Show } from "solid-js";2import { zxcvbn, zxcvbnOptions } from "@zxcvbn-ts/core";3import * as zxcvbnCommon from "@zxcvbn-ts/language-common";4import * as zxcvbnEn from "@zxcvbn-ts/language-en";5import type { AdvancedHealthReport, VaultEntry } from "../../shared/types";6import { getDisplayDomain } from "../../shared/domain";7import { sendMessage } from "../App";8import { createBreachScan } from "./breach-scan";9import { VaultView } from "./Vault";1011// Replaces the unmaintained `zxcvbn` package (LV-8; see Lock.tsx) — this file12// was missed by that migration. Health.tsx is already its own route-level13// lazy chunk, so a static import here carries the same load-timing as the14// dynamic imports used elsewhere; it just needs the dictionaries configured15// once before first use.16zxcvbnOptions.setOptions({17  translations: zxcvbnEn.translations,18  graphs: zxcvbnCommon.adjacencyGraphs,19  dictionary: { ...zxcvbnCommon.dictionary, ...zxcvbnEn.dictionary },20});2122function sha256(plain: string): Promise<string> {23  const encoder = new TextEncoder();24  const data = encoder.encode(plain);25  return crypto.subtle.digest("SHA-256", data).then((buf) => {26    return Array.from(new Uint8Array(buf))27      .map((b) => b.toString(16).padStart(2, "0"))28      .join("");29  });30}3132interface ReusedGroup {33  hash: string;34  entries: VaultEntry[];35}3637interface HealthProps {38  entries: VaultEntry[];39  isPro?: boolean;40  onFixEntry: (entry: VaultEntry) => void;41  onBack: () => void;42  onRefresh: () => void;43  /** Set by App while an entry edit is in progress so the view stays mounted44   *  but invisible — avoids re-running computeReused() on every back-nav. */45  hidden?: boolean;46}4748function formatExposure(count: number): string {49  if (count >= 1000) return `${(count / 1000).toFixed(count % 1000 === 0 ? 0 : 1)}k exposures`;50  return `${count.toLocaleString()} ${count === 1 ? "exposure" : "exposures"}`;51}5253function formatRelativeTime(ms: number): string {54  const seconds = Math.floor(ms / 1000);55  if (seconds < 60) return "just now";56  const minutes = Math.floor(seconds / 60);57  if (minutes < 60) return `${minutes} minute${minutes !== 1 ? "s" : ""} ago`;58  const hours = Math.floor(minutes / 60);59  if (hours < 24) return `${hours} hour${hours !== 1 ? "s" : ""} ago`;60  const days = Math.floor(hours / 24);61  if (days < 30) return `${days} day${days !== 1 ? "s" : ""} ago`;62  const months = Math.floor(days / 30);63  if (months < 12) return `${months} month${months !== 1 ? "s" : ""} ago`;64  const years = Math.floor(months / 12);65  return `${years} year${years !== 1 ? "s" : ""} ago`;66}6768function scoreLabel(score: number): string {69  const labels = ["very weak", "weak", "fair", "good", "strong"];70  return labels[score] ?? "unknown";71}7273export function HealthView(props: HealthProps) {74  const breachScan = createBreachScan(() => props.onRefresh());75  const [reusedGroups, setReusedGroups] = createSignal<ReusedGroup[]>([]);76  const [reusedLoading, setReusedLoading] = createSignal(true);77  const [expandedSections, setExpandedSections] = createSignal<Record<string, boolean>>({78    breached: true,79    reused: true,80    weak: true,81    old: true,82    passkeys: true,83  });84  const [viewingReusedGroup, setViewingReusedGroup] = createSignal<VaultEntry[] | null>(null);85  const [advancedReport, setAdvancedReport] = createSignal<AdvancedHealthReport | null>(null);86  // Start true for Pro users so the loading screen is visible on the very first render —87  // previously initialized to false and flipped in onMount, which left a blank-body flash.88  const [advancedLoading, setAdvancedLoading] = createSignal<boolean>(!!props.isPro);8990  onMount(async () => {91    if (!props.isPro) return;92    try {93      const res = await sendMessage({ type: "GET_ADVANCED_HEALTH_REPORT" });94      if ((res as { ok: boolean }).ok) {95        setAdvancedReport((res as { ok: boolean; data?: AdvancedHealthReport }).data ?? null);96      }97    } finally {98      setAdvancedLoading(false);99    }100  });101102  const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;103104  const breachedEntries = createMemo(() =>105    props.entries106      .filter((e) => (e.breach ?? 0) > 0)107      .sort((a, b) => (b.breach ?? 0) - (a.breach ?? 0))108  );109110  const weakEntries = createMemo(() => {111    // Precompute scores once — zxcvbn is expensive, avoid calling it multiple times per entry112    const scored = props.entries113      .filter((e) => e.type !== "note" && e.password)114      .map((entry) => ({ entry, score: zxcvbn(entry.password!).score }))115      .filter(({ score }) => score <= 1);116    scored.sort((a, b) => a.score - b.score);117    return scored;118  });119120  const oldEntries = createMemo(() =>121    props.entries122      .filter((e) => e.type === "login" && e.modifiedAt < Date.now() - ONE_YEAR_MS)123      .sort((a, b) => a.modifiedAt - b.modifiedAt)124  );125126  const stalePasskeys = createMemo(() =>127    props.entries128      .filter((e) => e.passkey !== undefined)129      .map((entry) => {130        const passkey = entry.passkey!;131        const lastActivity = passkey.lastUsedAt ?? passkey.createdAt ?? entry.createdAt;132        const ageMs = Date.now() - lastActivity;133        const status =134          passkey.signCount === 0 && ageMs >= 30 * 24 * 60 * 60 * 1000135            ? "Unused"136            : ageMs >= ONE_YEAR_MS137              ? "Old"138              : null;139        return { entry, lastActivity, status };140      })141      .filter((item) => item.status !== null)142      .sort((a, b) => a.lastActivity - b.lastActivity)143  );144145  const entriesById = createMemo(() => {146    const map = new Map<string, VaultEntry>();147    for (const entry of props.entries) map.set(entry.id, entry);148    return map;149  });150151  async function computeReused() {152    const loginEntries = props.entries.filter((e) => e.type !== "note" && e.password);153    if (loginEntries.length === 0) {154      setReusedGroups([]);155      setReusedLoading(false);156      return;157    }158    const hashes = await Promise.all(159      loginEntries.map(async (e) => ({ entry: e, hash: await sha256(e.password!) }))160    );161    const map = new Map<string, VaultEntry[]>();162    for (const { entry, hash } of hashes) {163      const group = map.get(hash) ?? [];164      group.push(entry);165      map.set(hash, group);166    }167    const groups: ReusedGroup[] = [];168    map.forEach((entries, hash) => {169      if (entries.length >= 2) {170        groups.push({ hash, entries });171      }172    });173    groups.sort((a, b) => b.entries.length - a.entries.length);174    setReusedGroups(groups);175    setReusedLoading(false);176  }177178  computeReused();179180  function toggleSection(key: string) {181    setExpandedSections((prev) => ({ ...prev, [key]: !prev[key] }));182  }183184185  const totalNeedsAttention = createMemo(186    () =>187      breachedEntries().length +188      reusedGroups().length +189      weakEntries().length +   // weakEntries returns { entry, score }[] now190      oldEntries().length +191      stalePasskeys().length192  );193194  const isLoading = () => reusedLoading() || (!!props.isPro && advancedLoading());195196  return (197    <>198      <div class="peach-overlay-view ov-enter-right" style={{ display: props.hidden ? "none" : "flex" }}>199        <div class="peach-overlay-header">200          <button201            class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"202            onClick={props.onBack}203            aria-label="Back"204          >205            <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">206              <path d="M6 1L1 6L6 11" />207            </svg>208          </button>209          <span class="peach-overlay-title">Advanced Vault Health</span>210          <div class="peach-overlay-spacer"></div>211        </div>212213        <div class="peach-health-body">214          <Show when={isLoading()}>215            <div class="peach-health-loading-screen" aria-busy="true" aria-live="polite">216              <div class="peach-health-loading-glyph" aria-hidden="true">217                <svg width="32" height="32" viewBox="0 0 32 32" fill="none">218                  <circle cx="16" cy="16" r="13" stroke="currentColor" stroke-width="1.2" opacity="0.18" />219                  <path d="M16 3a13 13 0 0 1 13 13" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">220                    <animateTransform attributeName="transform" type="rotate" from="0 16 16" to="360 16 16" dur="1.2s" repeatCount="indefinite" />221                  </path>222                </svg>223              </div>224              <h2 class="peach-health-loading-title">Checking your vault's health</h2>225              <p class="peach-health-loading-copy">226                Scanning for reused, breached, weak, and aging credentials.227                Just a moment…228              </p>229              <div class="peach-health-loading-track" aria-hidden="true">230                <div class="peach-health-loading-fill"></div>231              </div>232            </div>233          </Show>234          <Show when={!isLoading()}>235          <Show when={props.isPro && advancedReport() && advancedReport()!.remediation.length > 0}>236            <div class="peach-health-pro-queue">237              <div class="peach-health-pro-queue-head">238                <span class="peach-health-pro-queue-title">Remediation queue</span>239                <span class="peach-health-pro-queue-score">240                  Vault score {advancedReport()!.vaultScore}/100241                </span>242              </div>243              <For each={advancedReport()!.remediation.slice(0, 8)}>244                {(item) => {245                  const entry = () => entriesById().get(item.id);246                  return (247                    <div class="peach-health-pro-row">248                      <div class="peach-health-pro-row-info">249                        <span class="peach-health-pro-row-name">{item.title}</span>250                        <span class="peach-health-pro-row-meta">251                          {item.reasons.join(" · ")}252                        </span>253                        <div class="peach-health-pro-bar" aria-hidden="true">254                          <div255                            class="peach-health-pro-bar-fill"256                            style={{ width: `${Math.min(item.score, 100)}%` }}257                          ></div>258                        </div>259                      </div>260                      <Show when={entry()}>261                        {(target) => (262                          <button263                            class="peach-btn peach-btn--ghost peach-btn--sm peach-health-pro-action"264                            onClick={() => props.onFixEntry(target())}265                            aria-label={`Update password for ${item.title}`}266                          >267                            Update268                          </button>269                        )}270                      </Show>271                    </div>272                  );273                }}274              </For>275            </div>276          </Show>277278          <div class="peach-health-summary">279            <Show280              when={totalNeedsAttention() > 0}281              fallback={<span class="peach-health-summary-ok">No known issues in saved vault data.</span>}282            >283              <span class="peach-health-summary-warn">284                {totalNeedsAttention()} {totalNeedsAttention() === 1 ? "entry needs" : "entries need"} attention285              </span>286            </Show>287          </div>288289          <div class="peach-health-check-row">290            <button291              class="peach-btn peach-btn--accent peach-btn--sm peach-health-check-btn"292              onClick={() => void breachScan.start()}293              disabled={breachScan.checking()}294            >295              <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;">296                <path d="M9 6L5 10L1 6" />297                <path d="M5 10V2" />298              </svg>299              {breachScan.checking() ? "checking..." : "Check all breaches now"}300            </button>301          </div>302303          <Show when={breachScan.result()}>304            <p role="status">{breachScan.result()}</p>305          </Show>306307          <div class="peach-health-sections">308            <HealthSection309              title="Breached"310              count={breachedEntries().length}311              expanded={expandedSections().breached}312              onToggle={() => toggleSection("breached")}313              emptyMessage="No known breached entries"314            >315              <For each={breachedEntries()}>316                {(entry) => (317                  <div class="peach-health-row">318                    <div class="peach-health-row-info">319                      <span class="peach-health-row-name">{entry.title}</span>320                      <span class="peach-health-row-meta" style="color:var(--peach-breach);">321                        {formatExposure(entry.breach ?? 0)}322                      </span>323                    </div>324                    <button325                      class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"326                      onClick={() => props.onFixEntry(entry)}327                    >328                      Fix329                      <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;">330                        <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />331                      </svg>332                    </button>333                  </div>334                )}335              </For>336            </HealthSection>337338            <HealthSection339              title="Reused"340              count={reusedGroups().length}341              expanded={expandedSections().reused}342              onToggle={() => toggleSection("reused")}343              loading={reusedLoading()}344              emptyMessage="No reused passwords"345            >346              <Show when={!reusedLoading()} fallback={<div class="peach-health-loading">Computing...</div>}>347                <For each={reusedGroups()}>348                  {(group) => (349                    <div class="peach-health-row">350                      <div class="peach-health-row-info">351                        <span class="peach-health-row-name">352                          Used in {group.entries.length} places353                        </span>354                        <span class="peach-health-row-meta">355                          {group.entries.map((e) => e.title).join(", ")}356                        </span>357                      </div>358                      <button359                        class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"360                        onClick={() => setViewingReusedGroup(group.entries)}361                      >362                        View363                        <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;">364                          <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />365                        </svg>366                      </button>367                    </div>368                  )}369                </For>370              </Show>371            </HealthSection>372373            <HealthSection374              title="Weak"375              count={weakEntries().length}376              expanded={expandedSections().weak}377              onToggle={() => toggleSection("weak")}378              emptyMessage="No weak passwords"379            >380              <For each={weakEntries()}>381                {({ entry, score }) => (382                    <div class="peach-health-row">383                      <div class="peach-health-row-info">384                        <span class="peach-health-row-name">385                          {entry.url ? getDisplayDomain(entry.url) : entry.title}386                        </span>387                        <span class="peach-health-row-meta">388                          score: {score} ({scoreLabel(score)})389                        </span>390                      </div>391                      <button392                        class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"393                        onClick={() => props.onFixEntry(entry)}394                      >395                        Fix396                        <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;">397                          <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />398                        </svg>399                      </button>400                    </div>401                )}402              </For>403            </HealthSection>404405            <HealthSection406              title="Old"407              count={oldEntries().length}408              expanded={expandedSections().old}409              onToggle={() => toggleSection("old")}410              emptyMessage="No old entries"411            >412              <For each={oldEntries()}>413                {(entry) => {414                  const age = Date.now() - entry.modifiedAt;415                  return (416                    <div class="peach-health-row">417                      <div class="peach-health-row-info">418                        <span class="peach-health-row-name">419                          {entry.url ? getDisplayDomain(entry.url) : entry.title}420                        </span>421                        <span class="peach-health-row-meta">422                          last changed {formatRelativeTime(age)}423                        </span>424                      </div>425                      <button426                        class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"427                        onClick={() => props.onFixEntry(entry)}428                      >429                        Fix430                        <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;">431                          <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />432                        </svg>433                      </button>434                    </div>435                  );436                }}437              </For>438            </HealthSection>439440            <HealthSection441              title="Passkeys"442              count={stalePasskeys().length}443              expanded={expandedSections().passkeys}444              onToggle={() => toggleSection("passkeys")}445              emptyMessage="No stale passkeys"446            >447              <For each={stalePasskeys()}>448                {(item) => (449                  <div class="peach-health-row">450                    <div class="peach-health-row-info">451                      <span class="peach-health-row-name">{item.entry.title}</span>452                      <span class="peach-health-row-meta">453                        {item.status} • {item.entry.passkey?.rpId} • {formatRelativeTime(Date.now() - item.lastActivity)}454                      </span>455                    </div>456                    <button457                      class="peach-btn peach-btn--ghost peach-btn--sm peach-health-fix-btn"458                      onClick={() => props.onFixEntry(item.entry)}459                    >460                      View461                      <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;">462                        <path d="M1 5L5 9M5 9L5 5M5 9L1 9" />463                      </svg>464                    </button>465                  </div>466                )}467              </For>468            </HealthSection>469          </div>470          </Show>{/* end !isLoading() */}471        </div>472      </div>473474      <Show when={viewingReusedGroup()}>475        <VaultView476          entries={viewingReusedGroup()!}477          selectedEntryId={undefined}478          sortOrder="az"479          onSortOrderChange={() => {}}480          onSelectEntry={(entry) => {481            setViewingReusedGroup(null);482            props.onFixEntry(entry);483          }}484          onAdd={() => {}}485          onClose={() => setViewingReusedGroup(null)}486        />487      </Show>488    </>489  );490}491492interface HealthSectionProps {493  title: string;494  count: number;495  expanded: boolean;496  onToggle: () => void;497  loading?: boolean;498  emptyMessage: string;499  children: any;500}501502function HealthSection(props: HealthSectionProps) {503  return (504    <div class="peach-health-section">505      <button class="peach-health-section-header" onClick={props.onToggle}>506        <div class="peach-health-section-title-row">507          <span class="peach-health-count-badge">{props.count}</span>508          <span class="peach-health-section-title">{props.title}</span>509        </div>510        <svg511          class="peach-health-chevron"512          classList={{ "is-expanded": props.expanded }}513          width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"514        >515          <path d="M1 1L5 5L9 1" />516        </svg>517      </button>518      <Show when={props.expanded}>519        <div class="peach-health-section-body">520          <Show521            when={!props.loading && props.count > 0}522            fallback={523              <Show when={!props.loading}>524                <div class="peach-health-empty">{props.emptyMessage}</div>525              </Show>526            }527          >528            {props.children}529          </Show>530        </div>531      </Show>532    </div>533  );534}