From b53a8c7c41c1b467b3bc51ac442cee227fd3d2d2 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 24 Nov 2026 17:49:25 -0800 Subject: [PATCH 1/4] test(web): simplify the admin browser journey --- apps/web/e2e/auth.e2e.ts | 892 ++++++++++----------------------------- 1 file changed, 216 insertions(+), 676 deletions(-) diff --git a/apps/web/e2e/auth.e2e.ts b/apps/web/e2e/auth.e2e.ts index 3f7c052..442aec2 100644 --- a/apps/web/e2e/auth.e2e.ts +++ b/apps/web/e2e/auth.e2e.ts @@ -1,718 +1,258 @@ -import type { Request } from '@playwright/test'; +import type { Page, Request } from '@playwright/test'; import { expect, test } from './support/test.ts'; test.use({ withWorker: true }); +const domain = 'go.example.org'; +const domainPath = `/admin/domains/${domain}`; +const docsPath = `${domainPath}/links/docs`; +const analyticsPath = '/admin/analytics'; +const healthPath = '/admin/health'; const sharedTag = 'Work/100%é'; -const tagPath = '/admin/tags/Work%2F100%25%C3%A9'; -const docsTitle = 'New hire handbook'; +const demoPassword = 'e2e-only-password'; -test('shared credentials protect admin pages and sign-out removes access', async ({ +test('sign-in protects admin and lets operators inspect links, worker health and Analytics', async ({ page, request, appServer }) => { await page.setViewportSize({ width: 1280, height: 720 }); - const root = await request.get('/', { maxRedirects: 0 }); - expect(root.status()).toBe(404); - expect(root.headers().location).toBeUndefined(); - - const adminRedirect = await request.get('/admin/analytics', { - headers: { accept: 'text/html' }, - maxRedirects: 0 - }); - expect(adminRedirect.status()).toBe(303); - expect(adminRedirect.headers().location).toBe('/signin?callbackUrl=%2Fadmin%2Fanalytics'); - expect(adminRedirect.headers()['cache-control']).toBe('private, no-store'); - - const signInPage = await page.goto(`${appServer.origin}/admin`); - await expect(page).toHaveURL(/\/signin\?/); - expect(signInPage?.headers()['cache-control']).toBe('private, no-store'); - await expect(page).toHaveTitle('Sign in — GoTo'); - await expect(page.getByRole('heading', { name: 'Sign in to GoTo', exact: true })).toBeVisible(); - await page.getByLabel('Username', { exact: true }).fill('example'); - await page.getByLabel('Password', { exact: true }).fill('incorrect'); - const failedSignIn = page.waitForResponse(`${appServer.origin}/auth/sign-in/credentials`); - await page.getByRole('button', { name: 'Sign in', exact: true }).click(); - expect((await failedSignIn).headers()['cache-control']).toBe('private, no-store'); - await expect(page.getByRole('alert')).toContainText('Invalid username or password'); - - await page.getByLabel('Password', { exact: true }).fill('e2e-only-password'); - await page.getByRole('button', { name: 'Sign in', exact: true }).click(); - await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible(); - await expect(page.getByRole('region', { name: 'Domains', exact: true })).toContainText('2'); - const summary = page.getByRole('region', { name: 'Summary', exact: true }); - await expect(summary.locator('.admin-stat-label')).toHaveText([ - 'Domains', - 'Links', - 'Total Visits', - 'Invalid clicks', - 'Root visits' - ]); - const totalVisits = summary.getByRole('region', { name: 'Total Visits', exact: true }); - const invalidClicks = page.getByRole('region', { name: 'Invalid clicks', exact: true }); - const rootVisits = page.getByRole('region', { name: 'Root visits', exact: true }); - await expect(totalVisits.getByText('4', { exact: true })).toBeVisible(); - await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1'); - await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1'); - await expect(summary.getByRole('link')).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( - 0 - ); - const heading = page.locator('.admin-heading'); - await expect(heading.locator('.admin-title > h1 + time')).toBeVisible(); - const timeframe = heading.getByRole('group', { name: 'Timeframe', exact: true }); - await expect(timeframe).toHaveCount(0); - const domainLink = page.getByRole('link', { name: 'go.example.org', exact: true }); - const domainRow = page.getByRole('listitem').filter({ has: domainLink }); - await expect(domainRow.locator('.admin-inventory-number')).toHaveText(['6', '2']); - const overviewResponse = await page.goto(`${appServer.origin}/admin?period=7d`); - expect(overviewResponse?.headers()['cache-control']).toBe('private, no-store'); - await expect(totalVisits.getByText('4', { exact: true })).toBeVisible(); const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true }); - const overviewLink = adminNav.getByRole('link', { name: 'GoTo', exact: true }); - await expect(adminNav.getByText('GoTo', { exact: true })).toBeVisible(); - await expect(overviewLink).toHaveCount(0); - await domainLink.click(); - await expect(page.getByRole('heading', { name: 'Domain', exact: true })).toBeVisible(); - const context = page.locator('.admin-context'); - await expect(context).toHaveCount(0); - await expect(page).toHaveTitle('Domain — go.example.org — GoTo'); - await expect(timeframe).toHaveCount(0); - const trend = page.getByRole('region', { name: 'Visits over time', exact: true }); - await expect(trend).toHaveCount(0); - await expect(overviewLink).toHaveAttribute('href', '/admin'); - const appIcon = overviewLink.locator('img[src="/@static/favicon.svg"]'); - await expect(appIcon).toBeVisible(); - await expect - .poll(() => appIcon.evaluate((image: HTMLImageElement) => image.naturalWidth)) - .toBeGreaterThan(0); - await expect(page.getByRole('link', { name: 'Overview', exact: true })).toHaveCount(0); - await expect(summary.locator('.admin-stat-label')).toHaveText([ - 'Links', - 'Total Visits', - 'Invalid clicks', - 'Root visits' - ]); - await expect(totalVisits.getByText('2', { exact: true })).toBeVisible(); - await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1'); - await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1'); - const linksInventory = page.getByRole('region', { name: 'Links on go.example.org', exact: true }); - const domainDetails = page.getByRole('region', { name: 'Details', exact: true }); - const rootRow = linksInventory.getByRole('listitem').filter({ - has: page.getByRole('link', { name: '(root)', exact: true }) + + await test.step('Reject anonymous requests and invalid credentials', async () => { + const root = await request.get('/', { maxRedirects: 0 }); + expect(root.status()).toBe(404); + expect(root.headers().location).toBeUndefined(); + + const redirect = await request.get(analyticsPath, { + headers: { accept: 'text/html' }, + maxRedirects: 0 + }); + expect(redirect.status()).toBe(303); + expect(redirect.headers().location).toBe('/signin?callbackUrl=%2Fadmin%2Fanalytics'); + expect(redirect.headers()['cache-control']).toBe('private, no-store'); + + const signInPage = await page.goto('/admin'); + await expect(page).toHaveURL(/\/signin\?/); + expect(signInPage?.headers()['cache-control']).toBe('private, no-store'); + const failedSignIn = page.waitForResponse(`${appServer.origin}/auth/sign-in/credentials`); + await submitCredentials(page, 'incorrect'); + expect((await failedSignIn).headers()['cache-control']).toBe('private, no-store'); + await expect(page.getByRole('alert')).toContainText('Invalid username or password'); }); - const rootLink = rootRow.getByRole('link', { name: '(root)', exact: true }); - await expect(rootRow.locator('.admin-inventory-secondary')).toHaveText('[not found]'); - await expect(rootRow.locator('.admin-inventory-state')).toHaveText('Active'); - const columns = ['Path', 'Destination', 'State', 'Visits']; - await expect(linksInventory.locator('.admin-inventory-heading > span')).toHaveText(columns); - const percentLinkRow = linksInventory - .getByRole('listitem') - .filter({ has: page.getByRole('link', { name: '/a%2Fb', exact: true }) }); - await expect(percentLinkRow.getByRole('link')).toHaveCount(1); - await expect(percentLinkRow.locator('.admin-inventory-number')).toHaveText('1'); - const historicalInvalid = linksInventory - .getByRole('listitem') - .filter({ has: page.getByRole('link', { name: '/a/b', exact: true }) }); - await expect(historicalInvalid.locator('.admin-inventory-number')).toHaveText('0'); - await expect(domainDetails.getByRole('heading', { name: 'Details', exact: true })).toBeVisible(); - const domainReportPath = '/admin/analytics?domain=go.example.org'; - await expect(domainDetails.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback', 'Analytics']); - await expect(domainDetails.locator('dd')).toHaveText([ - 'go.example.org', - 'Uses fallback', - '404 Not found', - domainReportPath - ]); - await expect(rootRow.getByText('Root visits', { exact: true })).toHaveCount(0); - await expect(rootRow.locator('.admin-inventory-number')).toHaveText('1'); - await expect(domainDetails.getByRole('link', { name: 'Root', exact: true })).toHaveCount(0); - await expect(domainDetails.getByRole('link', { name: 'Fallback', exact: true })).toHaveCount(0); - const domainAnalyticsLink = domainDetails.getByRole('link', { - name: domainReportPath, - exact: true + + await test.step('Open the inventory and its scoped reports after signing in', async () => { + await submitCredentials(page, demoPassword); + await expect(page).toHaveURL('/admin'); + const overview = await page.goto('/admin?period=7d'); + expect(overview?.headers()['cache-control']).toBe('private, no-store'); + const lifetimeVisits = page.getByRole('region', { name: 'Total Visits', exact: true }); + await expect(lifetimeVisits.getByText('4', { exact: true })).toBeVisible(); + + await page.getByRole('link', { name: domain, exact: true }).click(); + await expect(page).toHaveURL(domainPath); + const rootLink = page.getByRole('link', { name: '(root)', exact: true }); + const rootRow = page.getByRole('listitem').filter({ has: rootLink }); + await expect(rootRow.getByText('Root visits', { exact: true })).toHaveCount(0); + await expect(rootRow.locator('.admin-inventory-number')).toHaveText('1'); + await rootLink.click(); + await expect(page).toHaveURL(`${domainPath}/links`); + const rootReport = `${analyticsPath}?domain=${domain}&path=%2F`; + await expect(page.getByRole('link', { name: rootReport, exact: true })).toHaveAttribute( + 'href', + rootReport + ); + + await page.goBack(); + await page.getByRole('link', { name: '/docs', exact: true }).click(); + await expect(page).toHaveURL(docsPath); + const tagLink = page.getByRole('link', { name: sharedTag, exact: true }); + await tagLink.click(); + await expect(page).toHaveURL(`/admin/tags/${encodeURIComponent(sharedTag)}`); + const tagReport = `${analyticsPath}?${new URLSearchParams({ tag: sharedTag })}`; + await page.getByRole('link', { name: tagReport, exact: true }).click(); + await expect(page).toHaveURL(tagReport); + await expect(page.getByRole('combobox', { name: 'Report scope' })).toHaveAttribute( + 'placeholder', + `Tag: ${sharedTag}` + ); + const languages = page.getByRole('region', { name: 'Accepted languages', exact: true }); + await expect(languages.getByRole('row', { name: 'fr 1 50%', exact: true })).toBeVisible(); }); - await expect(domainAnalyticsLink).toHaveAttribute('href', domainReportPath); - await expect( - linksInventory.getByText('https://example.org/first-domain', { exact: true }) - ).toBeVisible(); - await expect( - linksInventory.getByRole('link', { name: 'https://example.org/first-domain', exact: true }) - ).toHaveCount(0); - await expect(rootLink).toHaveAttribute('href', '/admin/domains/go.example.org/links'); - const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true }); - const settingsCard = page.getByRole('region', { name: 'Settings', exact: true }); - const docsPath = '/admin/domains/go.example.org/links/docs'; - await page.getByRole('link', { name: '/docs', exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}${docsPath}`); - await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); - const summaryVisitCount = page - .getByRole('region', { name: 'Summary', exact: true }) - .getByRole('region', { name: 'Total Visits', exact: true }) - .locator('.admin-stat-value'); - const acceptedLanguages = page.getByRole('region', { name: 'Accepted languages', exact: true }); - await expect(context).toHaveCount(0); - await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ - 'Summary', - 'Redirect', - 'Settings' - ]); - await expect(redirectCard.locator('dt')).toHaveText([ - 'Domain', - 'Path', - 'Title', - 'Destination', - 'Rules', - 'Analytics' - ]); - await expect(redirectCard.getByText(docsTitle, { exact: true })).toBeVisible(); - await expect(settingsCard.locator('dt')).toHaveText([ - 'HTTP status', - 'Case insensitive', - 'Trailing slash', - 'Path forwarding', - 'Query forwarding', - 'Starts', - 'Expires', - 'Tags' - ]); - await expect(settingsCard.locator('time').first()).toBeVisible(); - await expect(settingsCard.locator('time').first()).toHaveAttribute( - 'datetime', - '2020-01-01T00:00:00Z' - ); - await expect(settingsCard.locator('time').last()).toHaveAttribute( - 'datetime', - '2100-01-01T00:00:00Z' - ); - await expect( - settingsCard.getByRole('list', { name: 'Tags', exact: true }).getByRole('link') - ).toHaveText(['work', 'docs', sharedTag]); - await expect(settingsCard.getByRole('link', { name: sharedTag, exact: true })).toHaveAttribute( - 'href', - tagPath - ); - const destinations = redirectCard.getByRole('list', { name: 'Destinations', exact: true }); - await expect(destinations.getByRole('link')).toHaveText([ - 'https://example.org/french-linux', - 'https://example.org/french', - 'https://example.org/ios', - 'https://example.org/first-domain' - ]); - await expect( - redirectCard.getByRole('list', { name: 'Rules', exact: true }).locator('.setting-value') - ).toHaveText(['language fr AND OS linux', 'language fr', 'OS ios', 'default']); - const domainField = redirectCard.locator('dd').first(); - await expect(domainField).toHaveText('go.example.org'); - await expect(domainField.getByRole('link')).toHaveAttribute( - 'href', - '/admin/domains/go.example.org' - ); - await expect(redirectCard.locator('dd').nth(1)).toHaveText('/docs'); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ - 'Total Visits', - 'Status' - ]); - await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active'); - await expect(page).toHaveTitle('Link — go.example.org/docs — GoTo'); - await expect(summaryVisitCount).toHaveText('1'); - await expect(timeframe).toHaveCount(0); - await expect(trend).toHaveCount(0); - await expect(acceptedLanguages).toHaveCount(0); - await expect(overviewLink).toHaveAttribute('href', '/admin'); - await expect( - page.getByRole('region', { name: 'Links on go.example.org', exact: true }) - ).toHaveCount(0); - - await settingsCard.getByRole('link', { name: sharedTag, exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}${tagPath}`); - await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible(); - await expect(page).toHaveTitle(`Tag: ${sharedTag} — GoTo`); - await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ - 'Summary', - 'Details', - 'Links' - ]); - const tagDetails = page.getByRole('region', { name: 'Details', exact: true }); - const tagQuery = new URLSearchParams({ tag: sharedTag }); - const tagReportPath = `/admin/analytics?${tagQuery}`; - await expect(tagDetails.locator('dt')).toHaveText(['Tag Name', 'Analytics']); - await expect(tagDetails.locator('dd')).toHaveText([sharedTag, tagReportPath]); - const tagAnalyticsLink = tagDetails.getByRole('link', { name: tagReportPath, exact: true }); - await tagAnalyticsLink.click(); - await expect(page).toHaveURL(`${appServer.origin}${tagReportPath}`); - const tagScopePicker = page.getByRole('combobox', { name: 'Report scope', exact: true }); - await expect(tagScopePicker).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); - await page.goBack(); - const tagSummary = page.getByRole('region', { name: 'Summary', exact: true }); - await expect(tagSummary.locator('.admin-stat-label')).toHaveText([ - 'Domains', - 'Links', - 'Total Visits' - ]); - await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '2']); - await expect(timeframe).toHaveCount(0); - await expect(trend).toHaveCount(0); - const taggedLinks = page.getByRole('region', { name: `Links tagged ${sharedTag}`, exact: true }); - await expect(taggedLinks.getByRole('link')).toHaveCount(2); - await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([ - 'Domain', - 'Path', - 'State', - 'Total Visits' - ]); - await expect(taggedLinks.locator('.admin-inventory-number')).toHaveText(['1', '1']); - const taggedDocs = taggedLinks.getByRole('link', { name: 'go.example.org/docs', exact: true }); - await expect(taggedDocs.locator('.admin-inventory-primary')).toHaveText('go.example.org'); - await expect(taggedDocs.locator('.admin-inventory-secondary')).toHaveText('/docs'); - await expect(taggedDocs).toHaveAttribute('href', docsPath); - await expect( - taggedLinks.getByRole('link', { name: 'tiny.example.org/docs', exact: true }) - ).toBeVisible(); - await taggedDocs.click(); - await expect(page).toHaveURL(`${appServer.origin}${docsPath}`); - await expect(summaryVisitCount).toHaveText('1'); - - await overviewLink.click(); - await domainLink.click(); - await page.getByRole('link', { name: '/a%2Fb', exact: true }).click(); - await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); - await expect(page).toHaveTitle('Link — go.example.org/a%2Fb — GoTo'); - await expect(redirectCard.getByText('Title', { exact: true })).toHaveCount(0); - await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a%252Fb`); - await expect(summaryVisitCount).toHaveText('1'); - const literalPercentReportPath = `${domainReportPath}&path=%2Fa%252Fb`; - const literalPercentReport = redirectCard.getByRole('link', { - name: literalPercentReportPath, - exact: true + await test.step('Check the real worker from Health', async () => { + await adminNav.getByRole('link', { name: 'Health', exact: true }).click(); + const worker = page.getByRole('region', { name: 'Worker', exact: true }); + await expect(worker.getByRole('status')).toHaveText('Not checked'); + await worker.getByRole('button', { name: 'Test worker', exact: true }).click(); + await expect(worker.getByRole('alert')).toContainText('Worker is reachable.'); }); - await expect(literalPercentReport).toHaveAttribute('href', literalPercentReportPath); - const linkSummary = page.getByRole('region', { name: 'Summary', exact: true }); - await expect(linkSummary.getByRole('region', { name: 'Status', exact: true })).toContainText( - 'Limit Exceeded' - ); - await expect( - linkSummary - .getByRole('region', { name: 'Max visits', exact: true }) - .getByText('1', { exact: true }) - ).toBeVisible(); - await page.goBack(); - await page.getByRole('link', { name: '/a/b', exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a/b`); - await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); - await expect(page).toHaveTitle('Link — go.example.org/a/b — GoTo'); - await expect(summaryVisitCount).toHaveText('0'); - const nestedReportPath = `${domainReportPath}&path=%2Fa%2Fb`; - const nestedReport = redirectCard.getByRole('link', { name: nestedReportPath, exact: true }); - await expect(nestedReport).toHaveAttribute('href', nestedReportPath); - await page.goBack(); - await rootLink.click(); - await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links`); - await expect(page.getByRole('heading', { name: 'Root', exact: true })).toBeVisible(); - await expect(page).toHaveTitle('Root — go.example.org — GoTo'); - await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ - 'Summary', - 'Root details', - 'Fallback' - ]); - await expect(timeframe).toHaveCount(0); - await expect(trend).toHaveCount(0); - await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1'); - await expect(page.getByRole('region', { name: 'Status', exact: true })).toHaveCount(0); - const rootDetails = page.getByRole('region', { name: 'Root details', exact: true }); - await expect(rootDetails.locator('dt')).toHaveText([ - 'Domain', - 'Address', - 'Destination', - 'Analytics' - ]); - const rootReportPath = `${domainReportPath}&path=%2F`; - await expect(rootDetails.locator('dd')).toHaveText([ - 'go.example.org', - 'go.example.org/', - 'Uses fallback', - rootReportPath - ]); - await expect(page.getByRole('region', { name: 'Fallback', exact: true })).toContainText( - '404 Not found' - ); - const rootAnalyticsLink = rootDetails.getByRole('link', { name: rootReportPath, exact: true }); - await expect(rootAnalyticsLink).toHaveAttribute('href', rootReportPath); - await rootDetails.getByRole('link', { name: 'go.example.org', exact: true }).click(); - await expect(totalVisits.getByText('2', { exact: true })).toBeVisible(); - - await page - .getByRole('navigation', { name: 'Administration', exact: true }) - .getByRole('link', { name: 'Health', exact: true }) - .click(); - await expect(page).toHaveURL(`${appServer.origin}/admin/health`); - await expect(page.getByRole('heading', { name: 'Health', exact: true })).toBeVisible(); - await expect(page.getByRole('region', { name: 'Application', exact: true })).toContainText( - 'Shared credentials' - ); - await expect( - page.getByRole('region', { name: 'Analytics', exact: true }).getByRole('alert') - ).toHaveCount(0); - await expect( - page - .getByRole('region', { name: 'Tags', exact: true }) - .getByRole('link', { name: sharedTag, exact: true }) - ).toHaveCount(1); - const workerHealth = page.getByRole('region', { name: 'Worker', exact: true }); - await expect(workerHealth.getByRole('status')).toHaveText('Not checked'); - await workerHealth.getByRole('button', { name: 'Test worker', exact: true }).click(); - await expect(workerHealth.getByRole('alert')).toContainText('Worker is reachable.'); - await expect(workerHealth.locator('time')).toBeVisible(); - - await page - .getByRole('navigation', { name: 'Administration', exact: true }) - .getByRole('link', { name: 'Analytics', exact: true }) - .click(); - await expect(page.getByRole('heading', { name: 'Analytics', exact: true })).toBeVisible(); - const analyticsVisits = page.getByRole('region', { name: 'Visits', exact: true }); - const analyticsChart = page.getByRole('region', { name: 'Visits over time', exact: true }); - await expect(analyticsVisits).toContainText('2'); - await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); - await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1'); - await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1'); + await adminNav.getByRole('link', { name: 'Analytics', exact: true }).click(); + const chart = page.getByRole('region', { name: 'Visits over time', exact: true }); + const timeframe = page.getByRole('group', { name: 'Timeframe', exact: true }); const reportFilters = page.getByRole('group', { name: 'Report filters', exact: true }); const scopeInput = reportFilters.getByRole('combobox', { name: 'Report scope', exact: true }); const scopeOptions = page.getByRole('listbox', { name: 'Report scopes', exact: true }); - async function chooseReportScope(option: string) { + const weekPath = `${analyticsPath}?period=7d`; + const domainWeekPath = `${weekPath}&domain=${domain}`; + + async function chooseReportScope(label: string) { await scopeInput.click(); - await scopeOptions.getByRole('option', { name: option, exact: true }).click(); + await scopeOptions.getByRole('option', { name: label, exact: true }).click(); } - await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic'); - const analyticsUrl = `${appServer.origin}/admin/analytics`; - const goReportUrl = `${analyticsUrl}?period=7d&domain=go.example.org`; - await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); - await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); - await chooseReportScope('go.example.org'); - await expect(page).toHaveURL(goReportUrl); - await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); - const isHeldRedirectRequest = (url: URL) => - url.pathname === '/admin/analytics/__data.json' && - url.searchParams.get('domain') === 'go.example.org' && - url.searchParams.get('path') === '/a/b'; - const releaseRedirectReport = Promise.withResolvers(); - await page.route( - isHeldRedirectRequest, - async (route) => { - await releaseRedirectReport.promise; - await route.continue(); - }, - { times: 1 } - ); - try { - const [heldRequest] = await Promise.all([ - page.waitForRequest((request) => isHeldRedirectRequest(new URL(request.url()))), - chooseReportScope('go.example.org/a/b') - ]); - await expect(reportFilters).toHaveAttribute('aria-busy', 'true'); - await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org'); - await timeframe.getByRole('button', { name: '30 days', exact: true }).click(); - await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`); - - releaseRedirectReport.resolve(); - const lateResponse = await heldRequest.response(); - expect(lateResponse?.ok()).toBe(true); - await expect(reportFilters).toHaveAttribute('aria-busy', 'false'); - await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`); - await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org'); - await expect(analyticsVisits).toContainText('1'); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - } finally { - releaseRedirectReport.resolve(); + async function expectChartTotal(total: number) { + await expect(chart.getByRole('row', { name: `Total ${total}`, exact: true })).toBeVisible(); } - await page.goBack(); - await page.goBack(); - await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); - await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic'); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - const searchRequests: string[] = []; - function recordSearchRequest(request: Request) { - const url = new URL(request.url()); - if (url.origin === appServer.origin && url.pathname.startsWith('/admin/analytics')) { - searchRequests.push(url.href); + await test.step('A late scope response cannot replace a newer timeframe', async () => { + await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); + await chooseReportScope(domain); + await expect(page).toHaveURL(domainWeekPath); + + function isNestedLinkReport(url: URL) { + return ( + url.pathname === `${analyticsPath}/__data.json` && + url.searchParams.get('domain') === domain && + url.searchParams.get('path') === '/a/b' + ); } - } - page.on('request', recordSearchRequest); - try { - await scopeInput.fill('/DOCS'); - await expect(scopeOptions.getByRole('option')).toHaveText([ - 'go.example.org/docs', - 'tiny.example.org/docs' - ]); - await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - expect(searchRequests).toEqual([]); - } finally { - page.off('request', recordSearchRequest); - } - await scopeOptions.getByRole('option', { name: 'go.example.org/docs', exact: true }).click(); - await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`); - await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); - await chooseReportScope('go.example.org/ (Root)'); - await expect(page).toHaveURL(`${goReportUrl}&path=%2F`); - const rootChart = page.getByRole('region', { name: 'Root visits over time', exact: true }); - await expect(rootChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1'); - await expect(invalidClicks).toHaveCount(0); - await page.goBack(); - await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/docs'); - await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + const releaseReport = Promise.withResolvers(); + await page.route( + isNestedLinkReport, + async (route) => { + await releaseReport.promise; + await route.continue(); + }, + { times: 1 } + ); + try { + const [heldRequest] = await Promise.all([ + page.waitForRequest((request) => isNestedLinkReport(new URL(request.url()))), + chooseReportScope(`${domain}/a/b`) + ]); + await expect(reportFilters).toHaveAttribute('aria-busy', 'true'); + await expect(scopeInput).toHaveAttribute('placeholder', `Domain: ${domain}`); + await timeframe.getByRole('button', { name: '30 days', exact: true }).click(); + const selectedReport = `${analyticsPath}?domain=${domain}`; + await expect(page).toHaveURL(selectedReport); - await chooseReportScope('tiny.example.org/docs'); - const tinyReportUrl = `${analyticsUrl}?period=7d&domain=tiny.example.org`; - await expect(page).toHaveURL(`${tinyReportUrl}&path=%2Fdocs`); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + releaseReport.resolve(); + expect((await heldRequest.response())?.ok()).toBe(true); + await expect(reportFilters).toHaveAttribute('aria-busy', 'false'); + await expect(page).toHaveURL(selectedReport); + await expect(scopeInput).toHaveAttribute('placeholder', `Domain: ${domain}`); + await expectChartTotal(1); + } finally { + releaseReport.resolve(); + } + }); - await scopeInput.click(); - await expect(scopeOptions).toBeVisible(); - const popupId = await scopeOptions.getAttribute('id'); - expect(popupId).toBeTruthy(); - await expect(scopeInput).toHaveAttribute('aria-controls', popupId ?? ''); - await scopeInput.press('Home'); - const allTraffic = scopeOptions.getByRole('option', { name: 'All traffic', exact: true }); - await expect(scopeInput).toHaveAttribute( - 'aria-activedescendant', - (await allTraffic.getAttribute('id')) ?? '' - ); - await scopeInput.fill('work/100%'); - await expect(scopeOptions.getByRole('option')).toHaveText([sharedTag]); - await scopeInput.press('ArrowDown'); - await scopeInput.press('Enter'); - const tagReportUrl = `${analyticsUrl}?period=7d&${new URLSearchParams({ tag: sharedTag })}`; - await expect(page).toHaveURL(tagReportUrl); - await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - await timeframe.getByRole('button', { name: '30 days', exact: true }).click(); - await expect(page).toHaveURL(`${analyticsUrl}?${new URLSearchParams({ tag: sharedTag })}`); - await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); - await expect(acceptedLanguages.getByRole('row', { name: 'fr 1 50%', exact: true })).toBeVisible(); - await page.goBack(); - await expect(page).toHaveURL(tagReportUrl); - await page.reload(); - await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + await test.step('Go back to the unfiltered week', async () => { + await page.goBack(); + await page.goBack(); + await expect(page).toHaveURL(weekPath); + await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic'); + }); - await scopeInput.click(); - await expect(scopeOptions).toBeVisible(); - await scopeInput.fill('long-picker-tag-'); - const longTag = `long-picker-tag-${'w'.repeat(1400)}`; - await expect(scopeOptions.getByRole('option')).toHaveText([longTag]); - await scopeInput.press('ArrowDown'); - await scopeInput.press('Enter'); - await expect(page).toHaveURL( - `${analyticsUrl}?period=7d&${new URLSearchParams({ tag: longTag })}` - ); - await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + await test.step('Search without a request and select a wrapped option with the keyboard', async () => { + const searchRequests: string[] = []; + function recordSearchRequest(request: Request) { + const url = new URL(request.url()); + if (url.origin === appServer.origin && url.pathname.startsWith(analyticsPath)) { + searchRequests.push(url.href); + } + } + page.on('request', recordSearchRequest); + try { + await scopeInput.fill('/DOCS'); + await expect(scopeOptions.getByRole('option')).toHaveText([ + `${domain}/docs`, + 'tiny.example.org/docs' + ]); + await expect(page).toHaveURL(weekPath); + expect(searchRequests).toEqual([]); + } finally { + page.off('request', recordSearchRequest); + } - await page.goto(`${analyticsUrl}?period=7d&tag=Removed`); - await expect(page.getByRole('status')).toContainText( - 'This report scope is no longer configured.' - ); - await expect(analyticsChart).toHaveCount(0); - await chooseReportScope('All traffic'); - await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + const popupId = await scopeOptions.getAttribute('id'); + expect(popupId).toBeTruthy(); + await expect(scopeInput).toHaveAttribute('aria-controls', popupId ?? ''); - await chooseReportScope('go.example.org/docs'); - await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`); - await page.setViewportSize({ width: 390, height: 844 }); - const graph = analyticsChart.getByRole('img'); - const browsers = page.getByRole('region', { name: 'Browsers', exact: true }); - const operatingSystems = page.getByRole('region', { name: 'Operating systems', exact: true }); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./); - await expect(browsers).toContainText('No visits in this period.'); - await expect(operatingSystems).toContainText('No visits in this period.'); - await expect(acceptedLanguages).toContainText('No visits in this period.'); + const longTagPrefix = 'long-picker-tag-'; + const longTag = `${longTagPrefix}${'w'.repeat(1400)}`; + await scopeInput.fill(longTagPrefix); + await expect(scopeOptions.getByRole('option')).toHaveText([longTag]); + await scopeInput.press('ArrowDown'); + await scopeInput.press('Enter'); + await expect(page).toHaveURL(`${weekPath}&${new URLSearchParams({ tag: longTag })}`); + }); - await page.getByRole('button', { name: 'Timeframe: 7 days', exact: true }).click(); - await page - .getByRole('listbox', { name: 'Timeframe', exact: true }) - .getByRole('option', { name: '90 days', exact: true }) - .click(); - const fullDomainUrl = `${analyticsUrl}?period=all&domain=go.example.org`; - await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fdocs`); - await expect(graph).toHaveAttribute('aria-busy', 'false'); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./); - await expect(browsers.getByRole('row', { name: 'Firefox 1 100%', exact: true })).toBeVisible(); - await expect( - operatingSystems.getByRole('row', { name: 'Linux 1 100%', exact: true }) - ).toBeVisible(); - await expect( - acceptedLanguages.getByRole('row', { name: 'fr 1 100%', exact: true }) - ).toBeVisible(); - await page.setViewportSize({ width: 1280, height: 720 }); - await chooseReportScope('go.example.org/a%2Fb'); - const literalPathUrl = `${fullDomainUrl}&path=%2Fa%252Fb`; - await expect(page).toHaveURL(literalPathUrl); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); - await chooseReportScope('go.example.org/a/b'); - await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fa%2Fb`); - await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); - await page.goBack(); - await expect(page).toHaveURL(literalPathUrl); - await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/a%2Fb'); - await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + await test.step('Change the report window on mobile without losing the link scope', async () => { + await chooseReportScope(`${domain}/docs`); + await expect(page).toHaveURL(`${domainWeekPath}&path=%2Fdocs`); + await page.setViewportSize({ width: 390, height: 844 }); + const graph = chart.getByRole('img'); + await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./); + await page.getByRole('button', { name: 'Timeframe: 7 days', exact: true }).click(); + await page + .getByRole('listbox', { name: 'Timeframe', exact: true }) + .getByRole('option', { name: '90 days', exact: true }) + .click(); + await expect(page).toHaveURL(`${analyticsPath}?period=all&domain=${domain}&path=%2Fdocs`); + await expect(graph).toHaveAttribute('aria-busy', 'false'); + await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./); + }); - const html = await page.content(); - await expect(html).not.toContain('e2e-only-password'); - await page.setViewportSize({ width: 390, height: 844 }); - await page - .getByRole('navigation', { name: 'Administration', exact: true }) - .getByRole('button', { name: 'Sign out', exact: true }) - .click(); - await expect(page).toHaveURL(/\/signin\?/); - await page.goto(`${appServer.origin}${docsPath}`); - await expect(page).toHaveURL(/\/signin\?/); - await expect(page.getByLabel('Username', { exact: true })).toBeVisible(); + await test.step('Keep literal percent paths and nested paths distinct', async () => { + await page.setViewportSize({ width: 1280, height: 720 }); + const report = `${analyticsPath}?period=all&domain=${domain}`; + await chooseReportScope(`${domain}/a%2Fb`); + const literalPath = `${report}&path=%2Fa%252Fb`; + await expect(page).toHaveURL(literalPath); + await expectChartTotal(1); + await chooseReportScope(`${domain}/a/b`); + await expect(page).toHaveURL(`${report}&path=%2Fa%2Fb`); + await expectChartTotal(0); + await page.goBack(); + await expect(page).toHaveURL(literalPath); + await expect(scopeInput).toHaveAttribute('placeholder', `${domain}/a%2Fb`); + }); + + await test.step('Signing out revokes access to a previously visited page', async () => { + expect(await page.content()).not.toContain(demoPassword); + await page.setViewportSize({ width: 390, height: 844 }); + await adminNav.getByRole('button', { name: 'Sign out', exact: true }).click(); + await expect(page).toHaveURL(/\/signin\?/); + await page.goto(docsPath); + await expect(page).toHaveURL(/\/signin\?/); + await expect(page.getByLabel('Username', { exact: true })).toBeVisible(); + }); }); test.describe('analytics disabled', () => { test.use({ withWorker: false, retentionMonths: 0 }); - test('disabled analytics keeps inventory and settings usable without traffic controls', async ({ - page, - appServer - }) => { - await page.goto(`${appServer.origin}/admin`); - await page.getByLabel('Username', { exact: true }).fill('example'); - await page.getByLabel('Password', { exact: true }).fill('e2e-only-password'); - await page.getByRole('button', { name: 'Sign in', exact: true }).click(); - await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible(); + test('inventory stays usable while Analytics navigation is disabled', async ({ page }) => { + await page.goto('/admin'); + await submitCredentials(page, demoPassword); + await expect(page).toHaveURL('/admin'); const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true }); await expect(adminNav.getByRole('link', { name: 'Analytics', exact: true })).toHaveCount(0); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ - 'Domains', - 'Links', - 'Total Visits', - 'Invalid clicks', - 'Root visits' - ]); - await expect( - page - .getByRole('region', { name: 'Total Visits', exact: true }) - .getByText('0', { exact: true }) - ).toBeVisible(); - await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount( - 0 - ); - await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( - 0 - ); - await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount( - 0 - ); - await expect( - page - .getByRole('region', { name: 'Domain inventory', exact: true }) - .locator('.admin-inventory-heading > span') - ).toHaveText(['Host', 'Links', 'Total Visits']); - await page.getByRole('link', { name: 'go.example.org', exact: true }).click(); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ - 'Links', - 'Total Visits', - 'Invalid clicks', - 'Root visits' - ]); - await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( - 0 - ); - await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount( - 0 - ); - await expect( - page - .getByRole('region', { name: 'Links on go.example.org', exact: true }) - .locator('.admin-inventory-heading > span') - ).toHaveText(['Path', 'Destination', 'State', 'Visits']); - const details = page.getByRole('region', { name: 'Details', exact: true }); - const reportLinks = 'a[href^="/admin/analytics"]'; - await expect(details.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback']); - await expect(details.locator(reportLinks)).toHaveCount(0); - const rootLink = page - .getByRole('region', { name: 'Links on go.example.org', exact: true }) - .getByRole('link', { name: '(root)', exact: true }); - await rootLink.click(); - const rootDetails = page.getByRole('region', { name: 'Root details', exact: true }); - await expect(rootDetails).toBeVisible(); - await expect(rootDetails.locator(reportLinks)).toHaveCount(0); - await page.goBack(); - await page.getByRole('link', { name: '/docs', exact: true }).click(); - const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true }); - await expect(redirectCard).toBeVisible(); - await expect(redirectCard.locator(reportLinks)).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount( - 0 - ); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ - 'Total Visits', - 'Status' - ]); - await expect( - page - .getByRole('region', { name: 'Total Visits', exact: true }) - .getByText('0', { exact: true }) - ).toBeVisible(); - await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active'); - await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( - 0 - ); - await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount( - 0 - ); - await page.goto('/admin/analytics?period=7d'); - await expect(page).toHaveURL(`${appServer.origin}/admin/health`); - await expect( - page.getByRole('region', { name: 'Analytics', exact: true }).locator('dd') - ).toHaveText(['Disabled', 'Disabled', 'Disabled']); - await expect( - page.getByRole('region', { name: 'Analytics', exact: true }).getByRole('alert') - ).toHaveCount(0); - await expect( - page.getByRole('region', { name: 'Worker', exact: true }).getByRole('status') - ).toHaveText('Not checked'); - await page - .getByRole('region', { name: 'Tags', exact: true }) - .getByRole('link', { name: sharedTag, exact: true }) - .click(); - await expect(page).toHaveURL(`${appServer.origin}${tagPath}`); - await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible(); - await expect(details.locator('dt')).toHaveText('Tag Name'); - await expect(details.locator('dd')).toHaveText(sharedTag); - await expect(details.locator(reportLinks)).toHaveCount(0); - const tagSummary = page.getByRole('region', { name: 'Summary', exact: true }); - await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '0']); - await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); - await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( - 0 - ); - await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount( - 0 - ); - const taggedLinks = page.getByRole('region', { - name: `Links tagged ${sharedTag}`, - exact: true - }); - await expect(taggedLinks.getByRole('link')).toHaveCount(2); - await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([ - 'Domain', - 'Path', - 'State', - 'Total Visits' - ]); + await page.getByRole('link', { name: domain, exact: true }).click(); + await expect(page).toHaveURL(domainPath); + await expect(page.getByRole('link', { name: '/docs', exact: true })).toBeVisible(); + await expect(page.locator('main a[href^="/admin/analytics"]')).toHaveCount(0); + + await page.goto(`${analyticsPath}?period=7d`); + await expect(page).toHaveURL(healthPath); }); }); + +async function submitCredentials(page: Page, password: string) { + await page.getByLabel('Username', { exact: true }).fill('example'); + await page.getByLabel('Password', { exact: true }).fill(password); + await page.getByRole('button', { name: 'Sign in', exact: true }).click(); +} -- 2.54.1 From d8d083e2f7bc9d3c635d7f8d0ef3521e4c5e92b2 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 24 Nov 2026 18:09:11 -0800 Subject: [PATCH 2/4] test(web): focus request boundary coverage --- apps/web/e2e/appearance.e2e.ts | 59 ++++---- apps/web/e2e/reload.e2e.ts | 8 -- apps/web/src/hooks.server.test.ts | 47 ++++-- apps/web/src/lib/server/application.test.ts | 135 ++++++------------ apps/web/src/lib/server/dispatch.test.ts | 65 ++++----- apps/web/src/lib/server/ingress.test.ts | 19 ++- apps/web/src/lib/server/redirect.test.ts | 60 +++----- .../src/lib/server/request-context.test.ts | 14 -- 8 files changed, 162 insertions(+), 245 deletions(-) diff --git a/apps/web/e2e/appearance.e2e.ts b/apps/web/e2e/appearance.e2e.ts index 63a95c3..a97c15f 100644 --- a/apps/web/e2e/appearance.e2e.ts +++ b/apps/web/e2e/appearance.e2e.ts @@ -26,37 +26,40 @@ test('serves the favicon and Open Graph image on the app and shortening hosts', const imageURL = `${appServer.origin}/@static/og.png`; await expect(page.locator('meta[property="og:image"]')).toHaveAttribute('content', imageURL); - const imageBytes = await readFile(new URL('../static/@static/og.png', import.meta.url)); - expect(imageBytes.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); - expect(imageBytes.readUInt32BE(16)).toBe(1200); - expect(imageBytes.readUInt32BE(20)).toBe(630); + const publicHost = { headers: { host: 'go.example.org' }, maxRedirects: 0 }; const assets = [ - { - path: '/@static/favicon.svg', - contentType: 'image/svg+xml', - bytes: await readFile(new URL('../static/@static/favicon.svg', import.meta.url)) - }, - { path: '/@static/og.png', contentType: 'image/png', bytes: imageBytes }, - { - path: '/@static/og.svg', - contentType: 'image/svg+xml', - bytes: await readFile(new URL('../static/@static/og.svg', import.meta.url)) - } + ['favicon.svg', 'image/svg+xml'], + ['og.png', 'image/png'], + ['og.svg', 'image/svg+xml'] ]; - for (const host of [new URL(appServer.origin).host, 'go.example.org', 'tiny.example.org']) { - for (const { path, contentType, bytes } of assets) { - const options = { headers: { host }, maxRedirects: 0 }; - const asset = await request.get(path, options); - expect(asset.status()).toBe(200); - expect(asset.headers()['content-type']?.split(';', 1)[0]).toBe(contentType); - expect(await asset.body()).toEqual(bytes); - - const head = await request.head(path, options); - expect(head.status()).toBe(200); - expect(head.headers()['content-type']?.split(';', 1)[0]).toBe(contentType); - expect(await head.body()).toHaveLength(0); - } + for (const [name, contentType] of assets) { + const asset = await request.get(`/@static/${name}`, publicHost); + expect(asset.status()).toBe(200); + expect(asset.headers()['content-type']?.split(';', 1)[0]).toBe(contentType); + expect(await asset.body()).toEqual( + await readFile(new URL(`../static/@static/${name}`, import.meta.url)) + ); } + + const adminImage = await request.get(imageURL, { maxRedirects: 0 }); + expect(adminImage.status()).toBe(200); + expect(adminImage.headers()['content-type']?.split(';', 1)[0]).toBe('image/png'); + const imageBytes = await adminImage.body(); + expect(imageBytes).toEqual(await readFile(new URL('../static/@static/og.png', import.meta.url))); + expect(imageBytes.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); + await expect(page.locator('meta[property="og:image:width"]')).toHaveAttribute( + 'content', + String(imageBytes.readUInt32BE(16)) + ); + await expect(page.locator('meta[property="og:image:height"]')).toHaveAttribute( + 'content', + String(imageBytes.readUInt32BE(20)) + ); + + const head = await request.head('/@static/favicon.svg', publicHost); + expect(head.status()).toBe(200); + expect(head.headers()['content-type']?.split(';', 1)[0]).toBe('image/svg+xml'); + expect(await head.body()).toHaveLength(0); }); test('renders responsive error pages on the app and shortening hosts', async ({ diff --git a/apps/web/e2e/reload.e2e.ts b/apps/web/e2e/reload.e2e.ts index 23b03ed..d785fcf 100644 --- a/apps/web/e2e/reload.e2e.ts +++ b/apps/web/e2e/reload.e2e.ts @@ -44,14 +44,6 @@ test('atomic YAML saves update redirects while rejected saves retain the last wo .toContain('Retention reduction requires a coordinated restart'); expect(await destination()).toBe(link.url); - await save('site: [\n'); - await expect - .poll(appServer.logs, polling) - .toContain( - 'Invalid configuration update; previous configuration remains active until a valid update is loaded' - ); - expect(await destination()).toBe(link.url); - link.url = 'https://example.org/recovered'; await save(JSON.stringify(configuration)); await expect.poll(destination, polling).toBe(link.url); diff --git a/apps/web/src/hooks.server.test.ts b/apps/web/src/hooks.server.test.ts index 2b084c6..9a739b5 100644 --- a/apps/web/src/hooks.server.test.ts +++ b/apps/web/src/hooks.server.test.ts @@ -6,11 +6,32 @@ import { beforeEach, describe, expect, test, vi } from 'vitest'; import type { Application } from '#lib/server/application.js'; import { bindApplication } from '#lib/server/request-context.js'; import { prepareSnapshot } from '#lib/server/snapshot.js'; -import { adminOriginGate, applicationContext, securityHeaders } from './hooks.server.js'; +import { adminOriginGate, applicationContext, handle, securityHeaders } from './hooks.server.js'; const framework = vi.hoisted(() => ({ building: false })); vi.mock('$app/env', () => framework); +// Kit's real hook sequence expects a request store outside the production adapter. +vi.mock('@sveltejs/kit/hooks', async (importOriginal) => { + const { sequence } = await importOriginal(); + const { with_request_store } = await vi.importActual<{ + with_request_store: (store: unknown, run: () => ReturnType) => ReturnType; + }>('@sveltejs/kit/internal/server'); + return { + sequence: (...handlers: Handle[]): Handle => { + const handle = sequence(...handlers); + return (input) => + with_request_store( + { + event: input.event, + state: { tracing: { record_span: ({ fn }: { fn: () => unknown }) => fn() } } + }, + () => handle(input) + ); + } + }; +}); + type RequestEvent = Parameters[0]['event']; function event( @@ -98,9 +119,12 @@ describe('application context', () => { test('uses the application captured on the development Web Request', async () => { const current = event(); const captured = application(); + const snapshot = captured.currentSnapshot(); bindApplication(current.request, captured); + vi.spyOn(captured, 'currentSnapshot').mockReturnValue(application().currentSnapshot()); const resolve = vi.fn(async (received: RequestEvent) => { - expect(received.locals.application === captured).toBe(true); + expect(received.locals.application).toBe(captured); + expect(received.locals.snapshot).toBe(snapshot); return new Response('ready'); }); @@ -113,14 +137,17 @@ describe('application context', () => { test('uses the application captured on the production IncomingMessage', async () => { const incoming = new IncomingMessage(new Socket()); const captured = application(); + const snapshot = captured.currentSnapshot(); bindApplication(incoming, captured); + vi.spyOn(captured, 'currentSnapshot').mockReturnValue(application().currentSnapshot()); const current = event( 'https://admin.example.org/schema.json', '/(admin)/(public)/schema.json', incoming ); const resolve = vi.fn(async (received: RequestEvent) => { - expect(received.locals.application === captured).toBe(true); + expect(received.locals.application).toBe(captured); + expect(received.locals.snapshot).toBe(snapshot); return new Response('schema'); }); @@ -145,10 +172,7 @@ describe('application context', () => { test('rejects a missing capture before resolving, with security headers', async () => { const current = event(); const resolve = vi.fn(async () => new Response('must not resolve')); - const response = await securityHeaders({ - event: current, - resolve: async (event) => applicationContext({ event, resolve }) - }); + const response = await handle({ event: current, resolve }); expect(response.status).toBe(503); expect(response.headers.get('cache-control')).toBe('no-store'); @@ -223,14 +247,7 @@ describe('admin group origin', () => { bindApplication(current.request, application()); const resolve = vi.fn(async () => new Response('admin response')); - const response = await securityHeaders({ - event: current, - resolve: async (event) => - applicationContext({ - event, - resolve: async (event) => adminOriginGate({ event, resolve }) - }) - }); + const response = await handle({ event: current, resolve }); expect(response.status).toBe(404); expect(response.headers.get('cache-control')).toBe('no-store'); diff --git a/apps/web/src/lib/server/application.test.ts b/apps/web/src/lib/server/application.test.ts index 895edbc..26059bf 100644 --- a/apps/web/src/lib/server/application.test.ts +++ b/apps/web/src/lib/server/application.test.ts @@ -323,111 +323,56 @@ test('shutdown prevents a pending candidate from publishing', async () => { expect(await reload.onChange(withNewLink(), prepared())).toBe(false); }); -test('counts final canonical named GETs in memory before queue admission, not HEAD, root or invalid visits', async () => { - const initial = prepared('https://example.org/docs', { +test('HEAD does not consume a visit, and the last allowed GET counts even if the writer rejects it', async () => { + const domain = 'go.example.test'; + const path = '/docs'; + const destination = 'https://example.org/docs'; + const fallback = 'https://example.org/inactive'; + const initial = prepared(destination, { + analytics: { retention_months: 0 }, domains: { - 'go.example.test': { - links: { - '/docs': { - url: 'https://example.org/docs', - case_insensitive: true, - ignore_trailing_slash: true, - forward_path: true - }, - '/off': { url: 'https://example.org/off', enabled: false }, - '/loop': { url: 'https://example.org/loop' } - } + [domain]: { + fallback: { url: fallback, status_code: 307 }, + links: { [path]: { url: destination, max_visits: 2 } } } } }); - initial.domains['go.example.test']!.links['/loop']!.url = 'https://go.example.test/loop'; vi.mocked(loadConfigFile).mockResolvedValueOnce(initial); + vi.mocked(readStoredLinkVisitCounts).mockResolvedValueOnce([{ domain, path, visits: 1 }]); const application = await createApplication(options); + + expect(send(application, path, 'HEAD')?.headers.get('location')).toBe(destination); + expect(application.linkVisitCount(domain, path)).toBe(1); + expect(queueVisit).not.toHaveBeenCalled(); + let visitsAtAdmission: number | undefined; queueVisit.mockImplementationOnce(() => { - visitsAtAdmission = application.linkVisitCount('go.example.test', '/docs'); + visitsAtAdmission = application.linkVisitCount(domain, path); throw new Error('Rejected by bounded admission'); }); - expect(send(application, '/DOCS/?query=not-a-link-key')?.status).toBe(302); - expect(visitsAtAdmission).toBe(1); - expect(send(application, '/docs/guide')?.status).toBe(302); - expect(send(application, '/docs', 'HEAD')?.status).toBe(302); - expect(send(application, '/')?.status).toBe(404); - expect(send(application, '/missing')?.status).toBe(404); - expect(send(application, '/off')?.status).toBe(404); - expect(send(application, '/loop')?.status).toBe(404); - expect(application.linkVisitCount('go.example.test', '/docs')).toBe(2); - expect(application.linkVisitCount('go.example.test', '/off')).toBe(0); - expect(application.linkVisitCount('go.example.test', '/loop')).toBe(0); - expect(application.linkVisitCount('go.example.test', '/')).toBe(0); + const lastAllowed = send(application, '/DOCS/'); + expect(lastAllowed?.status).toBe(302); + expect(lastAllowed?.headers.get('location')).toBe(destination); + expect(visitsAtAdmission).toBe(2); + expect(queueVisit).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ domain, path, outcome: 'valid' }) + ); + + const exhaustedHead = send(application, path, 'HEAD'); + expect(exhaustedHead?.status).toBe(307); + expect(exhaustedHead?.headers.get('location')).toBe(fallback); + expect(queueVisit).toHaveBeenCalledOnce(); + + const exhausted = send(application, path); + expect(exhausted?.status).toBe(307); + expect(exhausted?.headers.get('location')).toBe(fallback); + expect(queueVisit).toHaveBeenLastCalledWith( + expect.objectContaining({ domain, path, outcome: 'invalid' }) + ); + expect(application.linkVisitCount(domain, path)).toBe(2); await application.close?.(); }); -test.each([0, 3])( - 'allows the Nth canonical GET, then exhausts without consuming HEAD at retention %s', - async (retentionMonths) => { - const initial = prepared('https://example.org/docs', { - analytics: { retention_months: retentionMonths }, - domains: { - 'go.example.test': { - fallback: { url: 'https://example.org/inactive', status_code: 307 }, - links: { - '/docs': { - url: 'https://example.org/docs', - max_visits: 2, - forward_path: true, - forward_query: true, - redirect: [{ if: { language: 'fr', os: 'ios' }, to: 'https://example.org/french' }] - } - } - } - } - }); - vi.mocked(loadConfigFile).mockResolvedValueOnce(initial); - vi.mocked(readStoredLinkVisitCounts).mockResolvedValueOnce([ - { domain: 'go.example.test', path: '/docs', visits: 1 } - ]); - const application = await createApplication(options); - const headers = { 'accept-language': 'fr', 'user-agent': 'iPhone' }; - - const head = send(application, '/DOCS/guide?x=1', 'HEAD', headers); - expect(head?.headers.get('location')).toBe('https://example.org/french/guide?x=1'); - expect(application.linkVisitCount('go.example.test', '/docs')).toBe(1); - expect(queueVisit).not.toHaveBeenCalled(); - - let visitsAtAdmission: number | undefined; - queueVisit.mockImplementationOnce(() => { - visitsAtAdmission = application.linkVisitCount('go.example.test', '/docs'); - }); - const lastAllowed = send(application, '/%64ocs/?x=1', 'GET', headers); - expect(lastAllowed?.headers.get('location')).toBe('https://example.org/french?x=1'); - expect(lastAllowed?.headers.get('vary')).toBe('Accept-Language, User-Agent'); - expect(visitsAtAdmission).toBe(2); - expect(queueVisit).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - path: '/docs', - outcome: 'valid', - user_agent: retentionMonths === 0 ? null : 'iPhone', - accept_language: retentionMonths === 0 ? null : 'fr' - }) - ); - - const exhaustedHead = send(application, '/docs/guide', 'HEAD', headers); - expect(exhaustedHead?.status).toBe(307); - expect(exhaustedHead?.headers.get('location')).toBe('https://example.org/inactive'); - expect(queueVisit).toHaveBeenCalledOnce(); - const exhausted = send(application, '/DOCS/?x=2', 'GET', headers); - expect(exhausted?.status).toBe(307); - expect(exhausted?.headers.get('location')).toBe('https://example.org/inactive'); - expect(queueVisit).toHaveBeenLastCalledWith( - expect.objectContaining({ domain: 'go.example.test', path: '/docs', outcome: 'invalid' }) - ); - expect(application.linkVisitCount('go.example.test', '/docs')).toBe(2); - expect(readStoredLinkVisitCounts).toHaveBeenCalledOnce(); - await application.close?.(); - } -); - test('final redirect guards leave a limited link available until a valid GET succeeds', async () => { const initial = prepared('https://example.org/docs', { domains: { @@ -450,10 +395,10 @@ test('final redirect guards leave a limited link available until a valid GET suc const blocked = send(application, '/docs/start', 'GET', { 'accept-language': 'fr' }); expect(blocked?.status).toBe(404); - expect(blocked?.headers.get('vary')).toBe('Accept-Language'); - expect(send(application, '/docs/%00')?.status).toBe(404); expect(application.linkVisitCount('go.example.test', '/docs')).toBe(0); - expect(queueVisit.mock.calls.map(([visit]) => visit.outcome)).toEqual(['invalid', 'invalid']); + expect(queueVisit).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ path: '/docs', outcome: 'invalid' }) + ); expect(send(application, '/docs')?.status).toBe(302); expect(application.linkVisitCount('go.example.test', '/docs')).toBe(1); expect(send(application, '/docs')?.status).toBe(404); diff --git a/apps/web/src/lib/server/dispatch.test.ts b/apps/web/src/lib/server/dispatch.test.ts index 4cfe13d..159d410 100644 --- a/apps/web/src/lib/server/dispatch.test.ts +++ b/apps/web/src/lib/server/dispatch.test.ts @@ -160,22 +160,18 @@ test('reserved assets bypass prefix redirects, fallback, and visit capture', () const tracked = { ...application, currentSnapshot: () => fallbackSnapshot, recordVisit }; for (const method of ['GET', 'HEAD']) { - for (const path of ['/@static/favicon.svg', '/@static/og.png?version=1', '/@static/og.svg']) { - const incoming = request('go.example.test', path); - incoming.method = method; + const incoming = request('go.example.test', '/@static/og.png?version=1'); + incoming.method = method; - expect(handleIngress(tracked, incoming, {})).toBeUndefined(); - const context = requestContext(incoming); - expect(context?.application).toBe(tracked); - expect(context?.snapshot).toBe(fallbackSnapshot); - expect(context?.origin).toBe('https://go.example.test'); - } - } - for (const pathname of ['/@static/missing.svg', '/%40static/missing.svg']) { - const missing = request('go.example.test', pathname); - expect(handleIngress(tracked, missing, {})?.status).toBe(404); - expect(requestContext(missing)).toBeUndefined(); + expect(handleIngress(tracked, incoming, {})).toBeUndefined(); + const context = requestContext(incoming); + expect(context?.application).toBe(tracked); + expect(context?.snapshot).toBe(fallbackSnapshot); + expect(context?.origin).toBe('https://go.example.test'); } + const missing = request('go.example.test', '/%40static/missing.svg'); + expect(handleIngress(tracked, missing, {})?.status).toBe(404); + expect(requestContext(missing)).toBeUndefined(); expect(recordVisit).not.toHaveBeenCalled(); }); @@ -279,29 +275,26 @@ test('allows an actual internal probe without enrolling arbitrary hosts', () => ).toBe(404); }); -test.each(['/_app/version.json', '/@static/favicon.svg'])( - 'rejects unknown-host %s with a bare 404 before the adapter', - async (path) => { - const recordVisit = vi.fn(); - const incoming = request('unknown.example.test', path); - const response = handleIngress({ ...application, recordVisit }, incoming, {}); +test.each([ + ['unknown authority', 'unknown.example.test', 'https'], + ['wrong scheme on the admin authority', 'admin.example.test', 'http'] +] as const)('rejects an asset on %s before serving it', async (_scenario, host, scheme) => { + const recordVisit = vi.fn(); + const serveAsset = vi.fn(async () => new Response('must not serve')); + const incoming = request(host, '/@static/favicon.svg'); + const response = await handleIngress( + { ...application, recordVisit }, + incoming, + {}, + scheme, + serveAsset + ); - expect(response?.status).toBe(404); - expect(await response?.text()).toBe(''); - expect(requestContext(incoming)).toBeUndefined(); - expect(recordVisit).not.toHaveBeenCalled(); - } -); - -test('rejects another origin on the admin authority before serving static assets', async () => { - for (const path of ['/_app/version.json', '/@static/favicon.svg']) { - const incoming = request('admin.example.test', path); - const response = handleIngress(application, incoming, {}, 'http'); - - expect(response?.status).toBe(404); - expect(await response?.text()).toBe(''); - expect(requestContext(incoming)).toBeUndefined(); - } + expect(response?.status).toBe(404); + expect(await response?.text()).toBe(''); + expect(requestContext(incoming)).toBeUndefined(); + expect(serveAsset).not.toHaveBeenCalled(); + expect(recordVisit).not.toHaveBeenCalled(); }); test('does not trust forwarded authority unless explicitly configured', () => { diff --git a/apps/web/src/lib/server/ingress.test.ts b/apps/web/src/lib/server/ingress.test.ts index 1ec3d8c..a430949 100644 --- a/apps/web/src/lib/server/ingress.test.ts +++ b/apps/web/src/lib/server/ingress.test.ts @@ -190,12 +190,19 @@ describe('readIngress', () => { expect(readIngress(incoming, forwarding)).toBeUndefined(); }); - test.each(['', '*', 'https://other.example.test/docs', '/docs\\other', '/docs\n', '/docs#hash'])( - 'rejects a malformed request target %j', - (target) => { - expect(readIngress(request({ host: 'go.example.test' }, target), {})).toBeUndefined(); - } - ); + test.each([ + '', + '*', + 'https://other.example.test/docs', + '/docs\\other', + '/doc s', + '/docs#hash', + '/docs\u0000', + '/docs\u007f', + '/docs\ud800' + ])('rejects a malformed request target %j', (target) => { + expect(readIngress(request({ host: 'go.example.test' }, target), {})).toBeUndefined(); + }); test('returns undefined when the request target is missing', () => { const incoming = request(); diff --git a/apps/web/src/lib/server/redirect.test.ts b/apps/web/src/lib/server/redirect.test.ts index ad29d39..5e6baa3 100644 --- a/apps/web/src/lib/server/redirect.test.ts +++ b/apps/web/src/lib/server/redirect.test.ts @@ -388,56 +388,30 @@ describe('HTTP responses', () => { } ); - test.each(['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'CONNECT', 'TRACE', 'get'])( - 'rejects %s without resolving a link or fallback', - (method) => { - const domain = preparedDomain({ '/docs': preparedLink() }, fallback); - const { response, visit } = resolveRedirect( - domain, - host, - '/docs', - method, - zeroLinkVisitCount - ); + test.each(['POST', 'get'])('rejects %s without resolving a link or fallback', (method) => { + const domain = preparedDomain({ '/docs': preparedLink() }, fallback); + const { response, visit } = resolveRedirect(domain, host, '/docs', method, zeroLinkVisitCount); - expect(response.status).toBe(405); + expect(response.status).toBe(405); + expect(visit).toBeUndefined(); + expect(response.headers.get('allow')).toBe('GET, HEAD'); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.headers.has('location')).toBe(false); + }); + + test.each(['/%GG', '/%C3%28'])( + 'rejects an undecodable path %j before using fallback', + (target) => { + const domain = preparedDomain({}, fallback); + const { response, visit } = resolveRedirect(domain, host, target, 'GET', zeroLinkVisitCount); + + expect(response.status).toBe(400); expect(visit).toBeUndefined(); - expect(response.headers.get('allow')).toBe('GET, HEAD'); expect(response.headers.get('cache-control')).toBe('no-store'); expect(response.headers.has('location')).toBe(false); } ); - test.each([ - '', - '*', - 'docs', - 'https://go.example.test/docs', - '?name=value', - '/docs#fragment', - '/docs?name=value#fragment', - '/doc s', - '/docs?name=two words', - '/docs\t', - '/docs\r\n', - '/docs\u0000', - '/docs\u007f', - '/docs\\other', - '/docs\ud800', - '/%', - '/%GG', - '/%C3%28', - '/%FF' - ])('rejects malformed raw target %j before using fallback', (target) => { - const domain = preparedDomain({}, fallback); - const { response, visit } = resolveRedirect(domain, host, target, 'GET', zeroLinkVisitCount); - - expect(response.status).toBe(400); - expect(visit).toBeUndefined(); - expect(response.headers.get('cache-control')).toBe('no-store'); - expect(response.headers.has('location')).toBe(false); - }); - test.each([ { target: '/docs', fallback: null, root: null, status: 308 }, { diff --git a/apps/web/src/lib/server/request-context.test.ts b/apps/web/src/lib/server/request-context.test.ts index 8e99d0b..f54726c 100644 --- a/apps/web/src/lib/server/request-context.test.ts +++ b/apps/web/src/lib/server/request-context.test.ts @@ -76,20 +76,6 @@ describe.each(['web', 'node'] as const)('%s request application', (kind) => { }); }); -test('bridges the same captured reference from a Node request to a Web Request', () => { - const incoming = new IncomingMessage(new Socket()); - const web = new Request('https://admin.example.org/schema.json'); - const captured = application(); - bindApplication(incoming, captured); - const bridged = requestApplication(incoming); - if (!bridged) throw new Error('Expected a captured application'); - - bindApplication(web, bridged); - - expect(requestApplication(incoming) === captured).toBe(true); - expect(requestApplication(web) === captured).toBe(true); -}); - test('carries the trusted request origin separately from the configured admin origin', () => { const incoming = new IncomingMessage(new Socket()); const captured = application(); -- 2.54.1 From ae865e608b2bb32b43fd4871fc74ae4d435fd885 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 24 Nov 2026 18:18:04 -0800 Subject: [PATCH 3/4] test(worker): reduce worker and SQLite overlap --- apps/worker/e2e/startup.js | 42 +++++-------- .../src/services/maintain-visits.test.ts | 59 +++--------------- apps/worker/src/services/startup.test.ts | 62 ++----------------- .../services/update-daily-statistics.test.ts | 45 -------------- packages/db/src/visit-reports/storage.test.ts | 14 +---- 5 files changed, 33 insertions(+), 189 deletions(-) diff --git a/apps/worker/e2e/startup.js b/apps/worker/e2e/startup.js index 96e691c..909c40a 100644 --- a/apps/worker/e2e/startup.js +++ b/apps/worker/e2e/startup.js @@ -205,14 +205,14 @@ async function checkStartup(mode, port = 0) { database.close(); } assert.equal(dailyVisitCount(directory), mode === 'retention-change' ? 2 : 0); - if (mode === 'storage-change' || mode === 'retention-change') { + if (mode === 'retention-change') { const stopped = new AbortController(); void finished.then( () => stopped.abort(), () => stopped.abort() ); const readOutput = () => output; - await verifyRestartOnlyEdit(mode, directory, readOutput, stopped.signal); + await verifyRestartOnlyEdits(directory, readOutput, stopped.signal); const stillRunning = await fetch(`http://127.0.0.1:${ready.port}/healthz`, { signal: AbortSignal.timeout(2000) }); @@ -235,22 +235,23 @@ async function checkStartup(mode, port = 0) { } } -async function verifyRestartOnlyEdit(mode, directory, readOutput, signal) { +async function verifyRestartOnlyEdits(directory, readOutput, signal) { const path = join(directory, 'config/goto.yaml'); - const configuration = JSON.parse(await readFile(path, 'utf8')); - if (mode === 'storage-change') { - configuration.database = { path: './data/replacement.sqlite' }; - await saveConfiguration(path, configuration); - await waitUntil( - () => readOutput().includes('Database path change requires a coordinated restart'), - signal - ); - assert(!existsSync(join(directory, 'data/replacement.sqlite'))); - return; - } + const accepted = JSON.parse(await readFile(path, 'utf8')); + await saveConfiguration(path, { + ...accepted, + database: { path: './data/replacement.sqlite' } + }); + await waitUntil( + () => readOutput().includes('Database path change requires a coordinated restart'), + signal + ); + assert(!existsSync(join(directory, 'data/replacement.sqlite'))); - configuration.analytics.retention_months = 3; - await saveConfiguration(path, configuration); + await saveConfiguration(path, { + ...accepted, + analytics: { retention_months: 3 } + }); await waitUntil( () => readOutput().includes('Retention reduction requires a coordinated restart'), signal @@ -261,14 +262,6 @@ async function verifyRestartOnlyEdit(mode, directory, readOutput, signal) { 2, 'A live retention reduction must not delete daily detail' ); - - configuration.analytics.retention_months = 0; - await saveConfiguration(path, configuration); - await waitUntil( - () => readOutput().includes('Detailed analytics change requires a coordinated restart'), - signal - ); - assert.equal(visitCount(directory), 2, 'Live collection disable must not remove history'); assert.equal( lifetimeVisitCount(directory), 3, @@ -277,7 +270,6 @@ async function verifyRestartOnlyEdit(mode, directory, readOutput, signal) { } await checkStartup('source'); -await checkStartup('storage-change'); await checkStartup('retention-change'); await checkStartup('zero-accounting'); await checkStartup('database-failure'); diff --git a/apps/worker/src/services/maintain-visits.test.ts b/apps/worker/src/services/maintain-visits.test.ts index 635e699..a3b37df 100644 --- a/apps/worker/src/services/maintain-visits.test.ts +++ b/apps/worker/src/services/maintain-visits.test.ts @@ -7,7 +7,6 @@ import { processVisitBatch, deleteExpiredVisitBatch, deleteProcessedVisitBatch, - addVisitTotals, readVisitTotals, type ClassifiedVisit } from '@goto/db'; @@ -26,8 +25,7 @@ vi.mock('@goto/db', async (importOriginal) => { ...actual, processVisitBatch: vi.fn(actual.processVisitBatch), deleteExpiredVisitBatch: vi.fn(actual.deleteExpiredVisitBatch), - deleteProcessedVisitBatch: vi.fn(actual.deleteProcessedVisitBatch), - addVisitTotals: vi.fn(actual.addVisitTotals) + deleteProcessedVisitBatch: vi.fn(actual.deleteProcessedVisitBatch) }; }); @@ -41,7 +39,6 @@ afterEach(() => { vi.mocked(processVisitBatch).mockReset(); vi.mocked(deleteExpiredVisitBatch).mockReset(); vi.mocked(deleteProcessedVisitBatch).mockReset(); - vi.mocked(addVisitTotals).mockReset(); vi.mocked(addDailyStatistics).mockReset(); }); @@ -86,7 +83,7 @@ async function readTotals(db: WorkerContext['db'], scope: ReportScope): Promise< ); } -test('prepares bounded pending batches once and subtracts expired visits within a partial day', async () => { +test('accounts visits once across a batch boundary and keeps the cutoff-day survivor', async () => { const ctx = await context(); try { const now = reportNow; @@ -117,14 +114,6 @@ test('prepares bounded pending batches once and subtracts expired visits within accept_language: 'en;q=0.8' }); await maintainVisits(ctx, now); - expect(vi.mocked(addDailyStatistics).mock.calls.map(([, facts]) => facts.length)).toEqual([ - 1000, 4 - ]); - expect(vi.mocked(addVisitTotals).mock.calls[0]?.[1]).toEqual([ - { scope: overview, totals: { validVisits: 1000, invalidVisits: 0 } }, - { scope: domain, totals: { validVisits: 1000, invalidVisits: 0 } }, - { scope: docs, totals: { validVisits: 1000, invalidVisits: 0 } } - ]); expect(await readVisitTotals(ctx.db, overview)).toEqual({ validVisits: 1003, invalidVisits: 1 @@ -141,16 +130,7 @@ test('prepares bounded pending batches once and subtracts expired visits within expect(await readTotals(ctx.db, root)).toEqual({ validVisits: 1, invalidVisits: 0 }); const details = await readVisitDetails(ctx.db, domain, period); expect(details.lastActivityAt).toBe(new Date(now - 1000).toISOString()); - expect(details.browsers).toEqual([ - { day: '2026-03-02', name: 'Firefox', validVisits: 1, invalidVisits: 0 }, - { day: '2026-05-31', name: 'Firefox', validVisits: 1, invalidVisits: 1 } - ]); - expect(details.acceptedLanguages).toEqual([ - { day: '2026-03-02', name: 'en', validVisits: 1, invalidVisits: 0 }, - { day: '2026-03-02', name: 'fr', validVisits: 1, invalidVisits: 0 }, - { day: '2026-05-31', name: 'de', validVisits: 1, invalidVisits: 0 }, - { day: '2026-05-31', name: 'Other', validVisits: 0, invalidVisits: 1 } - ]); + expect(details.daily[0]).toMatchObject({ partial: true, validVisits: 1, invalidVisits: 0 }); expect( await ctx.db .selectFrom('visits') @@ -221,7 +201,7 @@ test('partial daily cache loss warns with bounded examples, continues raw expiry const warning = vi.spyOn(logger, 'warn').mockImplementation(() => undefined); try { const cutoff = Date.parse(period.from); - for (let daysBefore = 1; daysBefore <= 6; daysBefore++) { + for (const daysBefore of [1, 2]) { await insertVisit(ctx.db, { ...visit, visited_at: cutoff - daysBefore * 86_400_000 }); } await insertVisit(ctx.db, { ...visit, visited_at: reportNow - 86_400_000 }); @@ -229,7 +209,7 @@ test('partial daily cache loss warns with bounded examples, continues raw expiry vi.mocked(deleteExpiredVisitBatch).mockRejectedValueOnce(failure); await expect(maintainVisits(ctx, reportNow)).rejects.toBe(failure); expect(await ctx.db.selectFrom('visits').select('processed').execute()).toEqual( - Array.from({ length: 7 }, () => ({ processed: 1 })) + Array.from({ length: 3 }, () => ({ processed: 1 })) ); await ctx.db.deleteFrom('visit_daily_statistics').execute(); await warnIfDailyStatisticsMissing(ctx.db); @@ -263,31 +243,10 @@ test('partial daily cache loss warns with bounded examples, continues raw expiry expect(await ctx.db.selectFrom('visits').select('visited_at').execute()).toEqual([ { visited_at: reportNow - 86_400_000 } ]); - expect(warning).toHaveBeenLastCalledWith( - { - table: 'visit_daily_statistics', - skippedBucketUpdates: 18, - examples: [ - ...[overview, domain, docs].map((scope) => ({ - scope, - day: '2026-02-24', - rowId: null, - reason: 'missing', - stored: null, - removing: { validVisits: 1, invalidVisits: 0 } - })), - ...[overview, domain].map((scope) => ({ - scope, - day: '2026-02-25', - rowId: null, - reason: 'missing', - stored: null, - removing: { validVisits: 1, invalidVisits: 0 } - })) - ] - }, - expect.stringContaining('Expired processed visits were deleted') - ); + const [summary, message] = warning.mock.lastCall ?? []; + expect(message).toContain('Expired processed visits were deleted'); + expect(summary).toMatchObject({ table: 'visit_daily_statistics', skippedBucketUpdates: 6 }); + expect(summary).toHaveProperty('examples.length', 5); await maintainVisits(ctx, Date.parse('2026-09-01T00:00:00Z')); expect(await ctx.db.selectFrom('visits').select('id').execute()).toEqual([]); expect(await ctx.db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual([]); diff --git a/apps/worker/src/services/startup.test.ts b/apps/worker/src/services/startup.test.ts index 8253cc4..2b930c9 100644 --- a/apps/worker/src/services/startup.test.ts +++ b/apps/worker/src/services/startup.test.ts @@ -48,48 +48,9 @@ async function writeConfiguration( const env = { HOST: '127.0.0.1', PORT: '0' }; -test('starts with zero-policy rollup active, no empty run, tag warnings and healthy service', async () => { +test('zero-policy startup accounts pending visits before readiness and clears raw and daily data', async () => { await writeConfiguration(undefined, ['', 'work']); const warning = vi.spyOn(logger, 'warn').mockImplementation(() => undefined); - const start = vi.spyOn(Worker.prototype, 'start'); - const service = await startWorkerService({ cwd: directory, env }); - try { - expect(start).toHaveBeenCalledOnce(); - expect(warning).toHaveBeenCalledExactlyOnceWith( - expect.stringContaining('/domains/*/links/*/tags/0') - ); - const response = await fetch(`http://127.0.0.1:${service.port}/healthz`, { - signal: AbortSignal.timeout(2000) - }); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ status: 'ok' }); - const state = new DatabaseSync(join(directory, 'state/worker.sqlite'), { readOnly: true }); - try { - expect( - Number(state.prepare('SELECT count(*) AS count FROM workflow_runs').get()?.count) - ).toBe(0); - expect( - state - .prepare('SELECT next_run_at FROM workflow_schedules WHERE id = ?') - .get('goto:retain-visits')?.next_run_at - ).not.toBeNull(); - } finally { - state.close(); - } - const db = await openDb(join(directory, 'data/visits.sqlite'), { readOnly: true }); - try { - expect(await db.selectFrom('visits').selectAll().execute()).toEqual([]); - expect(await db.selectFrom('visit_daily_statistics').select('id').execute()).toEqual([]); - } finally { - await db.destroy(); - } - } finally { - await service.stop(); - } -}); - -test('zero-policy startup accounts pending visits before readiness and clears raw and daily data', async () => { - await writeConfiguration(undefined, []); const path = join(directory, 'data/visits.sqlite'); const db = await openDb(path); try { @@ -102,15 +63,12 @@ test('zero-policy startup accounts pending visits before readiness and clears ra daily.browsers = [{ name: 'Other', validVisits: 1, invalidVisits: 0 }]; daily.operatingSystems = [{ name: 'Other', validVisits: 1, invalidVisits: 0 }]; daily.acceptedLanguages = [{ name: 'Other', validVisits: 1, invalidVisits: 0 }]; - await db.transaction().execute(async (transaction) => { - await transaction.deleteFrom('visit_daily_statistics').execute(); - await addDailyVisitStatistics(transaction, [daily]); - }); + await db.transaction().execute((transaction) => addDailyVisitStatistics(transaction, [daily])); await insertVisit(db, { domain: 'go.example.test', path: '/docs', outcome: 'valid', - visited_at: Date.now() - 1000, + visited_at: visitedAt, ip: null, user_agent: null, accept_language: null, @@ -122,6 +80,7 @@ test('zero-policy startup accounts pending visits before readiness and clears ra } const service = await startWorkerService({ cwd: directory, env }); try { + expect(warning).toHaveBeenCalledWith(expect.stringContaining('/domains/*/links/*/tags/0')); const reader = await openDb(path, { readOnly: true }); try { expect(await reader.selectFrom('visits').selectAll().execute()).toEqual([]); @@ -130,19 +89,6 @@ test('zero-policy startup accounts pending visits before readiness and clears ra validVisits: 1, invalidVisits: 0 }); - const state = new DatabaseSync(join(directory, 'state/worker.sqlite'), { readOnly: true }); - try { - expect( - Number(state.prepare('SELECT count(*) AS count FROM workflow_runs').get()?.count) - ).toBe(1); - expect( - state - .prepare('SELECT next_run_at FROM workflow_schedules WHERE id = ?') - .get('goto:retain-visits')?.next_run_at - ).not.toBeNull(); - } finally { - state.close(); - } } finally { await reader.destroy(); } diff --git a/apps/worker/src/services/update-daily-statistics.test.ts b/apps/worker/src/services/update-daily-statistics.test.ts index 7d394ea..52e4d56 100644 --- a/apps/worker/src/services/update-daily-statistics.test.ts +++ b/apps/worker/src/services/update-daily-statistics.test.ts @@ -123,51 +123,6 @@ test('actual events create scope/day rows with Root normalization, independent f ); }); -test('oldest-first subtraction preserves same-day survivors and activity, then deletes zero buckets', async () => { - const before = Date.parse(period.from); - const visits = await processRows([ - { ...visit, path: '/', outcome: 'invalid', visited_at: before - 1 }, - { ...visit, path: '/', outcome: 'invalid', visited_at: before } - ]); - const rows = await db.selectFrom('visit_daily_statistics').selectAll().execute(); - expect(rows).toHaveLength(3); - expect(rows.find(({ scope_kind }) => scope_kind === 'link')).toMatchObject({ - day: '2026-01-01', - valid_visits: 2, - invalid_visits: 0, - last_visit_at: before - }); - await db.transaction().execute(async (transaction) => { - await transaction - .updateTable('visits') - .set({ processed: 1 }) - .where('id', '=', visits[0]!.id) - .execute(); - await subtractDailyStatistics(transaction, [getVisitFacts(visits[0]!)]); - await transaction.deleteFrom('visits').where('id', '=', visits[0]!.id).execute(); - }); - expect(await readTotals(root)).toEqual({ validVisits: 1, invalidVisits: 0 }); - expect(await readVisitDetails(db, root, period)).toMatchObject({ - lastActivityAt: new Date(before).toISOString(), - browsers: [{ day: '2026-01-01', name: 'Firefox', validVisits: 1, invalidVisits: 0 }] - }); - await db.transaction().execute(async (transaction) => { - await transaction - .updateTable('visits') - .set({ processed: 1 }) - .where('id', '=', visits[1]!.id) - .execute(); - await subtractDailyStatistics(transaction, [getVisitFacts(visits[1]!)]); - await transaction.deleteFrom('visits').where('id', '=', visits[1]!.id).execute(); - }); - expect(await db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual([]); - expect(await readTotals(root)).toEqual(zeroVisitTotals()); - expect(await readVisitDetails(db, root, period)).toMatchObject({ - lastActivityAt: null, - browsers: [] - }); -}); - test('batches read no raw history, update only affected days and leave quiet data byte-identical without clock writes', async () => { await processRows([{ ...visit, domain: 'quiet.example.test', visited_at: asOf - 86_400_000 }]); const quietBefore = await db.selectFrom('visit_daily_statistics').selectAll().execute(); diff --git a/packages/db/src/visit-reports/storage.test.ts b/packages/db/src/visit-reports/storage.test.ts index 9a86444..cfc505d 100644 --- a/packages/db/src/visit-reports/storage.test.ts +++ b/packages/db/src/visit-reports/storage.test.ts @@ -92,17 +92,9 @@ test('native daily UPSERT adds SQL counters and day-only JSON; oldest-first part expect( await writer((transaction) => subtractDailyVisitStatistics(transaction, [early])) ).toEqual([]); - const upsert = statements.mock.calls.find(([query]) => - /INSERT INTO visit_daily_statistics/i.test(query) - )?.[0]; - expect(upsert).toMatch(/ON CONFLICT DO UPDATE/); - expect(upsert).toMatch(/valid_visits = visit_daily_statistics.valid_visits \+/); - expect(upsert).not.toContain('Firefox'); - const subtraction = statements.mock.calls.find(([query]) => - /^update "visit_daily_statistics"/i.test(query) - )?.[0]; - expect(subtraction).toMatch(/valid_visits -/); - expect(subtraction).toMatch(/where "id" =/); + const sqlStatements = statements.mock.calls.map(([query]) => query).join('\n'); + expect(sqlStatements).toMatch(/valid_visits\s*=\s*visit_daily_statistics\.valid_visits\s*\+/i); + expect(sqlStatements).toMatch(/valid_visits\s*-\s*\?/i); } finally { statements.mockRestore(); } -- 2.54.1 From 528c5eb11f0e663aa2cdfff87fc32005220a657b Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 24 Nov 2026 18:44:43 -0800 Subject: [PATCH 4/4] test: simplify fixtures and remove duplicate assertions --- apps/cli/src/cli.test.ts | 33 ----- .../links/[...path]/page.server.test.ts | 47 +------ .../(auth)/admin/health/page.server.test.ts | 38 ++---- .../analytics/src/breakdown-visits.test.ts | 36 +---- .../analytics/src/daily-statistics.test.ts | 32 ++--- packages/analytics/src/daily.test.ts | 29 ++-- packages/config/src/load.test.ts | 39 ++---- packages/config/src/resolve.test.ts | 25 +--- scripts/seed-visits.test.js | 129 ++++++++---------- 9 files changed, 113 insertions(+), 295 deletions(-) diff --git a/apps/cli/src/cli.test.ts b/apps/cli/src/cli.test.ts index 97d5ed2..1004315 100644 --- a/apps/cli/src/cli.test.ts +++ b/apps/cli/src/cli.test.ts @@ -16,17 +16,8 @@ auth: credentials: username: admin password: \${DUMMY_PASSWORD} -link_defaults: - status_code: 302 - forward_query: true -fallback: - url: \${DUMMY_DESTINATION} domains: go.example.test: - link_defaults: - status_code: 307 - root: - url: \${DUMMY_DESTINATION} links: /docs: url: \${DUMMY_DESTINATION} @@ -118,17 +109,6 @@ describe('goto-cli config validate', () => { expect(output.stderr).toHaveBeenCalledExactlyOnceWith( 'Configuration warnings\n /domains/*/links/*/tags/1: Dropped tag: ASCII control characters are not allowed\n' ); - const diagnostic = output.stderr.mock.calls[0]?.[0]; - for (const sensitive of [ - ...Object.values(env), - 'private-tag-do-not-print', - 'go.example.test', - '/docs', - source, - cwd - ]) { - expect(diagnostic).not.toContain(sensitive); - } }); it.each([ @@ -165,16 +145,6 @@ describe('goto-cli config validate', () => { source: validYaml, environment: { ...env, DUMMY_SECRET: 'too-short' } }, - { - name: 'nonarray tags', - source: `${validYaml} tags: Work\n`, - environment: env - }, - { - name: 'nonstring tag item', - source: `${validYaml} tags: [Work, 42]\n`, - environment: env - }, { name: 'invalid appearance alongside dropped tags', source: `${validYaml} tags: [., ""]\nappearance: false\n`, @@ -225,9 +195,6 @@ describe('goto-cli config validate', () => { expect(output.stderr).toHaveBeenCalledExactlyOnceWith( 'Configuration validation failed.\n /: Unable to read configuration file\n' ); - const diagnostic = output.stderr.mock.calls[0]?.[0]; - expect(diagnostic).not.toContain('missing-private-path.yaml'); - expect(diagnostic).not.toContain(cwd); }); it.each([ diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/page.server.test.ts b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/page.server.test.ts index 5d067bd..3eab8a9 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/page.server.test.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/page.server.test.ts @@ -1,4 +1,4 @@ -import { loadConfig, type DomainConfiguration, type LinkConfiguration } from '@goto/config'; +import { loadConfig, type LinkConfiguration } from '@goto/config'; import { beforeEach, expect, test, vi } from 'vitest'; import type { Application } from '#lib/server/application.js'; import { prepareSnapshot } from '#lib/server/snapshot.js'; @@ -33,7 +33,7 @@ function request( path = '/docs', options: { host?: string; retentionMonths?: number; link?: Partial } = {} ) { - const domainConfiguration: Partial = { + const domainConfiguration = { link_defaults: { forward_query: true, ignore_trailing_slash: false }, links: { '/docs': { @@ -51,13 +51,8 @@ function request( tags: ['guides', 'reference'], ...options.link }, - '/a/b': { url: 'https://example.test/nested', enabled: true, tags: [] }, - '/a%2Fb': { - url: 'https://example.test/percent', - redirect: [{ if: { language: 'fr' }, to: 'https://example.test/percent-fr' }], - enabled: false, - tags: [] - } + '/a/b': { url: 'https://example.test/nested' }, + '/a%2Fb': { url: 'https://example.test/percent' } } }; const prepared = loadConfig( @@ -118,25 +113,9 @@ test('keeps decoded nested and literal-percent identities distinct', async () => ); expect(nested.path).toBe('/a/b'); expect(nested.lifetimeVisits).toBe(3); - expect(nested).toMatchObject({ - response: { url: 'https://example.test/nested', status_code: 301, forward_query: true }, - redirectRules: [], - caseInsensitive: false, - ignoreTrailingSlash: false, - forwardPath: false, - maxVisits: null, - state: 'active', - validFrom: null, - validUntil: null, - tags: [] - }); + expect(percent.path).toBe('/a%2Fb'); expect(percent.lifetimeVisits).toBe(8); - expect(percent.maxVisits).toBeNull(); - expect(percent.state).toBe('disabled'); - expect(percent.redirectRules).toEqual([ - { language: 'fr', os: null, to: 'https://example.test/percent-fr' } - ]); expect(readLastActivity).toHaveBeenNthCalledWith(1, expect.any(Object), { kind: 'link', domain, @@ -167,22 +146,6 @@ test('rejects unknown scopes and keeps lifetime visits when activity is unavaila }); }); -test.each([ - { maxVisits: 102, state: 'exhausted' }, - { maxVisits: 103, state: 'active' } -])( - 'projects configured max $maxVisits and $state from one lifetime lookup', - async ({ maxVisits, state }) => { - const event = request('/docs', { link: { max_visits: maxVisits } }); - const data = await load(event); - expect(data).toMatchObject({ maxVisits, state, lifetimeVisits: 102 }); - expect(event.locals.application.linkVisitCount).toHaveBeenCalledExactlyOnceWith( - domain, - '/docs' - ); - } -); - test('disabled analytics preserves a configured limit and exhaustion without reading activity', async () => { const event = request('/docs', { retentionMonths: 0, link: { max_visits: 102 } }); const data = await load(event); diff --git a/apps/web/src/routes/(admin)/(auth)/admin/health/page.server.test.ts b/apps/web/src/routes/(admin)/(auth)/admin/health/page.server.test.ts index 8735c19..25b5ca4 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/health/page.server.test.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/health/page.server.test.ts @@ -105,31 +105,18 @@ test('projects OIDC mode and configured redirect defaults without exposing the p }); }); -const taggedDomains = { - 'go.example.test': { - links: { - '/docs': { url: 'https://example.test/docs', tags: ['Work', 'Work'] }, - '/disabled': { url: 'https://example.test/disabled', tags: ['work'], enabled: false }, - '/later': { - url: 'https://example.test/later', - tags: [' Work '], - valid_from: '2099-01-01T00:00:00Z' - }, - '/old': { - url: 'https://example.test/old', - tags: ['Old'], - valid_until: '2020-01-01T00:00:00Z' +test('zero retention skips the activity read but still lists tags', async () => { + const data = await load( + request({ + analytics: { retention_months: 0 }, + domains: { + 'go.example.test': { + links: { '/docs': { url: 'https://example.test/docs', tags: ['Work/100%é'] } } + } } - } - }, - 'other.example.test': { - links: { '/docs': { url: 'https://example.test/other', tags: ['Work', 'Work/100%é'] } } - } -}; - -test('zero retention skips the activity read and keeps all current tag labels available', async () => { - const data = await load(request({ analytics: { retention_months: 0 }, domains: taggedDomains })); - expect(data.tags).toEqual([' Work ', 'Old', 'Work', 'Work/100%é', 'work']); + }) + ); + expect(data.tags).toEqual(['Work/100%é']); expect(data.retentionMonths).toBe(0); expect(data.lastDataActivity).toBeNull(); expect(data.activityAvailable).toBe(true); @@ -140,8 +127,7 @@ test('zero retention skips the activity read and keeps all current tag labels av test('unavailable analytics storage does not prevent viewing settings', async () => { vi.mocked(readLastActivity).mockResolvedValue({ available: false, lastActivityAt: null }); - const data = await load(request({ domains: taggedDomains })); - expect(data.tags).toEqual([' Work ', 'Old', 'Work', 'Work/100%é', 'work']); + const data = await load(request()); expect(data.retentionMonths).toBe(3); expect(data.lastDataActivity).toBeNull(); expect(data.activityAvailable).toBe(false); diff --git a/packages/analytics/src/breakdown-visits.test.ts b/packages/analytics/src/breakdown-visits.test.ts index b1eea7e..ff5546a 100644 --- a/packages/analytics/src/breakdown-visits.test.ts +++ b/packages/analytics/src/breakdown-visits.test.ts @@ -12,7 +12,8 @@ test('counts only valid visits in each UTC timeframe, combining named counts and { day: '2026-06-15', name: 'Firefox', validVisits: 2, invalidVisits: 0 }, { day: '2026-06-15', name: 'Chrome', validVisits: 1, invalidVisits: 0 }, { day: '2026-06-15', name: 'Other', validVisits: 5, invalidVisits: 0 }, - { day: '2026-06-15', name: 'Safari', validVisits: 0, invalidVisits: 90 } + { day: '2026-06-15', name: 'Safari', validVisits: 0, invalidVisits: 90 }, + { day: '2026-06-16', name: 'Firefox', validVisits: 100, invalidVisits: 0 } ]; const original = structuredClone(rows); const timeframes: VisitTimeframe[] = ['7d', 'all']; @@ -36,39 +37,6 @@ test('counts only valid visits in each UTC timeframe, combining named counts and expect(rows).toEqual(original); }); -test('counts overlapping language memberships independently using valid visits in the selected window', () => { - const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z')); - const rows: DailyVisitCountByName[] = [ - { day: '2026-03-17', name: 'fr', validVisits: 100, invalidVisits: 0 }, - { day: '2026-06-08', name: 'Other', validVisits: 100, invalidVisits: 0 }, - { day: '2026-06-09', name: 'fr', validVisits: 2, invalidVisits: 40 }, - { day: '2026-06-09', name: 'en', validVisits: 2, invalidVisits: 40 }, - { day: '2026-06-15', name: 'fr', validVisits: 3, invalidVisits: 0 }, - { day: '2026-06-15', name: 'en', validVisits: 3, invalidVisits: 0 }, - { day: '2026-06-15', name: 'Other', validVisits: 1, invalidVisits: 0 }, - { day: '2026-06-15', name: 'de', validVisits: 0, invalidVisits: 9 }, - { day: '2026-06-16', name: 'fr', validVisits: 100, invalidVisits: 0 } - ]; - const timeframes: VisitTimeframe[] = ['7d', 'all']; - const windows = timeframes.map((timeframe) => ({ - timeframe, - window: visitWindow(period, timeframe) - })); - - expect(countBreakdownVisitsByTimeframe(rows, windows)).toEqual({ - '7d': [ - { name: 'en', visits: 5 }, - { name: 'fr', visits: 5 }, - { name: 'Other', visits: 1 } - ], - all: [ - { name: 'fr', visits: 105 }, - { name: 'Other', visits: 101 }, - { name: 'en', visits: 5 } - ] - }); -}); - test('intersects UTC days at partial and exclusive boundaries rather than filtering by midnight alone', () => { const rows = [ { day: '2024-02-27', name: 'Other', validVisits: 100, invalidVisits: 0 }, diff --git a/packages/analytics/src/daily-statistics.test.ts b/packages/analytics/src/daily-statistics.test.ts index a86f9f4..c3065db 100644 --- a/packages/analytics/src/daily-statistics.test.ts +++ b/packages/analytics/src/daily-statistics.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import { createVisitPeriod, visitDays } from './period.js'; +import { createVisitPeriod } from './period.js'; import { addDailyStatistics, canSubtractDailyStatistics, @@ -69,13 +69,20 @@ test('projection uses the explicit current period, fills missing dates, and expo const details = projectVisitDetails(scope, period, [outside, visible]); expect(details.version).toBe(5); expect(details.lastActivityAt).toBe('2026-04-01T10:00:00.000Z'); - expect(details.daily).toEqual( - visitDays(period).map((point) => ({ - ...point, - validVisits: point.start.startsWith(day) ? 2 : 0, - invalidVisits: point.start.startsWith(day) ? 1 : 0 - })) + expect(details.daily[0]?.start).toBe('2026-01-01T00:00:00.000Z'); + expect(details.daily).not.toContainEqual( + expect.objectContaining({ start: '2025-12-31T00:00:00.000Z' }) ); + expect(details.daily.at(-2)).toMatchObject({ + start: '2026-03-31T00:00:00.000Z', + validVisits: 0, + invalidVisits: 0 + }); + expect(details.daily.at(-1)).toMatchObject({ + start: '2026-04-01T00:00:00.000Z', + validVisits: 2, + invalidVisits: 1 + }); expect(details.browsers).toEqual([{ day, name: 'Other', validVisits: 2, invalidVisits: 1 }]); expect(details.acceptedLanguages).toEqual( visible.acceptedLanguages.map((row) => ({ day, ...row })) @@ -86,17 +93,6 @@ test('projection uses the explicit current period, fills missing dates, and expo expect(empty.browsers).toEqual([]); }); -test('partial-day expiry changes counts without turning activity into maintenance time', () => { - const cutoffPeriod = createVisitPeriod(3, Date.UTC(2026, 5, 30, 6)); - const earlier = contribution(1, 0, 1); - const later = contribution(1, 1, 10); - const combined = addDailyStatistics(earlier, later); - const remaining = subtractDailyStatistics(combined, earlier)!; - const details = projectVisitDetails(scope, cutoffPeriod, [remaining]); - expect(details.daily[0]).toMatchObject({ partial: true, validVisits: 1, invalidVisits: 1 }); - expect(details.lastActivityAt).toBe('2026-04-01T10:00:00.000Z'); -}); - test('daily guards keep exact family partitions, safe counts, and independent bounded language memberships', () => { const valid = contribution(2, 1, 10); expect(() => diff --git a/packages/analytics/src/daily.test.ts b/packages/analytics/src/daily.test.ts index ac93772..805398d 100644 --- a/packages/analytics/src/daily.test.ts +++ b/packages/analytics/src/daily.test.ts @@ -6,8 +6,7 @@ import { resolveVisitTimeframe, sumVisitTotals, visitGranularity, - visitWindow, - type VisitTimeframe + visitWindow } from './daily.js'; import { visitDays } from './period.js'; import type { ReportPeriod, VisitDetails } from './reports.js'; @@ -118,28 +117,16 @@ test('selected days are filtered before grouping and share the headline total wi invalidVisits: 2 } ]); - expect(sumVisitTotals(daily, window)).toEqual({ validVisits: 9, invalidVisits: 53 }); - expect(weeks.reduce((total, week) => total + week.validVisits, 0)).toBe(9); - expect(daily).toEqual(original); -}); - -test('window counts project both outcomes for each requested timeframe', () => { - const { period, daily } = dailyReport('2024-02-20T12:00:00.000Z', '2024-03-05T00:00:00.000Z', { - '2024-02-26': [100, 100], - '2024-02-27': [2, 50], - '2024-02-29': [3, 1], - '2024-03-04': [4, 2] - }); - const timeframes: VisitTimeframe[] = ['7d', 'all']; - const windows = timeframes.map((timeframe) => ({ - timeframe, - window: visitWindow(period, timeframe) - })); - - expect(countVisitWindows(daily, windows)).toEqual({ + expect( + countVisitWindows(daily, [ + { timeframe: '7d', window }, + { timeframe: 'all', window: visitWindow(period, 'all') } + ]) + ).toEqual({ '7d': { validVisits: 9, invalidVisits: 53 }, all: { validVisits: 109, invalidVisits: 153 } }); + expect(daily).toEqual(original); }); test('missing daily reports stay absent while empty and zero-filled reports give window zeros', () => { diff --git a/packages/config/src/load.test.ts b/packages/config/src/load.test.ts index 141a827..55e47bf 100644 --- a/packages/config/src/load.test.ts +++ b/packages/config/src/load.test.ts @@ -501,19 +501,11 @@ domains: ); }); - it.each([ - { - name: 'password mapping', - override: { - auth: { credentials: { username: 'admin', password: { [authoredKeyMarker]: null } } } - } - }, - { name: 'unknown option', override: { [authoredKeyMarker]: 'value' } }, - { name: 'missing variable', override: { [authoredKeyMarker]: '${MISSING}' } } - ])('keeps authored keys out of generic errors for $name', ({ override }) => { + it('does not expose authored keys from a malformed password mapping', () => { + const auth = { credentials: { username: 'admin', password: { [authoredKeyMarker]: null } } }; let error: unknown; try { - loadConfig({ ...configurationInput(), ...override }, options); + loadConfig({ ...configurationInput(), auth }, options); } catch (caught) { error = caught; } @@ -523,13 +515,12 @@ domains: expect(JSON.stringify(error)).not.toContain(authoredKeyMarker); }); - it.each([ - `${yaml}\nversion: 1\nversion: 1`, - `${yaml}\n<<: {version: 1}`, - `${yaml}\n---\n${yaml}` - ])('rejects non-strict YAML', (source) => { - expect(() => parseConfig(source, options)).toThrow(ConfigError); - }); + it.each([`${yaml}\n<<: {version: 1}`, `${yaml}\n---\n${yaml}`])( + 'rejects non-strict YAML', + (source) => { + expect(() => parseConfig(source, options)).toThrow(ConfigError); + } + ); it('converts numeric YAML domain keys to strings before normalizing hosts', () => { const { configuration, domains } = parseConfig( @@ -540,18 +531,6 @@ domains: expect(Object.keys(domains)).toEqual(['0.0.0.1']); }); - it('does not expose YAML parser snippets containing secrets', () => { - let error: unknown; - try { - parseConfig(`${yaml}\nauth: private-secret`, options); - } catch (caught) { - error = caught; - } - expect(error).toBeInstanceOf(ConfigError); - expect(error).toHaveProperty('message', 'Invalid configuration'); - expect(JSON.stringify(error)).not.toContain('private-secret'); - }); - it('allows small aliases but bounds repeated expansion', () => { const source = `${yaml.replace('domains: {}', '')}domains:\n go.example.com:\n links:\n /base: &link {url: https://example.com}\n`; expect( diff --git a/packages/config/src/resolve.test.ts b/packages/config/src/resolve.test.ts index 94a771e..df651ef 100644 --- a/packages/config/src/resolve.test.ts +++ b/packages/config/src/resolve.test.ts @@ -331,7 +331,6 @@ describe('effective domains', () => { ignore_trailing_slash: true, forward_path: true }, - fallback: { url: 'https://example.com' }, domains: { global: input.domains['go.example.com'], domain: { @@ -342,7 +341,6 @@ describe('effective domains', () => { ignore_trailing_slash: false, forward_path: false }, - fallback: { url: 'https://example.com/domain-missing' }, links: input.domains['go.example.com'].links } } @@ -375,10 +373,6 @@ describe('effective domains', () => { forward_path: 'link' } }); - expect(domains.global).toMatchObject({ - fallback: { url: 'https://example.com', status_code: 302, forward_query: false }, - provenance: { fallback: 'global' } - }); expect(domains.domain?.links['/inherit']).toMatchObject({ status_code: 307, forward_query: false, @@ -393,14 +387,6 @@ describe('effective domains', () => { forward_path: 'domain' } }); - expect(domains.domain).toMatchObject({ - fallback: { - url: 'https://example.com/domain-missing', - status_code: 302, - forward_query: false - }, - provenance: { fallback: 'domain' } - }); expect(domains.domain?.links['/override']).toMatchObject({ status_code: 308, forward_query: false, @@ -415,7 +401,6 @@ describe('effective domains', () => { forward_path: 'link' } }); - expect(domains.domain?.links['/override']).not.toHaveProperty('fallback'); }); it('replaces a global fallback as a whole and keeps root response options independent', () => { @@ -429,7 +414,7 @@ describe('effective domains', () => { replaced: { root: { url: 'https://example.com/root', status_code: 301, forward_query: true }, fallback: { url: 'https://example.com/domain' }, - links: {} + links: { '/docs': { url: 'https://example.com/docs' } } } } }, @@ -442,13 +427,13 @@ describe('effective domains', () => { links: {}, caseInsensitivePaths: {} }); - expect(domains.replaced).toEqual({ + expect(domains.replaced).toMatchObject({ root: { url: 'https://example.com/root', status_code: 301, forward_query: true }, fallback: { url: 'https://example.com/domain', status_code: 302, forward_query: false }, - provenance: { fallback: 'domain' }, - links: {}, - caseInsensitivePaths: {} + provenance: { fallback: 'domain' } }); + expect(domains.replaced?.links['/docs']).toBeDefined(); + expect(domains.replaced?.links['/docs']).not.toHaveProperty('fallback'); }); it.each([ diff --git a/scripts/seed-visits.test.js b/scripts/seed-visits.test.js index dc58954..d86e9e7 100644 --- a/scripts/seed-visits.test.js +++ b/scripts/seed-visits.test.js @@ -24,6 +24,38 @@ const fixture = { } }; +const existingVisit = { + domain: 'one.example.test', + path: '/keep', + outcome: 'valid', + visited_at: 1, + ip: '198.51.100.1', + user_agent: 'ExistingClient', + accept_language: null, + browser: 'Other', + os: 'Other' +}; + +async function createDatabaseWithExistingVisit(databasePath) { + const db = await openDb(databasePath); + try { + await runMigrations(db); + const id = await insertVisit(db, existingVisit); + return { id, processed: 0, ...existingVisit }; + } finally { + await db.destroy(); + } +} + +async function readVisits(databasePath) { + const db = await openDb(databasePath, { readOnly: true }); + try { + return (await db.selectFrom('visits').selectAll().execute()).map((row) => ({ ...row })); + } finally { + await db.destroy(); + } +} + function run(...args) { return spawnSync(process.execPath, ['--import', loader, script, ...args], { encoding: 'utf8', @@ -118,52 +150,29 @@ test('preview opens no SQLite file and applying refuses to create a missing data } }); -test('explicit apply appends all configured domains in bounded batches without replacing existing visits', async () => { +test('preview leaves existing visits untouched; apply appends visits for every domain', async () => { const directory = await mkdtemp(join(tmpdir(), 'goto-seed-apply-')); try { const { configPath, databasePath } = await deployment(directory); - const existing = { - domain: 'one.example.test', - path: '/keep', - outcome: 'valid', - visited_at: 1, - ip: '198.51.100.1', - user_agent: 'ExistingClient', - accept_language: null, - browser: 'Other', - os: 'Other' - }; - const writer = await openDb(databasePath); - let id; - try { - await runMigrations(writer); - id = await insertVisit(writer, existing); - } finally { - await writer.destroy(); - } - const result = run( - '--config', - configPath, - '--visits-per-domain', - '100', - '--seed', - '17', - '--apply' - ); + const existing = await createDatabaseWithExistingVisit(databasePath); + const args = ['--config', configPath, '--visits-per-domain', '100', '--seed', '17']; + const preview = run(...args); + assert.equal(preview.status, 0, preview.stderr); + assert.match(preview.stdout, /Dry run/); + assert.deepEqual(await readVisits(databasePath), [existing]); + + const result = run(...args, '--apply'); assert.equal(result.status, 0, result.stderr); assert.match(result.stdout, /Appended 300 synthetic visits/); - const reader = await openDb(databasePath, { readOnly: true }); - try { - const rows = await reader.selectFrom('visits').selectAll().execute(); - assert.equal(rows.length, 301); - const original = rows.find((row) => row.id === id); - assert.deepEqual({ ...original }, { id, processed: 0, ...existing }); - const synthetic = rows.filter((row) => row.user_agent?.endsWith(' GotoSeed/17')); - for (const domain of Object.keys(fixture.domains)) { - assert.equal(synthetic.filter((row) => row.domain === domain).length, 100); - } - } finally { - await reader.destroy(); + const rows = await readVisits(databasePath); + assert.equal(rows.length, 301); + assert.deepEqual( + rows.find(({ id }) => id === existing.id), + existing + ); + const synthetic = rows.filter((row) => row.user_agent?.endsWith(' GotoSeed/17')); + for (const domain of Object.keys(fixture.domains)) { + assert.equal(synthetic.filter((row) => row.domain === domain).length, 100); } } finally { await rm(directory, { recursive: true, force: true }); @@ -174,25 +183,7 @@ test('a failed second batch rolls back its partial writes and preserves committe const directory = await mkdtemp(join(tmpdir(), 'goto-seed-failure-')); try { const { configPath, databasePath } = await deployment(directory); - const existing = { - domain: 'one.example.test', - path: '/keep', - outcome: 'valid', - visited_at: 1, - ip: '198.51.100.1', - user_agent: 'ExistingClient', - accept_language: null, - browser: 'Other', - os: 'Other' - }; - const writer = await openDb(databasePath); - let id; - try { - await runMigrations(writer); - id = await insertVisit(writer, existing); - } finally { - await writer.destroy(); - } + const existing = await createDatabaseWithExistingVisit(databasePath); const triggerDb = new DatabaseSync(databasePath); try { triggerDb.exec(` @@ -219,17 +210,13 @@ test('a failed second batch rolls back its partial writes and preserves committe assert.equal(result.status, 1, result.stderr); assert.match(result.stderr, /synthetic fixture failure/); assert.match(result.stderr, /Stopped after 250 committed visits/); - const reader = await openDb(databasePath, { readOnly: true }); - try { - const rows = await reader.selectFrom('visits').selectAll().execute(); - const synthetic = rows.filter((row) => row.user_agent?.endsWith(' GotoSeed/17')); - assert.equal(synthetic.length, 250); - assert.equal(rows.length, 251); - const original = rows.find((row) => row.id === id); - assert.deepEqual({ ...original }, { id, processed: 0, ...existing }); - } finally { - await reader.destroy(); - } + const rows = await readVisits(databasePath); + assert.equal(rows.filter((row) => row.user_agent?.endsWith(' GotoSeed/17')).length, 250); + assert.equal(rows.length, 251); + assert.deepEqual( + rows.find(({ id }) => id === existing.id), + existing + ); } finally { await rm(directory, { recursive: true, force: true }); } -- 2.54.1