Entry.tsx

80.7 KB · raw

1import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js";2import type { ProFeature, VaultEntry } from "../../shared/types";3import { isPasskeyOnly } from "../../shared/types";4import { detectBrowser } from "../../shared/browser";5import { getDisplayDomain } from "../../shared/domain";6import { faviconUrl, faviconImgSig, globeFaviconSig, titleInitials, titleBackground } from "../../shared/favicon";7import { generateTOTP, parseOtpauthURI } from "../../crypto/totp";8import { sendMessage, triggerPipPulse, triggerRing } from "../App";9import { popupCopy } from "../copy";10import { GeneratorDrawer } from "../components/GeneratorDrawer";11import { NoteEditorInline, Toolbar } from "./NoteEditor";12import { IdentitySuggestList } from "./Add";1314type EditableField = "title" | "url" | "username" | "email" | "password" | "notes" | "totp" | null;1516// Compact "time since" label for the password-history list. Coarse on purpose —17// the user wants "roughly when", not a precise duration.18function timeSince(when: number): string {19  const secs = Math.max(0, Math.floor((Date.now() - when) / 1000));20  if (secs < 60) return "just now";21  const mins = Math.floor(secs / 60);22  if (mins < 60) return `${mins}m ago`;23  const hours = Math.floor(mins / 60);24  if (hours < 24) return `${hours}h ago`;25  const days = Math.floor(hours / 24);26  if (days < 30) return `${days}d ago`;27  const months = Math.floor(days / 30);28  if (months < 12) return `${months}mo ago`;29  return `${Math.floor(months / 12)}y ago`;30}3132interface EntryProps {33  entry: VaultEntry | null;34  /**35   * Current active tab's full URL (https only). Empty string when unavailable36   * — Capacitor, an extension page, or a chrome:///about: URL. The URL37   * editor uses this to render an "add current site" shortcut.38   */39  currentTabUrl?: string;40  onDelete: () => void;41  /** Called after any inline save so App can reload entries */42  onFieldSaved: () => void | Promise<void>;43  onEscape?: () => void;44  entries?: VaultEntry[];45  /** Whether the user holds an active Peach Pro license. Drives Pro gates on46   *  canary entries (see CanarySection). */47  isPro?: boolean;48  /** Invoked when a Pro-gated control is tapped on free tier. App owns the49   *  upgrade navigation + highlight state. */50  onProGate?: (feature: ProFeature) => void;51}5253// Inline 16×16 favicon for the domain row — shows coloured initials until a54// real favicon is confirmed (same globe-detection logic as the vault list).55function DomainFavicon(props: { domain: string; title: string }) {56  const src = props.domain ? faviconUrl(props.domain) : null;57  const [isReal, setIsReal] = createSignal(false);58  const label = () => titleInitials(props.title || props.domain);59  const bg = () => titleBackground(props.title || props.domain);60  const chipStyle = () =>61    `display:inline-flex;align-items:center;justify-content:center;` +62    `width:16px;height:16px;border-radius:3px;background:${bg()};` +63    `font-family:"IBM Plex Mono",monospace;font-size:0.4375rem;font-weight:600;` +64    `letter-spacing:0.04em;color:rgba(240,232,216,0.92);flex-shrink:0;margin-right:5px;`;65  return (66    <Show67      when={isReal()}68      fallback={69        <>70          <span style={chipStyle()} aria-hidden="true">{label()}</span>71          {src && (72            <img73              src={src}74              style="display:none"75              onError={() => {}}76              onLoad={async (e) => {77                const img = e.currentTarget as HTMLImageElement;78                if (img.naturalWidth <= 16) return;79                const sig = faviconImgSig(img);80                if (sig !== null) {81                  const gSig = await globeFaviconSig();82                  if (gSig !== null && sig === gSig) return;83                }84                setIsReal(true);85              }}86            />87          )}88        </>89      }90    >91      <img src={src!} width="16" height="16" alt="" style="border-radius:3px;margin-right:5px;flex-shrink:0;" />92    </Show>93  );94}9596export function EntryView(props: EntryProps) {97  const [editingField, setEditingField] = createSignal<EditableField>(null);98  const [draft, setDraft] = createSignal("");99  const [saving, setSaving] = createSignal(false);100  const [showPassword, setShowPassword] = createSignal(false);101  const [showGenerator, setShowGenerator] = createSignal(false);102  const [showHistory, setShowHistory] = createSignal(false);103  const [revealedHistory, setRevealedHistory] = createSignal<Set<number>>(new Set());104  const [copied, setCopied] = createSignal<string | null>(null);105  // Local draft for the additional URLs list, edited only while the URL field106  // is in inline-edit mode. Saved alongside `url` when the user confirms.107  const [additionalUrlsDraft, setAdditionalUrlsDraft] = createSignal<string[]>([]);108  const [editingTags, setEditingTags] = createSignal(false);109  const [tagsDraft, setTagsDraft] = createSignal<string[]>([]);110  const [tagInput, setTagInput] = createSignal("");111  const [showCardNumber, setShowCardNumber] = createSignal(false);112  const [showCardCvc, setShowCardCvc] = createSignal(false);113  const [totpTick, setTotpTick] = createSignal(0);114  const [confirmDelete, setConfirmDelete] = createSignal(false);115  const [totpHot, setTotpHot] = createSignal(false);116  const [noteEditorEl, setNoteEditorEl] = createSignal<HTMLDivElement | null>(null);117  // Auto-open advanced when entry already has passkey or canary configured118  const [showAdvanced, setShowAdvanced] = createSignal(false);119  const [identityHelperSuppressed, setIdentityHelperSuppressed] = createSignal(false);120  let usernameInlineInput: HTMLInputElement | undefined;121  let emailInlineInput: HTMLInputElement | undefined;122  let usernameIdentityEl: HTMLDivElement | undefined;123  let emailIdentityEl: HTMLDivElement | undefined;124  let lastSavedNote: string | null = null;125  let totpClickTimer: ReturnType<typeof setTimeout> | null = null;126  onCleanup(() => { if (totpClickTimer) clearTimeout(totpClickTimer); });127128  function noteExec(cmd: string, val?: string) {129    document.execCommand(cmd, false, val);130    noteEditorEl()?.focus();131  }132133  async function saveNoteInline(html: string) {134    const entry = props.entry;135    if (!entry) return;136    const currentStored = entry.notes ?? "";137    if (html === currentStored) return;138    if (lastSavedNote !== null && html === lastSavedNote) return;139    lastSavedNote = html;140    setSaving(true);141    try {142      await sendMessage({143        type: "UPDATE_ENTRY",144        payload: { id: entry.id, patch: { notes: html } },145      });146      triggerRing();147      await props.onFieldSaved();148    } catch {149      lastSavedNote = null;150    } finally {151      setSaving(false);152    }153  }154155  const allIdentities = createMemo(() => {156    const emailMap = new Map<string, number>();157    const usernameMap = new Map<string, number>();158    for (const e of props.entries ?? []) {159      const uname = e.username?.trim() ?? "";160      const em = e.email?.trim() ?? "";161      if (uname) {162        if (uname.includes("@")) emailMap.set(uname, (emailMap.get(uname) ?? 0) + 1);163        else usernameMap.set(uname, (usernameMap.get(uname) ?? 0) + 1);164      }165      if (em) emailMap.set(em, (emailMap.get(em) ?? 0) + 1);166    }167    const result: Array<{ value: string; count: number; type: "email" | "username" }> = [];168    const seen = new Set<string>();169    for (const v of new Set([...emailMap.keys(), ...usernameMap.keys()])) {170      if (seen.has(v)) continue;171      seen.add(v);172      const ec = emailMap.get(v) ?? 0;173      const uc = usernameMap.get(v) ?? 0;174      result.push({ value: v, count: Math.max(ec, uc), type: ec >= uc ? "email" : "username" });175    }176    return result.sort((a, b) => b.count - a.count);177  });178179  const identitySuggestions = createMemo(() => {180    const field = editingField();181    if (field !== "username" && field !== "email") return [];182    const input = draft().toLowerCase();183    return allIdentities()184      .filter(s => s.type === field && (!input || s.value.toLowerCase().includes(input)))185      .slice(0, 8);186  });187188  const interval = window.setInterval(() => setTotpTick((n) => n + 1), 1000);189  onCleanup(() => window.clearInterval(interval));190191  const displayDomain = createMemo(() =>192    props.entry?.url ? getDisplayDomain(props.entry.url) : ""193  );194195  // Reset transient prompts (trash confirmation, inline edits, advanced panel)196  // when the selected entry changes so they don't carry over between entries.197  // Track the last id so a same-entry refresh (e.g. after saving a field)198  // doesn't blow away in-flight edit state — that race used to cancel199  // startEdit calls that ran right after onFieldSaved.200  let lastEntryId: string | null = null;201  createEffect(() => {202    const id = props.entry?.id ?? null;203    if (id === lastEntryId) return;204    lastEntryId = id;205    setConfirmDelete(false);206    setEditingField(null);207    setEditingTags(false);208    setShowAdvanced(false);209  });210211  const totpState = createMemo(() => {212    void totpTick();213    if (!props.entry?.totp) return null;214    return generateTOTP(props.entry.totp);215  });216217  let prevTotpCode: string | undefined;218  createEffect(() => {219    const state = totpState();220    if (!state) { prevTotpCode = undefined; return; }221    if (prevTotpCode !== undefined && state.code !== prevTotpCode) {222      setTotpHot(true);223      window.setTimeout(() => setTotpHot(false), 3000);224    }225    prevTotpCode = state.code;226  });227228  const totpProgress = createMemo(() => {229    const state = totpState();230    if (!state) return 0;231    return ((state.remaining - 1) / 29) * 100;232  });233234  createEffect(() => {235    const shell = document.getElementById("hd-shell");236    if (!shell) return;237238    const state = totpState();239    if (!state) {240      delete shell.dataset.totpActive;241      shell.style.removeProperty("--peach-totp-progress");242      return;243    }244245    shell.dataset.totpActive = "true";246    shell.style.setProperty(247      "--peach-totp-progress",248      `${Math.max(0, totpProgress())}%`249    );250251    onCleanup(() => {252      delete shell.dataset.totpActive;253      shell.style.removeProperty("--peach-totp-progress");254    });255  });256257  const titleSizeClass = createMemo(() => {258    const length = props.entry?.title.length ?? 0;259    if (length >= 28) return "peach-entry-name--xxl";260    if (length >= 20) return "peach-entry-name--xl";261    if (length >= 14) return "peach-entry-name--lg";262    return "";263  });264  const useAnimatedTitle = createMemo(() => (props.entry?.title.length ?? 0) <= 13);265266  // ── Inline editing ────────────────────────────────────────────────267268  function startEdit(field: EditableField, value: string) {269    setEditingField(field);270    setDraft(value);271    setIdentityHelperSuppressed(false);272    setShowGenerator(false);273    setShowHistory(false);274    setRevealedHistory(new Set<number>());275    setConfirmDelete(false);276    if (field === "url") {277      setAdditionalUrlsDraft([...(props.entry?.additionalUrls ?? [])]);278    }279  }280281  // Compare URLs by string after trim — vault.ts has its own canonicalisation282  // when saving, so the dedupe here is a UX-level "don't show the button if283  // we'd just add a duplicate" rather than a security check.284  function urlMatchesAny(candidate: string, primary: string, others: string[]): boolean {285    const c = candidate.trim();286    if (!c) return true;287    if (primary.trim() === c) return true;288    return others.some((u) => u.trim() === c);289  }290291  function addCurrentSite(url: string) {292    if (!url) return;293    if (!draft().trim()) {294      setDraft(url);295      return;296    }297    if (urlMatchesAny(url, draft(), additionalUrlsDraft())) return;298    setAdditionalUrlsDraft((arr) => [...arr, url]);299  }300301  async function saveField() {302    const field = editingField();303    const entry = props.entry;304    if (!field || !entry) return;305    // Don't trim passwords — spaces may be intentional306    let value = field === "password" ? draft() : draft().trim();307    if (field === "totp" && value.startsWith("otpauth://")) {308      const parsed = parseOtpauthURI(value);309      value = parsed?.secret ?? value;310    }311    if (field === "password" && entry.type !== "note" && !value) {312      return;313    }314    setSaving(true);315    try {316      const patch: Partial<VaultEntry> = { [field]: value };317      if (field === "url") {318        // Sanitization layer in vault.ts trims, dedupes, and drops empties.319        patch.additionalUrls = additionalUrlsDraft();320      }321      await sendMessage({322        type: "UPDATE_ENTRY",323        payload: { id: entry.id, patch },324      });325      triggerRing();326      setEditingField(null);327      setShowGenerator(false);328      setShowHistory(false);329      setRevealedHistory(new Set<number>());330      await props.onFieldSaved();331    } catch {332      // silent — leave editing open333    } finally {334      setSaving(false);335    }336  }337338  function startEditTags() {339    setTagsDraft([...(props.entry?.tags ?? [])]);340    setTagInput("");341    setEditingTags(true);342  }343344  function addTag(value: string) {345    const n = value.toLowerCase().trim();346    if (!n || n.length > 32 || tagsDraft().includes(n) || tagsDraft().length >= 10) return;347    setTagsDraft([...tagsDraft(), n]);348    setTagInput("");349  }350351  async function saveTags() {352    if (tagInput()) addTag(tagInput());353    const entry = props.entry;354    if (!entry) return;355    const next = tagsDraft().length > 0 ? tagsDraft() : undefined;356    setEditingTags(false);357    setSaving(true);358    try {359      await sendMessage({360        type: "UPDATE_ENTRY",361        payload: { id: entry.id, patch: { tags: next } },362      });363      triggerRing();364      await props.onFieldSaved();365    } catch {366      // silent367    } finally {368      setSaving(false);369    }370  }371372  function cancelEdit() {373    setEditingField(null);374    setDraft("");375    setShowGenerator(false);376    setShowHistory(false);377    setRevealedHistory(new Set<number>());378  }379380  // Switch from one identity slot to the other.381  //382  // Migration source is the SAVED entry value, never the live draft — using383  // the draft caused data loss when the user typed or cleared the input384  // before clicking +add (the migration would skip and a later Save would385  // overwrite the original email-shape value with whatever was in the input).386  //387  // Drafts only get committed when they are non-empty AND actually changed,388  // so an empty input never accidentally clears a saved field.389  async function addOtherIdentity(target: "username" | "email") {390    const entry = props.entry;391    if (!entry) return;392    const current = editingField();393    const draftValue = draft().trim();394    const savedUsername = entry.username ?? "";395    const savedEmail = entry.email ?? "";396397    if (current === "username" && target === "username") {398      // Legacy fix-up: saved username is email-shaped and no separate email399      // exists yet. Move it to entry.email and free the username slot.400      if (savedUsername.includes("@") && !entry.email) {401        setSaving(true);402        try {403          await sendMessage({404            type: "UPDATE_ENTRY",405            payload: { id: entry.id, patch: { email: savedUsername, username: "" } },406          });407          await props.onFieldSaved();408        } finally {409          setSaving(false);410        }411      }412      startEdit("username", "");413      return;414    }415416    if (current === "username" && target === "email") {417      if (draftValue && draftValue !== savedUsername) {418        setSaving(true);419        try {420          await sendMessage({421            type: "UPDATE_ENTRY",422            payload: { id: entry.id, patch: { username: draftValue } },423          });424          await props.onFieldSaved();425        } finally {426          setSaving(false);427        }428      }429      startEdit("email", "");430      return;431    }432433    if (current === "email" && target === "username") {434      if (draftValue && draftValue !== savedEmail) {435        setSaving(true);436        try {437          await sendMessage({438            type: "UPDATE_ENTRY",439            payload: { id: entry.id, patch: { email: draftValue } },440          });441          await props.onFieldSaved();442        } finally {443          setSaving(false);444        }445      }446      startEdit("username", "");447      return;448    }449  }450451  function fieldValue(entry: VaultEntry, field: Exclude<EditableField, null>): string {452    switch (field) {453      case "title":454        return entry.title;455      case "url":456        return entry.url ?? "";457      case "username":458        return entry.username ?? "";459      case "email":460        return entry.email ?? "";461      case "password":462        return entry.password ?? "";463      case "notes":464        return entry.notes ?? "";465      case "totp":466        return entry.totp ?? "";467    }468  }469470  function handleEditorFocusOut(471    field: Exclude<EditableField, null>,472    event: FocusEvent & { currentTarget: HTMLElement; relatedTarget: EventTarget | null }473  ) {474    const nextTarget = event.relatedTarget;475    if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;476477    // addOtherIdentity / startEdit may have already switched editingField before478    // focusout fires (SolidJS removes the old editor node synchronously, which479    // triggers blur with relatedTarget=null). Don't cancel the new edit.480    if (editingField() !== field) return;481482    const entry = props.entry;483    if (!entry) return;484485    const currentValue = fieldValue(entry, field);486    const nextValue = field === "password" ? draft() : draft().trim();487    if (nextValue === currentValue) {488      cancelEdit();489    }490  }491492  // ── Copy ─────────────────────────────────────────────────────────493494  async function copyField(text: string, label: string, button?: HTMLButtonElement) {495    const ok = await popupCopy(text, label);496    if (ok) {497      const entry = props.entry;498      if (entry?.canary?.webhookUrl) {499        const trigger =500          label === "password"501            ? "password_copied"502            : label === "username"503              ? "username_copied"504              : undefined;505        if (trigger) {506          void sendMessage({507            type: "FIRE_CANARY_PING",508            payload: { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title, trigger },509          });510        }511      }512      triggerRing();513      triggerPipPulse();514      setCopied(null);515      requestAnimationFrame(() => setCopied(label));516      if (button) {517        button.classList.remove("is-copied", "is-retreat");518        void button.offsetWidth;519        const drain = document.createElement("span");520        drain.className = "peach-copy-drain";521        const bar = document.createElement("span"); bar.className = "peach-copy-drain-bar";522        drain.appendChild(bar);523        button.appendChild(drain);524        window.setTimeout(() => {525          button.classList.remove("is-copied");526          button.classList.add("is-retreat");527          drain.remove();528          window.setTimeout(() => button.classList.remove("is-retreat"), 160);529        }, 1800);530      }531      window.setTimeout(() => setCopied(null), 1800);532    }533  }534535  // ── Keyboard shortcuts ────────────────────────────────────────────536537  createEffect(() => {538    if (!props.entry) return;539    const handler = (e: KeyboardEvent) => {540      const inInput = e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLSelectElement || (e.target as HTMLElement).isContentEditable;541      if (inInput) return;542      switch (e.key) {543        case "c": e.preventDefault();544          if (props.entry?.password) void copyField(props.entry.password, "password"); break;545        case "u": e.preventDefault();546          if (props.entry?.username) void copyField(props.entry.username, "username"); break;547        case "Escape": e.preventDefault(); props.onEscape?.(); break;548      }549    };550    window.addEventListener("keydown", handler);551    onCleanup(() => window.removeEventListener("keydown", handler));552  });553554  // ── Input ref focus helper ────────────────────────────────────────555556  function autoFocus(el: HTMLInputElement | HTMLTextAreaElement) {557    requestAnimationFrame(() => { el.focus(); el.select?.(); });558  }559560  function onEditKeyDown(e: KeyboardEvent) {561    if (e.key === "Enter" && !(e.target instanceof HTMLTextAreaElement)) {562      e.preventDefault();563      void saveField();564    }565    if (e.key === "Escape") { e.preventDefault(); cancelEdit(); }566  }567568  function identityKeyDown(e: KeyboardEvent, field: "username" | "email") {569    const listEl = field === "username" ? usernameIdentityEl : emailIdentityEl;570    if (e.key === "ArrowDown" && listEl) {571      e.preventDefault();572      listEl.querySelector<HTMLElement>(".peach-identity-suggestion")?.focus();573      return;574    }575    onEditKeyDown(e);576  }577578  return (579    <>580      <div581        class="peach-ghost"582        aria-hidden="true"583        style="position:absolute;top:30px;left:12px;right:0;font-family:'Cormorant Garamond',Georgia,serif;font-size:150px;font-style:italic;font-weight:400;color:var(--t0);opacity:var(--peach-ghost-opacity,0.03);pointer-events:none;line-height:1.25;overflow:hidden;white-space:nowrap;z-index:0;"584      >585        {props.entry?.title || "empty"}586      </div>587588      <div class="peach-stage" style="position:relative;">589        <Show when={props.entry} fallback={<EmptyVaultState />}>590          {(entry) => (591            <>592              {/* ── Breach strip ─────────────────────────────────── */}593              <Show when={entry().type !== "note" && entry().type !== "card" && (entry().breach ?? 0) > 0}>594                <div class="peach-breach-badge">595                  <svg width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="var(--breach)" stroke-width="1.5" stroke-linecap="round">596                    <path d="M6 1L11 10H1L6 1z" />597                    <line x1="6" y1="5" x2="6" y2="7.5" />598                    <circle cx="6" cy="9" r="0.5" fill="var(--breach)" stroke="none" />599                  </svg>600                  <span style="flex:1">found in a known data breach</span>601                </div>602              </Show>603604              {/* ── Title + trash ─────────────────────────────────── */}605              <div class="peach-entry-header">606                <div class="peach-entry-header-name">607                  <Show608                    when={editingField() === "title"}609                    fallback={610                      <button611                        class="peach-entry-name-button"612                        title="Click to edit title"613                        onClick={() => startEdit("title", entry().title)}614                      >615                        <h1 class={`peach-entry-name ${titleSizeClass()}`} aria-label={entry().title}>616                          <span class="peach-entry-name-text">617                            <Show618                              when={useAnimatedTitle()}619                              fallback={entry().title}620                            >621                              <For each={entry().title.split("")}>622                                {(ch, i) => (623                                  <span class="peach-entry-name-char" style={`--char-index:${i()}`}>624                                    {ch === " " ? "\u00A0" : ch}625                                  </span>626                                )}627                              </For>628                            </Show>629                          </span>630                        </h1>631                      </button>632                    }633                  >634                    <div635                      class="peach-inline-title-wrap"636                      onFocusOut={(event) => handleEditorFocusOut("title", event)}637                    >638                      <input639                        class="peach-inline-title-input"640                        value={draft()}641                        onInput={(e) => setDraft(e.currentTarget.value)}642                        onKeyDown={onEditKeyDown}643                        ref={autoFocus}644                        disabled={saving()}645                      />646                      <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />647                    </div>648                  </Show>649                </div>650651                {/* Subtle trash icon — hidden while editing title */}652                <Show when={editingField() !== "title"}>653                  <Show654                    when={confirmDelete()}655                    fallback={656                      <button657                        class="peach-entry-trash-btn"658                        onClick={() => setConfirmDelete(true)}659                        aria-label="Move to trash"660                        title="Delete entry"661                      >662                        <svg width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">663                          <path d="M1 3h10M4 3V2h4v1M2 3l.7 8.5a1 1 0 0 0 1 .9h4.6a1 1 0 0 0 1-.9L10 3" />664                          <path d="M4.5 6l.3 3.5M7.5 6l-.3 3.5" />665                        </svg>666                      </button>667                    }668                  >669                    <div class="peach-entry-trash-confirm">670                      <span class="peach-entry-trash-confirm-label">trash?</span>671                      <button672                        class="peach-btn peach-btn--sm peach-btn--danger"673                        style="font-size:10px;padding:2px 8px;min-height:22px;"674                        onClick={() => { setConfirmDelete(false); props.onDelete(); }}675                      >676                        yes677                      </button>678                      <button679                        class="peach-btn peach-btn--ghost peach-btn--sm"680                        style="font-size:10px;padding:2px 8px;min-height:22px;"681                        onClick={() => setConfirmDelete(false)}682                      >683                        no684                      </button>685                    </div>686                  </Show>687                </Show>688              </div>689690              {/* ── Domain / URL ─────────────────────────────────── */}691              <Show when={entry().type !== "note" && entry().type !== "card"}>692                <div class="peach-domain" style="position:relative;z-index:1;">693                  <Show694                    when={editingField() === "url"}695                    fallback={696                      <div697                        class="peach-domain-row peach-inline-clickable"698                        title="Click to edit URL"699                        onClick={() => startEdit("url", entry().url ?? "")}700                      >701                        <DomainFavicon domain={displayDomain()} title={entry().title ?? ""} />702                        <span class="peach-domain-value">703                          {displayDomain() || (entry().url ? entry().url : "add a website url")}704                        </span>705                        <span class="peach-inline-edit-hint">edit</span>706                      </div>707                    }708                  >709                    <div710                      class="peach-inline-field-wrap peach-inline-field-wrap--url"711                      onFocusOut={(event) => handleEditorFocusOut("url", event)}712                    >713                      <div class="peach-inline-field-row">714                        <input715                          class="peach-inline-input"716                          type="url"717                          placeholder="https://"718                          value={draft()}719                          onInput={(e) => setDraft(e.currentTarget.value)}720                          onKeyDown={onEditKeyDown}721                          ref={autoFocus}722                          disabled={saving()}723                        />724                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />725                      </div>726                      <div class="peach-additional-urls">727                        <Show when={additionalUrlsDraft().length > 0}>728                          <span class="peach-label peach-additional-urls-label">also matches</span>729                        </Show>730                        <For each={additionalUrlsDraft()}>731                          {(value, i) => (732                            <div class="peach-additional-url-row">733                              <input734                                class="peach-inline-input"735                                type="url"736                                placeholder="https://"737                                value={value}738                                onInput={(e) => setAdditionalUrlsDraft((arr) => {739                                  const next = [...arr];740                                  next[i()] = e.currentTarget.value;741                                  return next;742                                })}743                                disabled={saving()}744                              />745                              <button746                                class="peach-additional-url-remove"747                                type="button"748                                aria-label="Remove URL"749                                onMouseDown={(e) => e.preventDefault()}750                                onClick={() => setAdditionalUrlsDraft((arr) => arr.filter((_, idx) => idx !== i()))}751                                disabled={saving()}752                              >×</button>753                            </div>754                          )}755                        </For>756                        <button757                          class="peach-add-field-link peach-additional-urls-add"758                          type="button"759                          onMouseDown={(e) => e.preventDefault()}760                          onClick={() => setAdditionalUrlsDraft((arr) => [...arr, ""])}761                          disabled={saving()}762                        >763                          + add another url764                        </button>765                        <Show when={props.currentTabUrl && !urlMatchesAny(props.currentTabUrl!, draft(), additionalUrlsDraft())}>766                          <button767                            class="peach-add-field-link peach-additional-urls-add peach-additional-urls-add-current"768                            type="button"769                            title={props.currentTabUrl}770                            onMouseDown={(e) => e.preventDefault()}771                            onClick={() => addCurrentSite(props.currentTabUrl!)}772                            disabled={saving()}773                          >774                            + add current site775                          </button>776                        </Show>777                      </div>778                    </div>779                  </Show>780                </div>781              </Show>782783              {/* ── Tags — read-only chips (editing state lives at bottom) */}784              <Show when={!editingTags() && entry().tags && entry().tags!.length > 0}>785                <div786                  style="display:flex;flex-wrap:wrap;gap:5px;margin:2px 0;position:relative;z-index:1;cursor:pointer;"787                  onClick={startEditTags}788                  title="Click to edit tags"789                >790                  <For each={entry().tags!}>791                    {(tag) => <span class="peach-tag-chip" style="font-size:10px;padding:2px 8px;">{tag}</span>}792                  </For>793                </div>794              </Show>795796              {/* ── Note toolbar + inline editor ─────────────────── */}797              <Show when={entry().type === "note"}>798                <div class="peach-entry-note-toolbar-row">799                  <Toolbar exec={noteExec} class="peach-note-toolbar-inline" />800                </div>801                <section class="peach-fields peach-note-body" style="position:relative;z-index:1;">802                  <NoteEditorInline803                    entryKey={entry().id}804                    initialContent={entry().notes ?? ""}805                    onReady={(el) => { setNoteEditorEl(el); lastSavedNote = null; }}806                    onBlur={saveNoteInline}807                    autoFocus={false}808                  />809                </section>810              </Show>811812              {/* ── Card detail view ─────────────────────────────── */}813              <Show when={entry().type === "card"}>814                <section class="peach-fields" style="position:relative;z-index:1;">815                  {/* Card subtitle: •••• last4 */}816                  <Show when={entry().last4}>817                    <div class="peach-field-card" style="padding-bottom:4px;">818                      <span class="peach-label">819                        <Show when={entry().network && entry().network !== "unknown"}>820                          <span class="peach-card-network-badge" style="margin-left:0;margin-right:6px;">{entry().network}</span>821                        </Show>822                        {entry().cardNickname || `•••• ${entry().last4}`}823                      </span>824                    </div>825                  </Show>826827                  {/* Cardholder name */}828                  <div class="peach-field-card">829                    <span class="peach-label">cardholder name</span>830                    <div class="peach-field-value-row">831                      <span class="peach-field-value">{entry().cardholderName || "—"}</span>832                      <Show when={entry().cardholderName}>833                        <button834                          class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "cardholderName" ? "is-copied" : ""}`}835                          onClick={(e) => void copyField(entry().cardholderName!, "cardholderName", e.currentTarget as HTMLButtonElement)}836                          aria-label="Copy cardholder name"837                        >838                          <CopyGlyph /><span class="peach-copy-sheen" />839                        </button>840                      </Show>841                    </div>842                  </div>843844                  {/* Card number */}845                  <div class="peach-field-card">846                    <span class="peach-label">card number</span>847                    <div class="peach-field-value-row">848                      <span class={`peach-field-value peach-card-number`}>849                        <Show when={showCardNumber()} fallback={850                          <span>{`•••• •••• •••• ${entry().last4 ?? "••••"}`}</span>851                        }>852                          <span>{entry().cardNumber ?? ""}</span>853                        </Show>854                      </span>855                      <div class="peach-field-actions">856                        <button857                          class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"858                          onClick={() => setShowCardNumber(!showCardNumber())}859                          aria-label={showCardNumber() ? "Hide card number" : "Reveal card number"}860                        >861                          <Show when={showCardNumber()} fallback={<EyeOpenGlyph />}>862                            <EyeClosedGlyph />863                          </Show>864                        </button>865                        <Show when={entry().cardNumber}>866                          <button867                            class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "cardNumber" ? "is-copied" : ""}`}868                            onClick={(e) => {869                              const cardNum = entry().cardNumber!;870                              if (entry().canary?.webhookUrl) {871                                void sendMessage({872                                  type: "FIRE_CANARY_PING",873                                  payload: { webhookUrl: entry().canary!.webhookUrl, entryTitle: entry().title, trigger: "password_copied" },874                                });875                              }876                              void copyField(cardNum, "cardNumber", e.currentTarget as HTMLButtonElement);877                            }}878                            aria-label="Copy card number"879                          >880                            <CopyGlyph /><span class="peach-copy-sheen" />881                          </button>882                        </Show>883                      </div>884                    </div>885                  </div>886887                  {/* Expiry */}888                  <Show when={entry().expMonth || entry().expYear}>889                    <div class="peach-field-card">890                      <span class="peach-label">expiry</span>891                      <div class="peach-field-value-row">892                        <span class="peach-field-value">{entry().expMonth} / {entry().expYear}</span>893                        <button894                          class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "expiry" ? "is-copied" : ""}`}895                          onClick={(e) => void copyField(`${entry().expMonth}/${entry().expYear}`, "expiry", e.currentTarget as HTMLButtonElement)}896                          aria-label="Copy expiry"897                        >898                          <CopyGlyph /><span class="peach-copy-sheen" />899                        </button>900                      </div>901                    </div>902                  </Show>903904                  {/* CVC */}905                  <Show when={entry().cvc}>906                    <div class="peach-field-card">907                      <span class="peach-label">CVC</span>908                      <div class="peach-field-value-row">909                        <span class="peach-field-value">910                          <Show when={showCardCvc()} fallback={<span class="peach-password-mask">•••</span>}>911                            <span>{entry().cvc}</span>912                          </Show>913                        </span>914                        <div class="peach-field-actions">915                          <button916                            class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"917                            onClick={() => setShowCardCvc(!showCardCvc())}918                            aria-label={showCardCvc() ? "Hide CVC" : "Show CVC"}919                          >920                            <Show when={showCardCvc()} fallback={<EyeOpenGlyph />}>921                              <EyeClosedGlyph />922                            </Show>923                          </button>924                          <button925                            class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "cvc" ? "is-copied" : ""}`}926                            onClick={(e) => void copyField(entry().cvc!, "cvc", e.currentTarget as HTMLButtonElement)}927                            aria-label="Copy CVC"928                          >929                            <CopyGlyph /><span class="peach-copy-sheen" />930                          </button>931                        </div>932                      </div>933                    </div>934                  </Show>935                </section>936              </Show>937938              {/* ── Login fields ─────────────────────────────────── */}939              <Show when={entry().type !== "note" && entry().type !== "card" && !isPasskeyOnly(entry())}>940                <section class="peach-fields" style="position:relative;z-index:1;">941942                  {/* Username — primary identity slot. Auto-labels as "email"943                      when the stored value is email-shaped and no separate944                      email field exists (legacy data path). */}945                  <Show when={entry().username || (!entry().username && !entry().email) || editingField() === "username"}>946                    <div class="peach-field-card" classList={{ "is-editing": editingField() === "username" }}>947                      <span class="peach-label">{entry().username?.includes("@") && !entry().email ? "email" : "username"}</span>948                      <Show949                        when={editingField() === "username"}950                        fallback={951                          <div class="peach-field-value-row">952                            <span953                              class="peach-field-value peach-inline-clickable"954                              title="Click to edit"955                              onClick={() => startEdit("username", entry().username ?? "")}956                            >957                              {entry().username || <span style="color:var(--t2);font-style:italic;">click to add username</span>}958                            </span>959                            <Show when={entry().username}>960                              <button961                                class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "username" ? "is-copied" : ""}`}962                                onClick={(e) => void copyField(entry().username!, "username", e.currentTarget as HTMLButtonElement)}963                                aria-label="Copy username"964                              >965                                <CopyGlyph /><span class="peach-copy-sheen" />966                              </button>967                            </Show>968                          </div>969                        }970                      >971                        <div972                          class="peach-inline-field-wrap"973                          onFocusOut={(event) => handleEditorFocusOut("username", event)}974                        >975                          <input976                            class="peach-inline-input"977                            value={draft()}978                            onInput={(e) => setDraft(e.currentTarget.value)}979                            onKeyDown={(e) => identityKeyDown(e, "username")}980                            ref={(el) => { usernameInlineInput = el; autoFocus(el); }}981                            disabled={saving()}982                            autocomplete="off"983                          />984                          <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />985                          <Show when={!identityHelperSuppressed() && identitySuggestions().length > 0 && editingField() === "username"}>986                            <IdentitySuggestList987                              listRef={(el) => (usernameIdentityEl = el)}988                              inputRef={() => usernameInlineInput}989                              suggestions={identitySuggestions()}990                              onPick={(v) => { setDraft(v); setIdentityHelperSuppressed(true); usernameInlineInput?.focus(); }}991                              onClose={() => { setIdentityHelperSuppressed(true); usernameInlineInput?.focus(); }}992                            />993                          </Show>994                          {/* +add the OTHER identity. If the slot is acting as995                              email (value has @, no separate email), offer996                              "+ add username" — clicking migrates the email997                              into entry.email. Otherwise offer "+ add email". */}998                          <Show when={!entry().email || !(entry().username && !entry().username?.includes("@"))}>999                            <button1000                              class="peach-add-field-btn"1001                              type="button"1002                              onMouseDown={(e) => e.preventDefault()}1003                              onClick={() => {1004                                const isEmailShape = draft().includes("@") || (entry().username?.includes("@") ?? false);1005                                const hasSeparateEmail = !!entry().email;1006                                if (isEmailShape && !hasSeparateEmail) {1007                                  void addOtherIdentity("username");1008                                } else {1009                                  void addOtherIdentity("email");1010                                }1011                              }}1012                            >1013                              {(() => {1014                                const isEmailShape = draft().includes("@") || (entry().username?.includes("@") ?? false);1015                                const hasSeparateEmail = !!entry().email;1016                                return (isEmailShape && !hasSeparateEmail) || hasSeparateEmail ? "+ add username" : "+ add email";1017                              })()}1018                            </button>1019                          </Show>1020                        </div>1021                      </Show>1022                    </div>1023                  </Show>10241025                  {/* Email — secondary identity slot. Visible whenever a1026                      separate email field is set, or while it is being edited. */}1027                  <Show when={entry().email || editingField() === "email"}>1028                    <div class="peach-field-card" classList={{ "is-editing": editingField() === "email" }}>1029                      <span class="peach-label">email</span>1030                      <Show1031                        when={editingField() === "email"}1032                        fallback={1033                          <div class="peach-field-value-row">1034                            <span1035                              class="peach-field-value peach-inline-clickable"1036                              title="Click to edit"1037                              onClick={() => startEdit("email", entry().email ?? "")}1038                            >1039                              {entry().email}1040                            </span>1041                            <Show when={entry().email}>1042                              <button1043                                class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "email" ? "is-copied" : ""}`}1044                                onClick={(e) => void copyField(entry().email!, "email", e.currentTarget as HTMLButtonElement)}1045                                aria-label="Copy email"1046                              >1047                                <CopyGlyph /><span class="peach-copy-sheen" />1048                              </button>1049                            </Show>1050                          </div>1051                        }1052                      >1053                        <div1054                          class="peach-inline-field-wrap"1055                          onFocusOut={(event) => handleEditorFocusOut("email", event)}1056                        >1057                          <input1058                            class="peach-inline-input"1059                            value={draft()}1060                            onInput={(e) => setDraft(e.currentTarget.value)}1061                            onKeyDown={(e) => identityKeyDown(e, "email")}1062                            ref={(el) => { emailInlineInput = el; autoFocus(el); }}1063                            disabled={saving()}1064                            autocomplete="email"1065                            type="email"1066                          />1067                          <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1068                          <Show when={!identityHelperSuppressed() && identitySuggestions().length > 0 && editingField() === "email"}>1069                            <IdentitySuggestList1070                              listRef={(el) => (emailIdentityEl = el)}1071                              inputRef={() => emailInlineInput}1072                              suggestions={identitySuggestions()}1073                              onPick={(v) => { setDraft(v); setIdentityHelperSuppressed(true); emailInlineInput?.focus(); }}1074                              onClose={() => { setIdentityHelperSuppressed(true); emailInlineInput?.focus(); }}1075                            />1076                          </Show>1077                          <Show when={!entry().username || entry().username?.includes("@")}>1078                            <button1079                              class="peach-add-field-btn"1080                              type="button"1081                              onMouseDown={(e) => e.preventDefault()}1082                              onClick={() => void addOtherIdentity("username")}1083                            >1084                              + add username1085                            </button>1086                          </Show>1087                        </div>1088                      </Show>1089                    </div>1090                  </Show>10911092                  {/* Password */}1093                  <div class="peach-field-card" classList={{ "is-editing": editingField() === "password" }}>1094                    <span class="peach-label">password</span>1095                    <Show1096                      when={editingField() === "password"}1097                      fallback={1098                        <div class="peach-field-value-row">1099                          <span1100                            class="peach-password-value"1101                            classList={{ "is-revealed": showPassword(), "is-breached": (entry().breach ?? 0) > 0 }}1102                            style="cursor:pointer;"1103                            title="Click to edit password"1104                            onClick={() => startEdit("password", entry().password ?? "")}1105                          >1106                            <Show1107                              when={showPassword()}1108                              fallback={<span class="peach-password-mask" aria-label="password hidden">••••••••••••••</span>}1109                            >1110                              <span class="peach-password-text">{entry().password ?? ""}</span>1111                            </Show>1112                          </span>1113                          <div class="peach-field-actions">1114                            <button1115                              class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1116                              onClick={() => setShowPassword(!showPassword())}1117                              aria-label="Reveal password"1118                            >1119                              <Show when={showPassword()} fallback={<EyeOpenGlyph />}>1120                                <EyeClosedGlyph />1121                              </Show>1122                            </button>1123                            <button1124                              class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === "password" ? "is-copied" : ""}`}1125                              onClick={(e) => { if (entry().password) void copyField(entry().password!, "password", e.currentTarget as HTMLButtonElement); }}1126                              aria-label="Copy password"1127                            >1128                              <CopyGlyph /><span class="peach-copy-sheen" />1129                            </button>1130                          </div>1131                        </div>1132                      }1133                    >1134                      {/* ── Edit mode: type / paste / generate ── */}1135                      <div1136                        class="peach-inline-field-wrap"1137                        onFocusOut={(event) => handleEditorFocusOut("password", event)}1138                      >1139                        <div class="peach-password-edit-row">1140                          <input1141                            class="peach-inline-input"1142                            type={showPassword() ? "text" : "password"}1143                            placeholder="paste or type a password"1144                            value={draft()}1145                            onInput={(e) => setDraft(e.currentTarget.value)}1146                            onKeyDown={(e) => {1147                              if (e.key === "Enter") { e.preventDefault(); void saveField(); }1148                              if (e.key === "Escape") { e.preventDefault(); cancelEdit(); }1149                            }}1150                            ref={autoFocus}1151                            disabled={saving()}1152                            autocomplete="new-password"1153                          />1154                          <button1155                            class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1156                            type="button"1157                            onClick={() => setShowPassword(!showPassword())}1158                            aria-label={showPassword() ? "Hide" : "Show"}1159                          >1160                            <Show when={showPassword()} fallback={<EyeOpenGlyph />}>1161                              <EyeClosedGlyph />1162                            </Show>1163                          </button>1164                        </div>1165                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1166                        <div class="peach-password-edit-links">1167                          <button1168                            class="peach-generate-toggle-link"1169                            type="button"1170                            onClick={() => { setShowGenerator(!showGenerator()); if (!showGenerator()) setShowHistory(false); }}1171                          >1172                            <svg width="10" height="10" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">1173                              <path d="M11 2.5A5.5 5.5 0 1 0 12.5 7" />1174                              <path d="M9.5 2.5H11V1" />1175                            </svg>1176                            {showGenerator() ? "hide generator" : "generate"}1177                          </button>1178                          <button1179                            class="peach-generate-toggle-link"1180                            type="button"1181                            onClick={() => { setShowHistory(!showHistory()); if (!showHistory()) setShowGenerator(false); }}1182                          >1183                            <svg width="10" height="10" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">1184                              <path d="M6.5 1a5.5 5.5 0 1 0 5.5 5.5" />1185                              <path d="M6.5 3.5V6.5L8.5 8" />1186                              <path d="M1 1.5V4H3.5" />1187                            </svg>1188                            {showHistory()1189                              ? "hide history"1190                              : (entry().passwordHistory?.length ? `history (${entry().passwordHistory!.length})` : "history")}1191                          </button>1192                        </div>1193                        <Show when={showGenerator()}>1194                          <GeneratorDrawer1195                            open={true}1196                            compact={true}1197                            onUse={(pw) => { setDraft(pw); setShowGenerator(false); }}1198                          />1199                        </Show>1200                        <Show when={showHistory()}>1201                          <div class="peach-password-history">1202                            <Show when={(entry().passwordHistory?.length ?? 0) === 0}>1203                              <div class="peach-history-empty">1204                                No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.1205                              </div>1206                            </Show>1207                            <For each={entry().passwordHistory ?? []}>1208                              {(item, i) => (1209                                <div class="peach-history-row">1210                                  <div class="peach-history-main">1211                                    <span class="peach-history-pw" classList={{ "is-revealed": revealedHistory().has(i()) }}>1212                                      <Show1213                                        when={revealedHistory().has(i())}1214                                        fallback={<span class="peach-password-mask">••••••••••••</span>}1215                                      >1216                                        {item.password}1217                                      </Show>1218                                    </span>1219                                    <span class="peach-history-age">{timeSince(item.changedAt)}</span>1220                                  </div>1221                                  <div class="peach-history-actions">1222                                    <button1223                                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1224                                      type="button"1225                                      title={revealedHistory().has(i()) ? "Hide" : "Reveal"}1226                                      onClick={() => setRevealedHistory((prev) => {1227                                        const next = new Set(prev);1228                                        if (next.has(i())) next.delete(i()); else next.add(i());1229                                        return next;1230                                      })}1231                                    >1232                                      <Show when={revealedHistory().has(i())} fallback={<EyeOpenGlyph />}>1233                                        <EyeClosedGlyph />1234                                      </Show>1235                                    </button>1236                                    <button1237                                      class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === `history-${i()}` ? "is-copied" : ""}`}1238                                      type="button"1239                                      title="Copy"1240                                      onClick={(e) => void copyField(item.password, `history-${i()}`, e.currentTarget as HTMLButtonElement)}1241                                    >1242                                      <CopyGlyph /><span class="peach-copy-sheen" />1243                                    </button>1244                                    <button1245                                      class="peach-btn peach-btn--ghost peach-btn--sm peach-history-use"1246                                      type="button"1247                                      title="Use this password again"1248                                      onClick={() => { setDraft(item.password); setShowPassword(true); setShowHistory(false); }}1249                                    >1250                                      use1251                                    </button>1252                                  </div>1253                                </div>1254                              )}1255                            </For>1256                          </div>1257                        </Show>1258                      </div>1259                    </Show>1260                  </div>12611262                </section>1263              </Show>12641265              {/* ── Notes (on login entries) ──────────────────────── */}1266              <Show when={entry().type !== "note" && entry().type !== "card"}>1267                <Show1268                  when={entry().notes || editingField() === "notes"}1269                  fallback={1270                    <button1271                      class="peach-add-field-link peach-entry-add-link"1272                      onClick={() => startEdit("notes", "")}1273                    >1274                      + notes1275                    </button>1276                  }1277                >1278                  <div style="position:relative;z-index:1;margin-top:6px;">1279                    <span class="peach-label" style="display:block;margin-bottom:4px;">notes</span>1280                    <Show1281                      when={editingField() === "notes"}1282                      fallback={1283                        <div1284                          class="peach-note-content peach-inline-clickable"1285                          style="cursor:text;white-space:pre-wrap;"1286                          onClick={() => startEdit("notes", entry().notes ?? "")}1287                        >1288                          {entry().notes}1289                        </div>1290                      }1291                    >1292                      <div1293                        class="peach-inline-field-wrap"1294                        onFocusOut={(event) => handleEditorFocusOut("notes", event)}1295                      >1296                        <textarea1297                          class="peach-inline-textarea"1298                          value={draft()}1299                          onInput={(e) => setDraft(e.currentTarget.value)}1300                          onKeyDown={(e) => { if (e.key === "Escape") { e.preventDefault(); cancelEdit(); } }}1301                          ref={(el) => requestAnimationFrame(() => el?.focus())}1302                          rows={4}1303                          disabled={saving()}1304                        />1305                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1306                      </div>1307                    </Show>1308                  </div>1309                </Show>1310              </Show>13111312              {/* ── Tags editor / add-tags link (between notes and TOTP) ─── */}1313              <Show1314                when={editingTags()}1315                fallback={1316                  <Show when={!entry().tags || entry().tags!.length === 0}>1317                    <button1318                      class="peach-add-field-link peach-entry-add-link"1319                      onClick={startEditTags}1320                    >1321                      + tags1322                    </button>1323                  </Show>1324                }1325              >1326                <div1327                  class="peach-inline-tag-editor"1328                  onFocusOut={(e) => {1329                    const next = e.relatedTarget;1330                    if (next instanceof Node && e.currentTarget.contains(next)) return;1331                    void saveTags();1332                  }}1333                >1334                  <span class="peach-label">tags</span>1335                  <div class="peach-tag-input-wrap">1336                    <For each={tagsDraft()}>1337                      {(tag) => (1338                        <span class="peach-tag-chip">1339                          {tag}1340                          <button1341                            class="peach-tag-chip-remove"1342                            onMouseDown={(e) => e.preventDefault()}1343                            onClick={() => setTagsDraft(tagsDraft().filter(t => t !== tag))}1344                            aria-label={`Remove ${tag}`}1345                          >×</button>1346                        </span>1347                      )}1348                    </For>1349                    <input1350                      class="peach-tag-input"1351                      placeholder={tagsDraft().length === 0 ? "type and press Enter…" : ""}1352                      value={tagInput()}1353                      onInput={(e) => setTagInput(e.currentTarget.value)}1354                      onKeyDown={(e) => {1355                        if (e.key === "Enter" || e.key === ",") {1356                          e.preventDefault();1357                          addTag(tagInput());1358                        } else if (e.key === "Backspace" && !tagInput() && tagsDraft().length > 0) {1359                          setTagsDraft(tagsDraft().slice(0, -1));1360                        } else if (e.key === "Escape") {1361                          e.preventDefault();1362                          setEditingTags(false);1363                          setTagInput("");1364                        }1365                      }}1366                      ref={(el) => requestAnimationFrame(() => el?.focus())}1367                      style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"1368                    />1369                  </div>1370                </div>1371              </Show>13721373              {/* ── TOTP ─────────────────────────────────────────── */}1374              <Show when={entry().type === "login"}>1375                <Show1376                  when={totpState() || editingField() === "totp"}1377                  fallback={1378                    <button1379                      class="peach-add-field-link peach-entry-add-link"1380                      onClick={() => startEdit("totp", "")}1381                    >1382                      + 2FA1383                    </button>1384                  }1385                >1386                  <section class="peach-totp-band">1387                    <Show1388                      when={editingField() === "totp"}1389                      fallback={1390                        <Show when={totpState()}>1391                          {(state) => (1392                            <>1393                              <div1394                                class="peach-totp-main"1395                                onClick={() => {1396                                  // Delay copy so a double-click can cancel it before1397                                  // it overwrites the clipboard the user wants to paste from.1398                                  if (totpClickTimer) return;1399                                  totpClickTimer = setTimeout(() => {1400                                    totpClickTimer = null;1401                                    void copyField(state().code.replace(" ", ""), "totp");1402                                  }, 220);1403                                }}1404                                onDblClick={() => {1405                                  if (totpClickTimer) { clearTimeout(totpClickTimer); totpClickTimer = null; }1406                                  startEdit("totp", entry().totp ?? "");1407                                }}1408                                title="Click to copy · double-click to edit"1409                              >1410                                <span class="peach-label">2-factor</span>1411                                <div class="peach-totp-code-row">1412                                  <p class={`peach-totp-code${totpHot() ? " is-hot" : ""}${copied() === "totp" ? " is-copied" : ""}`}>1413                                    <span class="peach-totp-code-text">1414                                      {state().code.slice(0, 3)} {state().code.slice(3)}1415                                    </span>1416                                  </p>1417                                </div>1418                              </div>1419                              <div class="peach-totp-meta">1420                                <span class="peach-label">expires</span>1421                                <div class="peach-totp-countdown">{state().remaining}s</div>1422                                <svg class="peach-totp-ring" width="44" height="44" viewBox="0 0 44 44">1423                                  <circle cx="22" cy="22" r="17" class="peach-totp-ring-track" />1424                                  <circle cx="22" cy="22" r="17" class="peach-totp-ring-progress"1425                                    stroke-dasharray="106.8"1426                                    stroke-dashoffset={(1 - state().remaining / 30) * 106.8}1427                                  />1428                                </svg>1429                              </div>1430                            </>1431                          )}1432                        </Show>1433                      }1434                    >1435                      <div1436                        class="peach-inline-field-wrap peach-inline-field-wrap--totp"1437                        onFocusOut={(event) => handleEditorFocusOut("totp", event)}1438                      >1439                        <span class="peach-label">2-factor</span>1440                        <input1441                          class="peach-inline-input"1442                          value={draft()}1443                          onInput={(e) => setDraft(e.currentTarget.value)}1444                          onKeyDown={onEditKeyDown}1445                          ref={autoFocus}1446                          disabled={saving()}1447                          placeholder="otpauth://... or base32 secret"1448                          autocomplete="off"1449                        />1450                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1451                      </div>1452                    </Show>1453                  </section>1454                </Show>1455              </Show>14561457              {/* ── Advanced (canary + passkey) ───────────────────── */}1458              <Show when={entry().type === "login"}>1459                <button1460                  class="peach-add-field-link peach-entry-add-link"1461                  onClick={() => setShowAdvanced((v) => !v)}1462                  aria-expanded={showAdvanced()}1463                >1464                  {showAdvanced() ? "− Advanced" : "+ Advanced"}1465                </button>1466                <Show when={showAdvanced()}>1467                  <Show when={!isPasskeyOnly(entry())}>1468                    <CanarySection entry={entry()} onSaved={props.onFieldSaved} isPro={props.isPro ?? false} onProGate={props.onProGate} />1469                  </Show>14701471                  <Show when={entry().passkey}>1472                    {(passkey) => {1473                      const currentBrowser = detectBrowser();1474                      const crossBrowser =1475                        passkey().browser &&1476                        currentBrowser !== "unknown" &&1477                        passkey().browser !== currentBrowser;1478                      const algorithmLabel =1479                        passkey().algorithm === -8 ? "EdDSA (Ed25519)" : "ES256 (P-256)";1480                      const formatDate = (ts?: number) =>1481                        ts ? new Date(ts).toLocaleDateString() : "Never";1482                      return (1483                        <section1484                          class="peach-fields peach-passkey-section"1485                          style="position:relative;z-index:1;margin-top:6px;"1486                        >1487                          <div class="peach-field-card">1488                            <span class="peach-label">passkey · {passkey().rpId}</span>1489                            <div class="peach-field-value-row">1490                              <span class="peach-field-value">{passkey().userName}</span>1491                              <span class="peach-passkey-badge">passkey</span>1492                            </div>1493                          </div>14941495                          <div class="peach-field-card">1496                            <span class="peach-label">algorithm</span>1497                            <div class="peach-field-value-row">1498                              <span class="peach-field-value">{algorithmLabel}</span>1499                            </div>1500                          </div>15011502                          <div class="peach-field-card">1503                            <span class="peach-label">activity</span>1504                            <div class="peach-field-value-row peach-passkey-activity">1505                              <span class="peach-field-value">1506                                used {passkey().signCount} time{passkey().signCount === 1 ? "" : "s"}1507                              </span>1508                              <span class="peach-passkey-meta">1509                                created {formatDate(passkey().createdAt)}1510                              </span>1511                              <span class="peach-passkey-meta">1512                                last used {formatDate(passkey().lastUsedAt)}1513                              </span>1514                            </div>1515                          </div>15161517                          <Show when={crossBrowser}>1518                            <div class="peach-info-notice peach-info-notice--warn">1519                              {`This passkey was created on ${1520                                passkey().browser === "chrome" ? "Chrome" : "Firefox"1521                              }. To use it on ${1522                                currentBrowser === "chrome" ? "Chrome" : "Firefox"1523                              }, re-register it on this device.`}1524                            </div>1525                          </Show>15261527                          <div class="peach-info-notice">1528                            {passkey().browser === "firefox"1529                              ? "This passkey is held by your platform authenticator. Peach stores only the metadata."1530                              : "The private key is stored encrypted in your Peach vault and is never shown in the UI."}1531                          </div>15321533                          <button1534                            class="peach-add-field-link peach-entry-add-link"1535                            style="color:rgba(220,38,38,0.7);"1536                            onClick={async () => {1537                              const id = entry().id;1538                              await sendMessage({1539                                type: "UPDATE_ENTRY",1540                                payload: { id, patch: { passkey: undefined } },1541                              });1542                              await props.onFieldSaved();1543                            }}1544                          >1545                            − remove passkey1546                          </button>1547                        </section>1548                      );1549                    }}1550                  </Show>1551                </Show>1552              </Show>15531554              {/* ── Bottom spacer ─────────────────────────────────── */}1555              <div style="height:4px;" />1556            </>1557          )}1558        </Show>1559      </div>15601561    </>1562  );1563}15641565// ── Sub-components ────────────────────────────────────────────────────15661567function InlineSaveCancelRow(props: { onSave: () => void; onCancel: () => void; saving: boolean }) {1568  return (1569    <div class="peach-inline-actions">1570      <button1571        class="peach-inline-save-btn"1572        onClick={props.onSave}1573        disabled={props.saving}1574        aria-label="Save"1575        title="Save (Enter)"1576      >1577        <svg width="11" height="9" viewBox="0 0 11 9" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">1578          <path d="M1 4.5L4 7.5L10 1.5" />1579        </svg>1580      </button>1581      <button1582        class="peach-inline-cancel-btn"1583        onClick={props.onCancel}1584        disabled={props.saving}1585        aria-label="Cancel"1586        title="Cancel (Esc)"1587      >1588        <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">1589          <path d="M1 1L8 8M8 1L1 8" />1590        </svg>1591      </button>1592    </div>1593  );1594}15951596function EmptyVaultState() {1597  return (1598    <>1599      <div class="peach-entry-name-wrap" style="position:relative;z-index:1;">1600        <div class="peach-entry-name">1601          <span class="peach-entry-name-text">1602            <span class="peach-entry-name-char" style="--char-index:0">e</span>1603            <span class="peach-entry-name-char" style="--char-index:1">m</span>1604            <span class="peach-entry-name-char" style="--char-index:2">p</span>1605            <span class="peach-entry-name-char" style="--char-index:3">t</span>1606            <span class="peach-entry-name-char" style="--char-index:4">y</span>1607          </span>1608        </div>1609      </div>1610      <div class="peach-empty-copy">1611        <span class="peach-label">vault</span>1612        <p>Your vault is ready for its first entry.</p>1613      </div>1614    </>1615  );1616}16171618function CopyGlyph() {1619  return (1620    <span class="peach-copy-icon">1621      <svg class="peach-copy-icon-svg" width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">1622        <rect x="4" y="4" width="8" height="9" rx="1.5" />1623        <path d="M10 4V2.5A1.5 1.5 0 0 0 8.5 1h-6A1.5 1.5 0 0 0 1 2.5v7A1.5 1.5 0 0 0 2.5 11H4" />1624      </svg>1625    </span>1626  );1627}16281629function EyeClosedGlyph() {1630  return (1631    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">1632      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />1633      <path d="M3.5 5.5L2.5 7.5" />1634      <path d="M7 6.5V8.5" />1635      <path d="M10.5 5.5L11.5 7.5" />1636    </svg>1637  );1638}16391640function EyeOpenGlyph() {1641  return (1642    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">1643      <path d="M1 5C1 5 2.8 1 7 1C11.2 1 13 5 13 5C13 5 11.2 9 7 9C2.8 9 1 5 1 5Z" />1644      <circle cx="7" cy="5" r="1.75" />1645    </svg>1646  );1647}16481649function CanarySection(props: { entry: VaultEntry; onSaved: () => void | Promise<void>; isPro: boolean; onProGate?: (feature: ProFeature) => void }) {1650  const [enabled, setEnabled] = createSignal(Boolean(props.entry.canary));1651  const [webhookUrl, setWebhookUrl] = createSignal(props.entry.canary?.webhookUrl ?? "");1652  const [label, setLabel] = createSignal(props.entry.canary?.label ?? "");1653  const [testResult, setTestResult] = createSignal<string | null>(null);1654  const [testing, setTesting] = createSignal(false);16551656  // Pro gate entry-point for canary creation. Free users cannot toggle the1657  // canary on; the server-side UPDATE_ENTRY handler is the single hard1658  // enforcement point, but this branch avoids the bad UX of letting the1659  // toggle slip into "on" before the save rejects. Existing canary entries1660  // (e.g. retained after a license deactivation, future-proofing) remain1661  // togglable off — gating only applies to enabling a new canary.1662  const isProGated = () => !props.isPro && !props.entry.canary;16631664  async function save() {1665    const url = webhookUrl().trim();1666    const nextLabel = label().trim() || undefined;1667    const canary = enabled() && url1668      ? {1669          webhookUrl: url,1670          label: nextLabel,1671          lastPinged: props.entry.canary?.lastPinged,1672          pingCount: props.entry.canary?.pingCount,1673        }1674      : undefined;1675    await sendMessage({1676      type: "UPDATE_ENTRY",1677      payload: { id: props.entry.id, patch: { canary } },1678    });1679    await props.onSaved();1680  }16811682  async function testPing() {1683    const url = webhookUrl().trim();1684    if (!url) return;1685    setTesting(true);1686    setTestResult(null);1687    const res = await sendMessage({1688      type: "FIRE_CANARY_PING",1689      payload: { webhookUrl: url, entryTitle: props.entry.title, trigger: "test" },1690    }) as { ok: boolean; error?: string };1691    setTestResult(res.ok ? "sent ✓" : `failed — ${res.error ?? "check URL"}`);1692    setTesting(false);1693  }16941695  return (1696    <div class="peach-canary-section">1697      <div class="peach-field-value-row">1698        <span class="peach-field-value" style="font-size:12px;">1699          canary alert1700          <Show when={isProGated()}>1701            <span class="peach-pro-mark" aria-label="Pro feature" style="margin-left:6px">✦</span>1702          </Show>1703        </span>1704        <button1705          class={`peach-toggle ${enabled() ? "is-on" : ""}`}1706          onClick={() => {1707            if (isProGated()) {1708              // Pro gate: tap on free tier navigates to the upgrade screen1709              // with Canary Entries highlighted. The toggle never flips on1710              // for a free user, regardless of click count.1711              props.onProGate?.("canary_entry");1712              return;1713            }1714            setEnabled(!enabled());1715            void save();1716          }}1717          aria-label="Toggle canary"1718          aria-disabled={isProGated() ? "true" : "false"}1719        >1720          <span class="peach-toggle-knob" />1721        </button>1722      </div>1723      <p style="font-size:10px;color:var(--peach-t2);margin:4px 0 0;line-height:1.5;">1724        Fires a silent webhook when this entry's password or username is copied. Great for honeypot credentials.1725      </p>1726      <Show when={enabled()}>1727        <div class="peach-inline-field-wrap" style="margin-top:8px;">1728          <input1729            class="peach-inline-input"1730            placeholder="https://hooks.zapier.com/..."1731            value={webhookUrl()}1732            onInput={(e) => setWebhookUrl(e.currentTarget.value)}1733            onBlur={() => void save()}1734          />1735          <p style="font-size:10px;color:var(--peach-t2);margin:4px 0 0;line-height:1.5;">1736            When triggered, the entry title is sent to this URL. Use an endpoint you control.1737          </p>1738          <input1739            class="peach-inline-input"1740            placeholder="label (optional, e.g. AWS decoy)"1741            value={label()}1742            onInput={(e) => setLabel(e.currentTarget.value)}1743            onBlur={() => void save()}1744          />1745          <div style="display:flex;align-items:center;gap:8px;margin-top:4px;">1746            <button1747              class="peach-btn peach-btn--ghost peach-btn--sm"1748              onClick={() => void testPing()}1749              disabled={testing() || !webhookUrl().trim()}1750            >1751              {testing() ? "sending..." : "test ping"}1752            </button>1753            <Show when={testResult()}>1754              <span style="font-size:10px;color:var(--peach-t2);font-family:var(--font-mono);">{testResult()}</span>1755            </Show>1756          </div>1757          <Show when={props.entry.canary?.lastPinged}>1758            <p style="font-size:10px;color:var(--peach-t2);margin-top:4px;">1759              Last triggered: {new Date(props.entry.canary!.lastPinged!).toLocaleDateString()}1760              {" · "}{props.entry.canary?.pingCount ?? 0} total alerts1761            </p>1762          </Show>1763        </div>1764      </Show>1765    </div>1766  );1767}