Entry.tsx

80.4 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                          <Show when={(entry().passwordHistory?.length ?? 0) > 0}>1179                            <button1180                              class="peach-generate-toggle-link"1181                              type="button"1182                              onClick={() => { setShowHistory(!showHistory()); if (!showHistory()) setShowGenerator(false); }}1183                            >1184                              <svg width="10" height="10" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">1185                                <path d="M6.5 1a5.5 5.5 0 1 0 5.5 5.5" />1186                                <path d="M6.5 3.5V6.5L8.5 8" />1187                                <path d="M1 1.5V4H3.5" />1188                              </svg>1189                              {showHistory() ? "hide history" : `history (${entry().passwordHistory!.length})`}1190                            </button>1191                          </Show>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                            <For each={entry().passwordHistory ?? []}>1203                              {(item, i) => (1204                                <div class="peach-history-row">1205                                  <div class="peach-history-main">1206                                    <span class="peach-history-pw" classList={{ "is-revealed": revealedHistory().has(i()) }}>1207                                      <Show1208                                        when={revealedHistory().has(i())}1209                                        fallback={<span class="peach-password-mask">••••••••••••</span>}1210                                      >1211                                        {item.password}1212                                      </Show>1213                                    </span>1214                                    <span class="peach-history-age">{timeSince(item.changedAt)}</span>1215                                  </div>1216                                  <div class="peach-history-actions">1217                                    <button1218                                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1219                                      type="button"1220                                      title={revealedHistory().has(i()) ? "Hide" : "Reveal"}1221                                      onClick={() => setRevealedHistory((prev) => {1222                                        const next = new Set(prev);1223                                        if (next.has(i())) next.delete(i()); else next.add(i());1224                                        return next;1225                                      })}1226                                    >1227                                      <Show when={revealedHistory().has(i())} fallback={<EyeOpenGlyph />}>1228                                        <EyeClosedGlyph />1229                                      </Show>1230                                    </button>1231                                    <button1232                                      class={`peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-copy-btn ${copied() === `history-${i()}` ? "is-copied" : ""}`}1233                                      type="button"1234                                      title="Copy"1235                                      onClick={(e) => void copyField(item.password, `history-${i()}`, e.currentTarget as HTMLButtonElement)}1236                                    >1237                                      <CopyGlyph /><span class="peach-copy-sheen" />1238                                    </button>1239                                    <button1240                                      class="peach-btn peach-btn--ghost peach-btn--sm peach-history-use"1241                                      type="button"1242                                      title="Use this password again"1243                                      onClick={() => { setDraft(item.password); setShowPassword(true); setShowHistory(false); }}1244                                    >1245                                      use1246                                    </button>1247                                  </div>1248                                </div>1249                              )}1250                            </For>1251                          </div>1252                        </Show>1253                      </div>1254                    </Show>1255                  </div>12561257                </section>1258              </Show>12591260              {/* ── Notes (on login entries) ──────────────────────── */}1261              <Show when={entry().type !== "note" && entry().type !== "card"}>1262                <Show1263                  when={entry().notes || editingField() === "notes"}1264                  fallback={1265                    <button1266                      class="peach-add-field-link peach-entry-add-link"1267                      onClick={() => startEdit("notes", "")}1268                    >1269                      + notes1270                    </button>1271                  }1272                >1273                  <div style="position:relative;z-index:1;margin-top:6px;">1274                    <span class="peach-label" style="display:block;margin-bottom:4px;">notes</span>1275                    <Show1276                      when={editingField() === "notes"}1277                      fallback={1278                        <div1279                          class="peach-note-content peach-inline-clickable"1280                          style="cursor:text;white-space:pre-wrap;"1281                          onClick={() => startEdit("notes", entry().notes ?? "")}1282                        >1283                          {entry().notes}1284                        </div>1285                      }1286                    >1287                      <div1288                        class="peach-inline-field-wrap"1289                        onFocusOut={(event) => handleEditorFocusOut("notes", event)}1290                      >1291                        <textarea1292                          class="peach-inline-textarea"1293                          value={draft()}1294                          onInput={(e) => setDraft(e.currentTarget.value)}1295                          onKeyDown={(e) => { if (e.key === "Escape") { e.preventDefault(); cancelEdit(); } }}1296                          ref={(el) => requestAnimationFrame(() => el?.focus())}1297                          rows={4}1298                          disabled={saving()}1299                        />1300                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1301                      </div>1302                    </Show>1303                  </div>1304                </Show>1305              </Show>13061307              {/* ── Tags editor / add-tags link (between notes and TOTP) ─── */}1308              <Show1309                when={editingTags()}1310                fallback={1311                  <Show when={!entry().tags || entry().tags!.length === 0}>1312                    <button1313                      class="peach-add-field-link peach-entry-add-link"1314                      onClick={startEditTags}1315                    >1316                      + tags1317                    </button>1318                  </Show>1319                }1320              >1321                <div1322                  class="peach-inline-tag-editor"1323                  onFocusOut={(e) => {1324                    const next = e.relatedTarget;1325                    if (next instanceof Node && e.currentTarget.contains(next)) return;1326                    void saveTags();1327                  }}1328                >1329                  <span class="peach-label">tags</span>1330                  <div class="peach-tag-input-wrap">1331                    <For each={tagsDraft()}>1332                      {(tag) => (1333                        <span class="peach-tag-chip">1334                          {tag}1335                          <button1336                            class="peach-tag-chip-remove"1337                            onMouseDown={(e) => e.preventDefault()}1338                            onClick={() => setTagsDraft(tagsDraft().filter(t => t !== tag))}1339                            aria-label={`Remove ${tag}`}1340                          >×</button>1341                        </span>1342                      )}1343                    </For>1344                    <input1345                      class="peach-tag-input"1346                      placeholder={tagsDraft().length === 0 ? "type and press Enter…" : ""}1347                      value={tagInput()}1348                      onInput={(e) => setTagInput(e.currentTarget.value)}1349                      onKeyDown={(e) => {1350                        if (e.key === "Enter" || e.key === ",") {1351                          e.preventDefault();1352                          addTag(tagInput());1353                        } else if (e.key === "Backspace" && !tagInput() && tagsDraft().length > 0) {1354                          setTagsDraft(tagsDraft().slice(0, -1));1355                        } else if (e.key === "Escape") {1356                          e.preventDefault();1357                          setEditingTags(false);1358                          setTagInput("");1359                        }1360                      }}1361                      ref={(el) => requestAnimationFrame(() => el?.focus())}1362                      style="flex:1;min-width:80px;background:transparent;border:none;outline:none;color:var(--t1);font-size:12px;padding:2px;"1363                    />1364                  </div>1365                </div>1366              </Show>13671368              {/* ── TOTP ─────────────────────────────────────────── */}1369              <Show when={entry().type === "login"}>1370                <Show1371                  when={totpState() || editingField() === "totp"}1372                  fallback={1373                    <button1374                      class="peach-add-field-link peach-entry-add-link"1375                      onClick={() => startEdit("totp", "")}1376                    >1377                      + 2FA1378                    </button>1379                  }1380                >1381                  <section class="peach-totp-band">1382                    <Show1383                      when={editingField() === "totp"}1384                      fallback={1385                        <Show when={totpState()}>1386                          {(state) => (1387                            <>1388                              <div1389                                class="peach-totp-main"1390                                onClick={() => {1391                                  // Delay copy so a double-click can cancel it before1392                                  // it overwrites the clipboard the user wants to paste from.1393                                  if (totpClickTimer) return;1394                                  totpClickTimer = setTimeout(() => {1395                                    totpClickTimer = null;1396                                    void copyField(state().code.replace(" ", ""), "totp");1397                                  }, 220);1398                                }}1399                                onDblClick={() => {1400                                  if (totpClickTimer) { clearTimeout(totpClickTimer); totpClickTimer = null; }1401                                  startEdit("totp", entry().totp ?? "");1402                                }}1403                                title="Click to copy · double-click to edit"1404                              >1405                                <span class="peach-label">2-factor</span>1406                                <div class="peach-totp-code-row">1407                                  <p class={`peach-totp-code${totpHot() ? " is-hot" : ""}${copied() === "totp" ? " is-copied" : ""}`}>1408                                    <span class="peach-totp-code-text">1409                                      {state().code.slice(0, 3)} {state().code.slice(3)}1410                                    </span>1411                                  </p>1412                                </div>1413                              </div>1414                              <div class="peach-totp-meta">1415                                <span class="peach-label">expires</span>1416                                <div class="peach-totp-countdown">{state().remaining}s</div>1417                                <svg class="peach-totp-ring" width="44" height="44" viewBox="0 0 44 44">1418                                  <circle cx="22" cy="22" r="17" class="peach-totp-ring-track" />1419                                  <circle cx="22" cy="22" r="17" class="peach-totp-ring-progress"1420                                    stroke-dasharray="106.8"1421                                    stroke-dashoffset={(1 - state().remaining / 30) * 106.8}1422                                  />1423                                </svg>1424                              </div>1425                            </>1426                          )}1427                        </Show>1428                      }1429                    >1430                      <div1431                        class="peach-inline-field-wrap peach-inline-field-wrap--totp"1432                        onFocusOut={(event) => handleEditorFocusOut("totp", event)}1433                      >1434                        <span class="peach-label">2-factor</span>1435                        <input1436                          class="peach-inline-input"1437                          value={draft()}1438                          onInput={(e) => setDraft(e.currentTarget.value)}1439                          onKeyDown={onEditKeyDown}1440                          ref={autoFocus}1441                          disabled={saving()}1442                          placeholder="otpauth://... or base32 secret"1443                          autocomplete="off"1444                        />1445                        <InlineSaveCancelRow onSave={saveField} onCancel={cancelEdit} saving={saving()} />1446                      </div>1447                    </Show>1448                  </section>1449                </Show>1450              </Show>14511452              {/* ── Advanced (canary + passkey) ───────────────────── */}1453              <Show when={entry().type === "login"}>1454                <button1455                  class="peach-add-field-link peach-entry-add-link"1456                  onClick={() => setShowAdvanced((v) => !v)}1457                  aria-expanded={showAdvanced()}1458                >1459                  {showAdvanced() ? "− Advanced" : "+ Advanced"}1460                </button>1461                <Show when={showAdvanced()}>1462                  <Show when={!isPasskeyOnly(entry())}>1463                    <CanarySection entry={entry()} onSaved={props.onFieldSaved} isPro={props.isPro ?? false} onProGate={props.onProGate} />1464                  </Show>14651466                  <Show when={entry().passkey}>1467                    {(passkey) => {1468                      const currentBrowser = detectBrowser();1469                      const crossBrowser =1470                        passkey().browser &&1471                        currentBrowser !== "unknown" &&1472                        passkey().browser !== currentBrowser;1473                      const algorithmLabel =1474                        passkey().algorithm === -8 ? "EdDSA (Ed25519)" : "ES256 (P-256)";1475                      const formatDate = (ts?: number) =>1476                        ts ? new Date(ts).toLocaleDateString() : "Never";1477                      return (1478                        <section1479                          class="peach-fields peach-passkey-section"1480                          style="position:relative;z-index:1;margin-top:6px;"1481                        >1482                          <div class="peach-field-card">1483                            <span class="peach-label">passkey · {passkey().rpId}</span>1484                            <div class="peach-field-value-row">1485                              <span class="peach-field-value">{passkey().userName}</span>1486                              <span class="peach-passkey-badge">passkey</span>1487                            </div>1488                          </div>14891490                          <div class="peach-field-card">1491                            <span class="peach-label">algorithm</span>1492                            <div class="peach-field-value-row">1493                              <span class="peach-field-value">{algorithmLabel}</span>1494                            </div>1495                          </div>14961497                          <div class="peach-field-card">1498                            <span class="peach-label">activity</span>1499                            <div class="peach-field-value-row peach-passkey-activity">1500                              <span class="peach-field-value">1501                                used {passkey().signCount} time{passkey().signCount === 1 ? "" : "s"}1502                              </span>1503                              <span class="peach-passkey-meta">1504                                created {formatDate(passkey().createdAt)}1505                              </span>1506                              <span class="peach-passkey-meta">1507                                last used {formatDate(passkey().lastUsedAt)}1508                              </span>1509                            </div>1510                          </div>15111512                          <Show when={crossBrowser}>1513                            <div class="peach-info-notice peach-info-notice--warn">1514                              {`This passkey was created on ${1515                                passkey().browser === "chrome" ? "Chrome" : "Firefox"1516                              }. To use it on ${1517                                currentBrowser === "chrome" ? "Chrome" : "Firefox"1518                              }, re-register it on this device.`}1519                            </div>1520                          </Show>15211522                          <div class="peach-info-notice">1523                            {passkey().browser === "firefox"1524                              ? "This passkey is held by your platform authenticator. Peach stores only the metadata."1525                              : "The private key is stored encrypted in your Peach vault and is never shown in the UI."}1526                          </div>15271528                          <button1529                            class="peach-add-field-link peach-entry-add-link"1530                            style="color:rgba(220,38,38,0.7);"1531                            onClick={async () => {1532                              const id = entry().id;1533                              await sendMessage({1534                                type: "UPDATE_ENTRY",1535                                payload: { id, patch: { passkey: undefined } },1536                              });1537                              await props.onFieldSaved();1538                            }}1539                          >1540                            − remove passkey1541                          </button>1542                        </section>1543                      );1544                    }}1545                  </Show>1546                </Show>1547              </Show>15481549              {/* ── Bottom spacer ─────────────────────────────────── */}1550              <div style="height:4px;" />1551            </>1552          )}1553        </Show>1554      </div>15551556    </>1557  );1558}15591560// ── Sub-components ────────────────────────────────────────────────────15611562function InlineSaveCancelRow(props: { onSave: () => void; onCancel: () => void; saving: boolean }) {1563  return (1564    <div class="peach-inline-actions">1565      <button1566        class="peach-inline-save-btn"1567        onClick={props.onSave}1568        disabled={props.saving}1569        aria-label="Save"1570        title="Save (Enter)"1571      >1572        <svg width="11" height="9" viewBox="0 0 11 9" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">1573          <path d="M1 4.5L4 7.5L10 1.5" />1574        </svg>1575      </button>1576      <button1577        class="peach-inline-cancel-btn"1578        onClick={props.onCancel}1579        disabled={props.saving}1580        aria-label="Cancel"1581        title="Cancel (Esc)"1582      >1583        <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">1584          <path d="M1 1L8 8M8 1L1 8" />1585        </svg>1586      </button>1587    </div>1588  );1589}15901591function EmptyVaultState() {1592  return (1593    <>1594      <div class="peach-entry-name-wrap" style="position:relative;z-index:1;">1595        <div class="peach-entry-name">1596          <span class="peach-entry-name-text">1597            <span class="peach-entry-name-char" style="--char-index:0">e</span>1598            <span class="peach-entry-name-char" style="--char-index:1">m</span>1599            <span class="peach-entry-name-char" style="--char-index:2">p</span>1600            <span class="peach-entry-name-char" style="--char-index:3">t</span>1601            <span class="peach-entry-name-char" style="--char-index:4">y</span>1602          </span>1603        </div>1604      </div>1605      <div class="peach-empty-copy">1606        <span class="peach-label">vault</span>1607        <p>Your vault is ready for its first entry.</p>1608      </div>1609    </>1610  );1611}16121613function CopyGlyph() {1614  return (1615    <span class="peach-copy-icon">1616      <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">1617        <rect x="4" y="4" width="8" height="9" rx="1.5" />1618        <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" />1619      </svg>1620    </span>1621  );1622}16231624function EyeClosedGlyph() {1625  return (1626    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">1627      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />1628      <path d="M3.5 5.5L2.5 7.5" />1629      <path d="M7 6.5V8.5" />1630      <path d="M10.5 5.5L11.5 7.5" />1631    </svg>1632  );1633}16341635function EyeOpenGlyph() {1636  return (1637    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">1638      <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" />1639      <circle cx="7" cy="5" r="1.75" />1640    </svg>1641  );1642}16431644function CanarySection(props: { entry: VaultEntry; onSaved: () => void | Promise<void>; isPro: boolean; onProGate?: (feature: ProFeature) => void }) {1645  const [enabled, setEnabled] = createSignal(Boolean(props.entry.canary));1646  const [webhookUrl, setWebhookUrl] = createSignal(props.entry.canary?.webhookUrl ?? "");1647  const [label, setLabel] = createSignal(props.entry.canary?.label ?? "");1648  const [testResult, setTestResult] = createSignal<string | null>(null);1649  const [testing, setTesting] = createSignal(false);16501651  // Pro gate entry-point for canary creation. Free users cannot toggle the1652  // canary on; the server-side UPDATE_ENTRY handler is the single hard1653  // enforcement point, but this branch avoids the bad UX of letting the1654  // toggle slip into "on" before the save rejects. Existing canary entries1655  // (e.g. retained after a license deactivation, future-proofing) remain1656  // togglable off — gating only applies to enabling a new canary.1657  const isProGated = () => !props.isPro && !props.entry.canary;16581659  async function save() {1660    const url = webhookUrl().trim();1661    const nextLabel = label().trim() || undefined;1662    const canary = enabled() && url1663      ? {1664          webhookUrl: url,1665          label: nextLabel,1666          lastPinged: props.entry.canary?.lastPinged,1667          pingCount: props.entry.canary?.pingCount,1668        }1669      : undefined;1670    await sendMessage({1671      type: "UPDATE_ENTRY",1672      payload: { id: props.entry.id, patch: { canary } },1673    });1674    await props.onSaved();1675  }16761677  async function testPing() {1678    const url = webhookUrl().trim();1679    if (!url) return;1680    setTesting(true);1681    setTestResult(null);1682    const res = await sendMessage({1683      type: "FIRE_CANARY_PING",1684      payload: { webhookUrl: url, entryTitle: props.entry.title, trigger: "test" },1685    }) as { ok: boolean; error?: string };1686    setTestResult(res.ok ? "sent ✓" : `failed — ${res.error ?? "check URL"}`);1687    setTesting(false);1688  }16891690  return (1691    <div class="peach-canary-section">1692      <div class="peach-field-value-row">1693        <span class="peach-field-value" style="font-size:12px;">1694          canary alert1695          <Show when={isProGated()}>1696            <span class="peach-pro-mark" aria-label="Pro feature" style="margin-left:6px">✦</span>1697          </Show>1698        </span>1699        <button1700          class={`peach-toggle ${enabled() ? "is-on" : ""}`}1701          onClick={() => {1702            if (isProGated()) {1703              // Pro gate: tap on free tier navigates to the upgrade screen1704              // with Canary Entries highlighted. The toggle never flips on1705              // for a free user, regardless of click count.1706              props.onProGate?.("canary_entry");1707              return;1708            }1709            setEnabled(!enabled());1710            void save();1711          }}1712          aria-label="Toggle canary"1713          aria-disabled={isProGated() ? "true" : "false"}1714        >1715          <span class="peach-toggle-knob" />1716        </button>1717      </div>1718      <p style="font-size:10px;color:var(--peach-t2);margin:4px 0 0;line-height:1.5;">1719        Fires a silent webhook when this entry's password or username is copied. Great for honeypot credentials.1720      </p>1721      <Show when={enabled()}>1722        <div class="peach-inline-field-wrap" style="margin-top:8px;">1723          <input1724            class="peach-inline-input"1725            placeholder="https://hooks.zapier.com/..."1726            value={webhookUrl()}1727            onInput={(e) => setWebhookUrl(e.currentTarget.value)}1728            onBlur={() => void save()}1729          />1730          <p style="font-size:10px;color:var(--peach-t2);margin:4px 0 0;line-height:1.5;">1731            When triggered, the entry title is sent to this URL. Use an endpoint you control.1732          </p>1733          <input1734            class="peach-inline-input"1735            placeholder="label (optional, e.g. AWS decoy)"1736            value={label()}1737            onInput={(e) => setLabel(e.currentTarget.value)}1738            onBlur={() => void save()}1739          />1740          <div style="display:flex;align-items:center;gap:8px;margin-top:4px;">1741            <button1742              class="peach-btn peach-btn--ghost peach-btn--sm"1743              onClick={() => void testPing()}1744              disabled={testing() || !webhookUrl().trim()}1745            >1746              {testing() ? "sending..." : "test ping"}1747            </button>1748            <Show when={testResult()}>1749              <span style="font-size:10px;color:var(--peach-t2);font-family:var(--font-mono);">{testResult()}</span>1750            </Show>1751          </div>1752          <Show when={props.entry.canary?.lastPinged}>1753            <p style="font-size:10px;color:var(--peach-t2);margin-top:4px;">1754              Last triggered: {new Date(props.entry.canary!.lastPinged!).toLocaleDateString()}1755              {" · "}{props.entry.canary?.pingCount ?? 0} total alerts1756            </p>1757          </Show>1758        </div>1759      </Show>1760    </div>1761  );1762}