diff --git a/scripts/e2e.mjs b/scripts/e2e.mjs index 9de3b6d..56e2914 100644 --- a/scripts/e2e.mjs +++ b/scripts/e2e.mjs @@ -135,27 +135,52 @@ try { const moved = await json(await context.request.delete(`${base}/api/kanban/columns/${custom.id}`)) assert.equal(moved.moved, 1) await page.goto(`${base}/pages`) - await page.locator('main').getByRole('button', { name: 'New page', exact: true }).click() + await page.getByRole('button', { name: 'New page', exact: true }).click() await page.getByRole('textbox', { name: 'Page title' }).waitFor() - await page.getByPlaceholder('Write Markdown notes… type / for blocks, paste links, lists, thoughts.').fill('# QA page\n\nAutosaved markdown.') + // TipTap contenteditable: drive it with keyboard.insertText (fill() does + // not work on contenteditable) and watch the workspace save badge. + const editor = page.locator('[data-page-editor]') + await editor.click() + await page.keyboard.insertText('Autosaved markdown from browser QA.') await page.getByText('Saved', { exact: true }).waitFor() const pages = await json(await context.request.get(`${base}/api/pages`)) - const detail = await json(await context.request.get(`${base}/api/pages/${pages[0].id}`)) - assert.equal(detail.content, '# QA page\n\nAutosaved markdown.') + let created = null + for (const p of pages) { + const detail = await json(await context.request.get(`${base}/api/pages/${p.id}`)) + if (detail.content.includes('Autosaved markdown from browser QA.')) { created = detail; break } + } + assert.ok(created, 'autosaved page content never reached the API') // Notion-style slash menu: "/h2" at the start of a line inserts a heading. - const editor = page.getByPlaceholder('Write Markdown notes… type / for blocks, paste links, lists, thoughts.') await editor.click() - await page.keyboard.press('Control+End') + await page.keyboard.press('End') await page.keyboard.press('Enter') await page.keyboard.type('/h2') await page.getByRole('option', { name: /Heading 2/ }).click() - await editor.evaluate((el, suffix) => new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(new Error(`slash command did not insert heading: ${JSON.stringify(el.value)}`)), 5000) - const check = setInterval(() => { if (el.value.endsWith(suffix)) { clearTimeout(timeout); clearInterval(check); resolve() } }, 25) - }), '\n## ') - console.log('PASS: slash command menu inserts Markdown blocks') - await json(await context.request.patch(`${base}/api/pages/${pages[0].id}`, { data: { addBookmarkId: bookmark.id } })) - const markdown = await context.request.get(`${base}/api/pages/${pages[0].id}/markdown`) + await page.keyboard.type('QA heading') + await page.getByText('Saved', { exact: true }).waitFor() + const slashed = await json(await context.request.get(`${base}/api/pages/${created.id}`)) + assert.ok(slashed.content.includes('## QA heading'), `slash command did not insert heading: ${JSON.stringify(slashed.content)}`) + console.log('PASS: pages autosave and slash commands insert Markdown headings') + await json(await context.request.patch(`${base}/api/pages/${created.id}`, { data: { addBookmarkId: bookmark.id } })) + // Product invariant: a URL added to the page (paste) becomes a bookmark. + // insertText does not fire ProseMirror's paste handler, so dispatch a real + // ClipboardEvent; arm both network waits before the event. + const bookmarkPost = page.waitForResponse(r => r.url().includes('/api/bookmarks') && r.request().method() === 'POST') + const linkPatch = page.waitForResponse(r => r.request().method() === 'PATCH' && r.url().includes('/api/pages/') && Boolean(r.request().postDataJSON()?.addBookmarkId)) + await editor.click() + await page.keyboard.press('Control+a') + await page.evaluate(() => { + const dt = new DataTransfer() + dt.setData('text/plain', 'https://e2e-url.test/qa-page-link') + document.querySelector('[data-page-editor]') + .dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })) + }) + const created2 = await (await bookmarkPost).json() + await linkPatch + const linked = await json(await context.request.get(`${base}/api/pages/${created.id}`)) + assert.ok(created2.url === 'https://e2e-url.test/qa-page-link', 'paste created a bookmark for the wrong URL') + assert.ok(linked.bookmarks.some(b => b.bookmark.url === 'https://e2e-url.test/qa-page-link'), 'pasted URL did not become a page bookmark') + const markdown = await context.request.get(`${base}/api/pages/${created.id}/markdown`) assert.equal(markdown.status(), 200) assert.ok((await markdown.text()).includes('Browser QA bookmark')) // Collections (Notion-like upgrades phase 2, validation scenario): an diff --git a/scripts/regressions.mjs b/scripts/regressions.mjs index a18598b..9128dd7 100644 --- a/scripts/regressions.mjs +++ b/scripts/regressions.mjs @@ -5,7 +5,10 @@ import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' // The real built Next server/UI with isolated API fixtures: no app users or DB writes. -const pages = new Map(['a', 'b'].map((id, position) => [id, { id, title: `Page ${id.toUpperCase()}`, content: '', version: 1, position, pinned: false, bookmarks: [] }])) +// The real Go projection (pageView) always carries these arrays; the fixture +// must too, or client code reading them crashes exactly as the tests prove. +const newPageFixture = (id, position) => ({ id, title: `Page ${id.toUpperCase()}`, content: '', version: 1, position, pinned: false, bookmarks: [], backlinks: [], links: [], embeds: [] }) +const pages = new Map(['a', 'b'].map((id, position) => [id, newPageFixture(id, position)])) const tags = [{ id: 'one', name: 'First tag', color: '#123456' }, { id: 'two', name: 'Second tag', color: '#654321' }] const kanbanColumns = [ { id: 'inbox', label: 'Inbox', color: '#123456', key: 'INBOX', position: 0 }, @@ -43,6 +46,15 @@ const api = http.createServer(async (req, res) => { try { let raw = '' for await (const chunk of req) raw += chunk + // Mirror Go's content-type discipline (internal/http security_test): + // mutating requests carrying a non-JSON Content-Type are rejected + // outright — the body is never JSON-sniffed. + const ctype = (req.headers['content-type'] || '').split(';')[0].trim().toLowerCase() + if (!['GET', 'HEAD', 'DELETE'].includes(req.method) && req.headers['content-type'] && ctype !== 'application/json') { + res.writeHead(415, { 'Content-Type': 'application/json' }) + res.end('{"error":"Content-Type must be application/json"}') + return + } const body = raw ? JSON.parse(raw) : {} const url = new URL(req.url, 'http://fixture') let result = [] @@ -81,15 +93,35 @@ const api = http.createServer(async (req, res) => { activeSaves++ maxConcurrentSaves = Math.max(maxConcurrentSaves, activeSaves) await new Promise(resolve => setTimeout(resolve, delaySaves)) - const { version, ...data } = body + const { version, addBookmarkId, removeBookmarkId, ...data } = body Object.assign(target, data) + // Mirrors Go's page PATCH link ops: add is visibility-checked and + // idempotent (ON CONFLICT DO NOTHING), remove just detaches. + if (removeBookmarkId) target.bookmarks = target.bookmarks.filter(x => x.bookmark.id !== removeBookmarkId) + if (addBookmarkId && !target.bookmarks.some(x => x.bookmark.id === addBookmarkId)) { + const bookmark = bookmarks.find(b => b.id === addBookmarkId) + if (bookmark) target.bookmarks.push({ pageId: id, bookmarkId: bookmark.id, position: target.bookmarks.length, bookmark }) + } if ('content' in body) target.version++ activeSaves-- } result = pages.get(id) + } else if (url.pathname === '/api/bookmarks' && req.method === 'POST') { + const bookmark = { + id: `bookmark-${bookmarks.length}`, ownerId: 'fixture-user', title: body.url, url: body.url, + description: '', notes: '', tags: [], sharedWith: [], kanbanStatus: 'INBOX', kanbanColumnId: null, kanbanPosition: null, + isPublic: false, imapWatchEnabled: false, alertAt: null, dueDate: null, version: 0, + createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), + } + bookmarks.push(bookmark) + result = bookmark } else if (url.pathname === '/api/bookmarks') { const shared = url.searchParams.get('shared') === 'true' - const matching = shared ? [] : bookmarks.filter(b => b.title.includes(url.searchParams.get('search') || '')) + const q = (url.searchParams.get('search') || '').toLowerCase() + // Go's search matches title, url, notes and tags (bookmarks.go); the + // url match is what lets the pages workspace reuse an existing bookmark + // for a URL instead of creating a duplicate. + const matching = shared ? [] : bookmarks.filter(b => !q || b.title.toLowerCase().includes(q) || b.url.toLowerCase().includes(q)) const offset = Number(url.searchParams.get('cursor') || 0) const limit = Number(url.searchParams.get('limit') || 200) // Mirror the Go permission-specific projections (PRIV-02): shared @@ -192,7 +224,7 @@ for (let attempt = 1; attempt <= 3; attempt++) { } const attacker = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html') - res.end(`
`) + res.end(`
`) }) await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve)) async function eventually(check, label) { @@ -202,6 +234,19 @@ async function eventually(check, label) { } assert.fail(label) } +// The UI logs in through NextAuth's credentials callback (app/login/client.tsx +// signIn('credentials')); the standalone Next /api/auth/login route was removed +// as dead in 4e421f6, so the tests must speak the same protocol as the browser: +// fetch a CSRF token, POST the callback, and prove the session landed. +async function fixtureLogin(context) { + const { csrfToken } = await context.request.get(`${base}/api/auth/csrf`).then(r => r.json()) + await context.request.post(`${base}/api/auth/callback/credentials`, { + headers: { Origin: base }, + form: { csrfToken, email: 'fixture@superbrain.test', password: 'password', callbackUrl: `${base}/pages` }, + }) + const session = await context.request.get(`${base}/api/auth/session`).then(r => r.json()) + assert.equal(session?.user?.id, 'fixture-user', 'fixture login did not establish a NextAuth session') +} let browser try { await eventually(async () => { try { return (await fetch(`${base}/login`)).ok } catch { return false } }, `Next server did not start: ${logs}`) @@ -212,17 +257,25 @@ try { page.on('pageerror', error => errors.push(error.message)) page.on('dialog', dialog => dialog.accept()) await page.goto(`http://127.0.0.1:${attacker.address().port}`) - await page.waitForURL(`${base}/api/auth/login`) + await page.waitForURL(`${base}/api/pages`) + await page.getByText('Invalid request origin').waitFor() assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined) - for (const headers of [{ Origin: 'https://attacker.invalid' }, {}]) { - const response = await context.request.post(`${base}/api/auth/login`, { headers, data: { email: 'attacker@superbrain.test', password: 'password' } }) - assert.equal(response.status(), 403) + // Proxy CSRF barriers (web/app/api/[...path]/route.ts): a present attacker + // Origin is rejected, and a stripped Origin cannot bypass the check for a + // cross-site Sec-Fetch-Site mutation. + for (const headers of [{ Origin: 'https://attacker.invalid' }, { 'sec-fetch-site': 'cross-site' }]) { + const response = await fetch(`${base}/api/pages`, { + method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: '{"title":"forged"}', + }) + assert.equal(response.status, 403, `mutating proxy request survived ${JSON.stringify(headers)}`) } - const plain = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base, 'Content-Type': 'text/plain' }, data: '{"email":"attacker@superbrain.test"}' }) - assert.equal(plain.status(), 415) - const login = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } }) - assert.equal(login.status(), 200) - console.log('PASS: forged logins rejected; legitimate login works') + // Go rejects non-JSON bodies with 415 (internal/http security_test); the + // fixture mirrors that discipline so the Next proxy's content-type + // passthrough is exercised end to end. + const plain = await fetch(`${base}/api/pages`, { method: 'POST', headers: { Origin: base, 'Content-Type': 'text/plain' }, body: '{"title":"forged"}' }) + assert.equal(plain.status, 415) + await fixtureLogin(context) + console.log('PASS: cross-site form posts and forged mutations rejected; fixture login works through NextAuth') // Review CR-14: an oversized chunked body (no usable Content-Length) must // be rejected by the proxy's streaming limit — counted while read and @@ -251,7 +304,7 @@ try { } await page.goto(`${base}/pages?id=a`) await setEditorText('A edits before switching') - await page.getByRole('button', { name: 'Page B', exact: true }).click() + await page.getByRole('link', { name: 'Page B', exact: true }).click() await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page B'), 'Page B not selected') await setEditorText('B edits') await eventually(() => pages.get('b').content === 'B edits', 'Page B not saved') @@ -270,11 +323,14 @@ try { failSaves = true await setEditorText('Recover this failed draft') - await page.getByRole('button', { name: 'Page A', exact: true }).click() + await page.getByRole('link', { name: 'Page A', exact: true }).click() await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() assert.equal(await page.getByRole('textbox', { name: 'Page title' }).inputValue(), 'Page B') - await page.reload() - await eventually(() => editor.inputValue().then(value => value === 'Recover this failed draft'), 'Draft not recovered after reload') + // The sidebar row is a , so the URL may move to ?id=a even while the + // workspace keeps its unsaved B draft. Recovery lives per page — reload + // where the draft actually is. + await page.goto(`${base}/pages?id=b`) + await eventually(() => editor.textContent().then(value => value === 'Recover this failed draft'), 'Draft not recovered after reload') failSaves = false await page.getByRole('button', { name: 'Save now', exact: true }).click() await eventually(() => pages.get('b').content === 'Recover this failed draft', 'Retry did not persist draft') @@ -312,7 +368,7 @@ try { pages.get('b').version++ failSaves = false await page.reload() - await eventually(() => editor.inputValue().then(value => value === 'Draft with an older base'), 'Draft not recovered after reload') + await eventually(() => editor.textContent().then(value => value === 'Draft with an older base'), 'Draft not recovered after reload') await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() // Snapshot AFTER recovery: the reload itself lets the departing page flush // its dirty draft once (the fixture rejects it with a 409 against the newer @@ -322,7 +378,7 @@ try { assert.equal(patchAttempts, attemptsAfterRecovery, 'Recovered draft saved without an explicit resolution') assert.equal(pages.get('b').content, 'Remote saved while draft failed', 'Recovery rebased onto and clobbered the newer version') await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() - await eventually(() => editor.inputValue().then(value => value === 'Remote saved while draft failed'), 'Discard did not load the remote content') + await eventually(() => editor.textContent().then(value => value === 'Remote saved while draft failed'), 'Discard did not load the remote content') console.log('PASS: recovered drafts keep their original base and conflict instead of rebasing') // Unknown-provenance draft (review DATA-06): a legacy plain-string draft @@ -334,13 +390,13 @@ try { await page.evaluate(() => sessionStorage.setItem('superbrain:page-draft:a', JSON.stringify('Legacy draft of unknown origin'))) const attemptsBeforeLegacy = patchAttempts await page.reload() - await eventually(() => editor.inputValue().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered') + await eventually(() => editor.textContent().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered') await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() await new Promise(resolve => setTimeout(resolve, 1000)) assert.equal(patchAttempts, attemptsBeforeLegacy, 'Unknown-base draft saved without review') assert.equal(pages.get('a').content, 'Typing must not overwrite', 'Unknown-base draft clobbered the remote content') await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() - await eventually(() => editor.inputValue().then(value => value === 'Typing must not overwrite'), 'Discard did not load the remote content') + await eventually(() => editor.textContent().then(value => value === 'Typing must not overwrite'), 'Discard did not load the remote content') console.log('PASS: unknown-base legacy drafts pause for review instead of saving') // Envelope refresh (review DATA-07): when a later save in the same serial @@ -356,7 +412,7 @@ try { await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() assert.equal(pages.get('b').content, 'Envelope part one', 'First save of the loop did not land') await page.reload() - await eventually(() => editor.inputValue().then(value => value === 'Envelope part two'), 'Newest loop content not recovered') + await eventually(() => editor.textContent().then(value => value === 'Envelope part two'), 'Newest loop content not recovered') assert.equal(await page.getByText('This page was changed elsewhere', { exact: true }).count(), 0, 'Recovery hit a spurious conflict — the stored base was not refreshed after the successful save') delaySaves = 0 @@ -380,7 +436,7 @@ try { await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() assert.equal(pages.get('a').content, 'Remote content stays', 'Metadata response rebased the stale draft over the remote content') await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() - await eventually(() => editor.inputValue().then(value => value === 'Remote content stays'), 'Discard did not load the remote content') + await eventually(() => editor.textContent().then(value => value === 'Remote content stays'), 'Discard did not load the remote content') console.log('PASS: metadata mutations do not rebase stale content drafts') await page.goto(`${base}/bookmarks`) @@ -442,6 +498,42 @@ try { await inboxColumn.locator('[data-bookmark-id="bookmark-3"]').waitFor() console.log('PASS: kanban drag reorders within a column and moves cards between columns') + // URLs added to a page become bookmarks (product invariant): the editor's + // Link button and a bare-URL paste each create — or reuse — a bookmark and + // attach it under "Links on this page". The pasted Markdown itself is + // never rewritten without an explicit click. + await page.goto(`${base}/pages?id=a`) + await page.locator('[data-page-editor]').waitFor() + await page.evaluate(() => { window.prompt = () => 'https://pages-url.test/report' }) + await page.getByRole('button', { name: 'Link', exact: true }).click() + await eventually(() => bookmarks.some(b => b.url === 'https://pages-url.test/report'), 'Link button did not save the URL as a bookmark') + await eventually(() => pages.get('a').bookmarks.some(x => x.bookmark.url === 'https://pages-url.test/report'), 'Link button bookmark was not attached to the page') + await page.getByText('pages-url.test').first().waitFor() + // Re-adding the same URL attaches nothing new: no duplicate bookmark row, + // no second link. + const urlsBefore = bookmarks.length + await page.evaluate(() => { window.prompt = () => 'https://pages-url.test/report/' }) + await page.getByRole('button', { name: 'Link', exact: true }).click() + await new Promise(resolve => setTimeout(resolve, 600)) + assert.equal(bookmarks.length, urlsBefore, 'Re-adding the same URL created a duplicate bookmark') + assert.equal(pages.get('a').bookmarks.filter(x => x.bookmark.url.startsWith('https://pages-url.test')).length, 1, 'Duplicate URL attached twice') + // A bare-URL paste reuses the EXISTING library bookmark whose url matches + // (search covers urls server-side) instead of POSTing a new one, and the + // raw text stays in the document. + const pasteTarget = bookmarks.find(b => b.url === 'https://127.0.0.1/changed') + await page.locator('[data-page-editor]').click() + await page.evaluate((url) => { + const dt = new DataTransfer() + dt.setData('text/plain', url) + document.querySelector('[data-page-editor]') + .dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })) + }, 'https://127.0.0.1/changed') + await eventually(() => pages.get('a').bookmarks.some(x => x.bookmark.id === pasteTarget.id), 'Pasted URL did not attach the existing bookmark') + await eventually(() => pages.get('a').content.includes('https://127.0.0.1/changed'), 'Pasted URL text was not inserted and saved') + assert.equal(bookmarks.length, urlsBefore, 'Pasted URL created a duplicate bookmark instead of reusing the existing one') + assert.ok(!pages.get('a').content.includes('[https://127.0.0.1/changed]'), 'Pasted URL was rewritten without an explicit click') + console.log('PASS: URLs added to a page (Link button and paste) become page bookmarks, reusing existing rows') + // The sidebar persists the complete order permutation (PUT /api/pages); // drag b above a. Reset the pin from the earlier metadata test so both // pages are in one reorder group. @@ -480,7 +572,7 @@ try { // backstop) posts to Go /api/auth/signout with a signed assertion, so the // tokenVersion bump kills Go cookie sessions and any previously minted // assertions — not just the local NextAuth JWT. - await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } }) + await fixtureLogin(context) await page.goto(`${base}/pages`) const revoked = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST') await page.getByRole('button', { name: 'Sign out', exact: true }).click()