1234567891011import { 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");2021export const VAULT_PASSWORD = "correct horse battery staple";222324export 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: false,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}606162async function reachCreateScreen(popup: Page): Promise<void> {63 64 65 const advanceButton = popup.getByRole("button", { name: /next|get started|create vault/i });66 67 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}8283848586878889export 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 100 101 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 109 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 122 123 await expect(confirmInputs.first()).toBeEnabled({ timeout: 30000 });124125 const words = await recoveryWords.allTextContents();126 127 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}165166167168169170171export 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}176177178export function listSearch(popup: Page) {179 return popup.locator(".peach-overlay-view .peach-search-input");180}181182183184185186187export 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 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}211212213export 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 223 224 if (!result?.ok) throw new Error(`addEntry(${entry.title}) failed: ${result?.error ?? "no response"}`);225}