1234567891011import { 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");202122export const VAULT_PASSWORD = "correct horse battery staple";232425export const UNLOCKED = ".peach-lock-btn[aria-label='Lock vault']";2627export async function makeContext(prefix = "peach"): Promise<BrowserContext> {28 const { chromium } = await import("playwright");29 const userDataDir = join(30 os.tmpdir(),31 `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,32 );33 await fs.mkdir(userDataDir, { recursive: true });34 return chromium.launchPersistentContext(userDataDir, {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}616263async function reachCreateScreen(popup: Page): Promise<void> {64 const advanceButton = popup.getByRole("button", { name: /next|get started/i });65 66 67 const pw = popup.locator("#master-password");68 for (let i = 0; i < 5 && !(await pw.isVisible().catch(() => false)); i++) {69 if (await advanceButton.isVisible({ timeout: 500 }).catch(() => false)) {70 await advanceButton.click();71 await popup.waitForTimeout(300);72 continue;73 }74 await popup.locator(".peach-onboarding-card").click();75 await popup.waitForTimeout(300);76 }77 if (!(await pw.isVisible().catch(() => false))) {78 throw new Error("setupVault: never reached the create-vault screen (#master-password)");79 }80}8182838485868788export async function setupVault(89 ctx: BrowserContext,90 password = VAULT_PASSWORD,91 opts: { confirmRecovery?: boolean } = {},92): Promise<{ popup: Page; extId: string }> {93 const { confirmRecovery = true } = opts;94 const { popup, extId } = await loadPopup(ctx);95 await reachCreateScreen(popup);96 await popup.locator("#master-password").fill(password);97 await popup.locator("#confirm-password").fill(password);98 99 100 101 const createBtn = popup.locator(".peach-newvault-submit");102 if (!(await createBtn.isEnabled().catch(() => false))) {103 await expect(createBtn, `create-vault gate not met: "${await createBtn.textContent()}"`)104 .toBeEnabled({ timeout: 5000 });105 }106 await createBtn.click();107 108 109 await expect(popup.locator(".lock-screen--recovery-display")).toBeVisible({ timeout: 30000 });110 if (confirmRecovery) await completeRecoveryConfirmation(popup);111 return { popup, extId };112}113114export async function completeRecoveryConfirmation(popup: Page): Promise<void> {115 const recoveryWords = popup.locator(".peach-recovery-word-text");116 const confirmInputs = popup.locator(".peach-recovery-confirm-input");117 const confirmButton = popup.getByRole("button", { name: /i wrote them down/i });118119 await expect(confirmInputs).toHaveCount(3);120 121 122 await expect(confirmInputs.first()).toBeEnabled({ timeout: 30000 });123124 const words = await recoveryWords.allTextContents();125 const confirmedWords = [words[2], words[6], words[10]];126 for (let i = 0; i < confirmedWords.length; i++) {127 const word = confirmedWords[i]?.trim();128 if (!word) throw new Error(`missing recovery word at position ${i}`);129 await confirmInputs.nth(i).fill(word);130 }131132 await expect(confirmButton).toBeEnabled({ timeout: 2000 });133 await confirmButton.click();134 await expect(135 popup.locator(UNLOCKED),136 "setupVault: recovery confirmation did not land in the unlocked vault",137 ).toBeVisible({ timeout: 10000 });138}139140export async function lockVault(popup: Page): Promise<void> {141 const lockBtn = popup.locator(UNLOCKED);142 await expect(lockBtn).toBeVisible({ timeout: 15000 });143 await lockBtn.click();144 await expect(popup.locator("#unlock-password")).toBeVisible({ timeout: 15000 });145}146147export async function unlockVault(popup: Page, password = VAULT_PASSWORD): Promise<void> {148 await popup.locator("#unlock-password").fill(password);149 await popup.getByRole("button", { name: /unlock/i }).click();150 await expect(popup.locator(UNLOCKED)).toBeVisible({ timeout: 20000 });151}152153export async function openSettings(popup: Page): Promise<void> {154 await popup.locator(".peach-icon-btn[aria-label='Settings']").click();155 await expect(popup.locator(".stk-shell")).toBeVisible({ timeout: 10000 });156}157158159160161162163export async function openList(popup: Page): Promise<void> {164 if (await popup.locator(".peach-overlay-view .peach-search-input").isVisible().catch(() => false)) return;165 await popup.locator(".peach-search-wrap .peach-search-input").click();166 await expect(popup.locator(".peach-overlay-view .peach-search-input")).toBeVisible({ timeout: 5000 });167}168169170export function listSearch(popup: Page) {171 return popup.locator(".peach-overlay-view .peach-search-input");172}173174175176177178179export async function createEntryViaForm(180 popup: Page,181 entry: { title: string; url?: string; username?: string; password?: string; totp?: string; notes?: string },182): Promise<void> {183 await openList(popup);184 await popup.locator(".peach-new-entry-row").click();185 await popup.locator(".peach-new-title-input").fill(entry.title);186 if (entry.url) await popup.locator(".peach-domain-value--edit").fill(entry.url);187 if (entry.username) await popup.locator('input[placeholder="johndoe"]').fill(entry.username);188 if (entry.password) await popup.locator('input[placeholder="password"]').fill(entry.password);189 190 if (entry.totp) {191 await popup.getByRole("button", { name: /add 2FA/i }).click();192 await popup.locator('input[placeholder*="BASE32" i]').fill(entry.totp);193 }194 if (entry.notes) {195 await popup.getByRole("button", { name: /add notes/i }).click();196 await popup.locator(".peach-new-textarea").fill(entry.notes);197 }198 const create = popup.getByRole("button", { name: /^create$/i });199 await expect(create, "create button stayed disabled — the entry form rejected the input").toBeEnabled();200 await create.click();201 await expect(popup.locator(".peach-new-title-input")).toHaveCount(0, { timeout: 10000 });202}203204205export async function addEntry(206 popup: Page,207 entry: { title: string; url?: string; username?: string; password?: string; totp?: string },208): Promise<void> {209 const result = await popup.evaluate(async (payload) => {210 return new Promise<{ ok?: boolean; error?: string }>((resolve) => {211 chrome.runtime.sendMessage({ type: "ADD_ENTRY", payload: { type: "login", ...payload } }, resolve);212 });213 }, entry);214 215 216 if (!result?.ok) throw new Error(`addEntry(${entry.title}) failed: ${result?.error ?? "no response"}`);217}