vault.ts

10.1 KB · raw

1/**2 * Shared vault setup for the Playwright specs.3 *4 * Every spec used to carry its own copy of this flow, and most copies still5 * filled "password123" — which fails the create-vault gate (12 chars AND6 * zxcvbn score >= 2), so the button stayed disabled, no vault was created, and7 * the rest of the spec ran against a locked popup while still reporting green.8 * setupVault() below asserts it reached the unlocked vault, so that failure9 * mode is now a loud error instead of a silent pass.10 */11import { chromium, expect, type BrowserContext, type Page } from "@playwright/test";12import { fileURLToPath } from "node:url";13import { dirname, join } from "node:path";14import os from "node:os";15import fs from "node:fs/promises";1617const __filename = fileURLToPath(import.meta.url);18const __dirname = dirname(__filename);19export const EXTENSION_PATH = join(__dirname, "..", "..", "dist-chrome");20/** Passes both the 12-character minimum and the zxcvbn strength gate. */21export const VAULT_PASSWORD = "correct horse battery staple";2223/** The unlocked vault's tell — present only once the vault view is mounted. */24export const UNLOCKED = ".peach-lock-btn[aria-label='Lock vault']";2526export async function makeContext(prefix = "peach"): Promise<BrowserContext> {27  const userDataDir = join(28    os.tmpdir(),29    `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,30  );31  await fs.mkdir(userDataDir, { recursive: true });32  return chromium.launchPersistentContext(userDataDir, {33    executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,34    headless: process.env.PEACH_RELEASE_BROWSER_GATE === "1",35    args: [36      `--load-extension=${EXTENSION_PATH}`,37      `--disable-extensions-except=${EXTENSION_PATH}`,38    ],39  });40}4142export async function waitForSW(ctx: BrowserContext, maxWait = 15000): Promise<string> {43  const start = Date.now();44  let sw = ctx.serviceWorkers()[0];45  while (!sw && Date.now() - start < maxWait) {46    await new Promise((r) => setTimeout(r, 500));47    sw = ctx.serviceWorkers()[0];48  }49  if (!sw) throw new Error(`No SW after ${maxWait}ms`);50  return new URL(sw.url()).host;51}5253export async function loadPopup(ctx: BrowserContext): Promise<{ popup: Page; extId: string }> {54  const extId = await waitForSW(ctx);55  const popup = await ctx.newPage();56  await popup.goto(`chrome-extension://${extId}/src/popup/index.html`);57  await popup.waitForTimeout(3000);58  return { popup, extId };59}6061/** Click through the intro carousel until the create-vault form is on screen. */62async function reachCreateScreen(popup: Page): Promise<void> {63  // Final card's nav button reads "Create vault"; card-body taps are guarded64  // there, so the carousel only advances via the button.65  const advanceButton = popup.getByRole("button", { name: /next|get started|create vault/i });66  // Create screen uses #master-password; the unlock/lock screen uses67  // #unlock-password. Keep this one pointed at the create field.68  const pw = popup.locator("#master-password");69  for (let i = 0; i < 5 && !(await pw.isVisible().catch(() => false)); i++) {70    if (await advanceButton.isVisible({ timeout: 500 }).catch(() => false)) {71      await advanceButton.click();72      await popup.waitForTimeout(300);73      continue;74    }75    await popup.locator(".peach-onboarding-card").click();76    await popup.waitForTimeout(300);77  }78  if (!(await pw.isVisible().catch(() => false))) {79    throw new Error("setupVault: never reached the create-vault screen (#master-password)");80  }81}8283/**84 * Create a vault and land in the unlocked view.85 *86 * confirmRecovery: false stops on the recovery-words screen instead — only for87 * specs that assert on that screen itself.88 */89export async function setupVault(90  ctx: BrowserContext,91  password = VAULT_PASSWORD,92  opts: { confirmRecovery?: boolean } = {},93): Promise<{ popup: Page; extId: string }> {94  const { confirmRecovery = true } = opts;95  const { popup, extId } = await loadPopup(ctx);96  await reachCreateScreen(popup);97  await popup.locator("#master-password").fill(password);98  await popup.locator("#confirm-password").fill(password);99  // The submit button's label is replaced by the blocker message while the100  // gate is unmet ("need 4 more characters"), so locate it by class rather101  // than by name — and surface that label if it never becomes enabled.102  const createBtn = popup.locator(".peach-newvault-submit");103  if (!(await createBtn.isEnabled().catch(() => false))) {104    await expect(createBtn, `create-vault gate not met: "${await createBtn.textContent()}"`)105      .toBeEnabled({ timeout: 5000 });106  }107  await createBtn.click();108  // Vault creation runs Argon2id, which can exceed a few seconds under load —109  // give the recovery display room so this doesn't flake.110  await expect(popup.locator(".lock-screen--recovery-display")).toBeVisible({ timeout: 30000 });111  if (confirmRecovery) await completeRecoveryConfirmation(popup);112  return { popup, extId };113}114115export async function completeRecoveryConfirmation(popup: Page): Promise<void> {116  const recoveryWords = popup.locator(".peach-recovery-word-text");117  const confirmInputs = popup.locator(".peach-recovery-confirm-input");118  const confirmButton = popup.getByRole("button", { name: /i wrote them down/i });119120  await expect(confirmInputs).toHaveCount(3);121  // The confirmation inputs stay disabled until the 12 words render, which122  // is slow when several browsers derive Argon2 at once.123  await expect(confirmInputs.first()).toBeEnabled({ timeout: 30000 });124125  const words = await recoveryWords.allTextContents();126  // The three positions are randomized per mount, so read each field's127  // "word N" label rather than assuming fixed slots.128  const fields = popup.locator(".peach-recovery-confirm-field");129  const fieldCount = await fields.count();130  if (fieldCount !== 3) throw new Error(`expected 3 confirm fields, saw ${fieldCount}`);131  for (let i = 0; i < fieldCount; i++) {132    const field = fields.nth(i);133    const numText = await field.locator(".peach-recovery-confirm-num").innerText();134    const pos = parseInt(numText.replace(/\D/g, ""), 10);135    const word = words[pos - 1]?.trim();136    if (!word) throw new Error(`missing recovery word for position ${pos}`);137    await field.locator(".peach-recovery-confirm-input").fill(word);138  }139140  await expect(confirmButton).toBeEnabled({ timeout: 2000 });141  await confirmButton.click();142  await expect(143    popup.locator(UNLOCKED),144    "setupVault: recovery confirmation did not land in the unlocked vault",145  ).toBeVisible({ timeout: 10000 });146}147148export async function lockVault(popup: Page): Promise<void> {149  const lockBtn = popup.locator(UNLOCKED);150  await expect(lockBtn).toBeVisible({ timeout: 15000 });151  await lockBtn.click();152  await expect(popup.locator("#unlock-password")).toBeVisible({ timeout: 15000 });153}154155export async function unlockVault(popup: Page, password = VAULT_PASSWORD): Promise<void> {156  await popup.locator("#unlock-password").fill(password);157  await popup.getByRole("button", { name: /unlock/i }).click();158  await expect(popup.locator(UNLOCKED)).toBeVisible({ timeout: 20000 });159}160161export async function openSettings(popup: Page): Promise<void> {162  await popup.locator(".peach-icon-btn[aria-label='Settings']").click();163  await expect(popup.locator(".stk-shell")).toBeVisible({ timeout: 10000 });164}165166/**167 * Open the entry list. The top search bar is readOnly — clicking it is what168 * mounts the list overlay, which is where the real search input and the169 * new-entry button live.170 */171export async function openList(popup: Page): Promise<void> {172  if (await popup.locator(".peach-overlay-view .peach-search-input").isVisible().catch(() => false)) return;173  await popup.locator(".peach-search-wrap .peach-search-input").click();174  await expect(popup.locator(".peach-overlay-view .peach-search-input")).toBeVisible({ timeout: 5000 });175}176177/** The editable search field, inside the list overlay. */178export function listSearch(popup: Page) {179  return popup.locator(".peach-overlay-view .peach-search-input");180}181182/**183 * Fill and submit the new-entry form. Selectors follow Add.tsx: the title field184 * is .peach-new-title-input (it was .peach-new-name-input in an older UI, which185 * is why the specs that still use that class fail to find it).186 */187export async function createEntryViaForm(188  popup: Page,189  entry: { title: string; url?: string; username?: string; password?: string; totp?: string; notes?: string },190): Promise<void> {191  await openList(popup);192  await popup.locator(".peach-new-entry-row").click();193  await popup.locator(".peach-new-title-input").fill(entry.title);194  if (entry.url) await popup.locator(".peach-domain-value--edit").fill(entry.url);195  if (entry.username) await popup.locator('input[placeholder="johndoe"]').fill(entry.username);196  if (entry.password) await popup.locator('input[placeholder="password"]').fill(entry.password);197  // 2FA and notes are behind "+ add" links until they hold a value.198  if (entry.totp) {199    await popup.getByRole("button", { name: /add 2FA/i }).click();200    await popup.locator('input[placeholder*="BASE32" i]').fill(entry.totp);201  }202  if (entry.notes) {203    await popup.getByRole("button", { name: /add notes/i }).click();204    await popup.locator(".peach-new-textarea").fill(entry.notes);205  }206  const create = popup.getByRole("button", { name: /^create$/i });207  await expect(create, "create button stayed disabled — the entry form rejected the input").toBeEnabled();208  await create.click();209  await expect(popup.locator(".peach-new-title-input")).toHaveCount(0, { timeout: 10000 });210}211212/** Add an entry through the background message API (faster than the new-entry form). */213export async function addEntry(214  popup: Page,215  entry: { title: string; url?: string; username?: string; password?: string; totp?: string },216): Promise<void> {217  const result = await popup.evaluate(async (payload) => {218    return new Promise<{ ok?: boolean; error?: string }>((resolve) => {219      chrome.runtime.sendMessage({ type: "ADD_ENTRY", payload: { type: "login", ...payload } }, resolve);220    });221  }, entry);222  // A locked vault answers { ok: false, error: "vault_locked" } — without this223  // check the entry silently never exists and the spec asserts nothing.224  if (!result?.ok) throw new Error(`addEntry(${entry.title}) failed: ${result?.error ?? "no response"}`);225}