Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add Playwright test scaffolding to web app (#2413)
Leendert de Borst90be72f8e3ae
diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.jsindex 8f7045647..876858d26 100644--- a/apps/web/eslint.config.js+++ b/apps/web/eslint.config.js@@ -12,18 +12,20 @@ export default [ignores: ["dist/**","node_modules/**",+ "playwright-report/**",+ "tests/test-results/**",]},js.configs.recommended,{- files: ["src/**/*.{ts,tsx}"],+ files: ["src/**/*.{ts,tsx}", "tests/**/*.ts", "playwright.config.ts"],languageOptions: {parser: tsParser,parserOptions: {ecmaFeatures: { jsx: true },ecmaVersion: "latest",sourceType: "module",- project: "./tsconfig.json",+ project: ["./tsconfig.json", "./tests/tsconfig.json"],tsconfigRootDir: import.meta.dirname,},},@@ -146,6 +148,13 @@ export default [},},},+ {+ // Playwright fixtures call their `use` callback, which the React hooks rule mistakes for a hook.+ files: ["tests/**/*.ts"],+ rules: {+ "react-hooks/rules-of-hooks": "off",+ },+ },{languageOptions: {globals: {diff --git a/apps/web/package-lock.json b/apps/web/package-lock.jsonindex fadd33f28..295890730 100644--- a/apps/web/package-lock.json+++ b/apps/web/package-lock.json@@ -21,6 +21,7 @@"react-router-dom": "^7.18.1"},"devDependencies": {+ "@playwright/test": "^1.63.0","@types/node": "^22.13.10","@types/qrcode": "^1.5.5","@types/react": "^19.0.7",@@ -582,6 +583,22 @@"url": "https://github.com/sponsors/oxc-project"}},+ "node_modules/@playwright/test": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",+ "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/@rolldown/binding-android-arm-eabi": {"version": "1.2.8","resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz",@@ -5139,6 +5156,35 @@"node": ">= 6"}},+ "node_modules/playwright": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/pngjs": {"version": "5.0.0","resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",diff --git a/apps/web/package.json b/apps/web/package.jsonindex 7446007bc..981531b92 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -10,9 +10,11 @@"dev": "vite","build": "vite build","preview": "vite preview",- "compile": "tsc --noEmit",- "lint": "eslint src",- "lint:fix": "eslint src --fix"+ "compile": "tsc --noEmit && tsc --noEmit -p tests",+ "lint": "eslint src tests playwright.config.ts",+ "lint:fix": "eslint src tests playwright.config.ts --fix",+ "test:e2e": "playwright test",+ "test:e2e:headed": "playwright test --headed --workers=1"},"dependencies": {"@aliasvault/client": "file:../../core/client",@@ -27,6 +29,7 @@"react-router-dom": "^7.18.1"},"devDependencies": {+ "@playwright/test": "^1.63.0","@types/node": "^22.13.10","@types/qrcode": "^1.5.5","@types/react": "^19.0.7",diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.tsnew file mode 100644index 000000000..83a38ea1f--- /dev/null+++ b/apps/web/playwright.config.ts@@ -0,0 +1,65 @@+import { defineConfig, devices } from '@playwright/test';++import { resolveApiUrl } from './tests/helpers/api-url';++/**+ * Playwright configuration for the web app E2E tests.+ *+ * The tests drive the built app in a browser against a running AliasVault API (Debug build, see global-setup.ts).+ * - ALIASVAULT_API_URL: the API to test against; defaults to the port block in the repo's dev.env.+ * - ALIASVAULT_WEB_URL: an already running web app (e.g. `./scripts/dev.sh web`); when unset, Playwright builds the+ * app and serves dist/ via `vite preview`.+ */+const API_URL = resolveApiUrl();+const PREVIEW_PORT = 4173;+const WEB_URL = process.env.ALIASVAULT_WEB_URL || `http://localhost:${PREVIEW_PORT}`;++process.env.ALIASVAULT_API_URL = API_URL;++export default defineConfig({+ testDir: './tests/e2e',++ // Checks the API is reachable and applies the test server settings.+ globalSetup: './tests/global-setup.ts',++ // Tests within a file run in order; files run in parallel, as every test registers its own account.+ fullyParallel: false,+ forbidOnly: !!process.env.CI,+ retries: process.env.CI ? 2 : 0,+ workers: process.env.CI ? 1 : 4,++ reporter: [+ ['html', { open: 'never' }],+ ['list'],+ ],++ // Registration and login run Argon2 key derivation in the browser, so allow for slower CI machines.+ timeout: 90000,+ expect: {+ timeout: 15000,+ },++ use: {+ baseURL: WEB_URL,+ locale: 'en-US',+ trace: 'on-first-retry',+ screenshot: 'only-on-failure',+ video: 'on-first-retry',+ },++ projects: [+ {+ name: 'chromium',+ use: { ...devices['Desktop Chrome'] },+ },+ ],++ webServer: process.env.ALIASVAULT_WEB_URL ? undefined : {+ command: `npx vite build && npx vite preview --port ${PREVIEW_PORT} --strictPort`,+ url: WEB_URL,+ reuseExistingServer: false,+ timeout: 60000,+ },++ outputDir: 'tests/test-results',+});diff --git a/apps/web/tests/fixtures/fixtures.ts b/apps/web/tests/fixtures/fixtures.tsnew file mode 100644index 000000000..f59168a20--- /dev/null+++ b/apps/web/tests/fixtures/fixtures.ts@@ -0,0 +1,76 @@+import { test as base } from '@playwright/test';++import { resolveApiUrl } from '../helpers/api-url';+import { createTestUser, generateTestUsername, TEST_PASSWORD } from '../helpers/test-api';++import { WebApp } from './WebApp';++/**+ * Credentials for a test account.+ */+export type TestCredentials = {+ username: string;+ password: string;+};++/**+ * Per-test fixtures.+ */+type TestFixtures = {+ apiUrl: string;+ app: WebApp;+ credentials: TestCredentials;+ testUser: TestCredentials;+};++/**+ * Test fixture with a fresh browser context per test, pointed at the test API.+ *+ * The app reads its API URL from appsettings.json at startup, so the fixture answers that request with the test+ * configuration; the same build then works against any API instance without rewriting files in dist/.+ */+export const test = base.extend<TestFixtures>({+ apiUrl: [resolveApiUrl(), { option: true }],++ /**+ * The default context, with appsettings.json answered by the test configuration.+ */+ context: async ({ context, apiUrl }, use) => {+ await context.route(/\/appsettings(\.Development)?\.json(\?.*)?$/, (route) => route.fulfill({+ contentType: 'application/json',+ body: JSON.stringify({+ ApiUrl: apiUrl,+ PrivateEmailDomains: ['example.tld', 'example2.tld'],+ HiddenPrivateEmailDomains: [],+ SupportEmail: '[email protected]',+ PublicRegistrationEnabled: 'true',+ DeploymentMode: 'e2e',+ }),+ }));+ await use(context);+ },++ /**+ * The page object for the test's page.+ */+ app: async ({ page }, use) => {+ await use(new WebApp(page));+ },++ /**+ * Fresh credentials for an account the test registers through the UI.+ */+ // eslint-disable-next-line no-empty-pattern+ credentials: async ({}, use) => {+ await use({ username: generateTestUsername(), password: TEST_PASSWORD });+ },++ /**+ * An account registered via the API, for tests that only need to log in.+ */+ testUser: async ({ apiUrl }, use) => {+ await use(await createTestUser(apiUrl));+ },+});++export const expect = test.expect;diff --git a/apps/web/tests/fixtures/index.ts b/apps/web/tests/fixtures/index.tsnew file mode 100644index 000000000..08b197ca1--- /dev/null+++ b/apps/web/tests/fixtures/index.ts@@ -0,0 +1,5 @@+/**+ * Test fixtures: `test`/`expect` with the web app fixtures, and the WebApp page object tests are written in.+ */+export { test, expect, type TestCredentials } from './fixtures';+export { WebApp, Timeouts } from './WebApp';diff --git a/apps/web/tests/global-setup.ts b/apps/web/tests/global-setup.tsnew file mode 100644index 000000000..ab2523884--- /dev/null+++ b/apps/web/tests/global-setup.ts@@ -0,0 +1,19 @@+/**+ * Global setup: runs once before the suite to check the API and apply the test server settings.+ */+import { resolveApiUrl } from './helpers/api-url';+import { isApiAvailable, setServerSetting } from './helpers/test-api';++/**+ * Fail early when the API is down, and lift the registration rate limit since every test registers from one IP.+ */+export default async function globalSetup(): Promise<void> {+ const apiUrl = resolveApiUrl();+ console.info(`Checking API availability at ${apiUrl}...`);++ if (!await isApiAvailable(apiUrl)) {+ throw new Error(`API is not available at ${apiUrl}. Start the AliasVault API (e.g. ./scripts/dev.sh api) or point ALIASVAULT_API_URL at a running instance.`);+ }++ await setServerSetting(apiUrl, 'MaxRegistrationsPerIpPer24Hours', '0');+}diff --git a/apps/web/tests/helpers/api-url.ts b/apps/web/tests/helpers/api-url.tsnew file mode 100644index 000000000..907e6b5f2--- /dev/null+++ b/apps/web/tests/helpers/api-url.ts@@ -0,0 +1,37 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++/** Default port layout, kept in sync with scripts/dev.sh. */+const DEFAULT_BASE_PORT = 5100;+const DEFAULT_PORT_STRIDE = 10;++/**+ * Resolve the API URL the tests run against: ALIASVAULT_API_URL, else the API port of the repo's dev.env instance.+ */+export function resolveApiUrl(): string {+ if (process.env.ALIASVAULT_API_URL) {+ return process.env.ALIASVAULT_API_URL.replace(/\/$/, '');+ }++ try {+ const devEnv: Record<string, string> = {};+ const devEnvPath = path.resolve(import.meta.dirname, '..', '..', '..', '..', 'dev.env');+ for (const line of readFileSync(devEnvPath, 'utf8').split('\n')) {+ const match = line.match(/^\s*([A-Z_]+)\s*=\s*(.*?)\s*$/);+ if (match) {+ devEnv[match[1]] = match[2];+ }+ }++ const base = Number(devEnv.AV_BASE_PORT ?? DEFAULT_BASE_PORT);+ const stride = Number(devEnv.AV_PORT_STRIDE ?? DEFAULT_PORT_STRIDE);+ const instance = Number(devEnv.AV_INSTANCE ?? 0);+ if ([base, stride, instance].every(Number.isInteger)) {+ return `http://localhost:${base + instance * stride}`;+ }+ } catch {+ // No readable dev.env, fall through to the default.+ }++ return `http://localhost:${DEFAULT_BASE_PORT}`;+}diff --git a/apps/web/tests/helpers/client-platform.ts b/apps/web/tests/helpers/client-platform.tsnew file mode 100644index 000000000..b97756e2f--- /dev/null+++ b/apps/web/tests/helpers/client-platform.ts@@ -0,0 +1,22 @@+/**+ * Node-side platform registration for the shared client core (`@aliasvault/client`).+ *+ * Import this module for its side effect from any helper that touches the core.+ */++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { createRustSqliteEngine } from '@aliasvault/client/database/RustSqliteEngine';+import { setPlatform } from '@aliasvault/client/platform';+import { createInMemoryPlatform } from '@aliasvault/client/platform/InMemoryPlatform';+import { createWasmRustCore } from '@aliasvault/client/rust/WasmRustCore';++const clientCoreDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../core/client');+const rustCore = createWasmRustCore(async (): Promise<BufferSource> => readFileSync(path.join(clientCoreDir, 'wasm/aliasvault_core_bg.wasm')));++setPlatform(createInMemoryPlatform({+ rustCore,+ sqlite: createRustSqliteEngine(rustCore),+}));diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.tsnew file mode 100644index 000000000..c769a1160--- /dev/null+++ b/apps/web/tests/helpers/test-api.ts@@ -0,0 +1,65 @@+/**+ * Direct API calls used by the E2E suite outside the browser.+ */++import { WebApiService } from '@aliasvault/client/api/WebApiService';+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';++import './client-platform';++/**+ * Fixed test password, so a developer can log in to a test account by hand during a paused run.+ */+export const TEST_PASSWORD = 'TestPass_e2e_dev!';++/**+ * A random, unused test username.+ */+export function generateTestUsername(): string {+ const randomPart = Math.random().toString(36).substring(2, 12);+ return `test_${randomPart}@example.tld`;+}++/**+ * Register an account via the API, skipping the setup wizard. The first login writes its empty vault.+ */+export async function createTestUser(apiUrl: string): Promise<{ username: string; password: string }> {+ const username = generateTestUsername();+ const baseUrl = WebApiService.versionedBaseUrl(apiUrl);+ const api = {+ /**+ * Send an auth request straight to the API.+ */+ rawFetch: (endpoint: string, options?: RequestInit): Promise<Response> => fetch(`${baseUrl}${endpoint}`, options),+ };+ await new SrpLoginService(api).register(username, TEST_PASSWORD);+ return { username, password: TEST_PASSWORD };+}++/**+ * Whether the API answers; the status endpoint returns 401 without a session, which still means it is up.+ */+export async function isApiAvailable(apiUrl: string): Promise<boolean> {+ try {+ const response = await fetch(`${apiUrl}/v2/Status`);+ return response.status === 401 || response.ok;+ } catch {+ return false;+ }+}++/**+ * Set a server setting via the DEBUG-only test controller.+ */+export async function setServerSetting(apiUrl: string, key: string, value: string): Promise<void> {+ const url = `${apiUrl}/v2/Test/server-settings`;+ const response = await fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ key, value }),+ });++ if (!response.ok) {+ throw new Error(`Failed to set server setting "${key}" via ${url} (status ${response.status}). The test controller only exists in DEBUG builds running with ASPNETCORE_ENVIRONMENT=Development.`);+ }+}diff --git a/apps/web/tests/tsconfig.json b/apps/web/tests/tsconfig.jsonnew file mode 100644index 000000000..1296f5424--- /dev/null+++ b/apps/web/tests/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../tsconfig.json",+ "compilerOptions": {+ "types": ["node"]+ },+ "include": ["./**/*.ts", "../playwright.config.ts"]+}