vault.ts

10.0 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 "url";13import { dirname, join } from "path";14import os from "os";15import fs from "fs/promises";1617const __filename = fileURLToPath(import.meta.url);18const __dirname = dirname(__filename);19export const EXTENSION_PATH = join(__dirname, "..", "..", "dist-chrome");2021/** Passes both the 12-character minimum and the zxcvbn strength gate. */22export const VAULT_PASSWORD = "correct horse battery staple";2324/** The unlocked vault's tell — present only once the vault view is mounted. */25export const UNLOCKED = ".peach-lock-btn[aria-label='Lock vault']";2627export async function makeContext(prefix = "peach"): Promise<BrowserContext> {28  const userDataDir = join(29    os.tmpdir(),30    `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,31  );32  await fs.mkdir(userDataDir, { recursive: true });33  return chromium.launchPersistentContext(userDataDir, {34    executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,35    headless: false,36    args: [37      `--load-extension=${EXTENSION_PATH}`,38      `--disable-extensions-except=${EXTENSION_PATH}`,39    ],40  });41}4243export async function waitForSW(ctx: BrowserContext, maxWait = 15000): Promise<string> {44  const start = Date.now();45  let sw = ctx.serviceWorkers()[0];46  while (!sw && Date.now() - start < maxWait) {47    await new Promise((r) => setTimeout(r, 500));48    sw = ctx.serviceWorkers()[0];49  }50  if (!sw) throw new Error(`No SW after ${maxWait}ms`);51  return new URL(sw.url()).host;52}5354export async function loadPopup(ctx: BrowserContext): Promise<{ popup: Page; extId: string }> {55  const extId = await waitForSW(ctx);56  const popup = await ctx.newPage();57  await popup.goto(`chrome-extension://${extId}/src/popup/index.html`);58  await popup.waitForTimeout(3000);59  return { popup, extId };60}6162/** Click through the intro carousel until the create-vault form is on screen. */63async function reachCreateScreen(popup: Page): Promise<void> {64  // Final card's nav button reads "Create vault"; card-body taps are guarded65  // there, so the carousel only advances via the button.66  const advanceButton = popup.getByRole("button", { name: /next|get started|create vault/i });67  // Create screen uses #master-password; the unlock/lock screen uses68  // #unlock-password. Keep this one pointed at the create field.69  const pw = popup.locator("#master-password");70  for (let i = 0; i < 5 && !(await pw.isVisible().catch(() => false)); i++) {71    if (await advanceButton.isVisible({ timeout: 500 }).catch(() => false)) {72      await advanceButton.click();73      await popup.waitForTimeout(300);74      continue;75    }76    await popup.locator(".peach-onboarding-card").click();77    await popup.waitForTimeout(300);78  }79  if (!(await pw.isVisible().catch(() => false))) {80    throw new Error("setupVault: never reached the create-vault screen (#master-password)");81  }82}8384/**85 * Create a vault and land in the unlocked view.86 *87 * confirmRecovery: false stops on the recovery-words screen instead — only for88 * specs that assert on that screen itself.89 */90export async function setupVault(91  ctx: BrowserContext,92  password = VAULT_PASSWORD,93  opts: { confirmRecovery?: boolean } = {},94): Promise<{ popup: Page; extId: string }> {95  const { confirmRecovery = true } = opts;96  const { popup, extId } = await loadPopup(ctx);97  await reachCreateScreen(popup);98  await popup.locator("#master-password").fill(password);99  await popup.locator("#confirm-password").fill(password);100  // The submit button's label is replaced by the blocker message while the101  // gate is unmet ("need 4 more characters"), so locate it by class rather102  // than by name — and surface that label if it never becomes enabled.103  const createBtn = popup.locator(".peach-newvault-submit");104  if (!(await createBtn.isEnabled().catch(() => false))) {105    await expect(createBtn, `create-vault gate not met: "${await createBtn.textContent()}"`)106      .toBeEnabled({ timeout: 5000 });107  }108  await createBtn.click();109  // Vault creation runs Argon2id, which can exceed a few seconds under load —110  // give the recovery display room so this doesn't flake.111  await expect(popup.locator(".lock-screen--recovery-display")).toBeVisible({ timeout: 30000 });112  if (confirmRecovery) await completeRecoveryConfirmation(popup);113  return { popup, extId };114}115116export async function completeRecoveryConfirmation(popup: Page): Promise<void> {117  const recoveryWords = popup.locator(".peach-recovery-word-text");118  const confirmInputs = popup.locator(".peach-recovery-confirm-input");119  const confirmButton = popup.getByRole("button", { name: /i wrote them down/i });120121  await expect(confirmInputs).toHaveCount(3);122  // The confirmation inputs stay disabled until the 12 words render, which123  // is slow when several browsers derive Argon2 at once.124  await expect(confirmInputs.first()).toBeEnabled({ timeout: 30000 });125126  const words = await recoveryWords.allTextContents();127  // The three positions are randomized per mount, so read each field's128  // "word N" label rather than assuming fixed slots.129  const fields = popup.locator(".peach-recovery-confirm-field");130  const fieldCount = await fields.count();131  if (fieldCount !== 3) throw new Error(`expected 3 confirm fields, saw ${fieldCount}`);132  for (let i = 0; i < fieldCount; i++) {133    const field = fields.nth(i);134    const numText = await field.locator(".peach-recovery-confirm-num").innerText();135    const pos = parseInt(numText.replace(/\D/g, ""), 10);136    const word = words[pos - 1]?.trim();137    if (!word) throw new Error(`missing recovery word for position ${pos}`);138    await field.locator(".peach-recovery-confirm-input").fill(word);139  }140141  await expect(confirmButton).toBeEnabled({ timeout: 2000 });142  await confirmButton.click();143  await expect(144    popup.locator(UNLOCKED),145    "setupVault: recovery confirmation did not land in the unlocked vault",146  ).toBeVisible({ timeout: 10000 });147}148149export async function lockVault(popup: Page): Promise<void> {150  const lockBtn = popup.locator(UNLOCKED);151  await expect(lockBtn).toBeVisible({ timeout: 15000 });152  await lockBtn.click();153  await expect(popup.locator("#unlock-password")).toBeVisible({ timeout: 15000 });154}155156export async function unlockVault(popup: Page, password = VAULT_PASSWORD): Promise<void> {157  await popup.locator("#unlock-password").fill(password);158  await popup.getByRole("button", { name: /unlock/i }).click();159  await expect(popup.locator(UNLOCKED)).toBeVisible({ timeout: 20000 });160}161162export async function openSettings(popup: Page): Promise<void> {163  await popup.locator(".peach-icon-btn[aria-label='Settings']").click();164  await expect(popup.locator(".stk-shell")).toBeVisible({ timeout: 10000 });165}166167/**168 * Open the entry list. The top search bar is readOnly — clicking it is what169 * mounts the list overlay, which is where the real search input and the170 * new-entry button live.171 */172export async function openList(popup: Page): Promise<void> {173  if (await popup.locator(".peach-overlay-view .peach-search-input").isVisible().catch(() => false)) return;174  await popup.locator(".peach-search-wrap .peach-search-input").click();175  await expect(popup.locator(".peach-overlay-view .peach-search-input")).toBeVisible({ timeout: 5000 });176}177178/** The editable search field, inside the list overlay. */179export function listSearch(popup: Page) {180  return popup.locator(".peach-overlay-view .peach-search-input");181}182183/**184 * Fill and submit the new-entry form. Selectors follow Add.tsx: the title field185 * is .peach-new-title-input (it was .peach-new-name-input in an older UI, which186 * is why the specs that still use that class fail to find it).187 */188export async function createEntryViaForm(189  popup: Page,190  entry: { title: string; url?: string; username?: string; password?: string; totp?: string; notes?: string },191): Promise<void> {192  await openList(popup);193  await popup.locator(".peach-new-entry-row").click();194  await popup.locator(".peach-new-title-input").fill(entry.title);195  if (entry.url) await popup.locator(".peach-domain-value--edit").fill(entry.url);196  if (entry.username) await popup.locator('input[placeholder="johndoe"]').fill(entry.username);197  if (entry.password) await popup.locator('input[placeholder="password"]').fill(entry.password);198  // 2FA and notes are behind "+ add" links until they hold a value.199  if (entry.totp) {200    await popup.getByRole("button", { name: /add 2FA/i }).click();201    await popup.locator('input[placeholder*="BASE32" i]').fill(entry.totp);202  }203  if (entry.notes) {204    await popup.getByRole("button", { name: /add notes/i }).click();205    await popup.locator(".peach-new-textarea").fill(entry.notes);206  }207  const create = popup.getByRole("button", { name: /^create$/i });208  await expect(create, "create button stayed disabled — the entry form rejected the input").toBeEnabled();209  await create.click();210  await expect(popup.locator(".peach-new-title-input")).toHaveCount(0, { timeout: 10000 });211}212213/** Add an entry through the background message API (faster than the new-entry form). */214export async function addEntry(215  popup: Page,216  entry: { title: string; url?: string; username?: string; password?: string; totp?: string },217): Promise<void> {218  const result = await popup.evaluate(async (payload) => {219    return new Promise<{ ok?: boolean; error?: string }>((resolve) => {220      chrome.runtime.sendMessage({ type: "ADD_ENTRY", payload: { type: "login", ...payload } }, resolve);221    });222  }, entry);223  // A locked vault answers { ok: false, error: "vault_locked" } — without this224  // check the entry silently never exists and the spec asserts nothing.225  if (!result?.ok) throw new Error(`addEntry(${entry.title}) failed: ${result?.error ?? "no response"}`);226}