AdoptVaultView.test.tsx

10.9 KB · raw

1// @vitest-environment jsdom23import type { JSX } from "solid-js";4import { readFileSync } from "node:fs";5import { afterEach, describe, expect, it, vi } from "vitest";6import { ONBOARDING_LAST_CARD, Onboarding } from "./Onboarding";7import { AdoptVaultView } from "./AdoptVaultView";8import { flushView, inputText, renderView } from "./view-test-utils";910vi.mock("@zxcvbn-ts/core", () => ({11  zxcvbn: (value: string) => ({ score: value.length >= 16 ? 4 : 1 }),12  zxcvbnOptions: { setOptions: vi.fn() },13}));14vi.mock("@zxcvbn-ts/language-common", () => ({15  adjacencyGraphs: {},16  dictionary: {},17}));18vi.mock("@zxcvbn-ts/language-en", () => ({19  translations: {},20  dictionary: {},21}));2223function button(container: HTMLElement, text: string): HTMLButtonElement {24  const found = Array.from(container.querySelectorAll("button")).find((b) =>25    (b.textContent ?? "").includes(text),26  );27  if (!found) throw new Error(`button not found: ${text}`);28  return found as HTMLButtonElement;29}3031async function enterStrongPassword(container: HTMLElement) {32  inputText(container.querySelector("#adopt-password") as HTMLInputElement, "9xQ!vZ2pLm74Tr#Ke8Wd5Bn");33  inputText(container.querySelector("#adopt-confirm-password") as HTMLInputElement, "9xQ!vZ2pLm74Tr#Ke8Wd5Bn");34  await flushView();35}3637describe("vault adoption onboarding", () => {38  const cleanups: Array<() => void> = [];3940  afterEach(() => {41    vi.useRealTimers();42    while (cleanups.length) cleanups.pop()!();43  });4445  function mounted(view: () => JSX.Element) {46    const rendered = renderView(view);47    cleanups.push(rendered.dispose);48    return rendered;49  }5051  it("T-A21: Onboarding separates pairing from backup restore", () => {52    vi.useFakeTimers();53    const onComplete = vi.fn();54    const onRestore = vi.fn();55    const onAdopt = vi.fn();56    const view = mounted(() => <Onboarding onComplete={onComplete} onRestore={onRestore} onAdopt={onAdopt} />);5758    button(view.container, "next").click();59    vi.advanceTimersByTime(220);60    button(view.container, "next").click();61    vi.advanceTimersByTime(220);6263    expect(view.container.textContent).toContain("Create vault");64    expect(view.container.textContent).toContain("Already using Peach?");65    expect(view.container.textContent).toContain("Pair with another device");66    expect(view.container.textContent).toContain("Scan a QR and confirm one 8-digit code.");67    expect(view.container.textContent).toContain("Restore a backup");68    button(view.container, "Pair with another device").click();69    expect(onAdopt).toHaveBeenCalledTimes(1);70  });7172  it("T-A21c: resumes on the final card when re-entered from a leave flow", async () => {73    const onComplete = vi.fn();74    const view = mounted(() => (75      <Onboarding onComplete={onComplete} onRestore={() => {}} onAdopt={() => {}} initialCard={ONBOARDING_LAST_CARD} />76    ));7778    // Landing straight on the final card shows the exit actions, not card 0.79    expect(view.container.textContent).toContain("Create vault");80    expect(view.container.textContent).toContain("Already using Peach?");81    expect(view.container.textContent).not.toContain("Two keys.");8283    // Back (matched by class — the "Restore a backup" label also contains the84    // substring "back") still responds and steps to the previous card.85    (view.container.querySelector(".peach-onboarding-back") as HTMLButtonElement).click();86    expect(view.container.querySelector(".peach-onboarding-card")?.classList.contains("is-exiting")).toBe(true);87    await new Promise((r) => setTimeout(r, 300));88    expect(view.container.textContent).toContain("Two keys.");89    expect(view.container.textContent).not.toContain("Create vault");90  });9192  it("T-A21b: create-vault is the nav call-to-action; a final-card tap does not silently create", () => {93    vi.useFakeTimers();94    const onComplete = vi.fn();95    const view = mounted(() => <Onboarding onComplete={onComplete} onRestore={() => {}} onAdopt={() => {}} />);9697    button(view.container, "next").click();98    vi.advanceTimersByTime(220);99    button(view.container, "next").click();100    vi.advanceTimersByTime(220);101102    expect(view.container.textContent).toContain("Create vault");103104    (view.container.querySelector(".peach-onboarding-card") as HTMLElement).click();105    expect(onComplete).not.toHaveBeenCalled();106107    button(view.container, "Create vault").click();108    vi.advanceTimersByTime(250);109    expect(onComplete).toHaveBeenCalledTimes(1);110  });111112  it("T-A22: password screen uses the same minimum-length gate as create-vault", () => {113    const view = mounted(() => <AdoptVaultView onCancel={() => {}} onDone={() => {}} />);114    const continueButton = button(view.container, "Continue");115    expect(continueButton.disabled).toBe(true);116    inputText(view.container.querySelector("#adopt-password") as HTMLInputElement, "short");117    inputText(view.container.querySelector("#adopt-confirm-password") as HTMLInputElement, "short");118    expect(view.container.textContent).toContain("need 7 more characters");119    expect(continueButton.disabled).toBe(true);120  });121122  it("T-A28: pair phase shows the pairing-request QR after a strong password", async () => {123    const view = mounted(() => <AdoptVaultView onCancel={() => {}} onDone={() => {}} />);124    await enterStrongPassword(view.container);125    button(view.container, "Continue").click();126    await flushView();127128    // The browser is the source of the QR now — the phone scans it.129    // We assert the heading + copy; the actual QR is rendered by a background130    // call that's out of scope for a jsdom test (chrome.runtime is undefined).131    expect(view.container.textContent).toContain("Pair a device");132    expect(view.container.textContent).toContain("Scan this QR in Peach");133    expect(view.container.querySelector(".peach-adopt-qr-wrap")).toBeTruthy();134    expect(view.container.querySelectorAll(".peach-adopt-bird-stage .peach-pair-bird")).toHaveLength(2);135    // The scan button from the old flow is gone — the phone is the scanner now.136    expect(view.container.textContent).not.toContain("Enter invitation manually");137  });138139  it("pins the compact receiver stage above the shared pairing-stage cascade", () => {140    const css = readFileSync("src/popup/styles/popup.css", "utf8");141    const rule = css.match(142      /\.peach-pair-stage\.peach-adopt-bird-stage\s*\{([^}]*)\}/,143    )?.[1];144145    expect(rule).toContain("height: 102px");146    expect(rule).toContain("margin: -6px auto 2px");147    expect(css).toMatch(148      /\.peach-adopt-card--pair\s*\{[^}]*border:\s*0;/s,149    );150  });151152  it("shows the receiver SAS without adding a second confirmation button", async () => {153    type RuntimeListener = (msg: { type?: string; payload?: unknown }) => void;154    const listeners: RuntimeListener[] = [];155    Object.defineProperty(globalThis, "chrome", {156      configurable: true,157      value: {158        runtime: {159          lastError: undefined,160          sendMessage(161            message: { type?: string },162            callback: (response: unknown) => void,163          ) {164            if (message.type === "START_ADOPTION_RECEIVER") {165              callback({ ok: true, data: { invitation: "peach-pair-v1:test" } });166            } else {167              callback({ ok: true });168            }169          },170          onMessage: {171            addListener(fn: RuntimeListener) { listeners.push(fn); },172            removeListener(fn: RuntimeListener) {173              const index = listeners.indexOf(fn);174              if (index >= 0) listeners.splice(index, 1);175            },176          },177        },178      },179    });180181    const view = mounted(() => <AdoptVaultView onCancel={() => {}} onDone={() => {}} />);182    await enterStrongPassword(view.container);183    button(view.container, "Continue").click();184    await flushView();185186    for (const listener of listeners) {187      listener({188        type: "ADOPTION_SOURCE_SAS",189        payload: { sas: "48219371", displayOnly: true },190      });191    }192    await flushView();193194    expect(view.container.textContent).toContain("48219371");195    expect(view.container.textContent).toContain("Confirm this code on your phone");196    expect(view.container.querySelector(".peach-adoption-sas")).toBeTruthy();197    expect(view.container.querySelector(".peach-pair-qr")).toBeNull();198    expect(view.container.textContent).not.toContain("They match");199    expect(view.container.textContent).not.toContain("They don't match");200201    for (const listener of listeners) {202      listener({203        type: "ADOPTION_SOURCE_RESULT",204        payload: { status: "error", error: "ADOPT_PRO_REQUIRED" },205      });206    }207    await flushView();208209    expect(view.container.textContent).toContain("Pair freely");210    expect(view.container.textContent).toContain("at least one of these two devices");211    expect(view.container.textContent).toContain("$39 once");212    expect(view.container.querySelector('a[href*="buy.polar.sh"]')).toBeTruthy();213  });214215  it("continues straight to initial sync when receiver pairing completes", async () => {216    type RuntimeListener = (msg: { type?: string; payload?: unknown }) => void;217    const listeners: RuntimeListener[] = [];218    Object.defineProperty(globalThis, "chrome", {219      configurable: true,220      value: {221        runtime: {222          lastError: undefined,223          sendMessage(224            message: { type?: string },225            callback: (response: unknown) => void,226          ) {227            if (message.type === "START_ADOPTION_RECEIVER") {228              callback({ ok: true, data: { invitation: "peach-pair-v1:test" } });229            } else {230              callback({ ok: true });231            }232          },233          onMessage: {234            addListener(fn: RuntimeListener) { listeners.push(fn); },235            removeListener(fn: RuntimeListener) {236              const index = listeners.indexOf(fn);237              if (index >= 0) listeners.splice(index, 1);238            },239          },240        },241      },242    });243    const onDone = vi.fn();244    const view = mounted(() => (245      <AdoptVaultView onCancel={() => {}} onDone={onDone} />246    ));247    await enterStrongPassword(view.container);248    button(view.container, "Continue").click();249    await flushView();250    vi.useFakeTimers();251252    for (const listener of listeners) {253      listener({254        type: "ADOPTION_SOURCE_RESULT",255        payload: { status: "complete" },256      });257    }258259    expect(onDone).not.toHaveBeenCalled();260    expect(view.container.textContent).toContain("Paired");261    expect(view.container.textContent).toContain("Secure connection established");262    expect(view.container.querySelector(".peach-adopt-bird-stage.act-paired")).toBeTruthy();263    expect(view.container.querySelectorAll(".peach-pair-bird-pose-happy")).toHaveLength(2);264    expect(view.container.querySelector(".peach-adopt-connection")).toBeTruthy();265    expect(view.container.textContent).not.toContain("Joined your vault");266    expect(view.container.textContent).not.toContain("Open Peach");267268    vi.advanceTimersByTime(4_999);269    expect(onDone).not.toHaveBeenCalled();270    vi.advanceTimersByTime(1);271    expect(onDone).toHaveBeenCalledOnce();272  });273});