123import 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 { LockView } from "./Lock";10import { ExportView } from "./Export";11import { SettingsView } from "./Settings";12import { DEFAULT_BINDINGS } from "../../shared/shortcuts";13import { EntryView } from "./Entry";14import { ImportView } from "./Import";15import { AddView } from "./Add";16import { NotesEditor } from "./NotesEditor";17import { RecoveryWordEntryView } from "./RecoveryWordEntry";18import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";19import { VaultView } from "./Vault";20import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";2122const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();23const triggerRingMock = vi.fn();24const triggerPipPulseMock = vi.fn();25const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();26const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2728vi.mock("../App", () => ({29 sendMessage: (msg: unknown) => sendMessageMock(msg),30 triggerRing: () => triggerRingMock(),31 triggerPipPulse: () => triggerPipPulseMock(),32}));3334vi.mock("../../shared/bridge", () => ({35 sendMessage: (msg: unknown) => sendMessageMock(msg),36}));3738vi.mock("../../shared/import", () => ({39 parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),40}));4142vi.mock("../../shared/favicon", async (importOriginal) => {43 const actual = await importOriginal<typeof import("../../shared/favicon")>();44 return { ...actual, faviconUrl: () => null };45});4647vi.mock("../../crypto/totp", () => ({48 generateTOTP: () => ({ code: "123 456", remaining: 24 }),49 parseOtpauthURI: (value: string) =>50 value.startsWith("otpauth://")51 ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }52 : null,53}));5455vi.mock("../components/GeneratorDrawer", () => ({56 GeneratorDrawer: () => null,57}));5859vi.mock("../components/RuneBackground", () => ({60 RuneBackground: () => null,61}));6263vi.mock("@zxcvbn-ts/core", () => ({64 zxcvbn: (value: string) => zxcvbnMock(value),65 zxcvbnOptions: { setOptions: vi.fn() },66}));67vi.mock("@zxcvbn-ts/language-common", () => ({68 adjacencyGraphs: {},69 dictionary: {},70}));71vi.mock("@zxcvbn-ts/language-en", () => ({72 translations: {},73 dictionary: {},74}));7576describe("popup contract tests", () => {77 const disposers: Array<() => void> = [];7879 beforeEach(() => {80 document.body.innerHTML = "";81 sendMessageMock.mockReset();82 triggerRingMock.mockReset();83 triggerPipPulseMock.mockReset();84 parseImportSourceMock.mockReset();85 zxcvbnMock.mockReset();86 zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));87 parseImportSourceMock.mockResolvedValue({88 format: "unknown",89 label: "Unknown format",90 entries: [],91 totalItems: 0,92 skippedItems: 0,93 });9495 vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {96 return window.setTimeout(() => cb(0), 0) as unknown as number;97 });98 vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));99 vi.stubGlobal("URL", {100 createObjectURL: vi.fn(() => "blob:peach-test"),101 revokeObjectURL: vi.fn(),102 });103 vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});104105 (globalThis as { chrome?: typeof chrome }).chrome = {106 runtime: {107 getManifest: () => ({ version: "1.4.47" }),108 onMessage: { addListener: vi.fn() },109 },110 } as unknown as typeof chrome;111 });112113 afterEach(() => {114 while (disposers.length > 0) {115 disposers.pop()?.();116 }117 vi.restoreAllMocks();118 vi.unstubAllGlobals();119 });120121 function mount(view: JSX.Element | (() => JSX.Element)) {122 const mounted = renderView(view);123 disposers.push(mounted.dispose);124 return mounted.container;125 }126127 function sampleEntry(overrides: Partial<VaultEntry> = {}): VaultEntry {128 return {129 id: "entry-1",130 type: "login",131 title: "GitHub",132 username: "june",133 password: "secret123",134 url: "https://github.com",135 totp: "JBSWY3DPEHPK3PXP",136 canary: {137 webhookUrl: "https://example.com/hook",138 },139 createdAt: 1,140 modifiedAt: 1,141 ...overrides,142 };143 }144145 function sampleImportResult(146 overrides: Partial<ImportParseResult> = {}147 ): ImportParseResult {148 return {149 format: "csv",150 label: "CSV import",151 entries: [152 {153 type: "login",154 title: "Imported site",155 username: "imported-user",156 password: "imported-pass",157 url: "https://imported.test",158 },159 ],160 totalItems: 1,161 skippedItems: 0,162 ...overrides,163 };164 }165166 function settingsProps(overrides: Partial<Parameters<typeof SettingsView>[0]> = {}) {167 return {168 entriesCount: 1,169 breachMonitoring: true,170 lockOnClose: true,171 autoLockMinutes: 5,172 lockedSyncRequiresUnlock: false,173 trashRetentionDays: 30,174 theme: "dark" as const,175 accentColor: "peach" as const,176 textSize: "medium" as const,177 reduceMotion: false,178 onBreachMonitoringChange: vi.fn(),179 onLockOnCloseChange: vi.fn(),180 onAutoLockMinutesChange: vi.fn(),181 onTrashRetentionChange: vi.fn(),182 onLockedSyncRequiresUnlockChange: vi.fn(),183 onThemeChange: vi.fn(),184 onAccentChange: vi.fn(),185 onTextSizeChange: vi.fn(),186 onReduceMotionChange: vi.fn(),187 shortcuts: DEFAULT_BINDINGS,188 onShortcutsChange: vi.fn(),189 onBack: vi.fn(),190 onImport: vi.fn(),191 onExport: vi.fn(),192 onBreachCheckDone: vi.fn(),193 ...overrides,194 };195 }196197 async function selectImportFile(198 container: HTMLElement,199 contents = '{"export":"test"}'200 ) {201 202 203 204 const fileCard = findButton(container, "Choose file →");205 if (fileCard) {206 fileCard.click();207 await flushView();208 }209 const input = container.querySelector('input[type="file"]') as HTMLInputElement;210 const file = new File([contents], "import.json", { type: "application/json" });211 Object.defineProperty(input, "files", {212 configurable: true,213 value: [file],214 });215 input.dispatchEvent(new Event("change", { bubbles: true }));216 await flushView();217 await flushView();218 }219220 function findButton(container: HTMLElement, text: string): HTMLButtonElement {221 return Array.from(container.querySelectorAll("button")).find(222 (candidate) => candidate.textContent?.trim() === text223 ) as HTMLButtonElement;224 }225226 it("Lock sends UNLOCK with the entered passphrase", async () => {227 sendMessageMock.mockResolvedValue({ ok: true });228 const onUnlock = vi.fn(async () => undefined);229 const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);230231 const password = container.querySelector("#unlock-password") as HTMLInputElement;232 inputText(password, "correct horse battery staple");233 (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();234 await flushView();235236 expect(sendMessageMock).toHaveBeenCalledWith({237 type: "UNLOCK",238 payload: { password: "correct horse battery staple" },239 });240 expect(onUnlock).toHaveBeenCalled();241 });242243 it("Lock uses a configured preferred PIN and keeps the password fallback available", async () => {244 sendMessageMock.mockImplementation(async (msg: unknown) => {245 const type = (msg as { type: string }).type;246 if (type === "GET_PIN_STATUS") {247 return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };248 }249 return type === "GET_SETTINGS"250 ? { ok: true, data: { pinEnabled: true, pinPreferred: true } }251 : { ok: true };252 });253 const onUnlock = vi.fn(async () => undefined);254 const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);255 await flushView();256257 inputText(container.querySelector("#unlock-pin") as HTMLInputElement, "1234");258 (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();259 await flushView();260261 expect(sendMessageMock).toHaveBeenCalledWith({262 type: "UNLOCK_WITH_PIN",263 payload: { pin: "1234" },264 });265 expect(onUnlock).toHaveBeenCalled();266 expect(container.textContent).toContain("use master password");267 });268269 it("places the PIN method switch below the unlock button", async () => {270 sendMessageMock.mockImplementation(async (msg: unknown) => {271 const type = (msg as { type: string }).type;272 if (type === "GET_PIN_STATUS") {273 return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };274 }275 return type === "GET_SETTINGS"276 ? { ok: true, data: { pinEnabled: true, pinPreferred: false } }277 : { ok: true };278 });279 const container = mount(<LockView hasVault={true} ready={true} onUnlock={vi.fn()} />);280 await flushView();281282 const buttons = Array.from(container.querySelectorAll("button"));283 const unlockIndex = buttons.findIndex((button) => button.textContent?.trim() === "unlock");284 const pinIndex = buttons.findIndex((button) => button.textContent?.trim() === "use PIN");285 expect(pinIndex).toBeGreaterThan(unlockIndex);286 });287288 it("keeps standalone note creation in Notes mode", async () => {289 const chromeApi = globalThis.chrome as unknown as {290 tabs?: { query: (queryInfo: object, callback: (tabs: unknown[]) => void) => void };291 };292 chromeApi.tabs = { query: vi.fn((_queryInfo, callback) => callback([])) };293294 const addContainer = mount(<AddView onBack={vi.fn()} onSave={vi.fn()} />);295 await flushView();296297 expect(Array.from(addContainer.querySelectorAll(".peach-new-type-btn")).map((button) => button.textContent?.trim()))298 .toEqual(["login", "card"]);299 expect(addContainer.querySelector(".peach-note-editor-body--inline")).toBeNull();300 });301302 it("gives Notes mode the full note-formatting toolbar", async () => {303 const container = mount(304 <NotesEditor305 note={null}306 onBack={vi.fn()}307 onSaved={vi.fn()}308 onDelete={vi.fn()}309 />310 );311 await flushView();312313 expect(container.querySelector('[title="Strikethrough"]')).toBeTruthy();314 expect(container.querySelector('[title="Divider"]')).toBeTruthy();315 expect(container.querySelector('[title="Quote"]')).toBeTruthy();316 expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button")).toHaveLength(9);317 expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button svg")).toHaveLength(9);318 expect(container.querySelector(".peach-notes-header-title")?.textContent).toBe("notes.");319 });320321 it("saves formatting applied by the Notes toolbar before leaving", async () => {322 const savedNote = {323 id: "note-1",324 type: "note" as const,325 title: "Untitled",326 notes: "<b>formatted</b>",327 createdAt: 1,328 modifiedAt: 2,329 };330 sendMessageMock.mockResolvedValue({ ok: true, data: savedNote });331 const originalExecCommand = document.execCommand;332 const execCommandMock = vi.fn(() => {333 const body = document.querySelector<HTMLDivElement>(".peach-note-body-field");334 if (body) body.innerHTML = "<b>formatted</b>";335 return true;336 });337 Object.defineProperty(document, "execCommand", { configurable: true, value: execCommandMock });338339 try {340 const container = mount(341 <NotesEditor342 note={null}343 onBack={vi.fn()}344 onSaved={vi.fn()}345 onDelete={vi.fn()}346 />347 );348 await flushView();349 container.querySelector<HTMLButtonElement>('[title="Bold"]')?.dispatchEvent(350 new MouseEvent("mousedown", { bubbles: true, cancelable: true })351 );352 expect(execCommandMock).toHaveBeenCalledWith("bold", false, undefined);353 container.querySelector<HTMLButtonElement>('[aria-label="Back to notes list"]')?.click();354 await flushView();355356 expect(sendMessageMock).toHaveBeenCalledWith({357 type: "SAVE_NOTE",358 payload: { id: undefined, title: "Untitled", body: "<b>formatted</b>" },359 });360 } finally {361 Object.defineProperty(document, "execCommand", { configurable: true, value: originalExecCommand });362 }363 });364365 it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {366 const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);367 const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;368 const password = container.querySelector("#master-password") as HTMLInputElement;369 const confirm = container.querySelector("#confirm-password") as HTMLInputElement;370371 inputText(password, "short");372 inputText(confirm, "short");373 await flushView();374 expect(createButton.disabled).toBe(true);375376 zxcvbnMock.mockImplementation(() => ({ score: 1 }));377 inputText(password, "weakweakweak");378 inputText(confirm, "weakweakweak");379 await flushView();380 expect(createButton.disabled).toBe(true);381 });382383 it("Lock create-vault header pins the wordmark left with back on the right", async () => {384 const container = mount(385 <LockView386 hasVault={false}387 ready={true}388 onUnlock={vi.fn()}389 onBackToOnboarding={() => {}}390 />391 );392 const header = container.querySelector(".peach-newvault-header") as HTMLElement;393 const wordmark = header.querySelector(".peach-wordmark-stack");394 const back = header.querySelector(".peach-newvault-back");395 expect(wordmark).toBeTruthy();396 expect(back).toBeTruthy();397 398 399 expect(header.firstElementChild).toBe(wordmark);400 expect(header.lastElementChild).toBe(back);401 await flushView();402 });403404 it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {405 406 sendMessageMock.mockImplementation(407 async (msg: unknown) => {408 const m = msg as { type: string; payload?: { password?: string } };409 if (m.type === "CREATE_VAULT") return { ok: true };410 if (m.type === "GET_RECOVERY_WORDS") {411 412 return {413 ok: true,414 data: [415 "abandon", "ability", "able", "about", "above", "absent",416 "absorb", "abstract", "absurd", "abuse", "access", "accident",417 ],418 };419 }420 return { ok: true };421 }422 );423 zxcvbnMock.mockImplementation(() => ({ score: 3 }));424 const onUnlock = vi.fn(async () => undefined);425 const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);426427 const password = container.querySelector("#master-password") as HTMLInputElement;428 const confirm = container.querySelector("#confirm-password") as HTMLInputElement;429 const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;430431 inputText(password, "correct horse battery staple");432 inputText(confirm, "correct horse battery staple");433 await flushView();434 expect(createButton.disabled).toBe(false);435436 pressEnter(confirm);437 await flushView();438439 expect(sendMessageMock).toHaveBeenCalledWith({440 type: "CREATE_VAULT",441 payload: { password: "correct horse battery staple" },442 });443 444 445 expect(onUnlock).not.toHaveBeenCalled();446 });447448 it("recovery display asks for three distinct randomized word positions and confirms", async () => {449 const words12 = [450 "abandon", "ability", "able", "about", "above", "absent",451 "absorb", "abstract", "absurd", "abuse", "access", "accident",452 ];453 sendMessageMock.mockImplementation(async (msg: unknown) => {454 const type = (msg as { type?: string }).type;455 if (type === "GET_RECOVERY_WORDS") return { ok: true, data: words12 };456 return { ok: true };457 });458459 vi.useFakeTimers();460 const onDone = vi.fn();461 try {462 const container = mount(<RecoveryWordDisplayView onDone={onDone} />);463 464 await vi.advanceTimersByTimeAsync(0);465466 const prompts = Array.from(467 container.querySelectorAll(".peach-recovery-confirm-num")468 ).map((el) => Number.parseInt((el.textContent ?? "").replace(/\D+/g, ""), 10));469 expect(prompts).toHaveLength(3);470 expect(new Set(prompts).size).toBe(3);471 for (const p of prompts) {472 expect(p).toBeGreaterThanOrEqual(1);473 expect(p).toBeLessThanOrEqual(12);474 }475476 477 const inputs = Array.from(478 container.querySelectorAll(".peach-recovery-confirm-input")479 ) as HTMLInputElement[];480 expect(inputs).toHaveLength(3);481 expect(inputs[0]!.disabled).toBe(true);482 await vi.advanceTimersByTimeAsync(5000);483 expect(inputs[0]!.disabled).toBe(false);484485 prompts.forEach((pos, i) => {486 inputText(inputs[i]!, words12[pos - 1]!);487 });488489 const confirmBtn = container.querySelector(".peach-recovery-confirm-btn") as HTMLButtonElement;490 expect(confirmBtn.disabled).toBe(false);491 confirmBtn.click();492 await vi.advanceTimersByTimeAsync(700); 493494 expect(onDone).toHaveBeenCalledTimes(1);495 } finally {496 vi.useRealTimers();497 }498 });499500 it.each([true, false])("Recovery words flow reports whether the saved password unlocked the vault (%s)", async (unlocked) => {501 sendMessageMock.mockImplementation(async (msg: unknown) => {502 const type = (msg as { type?: string }).type;503 if (type === "VALIDATE_RECOVERY_WORDS") {504 return { ok: true, data: { valid: true, invalid: [] } };505 }506 if (type === "RECOVER_WITH_WORDS") return { ok: true, data: { committed: true, unlocked } };507 return { ok: true };508 });509 const canvasContext = {510 clearRect: vi.fn(),511 fillText: vi.fn(),512 beginPath: vi.fn(),513 closePath: vi.fn(),514 arc: vi.fn(),515 fill: vi.fn(),516 stroke: vi.fn(),517 save: vi.fn(),518 restore: vi.fn(),519 translate: vi.fn(),520 rotate: vi.fn(),521 scale: vi.fn(),522 drawImage: vi.fn(),523 measureText: vi.fn(() => ({ width: 0 })),524 setTransform: vi.fn(),525 fillRect: vi.fn(),526 strokeRect: vi.fn(),527 } as unknown as CanvasRenderingContext2D;528 vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);529530 const onRecoveryComplete = vi.fn(async () => undefined);531 const onCancel = vi.fn();532 const container = mount(533 <RecoveryWordEntryView534 onCancel={onCancel}535 onRecoveryComplete={onRecoveryComplete}536 />537 );538539 const recoveryWords = WORD_LIST.slice(0, 12);540 for (let i = 0; i < recoveryWords.length; i++) {541 const input = container.querySelector(`#recovery-word-${i}`) as HTMLInputElement;542 inputText(input, recoveryWords[i]!);543 }544 await flushView();545546 findButton(container, "verify words").click();547 await flushView();548549 expect(container.textContent).toContain("new master password");550551 const newPassword = container.querySelector("#recovery-new-password") as HTMLInputElement;552 const confirmPassword = container.querySelector("#recovery-confirm-password") as HTMLInputElement;553 inputText(newPassword, "fresh-recovery-password");554 inputText(confirmPassword, "fresh-recovery-password");555 await flushView();556557 findButton(container, "recover vault").click();558 await flushView();559560 expect(sendMessageMock).toHaveBeenCalledWith({561 type: "RECOVER_WITH_WORDS",562 payload: {563 words: recoveryWords,564 newPassword: "fresh-recovery-password",565 },566 });567 if (unlocked) expect(onRecoveryComplete).toHaveBeenCalled();568 else {569 expect(onRecoveryComplete).not.toHaveBeenCalled();570 expect(container.textContent).toContain("your new password is saved");571 expect(container.textContent).toContain("use your new password to unlock your vault");572 expect(container.textContent).not.toContain("recovery failed");573 findButton(container, "back to unlock").click();574 expect(onCancel).toHaveBeenCalledOnce();575 }576 });577578 it("Export menu surfaces both backup formats", async () => {579 const container = mount(<ExportView onBack={vi.fn()} />);580 await flushView();581582 expect(container.textContent).toContain("PeachScript");583 expect(container.textContent).toContain("CSV");584 });585586 it("Lock can open directly on backup restore from onboarding", async () => {587 const container = mount(() => (588 <LockView589 hasVault={false}590 ready={true}591 onUnlock={vi.fn()}592 initialRestore={true}593 />594 ));595 await flushView();596597 expect(container.textContent).toContain("PeachScript");598 expect(container.textContent).toContain("Codex");599 expect(container.textContent).toContain("CSV");600 expect(container.querySelector("#master-password")).toBeNull();601 });602603 it("Lock restore back returns to onboarding, not the create-vault screen", async () => {604 const onBackToOnboarding = vi.fn();605 const container = mount(() => (606 <LockView607 hasVault={false}608 ready={true}609 onUnlock={vi.fn()}610 initialRestore={true}611 onBackToOnboarding={onBackToOnboarding}612 />613 ));614 await flushView();615616 (container.querySelector(".peach-restore-back") as HTMLButtonElement).click();617 await flushView();618 expect(onBackToOnboarding).toHaveBeenCalledTimes(1);619 });620621 it("Lock restore resumes on the picked PeachScript source, not the picker", async () => {622 const container = mount(() => (623 <LockView624 hasVault={false}625 ready={true}626 onUnlock={vi.fn()}627 initialRestore={true}628 initialRestoreSource="symbols"629 />630 ));631 await flushView();632633 expect(container.querySelector(".peach-restore-script")).toBeTruthy();634 expect(container.querySelector("#restore-backup-pass")).toBeTruthy();635 expect(container.querySelector(".peach-restore-sources")).toBeNull();636 });637638 it("Lock restore resumes on the picked CSV source, not the picker", async () => {639 const container = mount(() => (640 <LockView641 hasVault={false}642 ready={true}643 onUnlock={vi.fn()}644 initialRestore={true}645 initialRestoreSource="csv"646 />647 ));648 await flushView();649650 expect(container.querySelector("#restore-csv-pass")).toBeTruthy();651 expect(container.querySelector("#restore-csv-confirm")).toBeTruthy();652 expect(container.querySelector(".peach-restore-sources")).toBeNull();653 });654655 it("Lock restore PeachScript form loads a dropped .peach file", async () => {656 const container = mount(() => (657 <LockView658 hasVault={false}659 ready={true}660 onUnlock={vi.fn()}661 initialRestore={true}662 initialRestoreSource="symbols"663 />664 ));665 await flushView();666667 const form = container.querySelector(".peach-restore-form") as HTMLElement;668 expect(form).toBeTruthy();669670 671 672 const file = new File(["dropped-peach-backup"], "vault.peach", { type: "text/plain" });673 const drop = new Event("drop", { bubbles: true, cancelable: true }) as Event & {674 dataTransfer?: { files: File[] };675 };676 drop.dataTransfer = { files: [file] };677 form.dispatchEvent(drop);678 await flushView();679680 const script = container.querySelector(".peach-restore-script") as HTMLTextAreaElement;681 expect(script.value).toBe("dropped-peach-backup");682 });683684 it("HOLE 4: removing a device discloses that recovery words survive revocation", async () => {685 const device = {686 deviceId: "phone-1",687 deviceName: "June's Phone",688 deviceType: "android" as const,689 longTermPublicKeyHex: "a".repeat(64),690 signingPublicKeyHex: "b".repeat(64),691 pairedAt: 1,692 trustSource: "direct" as const,693 };694 sendMessageMock.mockImplementation(async (msg: unknown) => {695 const m = msg as { type: string };696 if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };697 return { ok: true, data: null };698 });699700 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);701 for (let i = 0; i < 30; i++) await Promise.resolve();702703 const openSync = Array.from(container.querySelectorAll("button")).find((b) =>704 /sync/i.test(b.textContent ?? ""),705 );706 openSync?.click();707 for (let i = 0; i < 30; i++) await Promise.resolve();708709 const remove = Array.from(container.querySelectorAll("button")).find(710 (b) => (b.textContent ?? "").trim() === "remove",711 );712 expect(remove).toBeTruthy();713714 715 716 expect(container.querySelector(".peach-unpair-confirm-note")).toBeNull();717718 remove!.click();719 for (let i = 0; i < 10; i++) await Promise.resolve();720721 722 723 const note = container.querySelector(".peach-unpair-confirm-note");724 expect(note).toBeTruthy();725 const text = note!.textContent ?? "";726 expect(text).toContain("master password");727 expect(text).toContain("recovery words");728 expect(text).toContain("future changes");729 });730731 it("PB-26-709: pending device approval identifies the key, time, provenance, and vault scope", async () => {732 sendMessageMock.mockImplementation(async (msg: unknown) => {733 const m = msg as { type: string };734 if (m.type === "GET_PENDING_VOUCHED_DEVICES") {735 return {736 ok: true,737 data: [{738 deviceId: "phone-source-id",739 deviceName: "June's Phone",740 deviceType: "android",741 longTermPublicKeyHex: "a1b2c3d4e5f6" + "0".repeat(52),742 signingPublicKeyHex: "b".repeat(64),743 pairedAt: Date.UTC(2026, 8, 5),744 receivedAt: Date.UTC(2026, 8, 6, 20, 15),745 vouchedByDeviceId: "trusted-browser-id",746 }],747 };748 }749 if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [] } };750 return { ok: true, data: null };751 });752753 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);754 for (let i = 0; i < 30; i++) await Promise.resolve();755 Array.from(container.querySelectorAll("button"))756 .find((button) => /sync/i.test(button.textContent ?? ""))757 ?.click();758 for (let i = 0; i < 30; i++) await Promise.resolve();759760 expect(container.textContent).toContain("a1b2 c3d4 e5f6");761 expect(container.textContent).toContain("trusted-browser-id");762 expect(container.textContent).toContain("2026-09-06");763 expect(container.textContent).toContain("existing vault contents");764 });765766 it("Settings keeps the paired-device list and revokes through UNPAIR_DEVICE", async () => {767 const device = {768 deviceId: "phone-1",769 deviceName: "June's Phone",770 deviceType: "android" as const,771 longTermPublicKeyHex: "a".repeat(64),772 signingPublicKeyHex: "b".repeat(64),773 pairedAt: 1,774 trustSource: "direct" as const,775 };776 let paired: typeof device[] = [device];777 sendMessageMock.mockImplementation(async (msg: any) => {778 if (msg?.type === "LIST_PAIRED_DEVICES") {779 return { ok: true, data: { devices: [...paired] } };780 }781 if (msg?.type === "UNPAIR_DEVICE") {782 783 784 paired = paired.filter((d) => d.deviceId !== msg.payload?.deviceId);785 return { ok: true };786 }787 if (msg?.type === "RENAME_PAIRED_DEVICE") {788 paired = paired.map((d) =>789 d.deviceId === msg.payload?.deviceId ? { ...d, localAlias: msg.payload.name } : d,790 );791 return { ok: true };792 }793 return { ok: true, data: null };794 });795796 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);797 for (let i = 0; i < 30; i++) await Promise.resolve();798 Array.from(container.querySelectorAll("button"))799 .find((b) => /sync/i.test(b.textContent ?? ""))800 ?.click();801 for (let i = 0; i < 30; i++) await Promise.resolve();802803 804 expect(container.textContent).toContain("PAIRED DEVICES");805 expect(container.textContent).toContain("June's Phone");806 expect(container.textContent).toContain("Android");807 Array.from(container.querySelectorAll("button"))808 .find((b) => (b.textContent ?? "").trim() === "rename")!809 .click();810 const renameInput = container.querySelector<HTMLInputElement>('input[aria-label="Rename June\'s Phone"]')!;811 renameInput.value = "Travel phone";812 renameInput.dispatchEvent(new InputEvent("input", { bubbles: true }));813 Array.from(container.querySelectorAll("button"))814 .find((b) => (b.textContent ?? "").trim() === "save")!815 .click();816 for (let i = 0; i < 30; i++) await Promise.resolve();817 expect(sendMessageMock).toHaveBeenCalledWith({818 type: "RENAME_PAIRED_DEVICE",819 payload: { deviceId: "phone-1", name: "Travel phone" },820 });821 expect(container.textContent).toContain("Travel phone");822 const syncNowButton = container.querySelector<HTMLButtonElement>(823 'button[aria-label="Sync this vault now"]',824 )!;825 const syncStatusRow = syncNowButton.closest(".peach-settings-row--meta");826 const syncCard = syncNowButton.closest('[data-settings-card-id="sync"]');827 expect(syncStatusRow).not.toBeNull();828 expect(syncStatusRow?.contains(syncNowButton)).toBe(true);829 expect(syncCard?.querySelectorAll(".peach-settings-row--meta")).toHaveLength(1);830 const labels = Array.from(container.querySelectorAll(".peach-settings-sub-label"));831 const addDeviceLabel = labels.find((label) => label.textContent?.includes("ADD A DEVICE"))!;832 const pairedDevicesLabel = labels.find((label) => label.textContent?.includes("PAIRED DEVICES"))!;833 expect(834 syncNowButton.compareDocumentPosition(addDeviceLabel) & Node.DOCUMENT_POSITION_FOLLOWING,835 ).toBeTruthy();836 expect(837 syncNowButton.compareDocumentPosition(pairedDevicesLabel) & Node.DOCUMENT_POSITION_FOLLOWING,838 ).toBeTruthy();839840 Array.from(container.querySelectorAll("button"))841 .find((b) => (b.textContent ?? "").trim() === "remove")!842 .click();843 for (let i = 0; i < 10; i++) await Promise.resolve();844 const confirm = Array.from(845 container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),846 ).find((b) => (b.textContent ?? "").trim() === "remove");847 confirm!.click();848 for (let i = 0; i < 30; i++) await Promise.resolve();849850 expect(sendMessageMock).toHaveBeenCalledWith({851 type: "UNPAIR_DEVICE",852 payload: { deviceId: "phone-1" },853 });854 855 856 857 expect(container.textContent).not.toContain("June's Phone");858 expect(container.textContent).not.toContain("PAIRED DEVICES");859 });860 it("Settings keeps the confirmation and shows revoke failures", async () => {861 const device = {862 deviceId: "phone-1",863 deviceName: "June's Phone",864 deviceType: "android" as const,865 longTermPublicKeyHex: "a".repeat(64),866 signingPublicKeyHex: "b".repeat(64),867 pairedAt: 1,868 trustSource: "direct" as const,869 };870 sendMessageMock.mockImplementation(async (msg: unknown) => {871 const message = msg as { type?: string; payload?: { deviceId?: string } };872 if (message.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };873 if (message.type === "UNPAIR_DEVICE") return { ok: false, error: "trust_data_corrupted" };874 return { ok: true, data: null };875 });876877 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);878 for (let i = 0; i < 30; i++) await Promise.resolve();879 for (let i = 0; i < 30; i++) await Promise.resolve();880 Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();881 for (let i = 0; i < 30; i++) await Promise.resolve();882 Array.from(container.querySelectorAll("button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();883 for (let i = 0; i < 10; i++) await Promise.resolve();884 Array.from(container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();885 for (let i = 0; i < 30; i++) await Promise.resolve();886887 expect(container.textContent).toContain("trust_data_corrupted");888 expect(container.textContent).toContain("June's Phone");889 });890891 it("Settings drops the secure-reset panel once the device is on the settled generation", async () => {892 const openSyncCard = async (state: "V2_ACTIVE" | "V2_ANCHOR" | "LEGACY_ACTIVE") => {893 sendMessageMock.mockImplementation(async (msg: unknown) => {894 const message = msg as { type?: string };895 if (message.type === "GET_SYNC_GENERATION") {896 return { ok: true, data: { schemaVersion: 1, generation: 2, state, createdAt: 1 } };897 }898 return { ok: true, data: null };899 });900 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);901 for (let i = 0; i < 30; i++) await Promise.resolve();902 Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();903 for (let i = 0; i < 30; i++) await Promise.resolve();904 return container;905 };906907 908 const settled = await openSyncCard("V2_ACTIVE");909 expect(settled.textContent).not.toContain("SECURE SYNC RESET");910 expect(settled.textContent).toContain("ADD A DEVICE");911912 913 const anchored = await openSyncCard("V2_ANCHOR");914 expect(anchored.textContent).toContain("SECURE SYNC RESET");915 expect(anchored.textContent).toContain("Not re-paired");916917 const legacy = await openSyncCard("LEGACY_ACTIVE");918 expect(legacy.textContent).toContain("SECURE SYNC RESET");919 expect(legacy.textContent).toContain("Legacy Sync generation");920 });921922 it("Settings keeps connection and recovery details collapsed until requested", async () => {923 sendMessageMock.mockImplementation(async (msg: any) => {924 if (msg?.type === "LIST_PAIRED_DEVICES") {925 return { ok: true, data: { devices: [] } };926 }927 return { ok: true, data: null };928 });929930 const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);931 for (let i = 0; i < 30; i++) await Promise.resolve();932 Array.from(container.querySelectorAll("button"))933 .find((button) => /sync/i.test(button.textContent ?? ""))934 ?.click();935 for (let i = 0; i < 20; i++) await Promise.resolve();936937 expect(container.textContent).toContain("SYNC STATUS");938 expect(container.textContent).toContain("ADD A DEVICE");939 expect(container.textContent).not.toContain("Public relay");940 expect(container.textContent).not.toContain("Rotate sync identity");941942 const connection = Array.from(container.querySelectorAll("button"))943 .find((button) => button.textContent?.includes("CONNECTION"));944 connection?.click();945 await Promise.resolve();946 expect(container.textContent).toContain("Public relay");947948 const recovery = Array.from(container.querySelectorAll("button"))949 .find((button) => button.textContent?.includes("RECOVERY & SECURITY"));950 recovery?.click();951 await Promise.resolve();952 expect(container.textContent).toContain("Rotate sync identity");953 });954955 it("Settings requires current, new, and confirm passwords before enabling save", async () => {956 sendMessageMock.mockResolvedValue({ ok: true, data: null });957 const container = mount(958 <SettingsView959 entriesCount={1}960 breachMonitoring={true}961 lockOnClose={true}962 lockedSyncRequiresUnlock={false}963 autoLockMinutes={5}964 trashRetentionDays={30}965 theme="dark"966 accentColor="peach"967 textSize="medium"968 reduceMotion={false}969 onBreachMonitoringChange={vi.fn()}970 onLockedSyncRequiresUnlockChange={vi.fn()}971 onLockOnCloseChange={vi.fn()}972 onAutoLockMinutesChange={vi.fn()}973 onTrashRetentionChange={vi.fn()}974 onThemeChange={vi.fn()}975 onAccentChange={vi.fn()}976 onTextSizeChange={vi.fn()}977 onReduceMotionChange={vi.fn()}978 shortcuts={DEFAULT_BINDINGS}979 onShortcutsChange={vi.fn()}980 onBack={vi.fn()}981 onImport={vi.fn()}982 onExport={vi.fn()}983 onBreachCheckDone={vi.fn()}984 />985 );986 await flushView();987988 expect(container.querySelectorAll(".stk-card").length).toBe(7);989 990 991 expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");992993 const changeButton = Array.from(container.querySelectorAll("button")).find(994 (candidate) => candidate.textContent?.trim() === "change"995 ) as HTMLButtonElement;996 changeButton.click();997 await flushView();998999 const saveButton = Array.from(container.querySelectorAll("button")).find(1000 (candidate) => candidate.textContent?.trim() === "save new password"1001 ) as HTMLButtonElement;1002 expect(saveButton.disabled).toBe(true);10031004 const inputs = container.querySelectorAll('input[type="password"]');1005 inputText(inputs[0] as HTMLInputElement, "current-pass");1006 inputText(inputs[1] as HTMLInputElement, "new-pass-12345");1007 await flushView();1008 expect(saveButton.disabled).toBe(true);10091010 inputText(inputs[2] as HTMLInputElement, "new-pass-12345");1011 await flushView();1012 expect(saveButton.disabled).toBe(false);1013 });10141015 it("Settings feedback highlights the selected category and hides the form after submit", async () => {1016 sendMessageMock.mockResolvedValue({ ok: true, data: null });1017 const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1018 ok: true,1019 json: async () => ({ success: true }),1020 }));1021 vi.stubGlobal("fetch", fetchMock);10221023 const container = mount(1024 <SettingsView1025 entriesCount={1}1026 breachMonitoring={true}1027 lockOnClose={true}1028 lockedSyncRequiresUnlock={false}1029 autoLockMinutes={5}1030 trashRetentionDays={30}1031 theme="dark"1032 accentColor="peach"1033 textSize="medium"1034 reduceMotion={false}1035 initialSection="feedback"1036 onLockedSyncRequiresUnlockChange={vi.fn()}1037 onBreachMonitoringChange={vi.fn()}1038 onLockOnCloseChange={vi.fn()}1039 onAutoLockMinutesChange={vi.fn()}1040 onTrashRetentionChange={vi.fn()}1041 onThemeChange={vi.fn()}1042 onAccentChange={vi.fn()}1043 onTextSizeChange={vi.fn()}1044 onReduceMotionChange={vi.fn()}1045 shortcuts={DEFAULT_BINDINGS}1046 onShortcutsChange={vi.fn()}1047 onBack={vi.fn()}1048 onImport={vi.fn()}1049 onExport={vi.fn()}1050 onBreachCheckDone={vi.fn()}1051 />1052 );1053 await flushView();10541055 const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;1056 expect(feedbackCard.classList.contains("is-active")).toBe(true);10571058 const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];1059 const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;1060 const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;1061 expect(bugButton.getAttribute("aria-pressed")).toBe("true");1062 expect(featureButton.getAttribute("aria-pressed")).toBe("false");10631064 featureButton.click();1065 await flushView();10661067 expect(bugButton.getAttribute("aria-pressed")).toBe("false");1068 expect(featureButton.getAttribute("aria-pressed")).toBe("true");1069 expect(featureButton.classList.contains("is-active")).toBe(true);10701071 inputText(1072 container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1073 '<script>alert("xss")</script> Please make this easier to see & safer.'1074 );1075 const sendButton = Array.from(container.querySelectorAll("button")).find(1076 (candidate) => candidate.textContent?.trim() === "Send"1077 ) as HTMLButtonElement;1078 sendButton.click();10791080 await vi.waitFor(() => {1081 expect(container.textContent).toContain("Thank you");1082 });10831084 const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));1085 expect(requestBody.subject).toContain("Feature request");1086 expect(requestBody.message).toBe(1087 "<script>alert("xss")</script> Please make this easier to see & safer."1088 );1089 expect(requestBody.message).not.toContain("<script>");1090 expect(container.textContent).toContain("Someone will process it soon");1091 expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1092 expect(container.querySelector(".peach-feedback-submit")).toBeNull();1093 });10941095 it("Settings keeps license activation on the full-screen celebration path", async () => {1096 const onLicenseChange = vi.fn(async () => undefined);1097 sendMessageMock.mockImplementation(async (msg: unknown) => {1098 const type = (msg as { type?: string }).type;1099 if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };1100 if (type === "ACTIVATE_LICENSE") {1101 return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1102 }1103 if (type === "GET_ENTRIES") return { ok: true, data: [] };1104 return { ok: true, data: null };1105 });11061107 const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);1108 await flushView();11091110 inputText(1111 container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,1112 "PEACH-TEST-KEY",1113 );1114 const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;1115 apply.click();11161117 await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));1118 expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);1119 expect(container.textContent).not.toContain("thank you ✦");1120 });11211122 it("Settings Pro star and peach clicks use the same in-card replay path", async () => {1123 sendMessageMock.mockImplementation(async (msg: unknown) => {1124 const type = (msg as { type?: string }).type;1125 if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1126 if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };1127 if (type === "GET_ENTRIES") return { ok: true, data: [] };1128 return { ok: true, data: null };1129 });11301131 const onLicenseChangeFromStar = vi.fn();1132 const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);1133 await flushView();1134 (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();1135 expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1136 expect(onLicenseChangeFromStar).not.toHaveBeenCalled();11371138 const onLicenseChangeFromPeach = vi.fn();1139 const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);1140 await flushView();1141 (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();1142 expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1143 expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();1144 });11451146 it("Settings feedback sends even if Firefox reports no data-collection consent — a user-initiated send is its own consent", async () => {1147 sendMessageMock.mockResolvedValue({ ok: true, data: null });1148 const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1149 ok: true,1150 json: async () => ({ success: true }),1151 }));1152 vi.stubGlobal("fetch", fetchMock);1153 1154 1155 1156 vi.stubGlobal("browser", {1157 permissions: {1158 getAll: vi.fn(async () => ({ data_collection: [] })),1159 request: vi.fn(async () => false),1160 },1161 });11621163 const container = mount(1164 <SettingsView1165 entriesCount={1}1166 breachMonitoring={true}1167 lockOnClose={true}1168 lockedSyncRequiresUnlock={false}1169 autoLockMinutes={5}1170 trashRetentionDays={30}1171 theme="dark"1172 accentColor="peach"1173 textSize="medium"1174 reduceMotion={false}1175 initialSection="feedback"1176 onLockedSyncRequiresUnlockChange={vi.fn()}1177 onBreachMonitoringChange={vi.fn()}1178 onLockOnCloseChange={vi.fn()}1179 onAutoLockMinutesChange={vi.fn()}1180 onTrashRetentionChange={vi.fn()}1181 onThemeChange={vi.fn()}1182 onAccentChange={vi.fn()}1183 onTextSizeChange={vi.fn()}1184 onReduceMotionChange={vi.fn()}1185 shortcuts={DEFAULT_BINDINGS}1186 onShortcutsChange={vi.fn()}1187 onBack={vi.fn()}1188 onImport={vi.fn()}1189 onExport={vi.fn()}1190 onBreachCheckDone={vi.fn()}1191 />1192 );1193 await flushView();11941195 inputText(1196 container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1197 "Please improve the feedback flow."1198 );1199 const sendButton = Array.from(container.querySelectorAll("button")).find(1200 (candidate) => candidate.textContent?.trim() === "Send"1201 ) as HTMLButtonElement;1202 sendButton.click();12031204 await vi.waitFor(() => {1205 expect(fetchMock).toHaveBeenCalledTimes(1);1206 });1207 await vi.waitFor(() => {1208 expect(container.textContent).toContain("Thank you");1209 });1210 expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1211 });12121213 it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {1214 sendMessageMock.mockImplementation(async (msg: unknown) => {1215 const m = msg as { type: string };1216 if (m.type === "GET_RECOVERY_WORDS") {1217 return {1218 ok: true,1219 data: [1220 "abandon", "ability", "able", "about", "above", "absent",1221 "absorb", "abstract", "absurd", "abuse", "access", "accident",1222 ],1223 };1224 }1225 return { ok: true, data: null };1226 });1227 const onAutoLockMinutesChange = vi.fn();1228 const onLockedSyncRequiresUnlockChange = vi.fn();1229 const onThemeChange = vi.fn();1230 const container = mount(1231 <SettingsView1232 entriesCount={1}1233 breachMonitoring={true}1234 lockOnClose={true}1235 lockedSyncRequiresUnlock={false}1236 autoLockMinutes={5}1237 trashRetentionDays={30}1238 theme="dark"1239 accentColor="peach"1240 textSize="medium"1241 reduceMotion={false}1242 onBreachMonitoringChange={vi.fn()}1243 onLockedSyncRequiresUnlockChange={onLockedSyncRequiresUnlockChange}1244 onLockOnCloseChange={vi.fn()}1245 onAutoLockMinutesChange={onAutoLockMinutesChange}1246 onTrashRetentionChange={vi.fn()}1247 onThemeChange={onThemeChange}1248 onAccentChange={vi.fn()}1249 onTextSizeChange={vi.fn()}1250 onReduceMotionChange={vi.fn()}1251 shortcuts={DEFAULT_BINDINGS}1252 onShortcutsChange={vi.fn()}1253 onBack={vi.fn()}1254 onImport={vi.fn()}1255 onExport={vi.fn()}1256 onBreachCheckDone={vi.fn()}1257 />1258 );1259 await flushView();1260 sendMessageMock.mockClear();12611262 1263 const selects = container.querySelectorAll("select");1264 changeSelect(selects[0] as HTMLSelectElement, "15");1265 expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);12661267 const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;1268 appearanceCard.click();1269 await flushView();1270 expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");1271 const themeButton = Array.from(container.querySelectorAll("button")).find(1272 (candidate) => candidate.textContent?.trim() === "Switch to light"1273 ) as HTMLButtonElement;1274 themeButton.click();1275 expect(onThemeChange).toHaveBeenCalledWith("light");12761277 1278 const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;1279 protectionCard.click();1280 await flushView();1281 const custodyToggle = container.querySelector<HTMLButtonElement>(1282 'button[aria-label="Toggle unlock requirement for locked Sync after restart"]',1283 );1284 expect(custodyToggle).not.toBeNull();1285 custodyToggle!.click();1286 expect(onLockedSyncRequiresUnlockChange).toHaveBeenCalledWith(true);12871288 const changeButton = Array.from(container.querySelectorAll("button")).find(1289 (candidate) => candidate.textContent?.trim() === "change"1290 ) as HTMLButtonElement;1291 changeButton.click();1292 await flushView();12931294 const inputs = container.querySelectorAll('input[type="password"]');1295 inputText(inputs[0] as HTMLInputElement, "current-pass");1296 inputText(inputs[1] as HTMLInputElement, "new-password-123");1297 inputText(inputs[2] as HTMLInputElement, "new-password-123");1298 await flushView();12991300 const saveButton = Array.from(container.querySelectorAll("button")).find(1301 (candidate) => candidate.textContent?.trim() === "save new password"1302 ) as HTMLButtonElement;1303 saveButton.click();1304 await flushView();13051306 expect(sendMessageMock).toHaveBeenCalledWith({1307 type: "CHANGE_PASSWORD",1308 payload: {1309 currentPassword: "current-pass",1310 newPassword: "new-password-123",1311 },1312 });13131314 1315 expect(container.textContent).toContain("save your recovery words");1316 expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });1317 });13181319 it("Entry copy actions send COPY and canary ping messages for password and username", async () => {1320 sendMessageMock.mockResolvedValue({ ok: true });1321 const container = mount(1322 <EntryView1323 entry={sampleEntry()}1324 onDelete={vi.fn()}1325 onFieldSaved={vi.fn(async () => undefined)}1326 />1327 );13281329 const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;1330 passwordButton.click();1331 await flushView();13321333 expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1334 type: "COPY",1335 payload: { text: "secret123", label: "password", alreadyWritten: false },1336 });1337 expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1338 type: "FIRE_CANARY_PING",1339 payload: {1340 webhookUrl: "https://example.com/hook",1341 entryTitle: "GitHub",1342 trigger: "password_copied",1343 },1344 });13451346 sendMessageMock.mockClear();1347 const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;1348 usernameButton.click();1349 await flushView();13501351 expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1352 type: "COPY",1353 payload: { text: "june", label: "username", alreadyWritten: false },1354 });1355 expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1356 type: "FIRE_CANARY_PING",1357 payload: {1358 webhookUrl: "https://example.com/hook",1359 entryTitle: "GitHub",1360 trigger: "username_copied",1361 },1362 });1363 });13641365 it("Entry keyboard password copy reports its canary after COPY", async () => {1366 sendMessageMock.mockResolvedValue({ ok: true });1367 mount(1368 <EntryView1369 entry={sampleEntry()}1370 onDelete={vi.fn()}1371 onFieldSaved={vi.fn(async () => undefined)}1372 />1373 );13741375 window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", bubbles: true }));1376 await flushView();13771378 expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1379 type: "COPY",1380 payload: { text: "secret123", label: "password", alreadyWritten: false },1381 });1382 await flushView();1383 expect(sendMessageMock.mock.calls).toContainEqual([{1384 type: "FIRE_CANARY_PING",1385 payload: {1386 webhookUrl: "https://example.com/hook",1387 entryTitle: "GitHub",1388 trigger: "password_copied",1389 },1390 }]);1391 });1392 it("Entry Cmd+C leaves the native clipboard shortcut untouched", async () => {1393 sendMessageMock.mockResolvedValue({ ok: true });1394 mount(1395 <EntryView1396 entry={sampleEntry()}1397 onDelete={vi.fn()}1398 onFieldSaved={vi.fn(async () => undefined)}1399 />1400 );14011402 window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", metaKey: true, bubbles: true }));1403 await flushView();14041405 expect(sendMessageMock).not.toHaveBeenCalledWith(expect.objectContaining({ type: "COPY" }));1406 });14071408 it("Vault password swipe copy reports its canary after COPY", async () => {1409 sendMessageMock.mockResolvedValue({ ok: true });1410 const container = mount(1411 <VaultView1412 entries={[sampleEntry()]}1413 sortOrder="url-first"1414 onSelectEntry={vi.fn()}1415 onSortOrderChange={vi.fn()}1416 onAdd={vi.fn()}1417 onClose={vi.fn()}1418 />1419 );1420 const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1421 row.dispatchEvent(new TouchEvent("touchstart", {1422 bubbles: true,1423 touches: [{ clientX: 0, clientY: 0 } as Touch],1424 }));1425 row.dispatchEvent(new TouchEvent("touchend", {1426 bubbles: true,1427 changedTouches: [{ clientX: 100, clientY: 0 } as Touch],1428 }));1429 await flushView();14301431 expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1432 type: "COPY",1433 payload: { text: "secret123", label: "password", alreadyWritten: false },1434 });1435 await flushView();1436 expect(sendMessageMock.mock.calls).toContainEqual([{1437 type: "FIRE_CANARY_PING",1438 payload: {1439 webhookUrl: "https://example.com/hook",1440 entryTitle: "GitHub",1441 trigger: "password_copied",1442 },1443 }]);1444 });14451446 it("Entry shows Advanced for passkey-bearing credential entries", async () => {1447 const container = mount(1448 <EntryView1449 entry={sampleEntry({1450 type: "passkey",1451 username: undefined,1452 password: undefined,1453 totp: undefined,1454 canary: undefined,1455 passkey: {1456 rpId: "vercel.com",1457 rpName: "Vercel",1458 credentialId: "cred-1",1459 publicKeyCose: "cose",1460 userHandle: "handle",1461 userName: "june",1462 userDisplayName: "June",1463 algorithm: -7,1464 signCount: 0,1465 aaguid: "",1466 backupEligible: false,1467 backupState: false,1468 createdAt: 1,1469 },1470 })}1471 onDelete={vi.fn()}1472 onFieldSaved={vi.fn(async () => undefined)}1473 />1474 );14751476 const advanced = Array.from(container.querySelectorAll(".peach-entry-add-link")).find(1477 (button) => button.textContent?.includes("Advanced")1478 ) as HTMLButtonElement | undefined;1479 expect(advanced).toBeDefined();1480 expect(advanced?.textContent).toContain("+ Advanced");14811482 advanced!.click();1483 await flushView();14841485 expect(container.textContent).toContain("passkey · vercel.com");1486 });14871488 it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {1489 sendMessageMock.mockResolvedValue({ ok: true });1490 const onFieldSaved = vi.fn(async () => undefined);1491 const container = mount(1492 <EntryView1493 entry={sampleEntry()}1494 onDelete={vi.fn()}1495 onFieldSaved={onFieldSaved}1496 />1497 );14981499 const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;1500 passwordValue.click();1501 await flushView();15021503 const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;1504 inputText(passwordInput, "");1505 await flushView();15061507 const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1508 saveButton.click();1509 await flushView();15101511 expect(sendMessageMock).not.toHaveBeenCalledWith(1512 expect.objectContaining({ type: "UPDATE_ENTRY" })1513 );1514 expect(onFieldSaved).not.toHaveBeenCalled();15151516 const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1517 totpMain.click();15181519 await vi.waitFor(() => {1520 expect(sendMessageMock).toHaveBeenLastCalledWith({1521 type: "COPY",1522 payload: { text: "123456", label: "totp", alreadyWritten: false },1523 });1524 }, { timeout: 500 });1525 });15261527 it("Entry closes an unchanged inline editor when focus leaves it", async () => {1528 sendMessageMock.mockResolvedValue({ ok: true });1529 const container = mount(1530 <EntryView1531 entry={sampleEntry()}1532 onDelete={vi.fn()}1533 onFieldSaved={vi.fn(async () => undefined)}1534 />1535 );15361537 const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;1538 usernameValue.click();1539 await flushView();15401541 const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;1542 usernameInput.blur();1543 await flushView();15441545 expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();1546 expect(sendMessageMock).not.toHaveBeenCalledWith(1547 expect.objectContaining({ type: "UPDATE_ENTRY" })1548 );1549 });15501551 it("Entry keeps the full used-email list available while editing an email", async () => {1552 const container = mount(1553 <EntryView1554 entry={sampleEntry({ email: "[email protected]" })}1555 entries={[1556 sampleEntry({ email: "[email protected]" }),1557 sampleEntry({ id: "entry-2", email: "[email protected]" }),1558 sampleEntry({ id: "entry-3", username: "duckuccino" }),1559 ]}1560 onDelete={vi.fn()}1561 onFieldSaved={vi.fn(async () => undefined)}1562 />1563 );15641565 const emailValue = Array.from(container.querySelectorAll(".peach-field-card")).find(1566 (card) => card.querySelector(".peach-label")?.textContent === "email"1567 )?.querySelector(".peach-inline-clickable") as HTMLSpanElement;1568 emailValue.click();1569 await flushView();15701571 const suggestions = Array.from(container.querySelectorAll(".peach-identity-suggestion-value"))1572 .map((element) => element.textContent);1573 expect(suggestions).toEqual(["[email protected]", "[email protected]"]);1574 });15751576 it("Entry lets TOTP secrets be edited inline", async () => {1577 sendMessageMock.mockResolvedValue({ ok: true });1578 const onFieldSaved = vi.fn(async () => undefined);1579 const container = mount(1580 <EntryView1581 entry={sampleEntry()}1582 onDelete={vi.fn()}1583 onFieldSaved={onFieldSaved}1584 />1585 );15861587 const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1588 totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));1589 await flushView();15901591 const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;1592 inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");1593 await flushView();15941595 const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1596 saveButton.click();1597 await flushView();15981599 expect(sendMessageMock).toHaveBeenCalledWith({1600 type: "UPDATE_ENTRY",1601 payload: {1602 id: "entry-1",1603 patch: { totp: "NB2W45DFOIZA====" },1604 },1605 });1606 expect(onFieldSaved).toHaveBeenCalled();1607 });16081609 it("Vault seeds and focuses search when a search seed is provided", async () => {1610 const container = mount(1611 <VaultView1612 entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1613 sortOrder="url-first"1614 searchSeed="g"1615 searchSeedNonce={1}1616 onSelectEntry={vi.fn()}1617 onSortOrderChange={vi.fn()}1618 onAdd={vi.fn()}1619 onClose={vi.fn()}1620 />1621 );16221623 await flushView();16241625 const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1626 expect(search.value).toBe("g");1627 expect(document.activeElement).toBe(search);1628 });16291630 it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1631 parseImportSourceMock.mockResolvedValue(1632 sampleImportResult({1633 entries: [1634 {1635 type: "login",1636 title: "Imported site",1637 username: "imported-user",1638 password: "imported-pass",1639 url: "https://imported.test",1640 },1641 ],1642 })1643 );1644 sendMessageMock.mockImplementation(async (msg: unknown) => {1645 const type = (msg as { type?: string }).type;1646 if (type === "GET_ENTRIES") {1647 return {1648 ok: true,1649 data: [1650 sampleEntry({1651 id: "existing-1",1652 title: "Imported site",1653 username: "imported-user",1654 url: "https://imported.test",1655 }),1656 ],1657 };1658 }1659 if (type === "BATCH_ADD_ENTRIES") {1660 return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1661 }1662 return { ok: true };1663 });1664 const onImport = vi.fn(async () => undefined);1665 const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1666 await flushView();1667 sendMessageMock.mockClear();16681669 await selectImportFile(container);1670 findButton(container, "Import 1").click();1671 await flushView();16721673 expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}');1674 expect(sendMessageMock).toHaveBeenCalledWith({1675 type: "BATCH_ADD_ENTRIES",1676 payload: {1677 entries: [1678 expect.objectContaining({1679 title: "Imported site",1680 username: "imported-user",1681 password: "imported-pass",1682 url: "https://imported.test",1683 }),1684 ],1685 },1686 });1687 expect(onImport).toHaveBeenCalled();1688 expect(container.textContent).toContain("1 entry appears to be duplicates");1689 });16901691 it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1692 parseImportSourceMock.mockResolvedValue(sampleImportResult());1693 sendMessageMock.mockImplementation(async (msg: unknown) => {1694 const type = (msg as { type?: string }).type;1695 if (type === "GET_ENTRIES") {1696 return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1697 }1698 if (type === "CLEAR_VAULT_ENTRIES") {1699 return { ok: true };1700 }1701 if (type === "BATCH_ADD_ENTRIES") {1702 return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1703 }1704 return { ok: true };1705 });1706 const onImport = vi.fn(async () => undefined);1707 const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1708 await flushView();1709 sendMessageMock.mockClear();17101711 await selectImportFile(container);1712 (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1713 await flushView();17141715 findButton(container, "Replace vault with 1").click();1716 await flushView();17171718 expect(sendMessageMock).not.toHaveBeenCalledWith(1719 expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1720 );1721 expect(container.textContent).toContain("Replace forever? This cannot be undone.");17221723 findButton(container, "Yes, replace forever").click();1724 await flushView();17251726 expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1727 expect(sendMessageMock).toHaveBeenCalledWith({1728 type: "BATCH_ADD_ENTRIES",1729 payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1730 });1731 expect(onImport).toHaveBeenCalled();1732 });17331734 it("Import onboarding mode waits for a matching master password before creating a vault", async () => {1735 parseImportSourceMock.mockResolvedValue(sampleImportResult());1736 sendMessageMock.mockImplementation(async (msg: unknown) => {1737 const type = (msg as { type?: string }).type;1738 if (type === "CREATE_VAULT") return { ok: true };1739 if (type === "BATCH_ADD_ENTRIES") {1740 return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1741 }1742 return { ok: true };1743 });1744 const onImport = vi.fn(async () => undefined);1745 const container = mount(1746 <ImportView1747 mode="onboarding"1748 replacesExistingVault={true}1749 onBack={vi.fn()}1750 onImport={onImport}1751 />1752 );17531754 await selectImportFile(container);17551756 const createButton = findButton(container, "Create vault + import 1");1757 expect(createButton.disabled).toBe(true);1758 expect(container.textContent).toContain("Restoring now replaces the locked local vault");1759 expect(container.textContent).toContain("Use at least 8 characters");17601761 const masterInput = container.querySelector(1762 'input[placeholder="new master password"]'1763 ) as HTMLInputElement;1764 const confirmInput = container.querySelector(1765 'input[placeholder="confirm master password"]'1766 ) as HTMLInputElement;1767 const revealButton = container.querySelector(1768 'button[aria-label="Show passwords"]'1769 ) as HTMLButtonElement;1770 expect(revealButton).toBeTruthy();1771 revealButton.click();1772 await flushView();1773 expect(masterInput.type).toBe("text");1774 expect(confirmInput.type).toBe("text");17751776 inputText(masterInput, "fresh-master-password");1777 inputText(confirmInput, "fresh-master-password");1778 await flushView();17791780 expect(createButton.disabled).toBe(false);1781 createButton.click();1782 await flushView();17831784 expect(sendMessageMock).toHaveBeenCalledWith({1785 type: "CREATE_VAULT",1786 payload: { password: "fresh-master-password" },1787 });1788 expect(sendMessageMock).toHaveBeenCalledWith({1789 type: "BATCH_ADD_ENTRIES",1790 payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1791 });1792 expect(onImport).toHaveBeenCalled();1793 });17941795});