contracts.test.tsx

70.8 KB · raw

1// @vitest-environment jsdom23import type { JSX } from "solid-js";4import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";56import type { ImportParseResult } from "../../shared/import";7import type { VaultEntry } from "../../shared/types";8import { WORD_LIST } from "../../shared/recovery-word-list";9import { PasskeyToast } from "../../content/passkey-toast/PasskeyToast";10import { PasskeyApprovalView } from "./PasskeyApproval";11import { LockView } from "./Lock";12import { ExportView } from "./Export";13import { SettingsView } from "./Settings";14import { DEFAULT_BINDINGS } from "../../shared/shortcuts";15import { EntryView } from "./Entry";16import { ImportView } from "./Import";17import { AddView } from "./Add";18import { NotesEditor } from "./NotesEditor";19import { RecoveryWordEntryView } from "./RecoveryWordEntry";20import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";21import { VaultView } from "./Vault";22import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";2324const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();25const triggerRingMock = vi.fn();26const triggerPipPulseMock = vi.fn();27const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();28const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2930vi.mock("../App", () => ({31  sendMessage: (msg: unknown) => sendMessageMock(msg),32  triggerRing: () => triggerRingMock(),33  triggerPipPulse: () => triggerPipPulseMock(),34}));3536vi.mock("../../shared/bridge", () => ({37  sendMessage: (msg: unknown) => sendMessageMock(msg),38}));3940vi.mock("../../shared/import", () => ({41  parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),42}));4344vi.mock("../../shared/favicon", async (importOriginal) => {45  const actual = await importOriginal<typeof import("../../shared/favicon")>();46  return { ...actual, faviconUrl: () => null };47});4849vi.mock("../../crypto/totp", () => ({50  generateTOTP: () => ({ code: "123 456", remaining: 24 }),51  parseOtpauthURI: (value: string) =>52    value.startsWith("otpauth://")53      ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }54      : null,55}));5657vi.mock("../components/GeneratorDrawer", () => ({58  GeneratorDrawer: () => null,59}));6061vi.mock("../components/RuneCanvas", () => ({ RuneCanvas: () => null }));6263vi.mock("../components/RuneBackground", () => ({64  RuneBackground: () => null,65}));6667vi.mock("@zxcvbn-ts/core", () => ({68  zxcvbn: (value: string) => zxcvbnMock(value),69  zxcvbnOptions: { setOptions: vi.fn() },70}));71vi.mock("@zxcvbn-ts/language-common", () => ({72  adjacencyGraphs: {},73  dictionary: {},74}));75vi.mock("@zxcvbn-ts/language-en", () => ({76  translations: {},77  dictionary: {},78}));7980describe("popup contract tests", () => {81  const disposers: Array<() => void> = [];8283  beforeEach(() => {84    document.body.innerHTML = "";85    sendMessageMock.mockReset();86    triggerRingMock.mockReset();87    triggerPipPulseMock.mockReset();88    parseImportSourceMock.mockReset();89    zxcvbnMock.mockReset();90    zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));91    parseImportSourceMock.mockResolvedValue({92      format: "unknown",93      label: "Unknown format",94      entries: [],95      totalItems: 0,96      skippedItems: 0,97    });9899    vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {100      return window.setTimeout(() => cb(0), 0) as unknown as number;101    });102    vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));103    vi.stubGlobal("URL", {104      createObjectURL: vi.fn(() => "blob:peach-test"),105      revokeObjectURL: vi.fn(),106    });107    vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});108109    (globalThis as { chrome?: typeof chrome }).chrome = {110      runtime: {111        getManifest: () => ({ version: "1.4.47" }),112        onMessage: { addListener: vi.fn() },113      },114    } as unknown as typeof chrome;115  });116117  afterEach(() => {118    while (disposers.length > 0) {119      disposers.pop()?.();120    }121    vi.restoreAllMocks();122    vi.unstubAllGlobals();123  });124125  function mount(view: JSX.Element | (() => JSX.Element)) {126    const mounted = renderView(view);127    disposers.push(mounted.dispose);128    return mounted.container;129  }130131  function sampleEntry(overrides: Partial<VaultEntry> = {}): VaultEntry {132    return {133      id: "entry-1",134      type: "login",135      title: "GitHub",136      username: "june",137      password: "secret123",138      url: "https://github.com",139      totp: "JBSWY3DPEHPK3PXP",140      canary: {141        webhookUrl: "https://example.com/hook",142      },143      createdAt: 1,144      modifiedAt: 1,145      ...overrides,146    };147  }148149  function sampleImportResult(150    overrides: Partial<ImportParseResult> = {}151  ): ImportParseResult {152    return {153      format: "csv",154      label: "CSV import",155      entries: [156        {157          type: "login",158          title: "Imported site",159          username: "imported-user",160          password: "imported-pass",161          url: "https://imported.test",162        },163      ],164      totalItems: 1,165      skippedItems: 0,166      ...overrides,167    };168  }169170  function settingsProps(overrides: Partial<Parameters<typeof SettingsView>[0]> = {}) {171    return {172      entriesCount: 1,173      breachMonitoring: true,174      lockOnClose: true,175      autoLockMinutes: 5,176      lockedSyncRequiresUnlock: false,177      trashRetentionDays: 30,178      theme: "dark" as const,179      accentColor: "peach" as const,180      textSize: "medium" as const,181      reduceMotion: false,182      onBreachMonitoringChange: vi.fn(),183      onLockOnCloseChange: vi.fn(),184      onAutoLockMinutesChange: vi.fn(),185      onTrashRetentionChange: vi.fn(),186      onLockedSyncRequiresUnlockChange: vi.fn(),187      onThemeChange: vi.fn(),188      onAccentChange: vi.fn(),189      onTextSizeChange: vi.fn(),190      onReduceMotionChange: vi.fn(),191      shortcuts: DEFAULT_BINDINGS,192      onShortcutsChange: vi.fn(),193      onBack: vi.fn(),194      onImport: vi.fn(),195      onExport: vi.fn(),196      onBreachCheckDone: vi.fn(),197      ...overrides,198    };199  }200201  async function selectImportFile(202    container: HTMLElement,203    contents = '{"export":"test"}'204  ) {205    // The Import view now opens onto a menu — click into the file subview206    // before locating the file input. Idempotent: a second click won't re-fire207    // because the menu unmounts once the subview renders.208    const fileCard = findButton(container, "Choose file →");209    if (fileCard) {210      fileCard.click();211      await flushView();212    }213    const input = container.querySelector('input[type="file"]') as HTMLInputElement;214    const file = new File([contents], "import.json", { type: "application/json" });215    Object.defineProperty(input, "files", {216      configurable: true,217      value: [file],218    });219    input.dispatchEvent(new Event("change", { bubbles: true }));220    await flushView();221    await flushView();222  }223224  function findButton(container: HTMLElement, text: string): HTMLButtonElement {225    return Array.from(container.querySelectorAll("button")).find(226      (candidate) => candidate.textContent?.trim() === text227    ) as HTMLButtonElement;228  }229230  it("Passkey toast shows the caller origin separately from the RP", async () => {231    const container = mount(() => <PasskeyToast site="example.com" origin="https://login.other.example:8443"232      displayName="June" username="june" requestId="1" onSignIn={() => {}} onDeny={() => {}} />);233    await flushView();234    expect(container.textContent).toContain("sign in to example.com?");235    expect(container.textContent).toContain("Request from https://login.other.example:8443");236  });237238  it("Passkey approval identifies the caller origin and embedded request", async () => {239    const container = mount(() => <PasskeyApprovalView type="get" rpId="example.com" rpName="Example"240      userName="june" origin="https://login.other.example:8443" crossOrigin={true} onApprove={() => {}} onDeny={() => {}} />);241    await flushView();242    expect(container.textContent).toContain("https://login.other.example:8443");243    expect(container.textContent).toContain("embedded in another site");244  });245246  it("Lock sends UNLOCK with the entered passphrase", async () => {247    sendMessageMock.mockResolvedValue({ ok: true });248    const onUnlock = vi.fn(async () => undefined);249    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);250251    const password = container.querySelector("#unlock-password") as HTMLInputElement;252    inputText(password, "correct horse battery staple");253    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();254    await flushView();255256    expect(sendMessageMock).toHaveBeenCalledWith({257      type: "UNLOCK",258      payload: { password: "correct horse battery staple" },259    });260    expect(onUnlock).toHaveBeenCalled();261  });262263  it("Lock uses a configured preferred PIN and keeps the password fallback available", async () => {264    sendMessageMock.mockImplementation(async (msg: unknown) => {265      const type = (msg as { type: string }).type;266      if (type === "GET_PIN_STATUS") {267        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };268      }269      return type === "GET_SETTINGS"270        ? { ok: true, data: { pinEnabled: true, pinPreferred: true } }271        : { ok: true };272    });273    const onUnlock = vi.fn(async () => undefined);274    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);275    await flushView();276277    inputText(container.querySelector("#unlock-pin") as HTMLInputElement, "1234");278    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();279    await flushView();280281    expect(sendMessageMock).toHaveBeenCalledWith({282      type: "UNLOCK_WITH_PIN",283      payload: { pin: "1234" },284    });285    expect(onUnlock).toHaveBeenCalled();286    expect(container.textContent).toContain("use master password");287  });288289  it("places the PIN method switch below the unlock button", async () => {290    sendMessageMock.mockImplementation(async (msg: unknown) => {291      const type = (msg as { type: string }).type;292      if (type === "GET_PIN_STATUS") {293        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };294      }295      return type === "GET_SETTINGS"296        ? { ok: true, data: { pinEnabled: true, pinPreferred: false } }297        : { ok: true };298    });299    const container = mount(<LockView hasVault={true} ready={true} onUnlock={vi.fn()} />);300    await flushView();301302    const buttons = Array.from(container.querySelectorAll("button"));303    const unlockIndex = buttons.findIndex((button) => button.textContent?.trim() === "unlock");304    const pinIndex = buttons.findIndex((button) => button.textContent?.trim() === "use PIN");305    expect(pinIndex).toBeGreaterThan(unlockIndex);306  });307308  it("keeps standalone note creation in Notes mode", async () => {309    const chromeApi = globalThis.chrome as unknown as {310      tabs?: { query: (queryInfo: object, callback: (tabs: unknown[]) => void) => void };311    };312    chromeApi.tabs = { query: vi.fn((_queryInfo, callback) => callback([])) };313314    const addContainer = mount(<AddView onBack={vi.fn()} onSave={vi.fn()} />);315    await flushView();316317    expect(Array.from(addContainer.querySelectorAll(".peach-new-type-btn")).map((button) => button.textContent?.trim()))318      .toEqual(["login", "card"]);319    expect(addContainer.querySelector(".peach-note-editor-body--inline")).toBeNull();320  });321322  it("gives Notes mode the full note-formatting toolbar", async () => {323    const container = mount(324      <NotesEditor325        note={null}326        onBack={vi.fn()}327        onSaved={vi.fn()}328        onDelete={vi.fn()}329      />330    );331    await flushView();332333    expect(container.querySelector('[title="Strikethrough"]')).toBeTruthy();334    expect(container.querySelector('[title="Divider"]')).toBeTruthy();335    expect(container.querySelector('[title="Quote"]')).toBeTruthy();336    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button")).toHaveLength(9);337    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button svg")).toHaveLength(9);338    expect(container.querySelector(".peach-notes-header-title")?.textContent).toBe("notes.");339  });340341  it("saves formatting applied by the Notes toolbar before leaving", async () => {342    const savedNote = {343      id: "note-1",344      type: "note" as const,345      title: "Untitled",346      notes: "<b>formatted</b>",347      createdAt: 1,348      modifiedAt: 2,349    };350    sendMessageMock.mockResolvedValue({ ok: true, data: savedNote });351    const originalExecCommand = document.execCommand;352    const execCommandMock = vi.fn(() => {353      const body = document.querySelector<HTMLDivElement>(".peach-note-body-field");354      if (body) body.innerHTML = "<b>formatted</b>";355      return true;356    });357    Object.defineProperty(document, "execCommand", { configurable: true, value: execCommandMock });358359    try {360      const container = mount(361        <NotesEditor362          note={null}363          onBack={vi.fn()}364          onSaved={vi.fn()}365          onDelete={vi.fn()}366        />367      );368      await flushView();369      container.querySelector<HTMLButtonElement>('[title="Bold"]')?.dispatchEvent(370        new MouseEvent("mousedown", { bubbles: true, cancelable: true })371      );372      expect(execCommandMock).toHaveBeenCalledWith("bold", false, undefined);373      container.querySelector<HTMLButtonElement>('[aria-label="Back to notes list"]')?.click();374      await flushView();375376      expect(sendMessageMock).toHaveBeenCalledWith({377        type: "SAVE_NOTE",378        payload: { id: undefined, title: "Untitled", body: "<b>formatted</b>" },379      });380    } finally {381      Object.defineProperty(document, "execCommand", { configurable: true, value: originalExecCommand });382    }383  });384385  it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {386    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);387    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;388    const password = container.querySelector("#master-password") as HTMLInputElement;389    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;390391    inputText(password, "short");392    inputText(confirm, "short");393    await flushView();394    expect(createButton.disabled).toBe(true);395396    zxcvbnMock.mockImplementation(() => ({ score: 1 }));397    inputText(password, "weakweakweak");398    inputText(confirm, "weakweakweak");399    await flushView();400    expect(createButton.disabled).toBe(true);401  });402403  it("Lock create-vault header pins the wordmark left with back on the right", async () => {404    const container = mount(405      <LockView406        hasVault={false}407        ready={true}408        onUnlock={vi.fn()}409        onBackToOnboarding={() => {}}410      />411    );412    const header = container.querySelector(".peach-newvault-header") as HTMLElement;413    const wordmark = header.querySelector(".peach-wordmark-stack");414    const back = header.querySelector(".peach-newvault-back");415    expect(wordmark).toBeTruthy();416    expect(back).toBeTruthy();417    // Wordmark first so it never shifts between onboarding screens; back418    // takes the opposite corner instead of displacing it.419    expect(header.firstElementChild).toBe(wordmark);420    expect(header.lastElementChild).toBe(back);421    await flushView();422  });423424  it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {425    // Sequence: CREATE_VAULT → show recovery words → GET_RECOVERY_WORDS → user confirms → onUnlock426    sendMessageMock.mockImplementation(427      async (msg: unknown) => {428        const m = msg as { type: string; payload?: { password?: string } };429        if (m.type === "CREATE_VAULT") return { ok: true };430        if (m.type === "GET_RECOVERY_WORDS") {431          // Return 12 fake words — must pass findInvalidWords432          return {433            ok: true,434            data: [435              "abandon", "ability", "able", "about", "above", "absent",436              "absorb", "abstract", "absurd", "abuse", "access", "accident",437            ],438          };439        }440        return { ok: true };441      }442    );443    zxcvbnMock.mockImplementation(() => ({ score: 3 }));444    const onUnlock = vi.fn(async () => undefined);445    const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);446447    const password = container.querySelector("#master-password") as HTMLInputElement;448    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;449    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;450451    inputText(password, "correct horse battery staple");452    inputText(confirm, "correct horse battery staple");453    await flushView();454    expect(createButton.disabled).toBe(false);455456    pressEnter(confirm);457    await flushView();458459    expect(sendMessageMock).toHaveBeenCalledWith({460      type: "CREATE_VAULT",461      payload: { password: "correct horse battery staple" },462    });463    // After CREATE_VAULT success, the recovery word display is shown.464    // onUnlock is NOT called yet — user must first confirm their recovery words.465    expect(onUnlock).not.toHaveBeenCalled();466  });467468  it("Lock reports saved-but-locked creation before requesting recovery words", async () => {469    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });470    zxcvbnMock.mockImplementation(() => ({ score: 3 }));471    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);472    inputText(container.querySelector<HTMLInputElement>("#master-password")!, "correct horse battery staple");473    inputText(container.querySelector<HTMLInputElement>("#confirm-password")!, "correct horse battery staple");474    await flushView();475    pressEnter(container.querySelector<HTMLInputElement>("#confirm-password")!);476    await flushView();477    expect(container.textContent).toContain("Your new vault and password were saved");478    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });479  });480481  it("Lock CSV restore stops when creation saved a locked vault", async () => {482    parseImportSourceMock.mockResolvedValue(sampleImportResult());483    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });484    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="csv" onUnlock={vi.fn()} />);485    await flushView();486    inputText(container.querySelector<HTMLInputElement>("#restore-csv-pass")!, "new-master-password");487    inputText(container.querySelector<HTMLInputElement>("#restore-csv-confirm")!, "new-master-password");488    const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;489    Object.defineProperty(input, "files", { configurable: true, value: [new File(["csv"], "backup.csv")] });490    input.dispatchEvent(new Event("change", { bubbles: true }));491    await flushView();492    expect(container.textContent).toContain("Your new vault and password were saved");493    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "BATCH_ADD_ENTRIES")).toBe(false);494  });495496  it("Lock PeachScript restore stops when creation saved a locked vault", async () => {497    const script = await import("../../crypto/peachScript");498    const payload = await import("../../crypto/peachPayload");499    vi.spyOn(script, "isPeachScript").mockImplementation((value) => value === "backup");500    vi.spyOn(script, "decodePeachScript").mockReturnValue(new Uint8Array());501    vi.spyOn(payload, "parsePayload").mockResolvedValue({ entries: [sampleEntry()], settings: {} });502    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });503    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="symbols" onUnlock={vi.fn()} />);504    await flushView();505    inputText(container.querySelector<HTMLTextAreaElement>(".peach-restore-script")!, "backup");506    inputText(container.querySelector<HTMLInputElement>("#restore-backup-pass")!, "new-master-password");507    container.querySelector<HTMLButtonElement>(".peach-restore-submit")!.click();508    await flushView();509    expect(container.textContent).toContain("Your new vault and password were saved");510    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "RESTORE_ENTRIES")).toBe(false);511  });512513  it("recovery display asks for three distinct randomized word positions and confirms", async () => {514    const words12 = [515      "abandon", "ability", "able", "about", "above", "absent",516      "absorb", "abstract", "absurd", "abuse", "access", "accident",517    ];518    sendMessageMock.mockImplementation(async (msg: unknown) => {519      const type = (msg as { type?: string }).type;520      if (type === "GET_RECOVERY_WORDS") return { ok: true, data: words12 };521      return { ok: true };522    });523524    vi.useFakeTimers();525    const onDone = vi.fn();526    try {527      const container = mount(<RecoveryWordDisplayView onDone={onDone} />);528      // onMount fires GET_RECOVERY_WORDS; let the resolved promise + render settle529      await vi.advanceTimersByTimeAsync(0);530531      const prompts = Array.from(532        container.querySelectorAll(".peach-recovery-confirm-num")533      ).map((el) => Number.parseInt((el.textContent ?? "").replace(/\D+/g, ""), 10));534      expect(prompts).toHaveLength(3);535      expect(new Set(prompts).size).toBe(3);536      for (const p of prompts) {537        expect(p).toBeGreaterThanOrEqual(1);538        expect(p).toBeLessThanOrEqual(12);539      }540541      // Inputs stay disabled until the 5s countdown expires542      const inputs = Array.from(543        container.querySelectorAll(".peach-recovery-confirm-input")544      ) as HTMLInputElement[];545      expect(inputs).toHaveLength(3);546      expect(inputs[0]!.disabled).toBe(true);547      await vi.advanceTimersByTimeAsync(5000);548      expect(inputs[0]!.disabled).toBe(false);549550      prompts.forEach((pos, i) => {551        inputText(inputs[i]!, words12[pos - 1]!);552      });553554      const confirmBtn = container.querySelector(".peach-recovery-confirm-btn") as HTMLButtonElement;555      expect(confirmBtn.disabled).toBe(false);556      confirmBtn.click();557      await vi.advanceTimersByTimeAsync(700); // success pause before onDone558559      expect(onDone).toHaveBeenCalledTimes(1);560    } finally {561      vi.useRealTimers();562    }563  });564565  it.each([true, false])("Recovery words flow reports whether the saved password unlocked the vault (%s)", async (unlocked) => {566    sendMessageMock.mockImplementation(async (msg: unknown) => {567      const type = (msg as { type?: string }).type;568      if (type === "VALIDATE_RECOVERY_WORDS") {569        return { ok: true, data: { valid: true, invalid: [] } };570      }571      if (type === "RECOVER_WITH_WORDS") return { ok: true, data: { committed: true, unlocked } };572      return { ok: true };573    });574    const canvasContext = {575      clearRect: vi.fn(),576      fillText: vi.fn(),577      beginPath: vi.fn(),578      closePath: vi.fn(),579      arc: vi.fn(),580      fill: vi.fn(),581      stroke: vi.fn(),582      save: vi.fn(),583      restore: vi.fn(),584      translate: vi.fn(),585      rotate: vi.fn(),586      scale: vi.fn(),587      drawImage: vi.fn(),588      measureText: vi.fn(() => ({ width: 0 })),589      setTransform: vi.fn(),590      fillRect: vi.fn(),591      strokeRect: vi.fn(),592    } as unknown as CanvasRenderingContext2D;593    vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);594595    const onRecoveryComplete = vi.fn(async () => undefined);596    const onCancel = vi.fn();597    const container = mount(598      <RecoveryWordEntryView599        onCancel={onCancel}600        onRecoveryComplete={onRecoveryComplete}601      />602    );603604    const recoveryWords = WORD_LIST.slice(0, 12);605    for (let i = 0; i < recoveryWords.length; i++) {606      const input = container.querySelector(`#recovery-word-${i}`) as HTMLInputElement;607      inputText(input, recoveryWords[i]!);608    }609    await flushView();610611    findButton(container, "verify words").click();612    await flushView();613614    expect(container.textContent).toContain("new master password");615616    const newPassword = container.querySelector("#recovery-new-password") as HTMLInputElement;617    const confirmPassword = container.querySelector("#recovery-confirm-password") as HTMLInputElement;618    inputText(newPassword, "fresh-recovery-password");619    inputText(confirmPassword, "fresh-recovery-password");620    await flushView();621622    findButton(container, "recover vault").click();623    await flushView();624625    expect(sendMessageMock).toHaveBeenCalledWith({626      type: "RECOVER_WITH_WORDS",627      payload: {628        words: recoveryWords,629        newPassword: "fresh-recovery-password",630      },631    });632    if (unlocked) expect(onRecoveryComplete).toHaveBeenCalled();633    else {634      expect(onRecoveryComplete).not.toHaveBeenCalled();635      expect(container.textContent).toContain("your new password is saved");636      expect(container.textContent).toContain("use your new password to unlock your vault");637      expect(container.textContent).not.toContain("recovery failed");638      findButton(container, "back to unlock").click();639      expect(onCancel).toHaveBeenCalledOnce();640    }641  });642643  it("Export menu surfaces both backup formats", async () => {644    const container = mount(<ExportView onBack={vi.fn()} />);645    await flushView();646647    expect(container.textContent).toContain("PeachScript");648    expect(container.textContent).toContain("CSV");649  });650651  it("Lock can open directly on backup restore from onboarding", async () => {652    const container = mount(() => (653      <LockView654        hasVault={false}655        ready={true}656        onUnlock={vi.fn()}657        initialRestore={true}658      />659    ));660    await flushView();661662    expect(container.textContent).toContain("PeachScript");663    expect(container.textContent).toContain("Codex");664    expect(container.textContent).toContain("CSV");665    expect(container.querySelector("#master-password")).toBeNull();666  });667668  it("Lock restore back returns to onboarding, not the create-vault screen", async () => {669    const onBackToOnboarding = vi.fn();670    const container = mount(() => (671      <LockView672        hasVault={false}673        ready={true}674        onUnlock={vi.fn()}675        initialRestore={true}676        onBackToOnboarding={onBackToOnboarding}677      />678    ));679    await flushView();680681    (container.querySelector(".peach-restore-back") as HTMLButtonElement).click();682    await flushView();683    expect(onBackToOnboarding).toHaveBeenCalledTimes(1);684  });685686  it("Lock restore resumes on the picked PeachScript source, not the picker", async () => {687    const container = mount(() => (688      <LockView689        hasVault={false}690        ready={true}691        onUnlock={vi.fn()}692        initialRestore={true}693        initialRestoreSource="symbols"694      />695    ));696    await flushView();697698    expect(container.querySelector(".peach-restore-script")).toBeTruthy();699    expect(container.querySelector("#restore-backup-pass")).toBeTruthy();700    expect(container.querySelector(".peach-restore-sources")).toBeNull();701  });702703  it("Lock restore resumes on the picked CSV source, not the picker", async () => {704    const container = mount(() => (705      <LockView706        hasVault={false}707        ready={true}708        onUnlock={vi.fn()}709        initialRestore={true}710        initialRestoreSource="csv"711      />712    ));713    await flushView();714715    expect(container.querySelector("#restore-csv-pass")).toBeTruthy();716    expect(container.querySelector("#restore-csv-confirm")).toBeTruthy();717    expect(container.querySelector(".peach-restore-sources")).toBeNull();718  });719720  it("Lock restore PeachScript form loads a dropped .peach file", async () => {721    const container = mount(() => (722      <LockView723        hasVault={false}724        ready={true}725        onUnlock={vi.fn()}726        initialRestore={true}727        initialRestoreSource="symbols"728      />729    ));730    await flushView();731732    const form = container.querySelector(".peach-restore-form") as HTMLElement;733    expect(form).toBeTruthy();734735    // The OS file picker dismisses the action popup, so drag-and-drop is the736    // file path that survives; a drop must land the file in the script field.737    const file = new File(["dropped-peach-backup"], "vault.peach", { type: "text/plain" });738    const drop = new Event("drop", { bubbles: true, cancelable: true }) as Event & {739      dataTransfer?: { files: File[] };740    };741    drop.dataTransfer = { files: [file] };742    form.dispatchEvent(drop);743    await flushView();744745    const script = container.querySelector(".peach-restore-script") as HTMLTextAreaElement;746    expect(script.value).toBe("dropped-peach-backup");747  });748749  it("HOLE 4: removing a device discloses that recovery words survive revocation", async () => {750    const device = {751      deviceId: "phone-1",752      deviceName: "June's Phone",753      deviceType: "android" as const,754      longTermPublicKeyHex: "a".repeat(64),755      signingPublicKeyHex: "b".repeat(64),756      pairedAt: 1,757      trustSource: "direct" as const,758    };759    sendMessageMock.mockImplementation(async (msg: unknown) => {760      const m = msg as { type: string };761      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };762      return { ok: true, data: null };763    });764765    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);766    for (let i = 0; i < 30; i++) await Promise.resolve();767768    const openSync = Array.from(container.querySelectorAll("button")).find((b) =>769      /sync/i.test(b.textContent ?? ""),770    );771    openSync?.click();772    for (let i = 0; i < 30; i++) await Promise.resolve();773774    const remove = Array.from(container.querySelectorAll("button")).find(775      (b) => (b.textContent ?? "").trim() === "remove",776    );777    expect(remove).toBeTruthy();778779    // Guard against a vacuous pass: the disclosure must not already be on780    // screen before the user asks to remove anything.781    expect(container.querySelector(".peach-unpair-confirm-note")).toBeNull();782783    remove!.click();784    for (let i = 0; i < 10; i++) await Promise.resolve();785786    // Revocation must never be presented as securing the vault against the787    // removed device — recovery words survive it and restore everything.788    const note = container.querySelector(".peach-unpair-confirm-note");789    expect(note).toBeTruthy();790    const text = note!.textContent ?? "";791    expect(text).toContain("master password");792    expect(text).toContain("recovery words");793    expect(text).toContain("future changes");794  });795796  it("PB-26-709: pending device approval identifies the key, time, provenance, and vault scope", async () => {797    sendMessageMock.mockImplementation(async (msg: unknown) => {798      const m = msg as { type: string };799      if (m.type === "GET_PENDING_VOUCHED_DEVICES") {800        return {801          ok: true,802          data: [{803            deviceId: "phone-source-id",804            deviceName: "June's Phone",805            deviceType: "android",806            longTermPublicKeyHex: "a1b2c3d4e5f6" + "0".repeat(52),807            signingPublicKeyHex: "b".repeat(64),808            pairedAt: Date.UTC(2026, 8, 5),809            receivedAt: Date.UTC(2026, 8, 6, 20, 15),810            vouchedByDeviceId: "trusted-browser-id",811          }],812        };813      }814      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [] } };815      return { ok: true, data: null };816    });817818    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);819    for (let i = 0; i < 30; i++) await Promise.resolve();820    Array.from(container.querySelectorAll("button"))821      .find((button) => /sync/i.test(button.textContent ?? ""))822      ?.click();823    for (let i = 0; i < 30; i++) await Promise.resolve();824825    expect(container.textContent).toContain("a1b2 c3d4 e5f6");826    expect(container.textContent).toContain("trusted-browser-id");827    expect(container.textContent).toContain("2026-09-06");828    expect(container.textContent).toContain("existing vault contents");829  });830831  it("Settings keeps the paired-device list and revokes through UNPAIR_DEVICE", async () => {832    const device = {833      deviceId: "phone-1",834      deviceName: "June's Phone",835      deviceType: "android" as const,836      longTermPublicKeyHex: "a".repeat(64),837      signingPublicKeyHex: "b".repeat(64),838      pairedAt: 1,839      trustSource: "direct" as const,840    };841    let paired: typeof device[] = [device];842    sendMessageMock.mockImplementation(async (msg: any) => {843      if (msg?.type === "LIST_PAIRED_DEVICES") {844        return { ok: true, data: { devices: [...paired] } };845      }846      if (msg?.type === "UNPAIR_DEVICE") {847        // Mirror the real handler: UNPAIR_DEVICE drops the row from the848        // registry. The next LIST_PAIRED_DEVICES must not see it.849        paired = paired.filter((d) => d.deviceId !== msg.payload?.deviceId);850        return { ok: true };851      }852      if (msg?.type === "RENAME_PAIRED_DEVICE") {853        paired = paired.map((d) =>854          d.deviceId === msg.payload?.deviceId ? { ...d, localAlias: msg.payload.name } : d,855        );856        return { ok: true };857      }858      return { ok: true, data: null };859    });860861    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);862    for (let i = 0; i < 30; i++) await Promise.resolve();863    Array.from(container.querySelectorAll("button"))864      .find((b) => /sync/i.test(b.textContent ?? ""))865      ?.click();866    for (let i = 0; i < 30; i++) await Promise.resolve();867868    // The list itself: extracting the relay selector must not take the hub with it.869    expect(container.textContent).toContain("PAIRED DEVICES");870    expect(container.textContent).toContain("June's Phone");871    expect(container.textContent).toContain("Android");872    Array.from(container.querySelectorAll("button"))873      .find((b) => (b.textContent ?? "").trim() === "rename")!874      .click();875    const renameInput = container.querySelector<HTMLInputElement>('input[aria-label="Rename June\'s Phone"]')!;876    renameInput.value = "Travel phone";877    renameInput.dispatchEvent(new InputEvent("input", { bubbles: true }));878    Array.from(container.querySelectorAll("button"))879      .find((b) => (b.textContent ?? "").trim() === "save")!880      .click();881    for (let i = 0; i < 30; i++) await Promise.resolve();882    expect(sendMessageMock).toHaveBeenCalledWith({883      type: "RENAME_PAIRED_DEVICE",884      payload: { deviceId: "phone-1", name: "Travel phone" },885    });886    expect(container.textContent).toContain("Travel phone");887    const syncNowButton = container.querySelector<HTMLButtonElement>(888      'button[aria-label="Sync this vault now"]',889    )!;890    const syncStatusRow = syncNowButton.closest(".peach-settings-row--meta");891    const syncCard = syncNowButton.closest('[data-settings-card-id="sync"]');892    expect(syncStatusRow).not.toBeNull();893    expect(syncStatusRow?.contains(syncNowButton)).toBe(true);894    expect(syncCard?.querySelectorAll(".peach-settings-row--meta")).toHaveLength(1);895    const labels = Array.from(container.querySelectorAll(".peach-settings-sub-label"));896    const addDeviceLabel = labels.find((label) => label.textContent?.includes("ADD A DEVICE"))!;897    const pairedDevicesLabel = labels.find((label) => label.textContent?.includes("PAIRED DEVICES"))!;898    expect(899      syncNowButton.compareDocumentPosition(addDeviceLabel) & Node.DOCUMENT_POSITION_FOLLOWING,900    ).toBeTruthy();901    expect(902      syncNowButton.compareDocumentPosition(pairedDevicesLabel) & Node.DOCUMENT_POSITION_FOLLOWING,903    ).toBeTruthy();904905    Array.from(container.querySelectorAll("button"))906      .find((b) => (b.textContent ?? "").trim() === "remove")!907      .click();908    for (let i = 0; i < 10; i++) await Promise.resolve();909    const confirm = Array.from(910      container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),911    ).find((b) => (b.textContent ?? "").trim() === "remove");912    confirm!.click();913    for (let i = 0; i < 30; i++) await Promise.resolve();914915    expect(sendMessageMock).toHaveBeenCalledWith({916      type: "UNPAIR_DEVICE",917      payload: { deviceId: "phone-1" },918    });919    // The list must be refreshed and the device must be gone. The regression920    // we're guarding against: a Settings view that calls UNPAIR_DEVICE but921    // never refreshes LIST_PAIRED_DEVICES, so the row stays in the UI.922    expect(container.textContent).not.toContain("June's Phone");923    expect(container.textContent).not.toContain("PAIRED DEVICES");924  });925  it("Settings keeps the confirmation and shows revoke failures", async () => {926    const device = {927      deviceId: "phone-1",928      deviceName: "June's Phone",929      deviceType: "android" as const,930      longTermPublicKeyHex: "a".repeat(64),931      signingPublicKeyHex: "b".repeat(64),932      pairedAt: 1,933      trustSource: "direct" as const,934    };935    sendMessageMock.mockImplementation(async (msg: unknown) => {936      const message = msg as { type?: string; payload?: { deviceId?: string } };937      if (message.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };938      if (message.type === "UNPAIR_DEVICE") return { ok: false, error: "trust_data_corrupted" };939      return { ok: true, data: null };940    });941942    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);943    for (let i = 0; i < 30; i++) await Promise.resolve();944    for (let i = 0; i < 30; i++) await Promise.resolve();945    Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();946    for (let i = 0; i < 30; i++) await Promise.resolve();947    Array.from(container.querySelectorAll("button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();948    for (let i = 0; i < 10; i++) await Promise.resolve();949    Array.from(container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();950    for (let i = 0; i < 30; i++) await Promise.resolve();951952    expect(container.textContent).toContain("trust_data_corrupted");953    expect(container.textContent).toContain("June's Phone");954  });955956  it("Settings drops the secure-reset panel once the device is on the settled generation", async () => {957    const openSyncCard = async (state: "V2_ACTIVE" | "V2_ANCHOR" | "LEGACY_ACTIVE") => {958      sendMessageMock.mockImplementation(async (msg: unknown) => {959        const message = msg as { type?: string };960        if (message.type === "GET_SYNC_GENERATION") {961          return { ok: true, data: { schemaVersion: 1, generation: 2, state, createdAt: 1 } };962        }963        return { ok: true, data: null };964      });965      const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);966      for (let i = 0; i < 30; i++) await Promise.resolve();967      Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();968      for (let i = 0; i < 30; i++) await Promise.resolve();969      return container;970    };971972    // Settled: the migration is over, so the panel must not linger as a label.973    const settled = await openSyncCard("V2_ACTIVE");974    expect(settled.textContent).not.toContain("SECURE SYNC RESET");975    expect(settled.textContent).toContain("ADD A DEVICE");976977    // Still actionable states keep the panel and its explanation.978    const anchored = await openSyncCard("V2_ANCHOR");979    expect(anchored.textContent).toContain("SECURE SYNC RESET");980    expect(anchored.textContent).toContain("Not re-paired");981982    const legacy = await openSyncCard("LEGACY_ACTIVE");983    expect(legacy.textContent).toContain("SECURE SYNC RESET");984    expect(legacy.textContent).toContain("Legacy Sync generation");985  });986987  it("Settings keeps connection and recovery details collapsed until requested", async () => {988    sendMessageMock.mockImplementation(async (msg: any) => {989      if (msg?.type === "LIST_PAIRED_DEVICES") {990        return { ok: true, data: { devices: [] } };991      }992      return { ok: true, data: null };993    });994995    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);996    for (let i = 0; i < 30; i++) await Promise.resolve();997    Array.from(container.querySelectorAll("button"))998      .find((button) => /sync/i.test(button.textContent ?? ""))999      ?.click();1000    for (let i = 0; i < 20; i++) await Promise.resolve();10011002    expect(container.textContent).toContain("SYNC STATUS");1003    expect(container.textContent).toContain("ADD A DEVICE");1004    expect(container.textContent).not.toContain("Public relay");1005    expect(container.textContent).not.toContain("Rotate sync identity");10061007    const connection = Array.from(container.querySelectorAll("button"))1008      .find((button) => button.textContent?.includes("CONNECTION"));1009    connection?.click();1010    await Promise.resolve();1011    expect(container.textContent).toContain("Public relay");10121013    const recovery = Array.from(container.querySelectorAll("button"))1014      .find((button) => button.textContent?.includes("RECOVERY & SECURITY"));1015    recovery?.click();1016    await Promise.resolve();1017    expect(container.textContent).toContain("Rotate sync identity");1018  });10191020  it("Settings requires current, new, and confirm passwords before enabling save", async () => {1021    sendMessageMock.mockResolvedValue({ ok: true, data: null });1022    const container = mount(1023      <SettingsView1024        entriesCount={1}1025        breachMonitoring={true}1026        lockOnClose={true}1027        lockedSyncRequiresUnlock={false}1028        autoLockMinutes={5}1029        trashRetentionDays={30}1030        theme="dark"1031        accentColor="peach"1032        textSize="medium"1033        reduceMotion={false}1034        onBreachMonitoringChange={vi.fn()}1035        onLockedSyncRequiresUnlockChange={vi.fn()}1036        onLockOnCloseChange={vi.fn()}1037        onAutoLockMinutesChange={vi.fn()}1038        onTrashRetentionChange={vi.fn()}1039        onThemeChange={vi.fn()}1040        onAccentChange={vi.fn()}1041        onTextSizeChange={vi.fn()}1042        onReduceMotionChange={vi.fn()}1043        shortcuts={DEFAULT_BINDINGS}1044        onShortcutsChange={vi.fn()}1045        onBack={vi.fn()}1046        onImport={vi.fn()}1047        onExport={vi.fn()}1048        onBreachCheckDone={vi.fn()}1049      />1050    );1051    await flushView();10521053    expect(container.querySelectorAll(".stk-card").length).toBe(7);1054    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]1055    // "open settings to card I (Peach Pro) instead of card II (Protection)".1056    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");10571058    const changeButton = Array.from(container.querySelectorAll("button")).find(1059      (candidate) => candidate.textContent?.trim() === "change"1060    ) as HTMLButtonElement;1061    changeButton.click();1062    await flushView();10631064    const saveButton = Array.from(container.querySelectorAll("button")).find(1065      (candidate) => candidate.textContent?.trim() === "save new password"1066    ) as HTMLButtonElement;1067    expect(saveButton.disabled).toBe(true);10681069    const inputs = container.querySelectorAll('input[type="password"]');1070    inputText(inputs[0] as HTMLInputElement, "current-pass");1071    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");1072    await flushView();1073    expect(saveButton.disabled).toBe(true);10741075    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");1076    await flushView();1077    expect(saveButton.disabled).toBe(false);1078  });10791080  it("Settings feedback highlights the selected category and hides the form after submit", async () => {1081    sendMessageMock.mockResolvedValue({ ok: true, data: null });1082    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1083      ok: true,1084      json: async () => ({ success: true }),1085    }));1086    vi.stubGlobal("fetch", fetchMock);10871088    const container = mount(1089      <SettingsView1090        entriesCount={1}1091        breachMonitoring={true}1092        lockOnClose={true}1093        lockedSyncRequiresUnlock={false}1094        autoLockMinutes={5}1095        trashRetentionDays={30}1096        theme="dark"1097        accentColor="peach"1098        textSize="medium"1099        reduceMotion={false}1100        initialSection="feedback"1101        onLockedSyncRequiresUnlockChange={vi.fn()}1102        onBreachMonitoringChange={vi.fn()}1103        onLockOnCloseChange={vi.fn()}1104        onAutoLockMinutesChange={vi.fn()}1105        onTrashRetentionChange={vi.fn()}1106        onThemeChange={vi.fn()}1107        onAccentChange={vi.fn()}1108        onTextSizeChange={vi.fn()}1109        onReduceMotionChange={vi.fn()}1110        shortcuts={DEFAULT_BINDINGS}1111        onShortcutsChange={vi.fn()}1112        onBack={vi.fn()}1113        onImport={vi.fn()}1114        onExport={vi.fn()}1115        onBreachCheckDone={vi.fn()}1116      />1117    );1118    await flushView();11191120    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;1121    expect(feedbackCard.classList.contains("is-active")).toBe(true);11221123    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];1124    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;1125    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;1126    expect(bugButton.getAttribute("aria-pressed")).toBe("true");1127    expect(featureButton.getAttribute("aria-pressed")).toBe("false");11281129    featureButton.click();1130    await flushView();11311132    expect(bugButton.getAttribute("aria-pressed")).toBe("false");1133    expect(featureButton.getAttribute("aria-pressed")).toBe("true");1134    expect(featureButton.classList.contains("is-active")).toBe(true);11351136    inputText(1137      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1138      '<script>alert("xss")</script> Please make this easier to see & safer.'1139    );1140    const sendButton = Array.from(container.querySelectorAll("button")).find(1141      (candidate) => candidate.textContent?.trim() === "Send"1142    ) as HTMLButtonElement;1143    sendButton.click();11441145    await vi.waitFor(() => {1146      expect(container.textContent).toContain("Thank you");1147    });11481149    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));1150    expect(requestBody.subject).toContain("Feature request");1151    expect(requestBody.message).toBe(1152      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."1153    );1154    expect(requestBody.message).not.toContain("<script>");1155    expect(container.textContent).toContain("Someone will process it soon");1156    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1157    expect(container.querySelector(".peach-feedback-submit")).toBeNull();1158  });11591160  it("Settings keeps license activation on the full-screen celebration path", async () => {1161    const onLicenseChange = vi.fn(async () => undefined);1162    sendMessageMock.mockImplementation(async (msg: unknown) => {1163      const type = (msg as { type?: string }).type;1164      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };1165      if (type === "ACTIVATE_LICENSE") {1166        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1167      }1168      if (type === "GET_ENTRIES") return { ok: true, data: [] };1169      return { ok: true, data: null };1170    });11711172    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);1173    await flushView();11741175    inputText(1176      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,1177      "PEACH-TEST-KEY",1178    );1179    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;1180    apply.click();11811182    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));1183    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);1184    expect(container.textContent).not.toContain("thank you ✦");1185  });11861187  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {1188    sendMessageMock.mockImplementation(async (msg: unknown) => {1189      const type = (msg as { type?: string }).type;1190      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1191      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };1192      if (type === "GET_ENTRIES") return { ok: true, data: [] };1193      return { ok: true, data: null };1194    });11951196    const onLicenseChangeFromStar = vi.fn();1197    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);1198    await flushView();1199    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();1200    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1201    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();12021203    const onLicenseChangeFromPeach = vi.fn();1204    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);1205    await flushView();1206    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();1207    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1208    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();1209  });12101211  it("Settings feedback sends even if Firefox reports no data-collection consent — a user-initiated send is its own consent", async () => {1212    sendMessageMock.mockResolvedValue({ ok: true, data: null });1213    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1214      ok: true,1215      json: async () => ({ success: true }),1216    }));1217    vi.stubGlobal("fetch", fetchMock);1218    // Firefox-style permissions API reporting the optional consent as absent.1219    // The old code gated send behind this and silently returned to idle, which1220    // read as a dead Send button. The gate is gone: Send must always send.1221    vi.stubGlobal("browser", {1222      permissions: {1223        getAll: vi.fn(async () => ({ data_collection: [] })),1224        request: vi.fn(async () => false),1225      },1226    });12271228    const container = mount(1229      <SettingsView1230        entriesCount={1}1231        breachMonitoring={true}1232        lockOnClose={true}1233        lockedSyncRequiresUnlock={false}1234        autoLockMinutes={5}1235        trashRetentionDays={30}1236        theme="dark"1237        accentColor="peach"1238        textSize="medium"1239        reduceMotion={false}1240        initialSection="feedback"1241        onLockedSyncRequiresUnlockChange={vi.fn()}1242        onBreachMonitoringChange={vi.fn()}1243        onLockOnCloseChange={vi.fn()}1244        onAutoLockMinutesChange={vi.fn()}1245        onTrashRetentionChange={vi.fn()}1246        onThemeChange={vi.fn()}1247        onAccentChange={vi.fn()}1248        onTextSizeChange={vi.fn()}1249        onReduceMotionChange={vi.fn()}1250        shortcuts={DEFAULT_BINDINGS}1251        onShortcutsChange={vi.fn()}1252        onBack={vi.fn()}1253        onImport={vi.fn()}1254        onExport={vi.fn()}1255        onBreachCheckDone={vi.fn()}1256      />1257    );1258    await flushView();12591260    inputText(1261      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1262      "Please improve the feedback flow."1263    );1264    const sendButton = Array.from(container.querySelectorAll("button")).find(1265      (candidate) => candidate.textContent?.trim() === "Send"1266    ) as HTMLButtonElement;1267    sendButton.click();12681269    await vi.waitFor(() => {1270      expect(fetchMock).toHaveBeenCalledTimes(1);1271    });1272    await vi.waitFor(() => {1273      expect(container.textContent).toContain("Thank you");1274    });1275    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1276  });12771278  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {1279    sendMessageMock.mockImplementation(async (msg: unknown) => {1280      const m = msg as { type: string };1281      if (m.type === "GET_RECOVERY_WORDS") {1282        return {1283          ok: true,1284          data: [1285            "abandon", "ability", "able", "about", "above", "absent",1286            "absorb", "abstract", "absurd", "abuse", "access", "accident",1287          ],1288        };1289      }1290      return { ok: true, data: null };1291    });1292    const onAutoLockMinutesChange = vi.fn();1293    const onLockedSyncRequiresUnlockChange = vi.fn();1294    const onThemeChange = vi.fn();1295    const container = mount(1296      <SettingsView1297        entriesCount={1}1298        breachMonitoring={true}1299        lockOnClose={true}1300        lockedSyncRequiresUnlock={false}1301        autoLockMinutes={5}1302        trashRetentionDays={30}1303        theme="dark"1304        accentColor="peach"1305        textSize="medium"1306        reduceMotion={false}1307        onBreachMonitoringChange={vi.fn()}1308        onLockedSyncRequiresUnlockChange={onLockedSyncRequiresUnlockChange}1309        onLockOnCloseChange={vi.fn()}1310        onAutoLockMinutesChange={onAutoLockMinutesChange}1311        onTrashRetentionChange={vi.fn()}1312        onThemeChange={onThemeChange}1313        onAccentChange={vi.fn()}1314        onTextSizeChange={vi.fn()}1315        onReduceMotionChange={vi.fn()}1316        shortcuts={DEFAULT_BINDINGS}1317        onShortcutsChange={vi.fn()}1318        onBack={vi.fn()}1319        onImport={vi.fn()}1320        onExport={vi.fn()}1321        onBreachCheckDone={vi.fn()}1322      />1323    );1324    await flushView();1325    sendMessageMock.mockClear();13261327    // ── Auto-lock + theme changes (before password change) ─────────────1328    const selects = container.querySelectorAll("select");1329    changeSelect(selects[0] as HTMLSelectElement, "15");1330    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);13311332    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;1333    appearanceCard.click();1334    await flushView();1335    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");1336    const themeButton = Array.from(container.querySelectorAll("button")).find(1337      (candidate) => candidate.textContent?.trim() === "Switch to light"1338    ) as HTMLButtonElement;1339    themeButton.click();1340    expect(onThemeChange).toHaveBeenCalledWith("light");13411342    // ── Locked Sync custody toggle ──────────────────────────────────────1343    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;1344    protectionCard.click();1345    await flushView();1346    const custodyToggle = container.querySelector<HTMLButtonElement>(1347      'button[aria-label="Toggle unlock requirement for locked Sync after restart"]',1348    );1349    expect(custodyToggle).not.toBeNull();1350    custodyToggle!.click();1351    expect(onLockedSyncRequiresUnlockChange).toHaveBeenCalledWith(true);13521353    const changeButton = Array.from(container.querySelectorAll("button")).find(1354      (candidate) => candidate.textContent?.trim() === "change"1355    ) as HTMLButtonElement;1356    changeButton.click();1357    await flushView();13581359    const inputs = container.querySelectorAll('input[type="password"]');1360    inputText(inputs[0] as HTMLInputElement, "current-pass");1361    inputText(inputs[1] as HTMLInputElement, "new-password-123");1362    inputText(inputs[2] as HTMLInputElement, "new-password-123");1363    await flushView();13641365    const saveButton = Array.from(container.querySelectorAll("button")).find(1366      (candidate) => candidate.textContent?.trim() === "save new password"1367    ) as HTMLButtonElement;1368    saveButton.click();1369    await flushView();13701371    expect(sendMessageMock).toHaveBeenCalledWith({1372      type: "CHANGE_PASSWORD",1373      payload: {1374        currentPassword: "current-pass",1375        newPassword: "new-password-123",1376      },1377    });13781379    // After a successful password change the recovery word display replaces settings.1380    expect(container.textContent).toContain("save your recovery words");1381    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });1382  });13831384  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {1385    sendMessageMock.mockResolvedValue({ ok: true });1386    const container = mount(1387      <EntryView1388        entry={sampleEntry()}1389        onDelete={vi.fn()}1390        onFieldSaved={vi.fn(async () => undefined)}1391      />1392    );13931394    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;1395    passwordButton.click();1396    await flushView();13971398    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1399      type: "COPY",1400      payload: { text: "secret123", label: "password", alreadyWritten: false },1401    });1402    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1403      type: "FIRE_CANARY_PING",1404      payload: {1405        webhookUrl: "https://example.com/hook",1406        entryTitle: "GitHub",1407        trigger: "password_copied",1408      },1409    });14101411    sendMessageMock.mockClear();1412    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;1413    usernameButton.click();1414    await flushView();14151416    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1417      type: "COPY",1418      payload: { text: "june", label: "username", alreadyWritten: false },1419    });1420    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1421      type: "FIRE_CANARY_PING",1422      payload: {1423        webhookUrl: "https://example.com/hook",1424        entryTitle: "GitHub",1425        trigger: "username_copied",1426      },1427    });1428  });14291430  it("Entry keyboard password copy reports its canary after COPY", async () => {1431    sendMessageMock.mockResolvedValue({ ok: true });1432    mount(1433      <EntryView1434        entry={sampleEntry()}1435        onDelete={vi.fn()}1436        onFieldSaved={vi.fn(async () => undefined)}1437      />1438    );14391440    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", bubbles: true }));1441    await flushView();14421443    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1444      type: "COPY",1445      payload: { text: "secret123", label: "password", alreadyWritten: false },1446    });1447    await flushView();1448    expect(sendMessageMock.mock.calls).toContainEqual([{1449      type: "FIRE_CANARY_PING",1450      payload: {1451        webhookUrl: "https://example.com/hook",1452        entryTitle: "GitHub",1453        trigger: "password_copied",1454      },1455    }]);1456  });1457  it("Entry Cmd+C leaves the native clipboard shortcut untouched", async () => {1458    sendMessageMock.mockResolvedValue({ ok: true });1459    mount(1460      <EntryView1461        entry={sampleEntry()}1462        onDelete={vi.fn()}1463        onFieldSaved={vi.fn(async () => undefined)}1464      />1465    );14661467    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", metaKey: true, bubbles: true }));1468    await flushView();14691470    expect(sendMessageMock).not.toHaveBeenCalledWith(expect.objectContaining({ type: "COPY" }));1471  });14721473  it("Vault password swipe copy reports its canary after COPY", async () => {1474    sendMessageMock.mockResolvedValue({ ok: true });1475    const container = mount(1476      <VaultView1477        entries={[sampleEntry()]}1478        sortOrder="url-first"1479        onSelectEntry={vi.fn()}1480        onSortOrderChange={vi.fn()}1481        onAdd={vi.fn()}1482        onClose={vi.fn()}1483      />1484    );1485    const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1486    row.dispatchEvent(new TouchEvent("touchstart", {1487      bubbles: true,1488      touches: [{ clientX: 0, clientY: 0 } as Touch],1489    }));1490    row.dispatchEvent(new TouchEvent("touchend", {1491      bubbles: true,1492      changedTouches: [{ clientX: 100, clientY: 0 } as Touch],1493    }));1494    await flushView();14951496    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1497      type: "COPY",1498      payload: { text: "secret123", label: "password", alreadyWritten: false },1499    });1500    await flushView();1501    expect(sendMessageMock.mock.calls).toContainEqual([{1502      type: "FIRE_CANARY_PING",1503      payload: {1504        webhookUrl: "https://example.com/hook",1505        entryTitle: "GitHub",1506        trigger: "password_copied",1507      },1508    }]);1509  });15101511  it("Entry shows Advanced for passkey-bearing credential entries", async () => {1512    const container = mount(1513      <EntryView1514        entry={sampleEntry({1515          type: "passkey",1516          username: undefined,1517          password: undefined,1518          totp: undefined,1519          canary: undefined,1520          passkey: {1521            rpId: "vercel.com",1522            rpName: "Vercel",1523            credentialId: "cred-1",1524            publicKeyCose: "cose",1525            userHandle: "handle",1526            userName: "june",1527            userDisplayName: "June",1528            algorithm: -7,1529            signCount: 0,1530            aaguid: "",1531            backupEligible: false,1532            backupState: false,1533            createdAt: 1,1534          },1535        })}1536        onDelete={vi.fn()}1537        onFieldSaved={vi.fn(async () => undefined)}1538      />1539    );15401541    const advanced = Array.from(container.querySelectorAll(".peach-entry-add-link")).find(1542      (button) => button.textContent?.includes("Advanced")1543    ) as HTMLButtonElement | undefined;1544    expect(advanced).toBeDefined();1545    expect(advanced?.textContent).toContain("+ Advanced");15461547    advanced!.click();1548    await flushView();15491550    expect(container.textContent).toContain("passkey · vercel.com");1551  });15521553  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {1554    sendMessageMock.mockResolvedValue({ ok: true });1555    const onFieldSaved = vi.fn(async () => undefined);1556    const container = mount(1557      <EntryView1558        entry={sampleEntry()}1559        onDelete={vi.fn()}1560        onFieldSaved={onFieldSaved}1561      />1562    );15631564    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;1565    passwordValue.click();1566    await flushView();15671568    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;1569    inputText(passwordInput, "");1570    await flushView();15711572    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1573    saveButton.click();1574    await flushView();15751576    expect(sendMessageMock).not.toHaveBeenCalledWith(1577      expect.objectContaining({ type: "UPDATE_ENTRY" })1578    );1579    expect(onFieldSaved).not.toHaveBeenCalled();15801581    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1582    totpMain.click();15831584    await vi.waitFor(() => {1585      expect(sendMessageMock).toHaveBeenLastCalledWith({1586        type: "COPY",1587        payload: { text: "123456", label: "totp", alreadyWritten: false },1588      });1589    }, { timeout: 500 });1590  });15911592  it("Entry closes an unchanged inline editor when focus leaves it", async () => {1593    sendMessageMock.mockResolvedValue({ ok: true });1594    const container = mount(1595      <EntryView1596        entry={sampleEntry()}1597        onDelete={vi.fn()}1598        onFieldSaved={vi.fn(async () => undefined)}1599      />1600    );16011602    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;1603    usernameValue.click();1604    await flushView();16051606    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;1607    usernameInput.blur();1608    await flushView();16091610    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();1611    expect(sendMessageMock).not.toHaveBeenCalledWith(1612      expect.objectContaining({ type: "UPDATE_ENTRY" })1613    );1614  });16151616  it("Entry keeps the full used-email list available while editing an email", async () => {1617    const container = mount(1618      <EntryView1619        entry={sampleEntry({ email: "[email protected]" })}1620        entries={[1621          sampleEntry({ email: "[email protected]" }),1622          sampleEntry({ id: "entry-2", email: "[email protected]" }),1623          sampleEntry({ id: "entry-3", username: "duckuccino" }),1624        ]}1625        onDelete={vi.fn()}1626        onFieldSaved={vi.fn(async () => undefined)}1627      />1628    );16291630    const emailValue = Array.from(container.querySelectorAll(".peach-field-card")).find(1631      (card) => card.querySelector(".peach-label")?.textContent === "email"1632    )?.querySelector(".peach-inline-clickable") as HTMLSpanElement;1633    emailValue.click();1634    await flushView();16351636    const suggestions = Array.from(container.querySelectorAll(".peach-identity-suggestion-value"))1637      .map((element) => element.textContent);1638    expect(suggestions).toEqual(["[email protected]", "[email protected]"]);1639  });16401641  it("Entry lets TOTP secrets be edited inline", async () => {1642    sendMessageMock.mockResolvedValue({ ok: true });1643    const onFieldSaved = vi.fn(async () => undefined);1644    const container = mount(1645      <EntryView1646        entry={sampleEntry()}1647        onDelete={vi.fn()}1648        onFieldSaved={onFieldSaved}1649      />1650    );16511652    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1653    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));1654    await flushView();16551656    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;1657    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");1658    await flushView();16591660    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1661    saveButton.click();1662    await flushView();16631664    expect(sendMessageMock).toHaveBeenCalledWith({1665      type: "UPDATE_ENTRY",1666      payload: {1667        id: "entry-1",1668        patch: { totp: "NB2W45DFOIZA====" },1669      },1670    });1671    expect(onFieldSaved).toHaveBeenCalled();1672  });16731674  it("Vault seeds and focuses search when a search seed is provided", async () => {1675    const container = mount(1676      <VaultView1677        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1678        sortOrder="url-first"1679        searchSeed="g"1680        searchSeedNonce={1}1681        onSelectEntry={vi.fn()}1682        onSortOrderChange={vi.fn()}1683        onAdd={vi.fn()}1684        onClose={vi.fn()}1685      />1686    );16871688    await flushView();16891690    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1691    expect(search.value).toBe("g");1692    expect(document.activeElement).toBe(search);1693  });16941695  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1696    parseImportSourceMock.mockResolvedValue(1697      sampleImportResult({1698        entries: [1699          {1700            type: "login",1701            title: "Imported site",1702            username: "imported-user",1703            password: "imported-pass",1704            url: "https://imported.test",1705          },1706        ],1707      })1708    );1709    sendMessageMock.mockImplementation(async (msg: unknown) => {1710      const type = (msg as { type?: string }).type;1711      if (type === "GET_ENTRIES") {1712        return {1713          ok: true,1714          data: [1715            sampleEntry({1716              id: "existing-1",1717              title: "Imported site",1718              username: "imported-user",1719              url: "https://imported.test",1720            }),1721          ],1722        };1723      }1724      if (type === "BATCH_ADD_ENTRIES") {1725        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1726      }1727      return { ok: true };1728    });1729    const onImport = vi.fn(async () => undefined);1730    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1731    await flushView();1732    sendMessageMock.mockClear();17331734    await selectImportFile(container);1735    findButton(container, "Import 1").click();1736    await flushView();17371738    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}');1739    expect(sendMessageMock).toHaveBeenCalledWith({1740      type: "BATCH_ADD_ENTRIES",1741      payload: {1742        entries: [1743          expect.objectContaining({1744            title: "Imported site",1745            username: "imported-user",1746            password: "imported-pass",1747            url: "https://imported.test",1748          }),1749        ],1750      },1751    });1752    expect(onImport).toHaveBeenCalled();1753    expect(container.textContent).toContain("1 entry appears to be duplicates");1754  });17551756  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1757    parseImportSourceMock.mockResolvedValue(sampleImportResult());1758    sendMessageMock.mockImplementation(async (msg: unknown) => {1759      const type = (msg as { type?: string }).type;1760      if (type === "GET_ENTRIES") {1761        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1762      }1763      if (type === "CLEAR_VAULT_ENTRIES") {1764        return { ok: true };1765      }1766      if (type === "BATCH_ADD_ENTRIES") {1767        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1768      }1769      return { ok: true };1770    });1771    const onImport = vi.fn(async () => undefined);1772    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1773    await flushView();1774    sendMessageMock.mockClear();17751776    await selectImportFile(container);1777    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1778    await flushView();17791780    findButton(container, "Replace vault with 1").click();1781    await flushView();17821783    expect(sendMessageMock).not.toHaveBeenCalledWith(1784      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1785    );1786    expect(container.textContent).toContain("Replace forever? This cannot be undone.");17871788    findButton(container, "Yes, replace forever").click();1789    await flushView();17901791    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1792    expect(sendMessageMock).toHaveBeenCalledWith({1793      type: "BATCH_ADD_ENTRIES",1794      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1795    });1796    expect(onImport).toHaveBeenCalled();1797  });17981799  it.each([true, false])("Import onboarding mode creates only after matching passwords (replacement %s)", async (replacesExistingVault) => {1800    parseImportSourceMock.mockResolvedValue(sampleImportResult());1801    sendMessageMock.mockImplementation(async (msg: unknown) => {1802      const type = (msg as { type?: string }).type;1803      if (type === "CREATE_VAULT") return { ok: true };1804      if (type === "BATCH_ADD_ENTRIES") {1805        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1806      }1807      return { ok: true };1808    });1809    const onImport = vi.fn(async () => undefined);1810    const container = mount(1811      <ImportView1812        mode="onboarding"1813        replacesExistingVault={replacesExistingVault}1814        onBack={vi.fn()}1815        onImport={onImport}1816      />1817    );18181819    await selectImportFile(container);18201821    const createButton = findButton(container, "Create vault + import 1");1822    expect(createButton.disabled).toBe(true);1823    expect(container.textContent?.includes("Restoring now replaces the locked local vault")).toBe(replacesExistingVault);1824    expect(container.textContent).toContain("Use at least 8 characters");18251826    const masterInput = container.querySelector(1827      'input[placeholder="new master password"]'1828    ) as HTMLInputElement;1829    const confirmInput = container.querySelector(1830      'input[placeholder="confirm master password"]'1831    ) as HTMLInputElement;1832    const revealButton = container.querySelector(1833      'button[aria-label="Show passwords"]'1834    ) as HTMLButtonElement;1835    expect(revealButton).toBeTruthy();1836    revealButton.click();1837    await flushView();1838    expect(masterInput.type).toBe("text");1839    expect(confirmInput.type).toBe("text");18401841    inputText(masterInput, "fresh-master-password");1842    inputText(confirmInput, "fresh-master-password");1843    await flushView();18441845    expect(createButton.disabled).toBe(false);1846    createButton.click();1847    await flushView();18481849    expect(sendMessageMock).toHaveBeenCalledWith({1850      type: "CREATE_VAULT",1851      payload: { password: "fresh-master-password", ...(replacesExistingVault ? { replacement: "warned-import" } : {}) },1852    });1853    expect(sendMessageMock).toHaveBeenCalledWith({1854      type: "BATCH_ADD_ENTRIES",1855      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1856    });1857    expect(onImport).toHaveBeenCalled();1858  });18591860});