A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Normalize design HTML once so its CSP always lands first in <head>
Pranit8c5b0b082e1c
diff --git a/README.md b/README.mdindex fcc5d48..88774c7 100644--- a/README.md+++ b/README.md@@ -170,6 +170,7 @@ npm run buildnpm run test:smoke # runs the production build with fake sessionsnpm run test:journal:integration # needs KV_REST_API_URL/TOKEN, writes under its own prefixnpm run test:trial:integration # needs local redis-server/redis-cli; no remote services+npm run test:artifact:browser # needs local Chrome (or CHROME_PATH); checks design CSP enforcement```The auth and route tests mock Vercel, AI Gateway and both databases, so check a real sign-in and real billing on a deployment.diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.tsindex 0e123b1..3f790fe 100644--- a/app/api/artifact-frame/route.ts+++ b/app/api/artifact-frame/route.ts@@ -2,6 +2,7 @@ import { DESIGN_ARTIFACT_EMBEDDED_CSP, prepareDesignArtifactHtml } from '../../.import { readDesignArtifactAt } from '../../../lib/journal'import { readGeneration } from '../../../lib/history'import { withSessionRoute } from '../../../lib/route-auth'+import { log } from '../../../lib/session'export const maxDuration = 30@@ -22,11 +23,15 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>return new Response(null, { status: 304, headers: { 'cache-control': 'private, no-cache', etag } })}const readyToken = crypto.randomUUID()- const preparedArtifact = artifact == null- ? `<!doctype html><html><head><meta charset="utf-8"><title>No design artifact</title></head><body><p>${- past ? 'This version is not in the history.' : 'No design artifact has been published for this session.'+ const prepared = artifact == null ? null : prepareDesignArtifactHtml(artifact, DESIGN_ARTIFACT_EMBEDDED_CSP, readyToken)+ // Every stored design passed validation, so this only guards against one that+ // somehow lacks a doctype: it is never shown without its CSP.+ if (artifact != null && prepared == null) log(sessionId, 'artifact:unrenderable', { revision: past ? revision : live!.revision })+ const preparedArtifact = prepared ??+ `<!doctype html><html><head><meta charset="utf-8"><title>No design artifact</title></head><body><p>${+ artifact != null ? 'This design could not be prepared for preview.'+ : past ? 'This version is not in the history.' : 'No design artifact has been published for this session.'}</p></body></html>`- : prepareDesignArtifactHtml(artifact, DESIGN_ARTIFACT_EMBEDDED_CSP, readyToken)const artifactUrl = `data:text/html;base64,${Buffer.from(preparedArtifact, 'utf8').toString('base64')}`const csp = ["default-src 'none'",diff --git a/lib/design-artifact.ts b/lib/design-artifact.tsindex c18d54e..8b86192 100644--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@ -30,14 +30,37 @@ function escapeAttribute(value: string): string {return value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')}-export function prepareDesignArtifactHtml(html: string, embeddedCsp?: string, readyToken?: string): string {+const DOCTYPE = '<!doctype html>'++// The one form of a design that is validated, stored, and rendered. Before the+// doctype the HTML parser ignores only ASCII whitespace; anything else, such as+// U+00A0 or U+FEFF, starts the body, so a CSP placed after the doctype would be+// ignored. Trimming the ends and rewriting the doctype leaves it first, exactly.+export function normalizeDesignArtifactHtml(html: string): string {+ return html.trim().replace(/^<!doctype\s+html\s*>/i, DOCTYPE)+}++// The CSP and bootstrap go right after the doctype, so they are the first things+// the parser puts in <head>. A design stored before normalization renders the same+// way; one without a doctype is not rendered at all (null), never without its CSP.+export function prepareDesignArtifactHtml(html: string, embeddedCsp?: string, readyToken?: string): string | null {+ const document = normalizeDesignArtifactHtml(html)+ if (!document.startsWith(DOCTYPE)) return nullconst csp = embeddedCsp? `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(embeddedCsp)}">`: ''- return html.replace(/^(\s*<!doctype\s+html\s*>)/i, `$1${csp}${designArtifactBootstrap(readyToken)}`)+ return DOCTYPE + csp + designArtifactBootstrap(readyToken) + document.slice(DOCTYPE.length)+}++// The start of a document, with invisible characters spelled out, so a rejected+// publish says exactly what came before the doctype.+function visibleStart(html: string): string {+ const start = html.length > 24 ? `${html.slice(0, 24)}…` : html+ return JSON.stringify(start).replace(/[^\x20-\x7e…]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`)}-export type DesignArtifactValidation = { ok: true; bytes: number } | { ok: false; error: string }+// `html` is the normalized document: the exact value to store.+export type DesignArtifactValidation = { ok: true; bytes: number; html: string } | { ok: false; error: string }interface HtmlTag {name: string@@ -211,19 +234,19 @@ function validateTag(tag: HtmlTag): string | null {}export function validateDesignArtifactHtml(html: string): DesignArtifactValidation {- const bytes = Buffer.byteLength(html, 'utf8')+ const source = normalizeDesignArtifactHtml(html)+ const bytes = Buffer.byteLength(source, 'utf8')if (bytes > MAX_DESIGN_ARTIFACT_BYTES) {return { ok: false, error: 'design artifact exceeds 512 KiB' }}- const source = html.trim()if (source.includes('<!--')) {return { ok: false, error: 'design artifact must not contain HTML comments' }}- if (!/^<!doctype\s+html\s*>/i.test(source)) {- return { ok: false, error: 'design artifact must start with <!doctype html>' }+ if (!source.startsWith(DOCTYPE)) {+ return { ok: false, error: `design artifact must start with <!doctype html>, but it starts with ${visibleStart(source)}` }}- const afterDoctype = source.replace(/^<!doctype\s+html\s*>/i, '')+ const afterDoctype = source.slice(DOCTYPE.length)if (/<(?:!|\?)/.test(afterDoctype)) {return { ok: false, error: 'design artifact must not contain markup declarations' }}@@ -250,5 +273,5 @@ export function validateDesignArtifactHtml(html: string): DesignArtifactValidatiif (error) return { ok: false, error }}- return { ok: true, bytes }+ return { ok: true, bytes, html: source }}diff --git a/lib/journal.ts b/lib/journal.tsindex 2839c78..7b350de 100644--- a/lib/journal.ts+++ b/lib/journal.ts@@ -582,8 +582,9 @@ export async function publishDesignArtifact(key(sessionId, 'draft'),key(sessionId, 'draft-chunks'),],+ // The stored design is the normalized one validation passed, never the raw input.// The turn lets the transcript group a turn's revisions under its activity.- [html, String(Date.now()), turnId == null ? '' : String(turnId)],+ [validation.html, String(Date.now()), turnId == null ? '' : String(turnId)],)const result = parseJson<{status: 'published' | 'unchanged' | 'fenced'diff --git a/package.json b/package.jsonindex a71474c..187cd92 100644--- a/package.json+++ b/package.json@@ -9,11 +9,12 @@"build": "next build","typecheck": "next typegen && tsc --noEmit --incremental false","start": "next start",- "test:core": "node --experimental-strip-types --test tests/core.test.mjs tests/transcript.test.mjs tests/design-draft.test.mjs tests/event-delivery.test.mjs tests/event-stream.test.mjs tests/public-fetch.test.mjs tests/runtime.test.mjs",+ "test:core": "node --experimental-strip-types --test tests/core.test.mjs tests/transcript.test.mjs tests/design-draft.test.mjs tests/design-publish.test.mjs tests/event-delivery.test.mjs tests/event-stream.test.mjs tests/public-fetch.test.mjs tests/runtime.test.mjs","test:auth": "node --experimental-strip-types --test tests/auth.test.mjs tests/auth-callback.test.mjs tests/signout.test.mjs tests/ownership.test.mjs tests/history.test.mjs tests/route-security.test.mjs tests/gateway-session.test.mjs tests/libfx-transport.test.mjs tests/libfx-agent.test.mjs tests/auth-ui.test.mjs tests/html-ui.test.mjs tests/guest-ui.test.mjs tests/guest-draft.test.mjs tests/trial.test.mjs tests/turn-funding.test.mjs","test:journal:integration": "node --env-file-if-exists=.env.local --experimental-strip-types --test tests/journal.integration.mjs","test:smoke": "node tests/local-auth-smoke.mjs","db:migrate": "node --env-file-if-exists=.env.local scripts/migrate-database.mjs",+ "test:artifact:browser": "node --experimental-strip-types --test tests/design-artifact.browser.mjs","test:trial:integration": "node --experimental-strip-types --test tests/trial.integration.mjs","test:credential:integration": "node --experimental-strip-types --test tests/turn-credential.integration.mjs"},diff --git a/tests/core.test.mjs b/tests/core.test.mjsindex 232143b..97faac4 100644--- a/tests/core.test.mjs+++ b/tests/core.test.mjs@@ -4,6 +4,7 @@ import './runtime.test.mjs'import {DESIGN_ARTIFACT_EMBEDDED_CSP,MAX_DESIGN_ARTIFACT_BYTES,+ normalizeDesignArtifactHtml,prepareDesignArtifactHtml,validateDesignArtifactHtml,} from '../lib/design-artifact.ts'@@ -453,6 +454,7 @@ test('design artifact validation accepts inline CSS, JavaScript, Canvas, data asassert.deepEqual(validateDesignArtifactHtml(SAFE_DESIGN), {ok: true,bytes: Buffer.byteLength(SAFE_DESIGN),+ html: SAFE_DESIGN,})const interactive = documentWith('<canvas id="scene"></canvas><button onclick="cancelAnimationFrame(window.frame)">Pause</button><script>const canvas=document.querySelector("#scene"); const context=canvas.getContext("2d"); context.fillRect(0,0,10,10); window.frame=requestAnimationFrame(() => {}); const example="<iframe src=https://example.com></iframe>";</script>',@@ -460,9 +462,10 @@ test('design artifact validation accepts inline CSS, JavaScript, Canvas, data asassert.deepEqual(validateDesignArtifactHtml(interactive), {ok: true,bytes: Buffer.byteLength(interactive),+ html: interactive,})const cited = documentWith('<p>Source: <a href="https://vercel.com/blog">Vercel blog</a></p>')- assert.deepEqual(validateDesignArtifactHtml(cited), { ok: true, bytes: Buffer.byteLength(cited) })+ assert.deepEqual(validateDesignArtifactHtml(cited), { ok: true, bytes: Buffer.byteLength(cited), html: cited })assert.match(prepareDesignArtifactHtml(cited, DESIGN_ARTIFACT_EMBEDDED_CSP, 'ready-token'), /type:"open",token,url/)const prepared = prepareDesignArtifactHtml(interactive)assert.match(prepared, /^<!doctype html><script>/i)@@ -569,8 +572,44 @@ test('design artifact CSP allows isolated inline scripts and denies ambient capaassert.doesNotMatch(DESIGN_ARTIFACT_EMBEDDED_CSP, /allow-same-origin|https?:|style-src[^;]*\*/)})+// JavaScript's whitespace (what trim() and \s remove) that the HTML parser does not+// skip before a doctype: any of these first starts the body.+const HTML_SPACES = ['\t', '\n', '\f', '\r', ' ']+const NON_HTML_SPACES = Array.from({ length: 0x10000 }, (_, code) => String.fromCharCode(code))+ .filter((character) => /\s/.test(character) && !HTML_SPACES.includes(character))+const codePoint = (character) => `U+${character.charCodeAt(0).toString(16).padStart(4, '0').toUpperCase()}`++test('a design is validated, stored, and rendered as one normalized document, its CSP first in <head>', () => {+ assert.ok(['\v', '\u00a0', '\u2028', '\u3000', '\ufeff'].every((space) => NON_HTML_SPACES.includes(space)))+ const cspFirst = '<!doctype html><meta http-equiv="Content-Security-Policy"'+ for (const space of [...HTML_SPACES, ...NON_HTML_SPACES]) {+ const variants = [space + SAFE_DESIGN, SAFE_DESIGN + space, SAFE_DESIGN.replace('<!doctype html>', `<!DOCTYPE${space}html${space}>`)]+ for (const raw of variants) {+ const label = `${codePoint(space)} in ${JSON.stringify(raw.slice(0, 20))}`+ const validation = validateDesignArtifactHtml(raw)+ assert.deepEqual(validation, { ok: true, bytes: Buffer.byteLength(SAFE_DESIGN), html: SAFE_DESIGN }, label)+ assert.equal(normalizeDesignArtifactHtml(validation.html), validation.html, `${label}: normalizing twice changes nothing`)+ const rendered = prepareDesignArtifactHtml(raw, DESIGN_ARTIFACT_EMBEDDED_CSP, 'token')+ assert.ok(rendered.startsWith(cspFirst), label)+ // A raw design stored before normalization renders exactly like the stored form.+ assert.equal(rendered, prepareDesignArtifactHtml(validation.html, DESIGN_ARTIFACT_EMBEDDED_CSP, 'token'), label)+ }+ }+})++test('a design that does not start with its doctype is rejected with what it starts with, and never rendered', () => {+ assertInvalid(`Here is the design:\n${SAFE_DESIGN}`,+ 'design artifact must start with <!doctype html>, but it starts with "Here is the design:\\n<!do…"')+ // U+200B is invisible but not whitespace, so it is spelled out rather than trimmed.+ assertInvalid(`\u200b${SAFE_DESIGN}`,+ 'design artifact must start with <!doctype html>, but it starts with "\\u200b<!doctype html><html><h…"')+ for (const html of [`\u200b${SAFE_DESIGN}`, '<main>fragment</main>', '']) {+ assert.equal(prepareDesignArtifactHtml(html, DESIGN_ARTIFACT_EMBEDDED_CSP, 'token'), null, JSON.stringify(html.slice(0, 20)))+ }+})+test('design artifact validation rejects fragments and oversized documents', () => {- assertInvalid('<main>fragment</main>', 'design artifact must start with <!doctype html>')+ assertInvalid('<main>fragment</main>', 'design artifact must start with <!doctype html>, but it starts with "<main>fragment</main>"')const oversized = '<!doctype html><html><head></head><body>' + 'x'.repeat(MAX_DESIGN_ARTIFACT_BYTES) + '</body></html>'assertInvalid(oversized, 'design artifact exceeds 512 KiB')})diff --git a/tests/design-artifact.browser.mjs b/tests/design-artifact.browser.mjsnew file mode 100644index 0000000..618af47--- /dev/null+++ b/tests/design-artifact.browser.mjs@@ -0,0 +1,94 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { execFile } from 'node:child_process'+import { existsSync } from 'node:fs'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { promisify } from 'node:util'+import { DESIGN_ARTIFACT_EMBEDDED_CSP, prepareDesignArtifactHtml, validateDesignArtifactHtml } from '../lib/design-artifact.ts'++// Opt-in: runs real Chrome headless on this machine. Set CHROME_PATH for another browser binary.+const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'++// Each design reports where its CSP <meta> landed and whether a script could open a+// nested data: frame, the escape the embedded CSP exists to block.+const PROBE = `<script>+addEventListener('DOMContentLoaded', () => {+ const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]')+ const report = (frame) => parent.postMessage({ name: document.body.dataset.case, csp: meta ? meta.parentElement.tagName : 'none', frame }, '*')+ addEventListener('securitypolicyviolation', (event) => { if (event.violatedDirective === 'frame-src') report('blocked') })+ const nested = document.createElement('iframe')+ nested.onload = () => report('loaded')+ nested.src = 'data:text/html,<p>nested</p>'+ document.body.append(nested)+})+</script>`+const design = (name) => `<!doctype html><html><head><title>design</title></head><body data-case="${name}"><p>design</p>${PROBE}</body></html>`++// JavaScript trims these, but before a doctype the HTML parser treats them as text.+const NON_HTML_SPACES = Array.from({ length: 0x10000 }, (_, code) => String.fromCharCode(code))+ .filter((character) => /\s/.test(character) && !'\t\n\f\r '.includes(character))+const label = (character) => `U+${character.charCodeAt(0).toString(16).padStart(4, '0').toUpperCase()}`++// Published now: validated, stored as the normalized document, then rendered.+function published(name, raw) {+ const validation = validateDesignArtifactHtml(raw)+ assert.equal(validation.ok, true, `${name}: ${validation.error}`)+ return prepareDesignArtifactHtml(validation.html, DESIGN_ARTIFACT_EMBEDDED_CSP, 'browser-test')+}++function cases() {+ const all = [+ // Control: a design without its CSP must show the nested frame loading, or this test proves nothing.+ ['control without CSP', prepareDesignArtifactHtml(design('control without CSP'), undefined, 'browser-test')],+ ['plain', published('plain', design('plain'))],+ ]+ for (const space of ['\t', '\n', '\f', '\r', ' ', ...NON_HTML_SPACES]) {+ const name = `${label(space)} before the doctype`+ all.push([name, published(name, space + design(name))])+ }+ // Stored before normalization existed: rendered straight from the raw value.+ for (const space of ['\u00a0', '\ufeff']) {+ const name = `stored with ${label(space)} first`+ all.push([name, prepareDesignArtifactHtml(space + design(name), DESIGN_ARTIFACT_EMBEDDED_CSP, 'browser-test')])+ }+ return all+}++const page = (all) => `<!doctype html><html><head><title>design CSP</title></head><body><pre id="out">{}</pre><script>+const results = {}+addEventListener('message', ({ data }) => {+ const seen = results[data.name]+ results[data.name] = { csp: data.csp, frame: seen?.frame === 'blocked' || data.frame === 'blocked' ? 'blocked' : data.frame }+ document.getElementById('out').textContent = JSON.stringify(results)+})+for (const url of ${JSON.stringify(all.map(([, html]) => `data:text/html;base64,${Buffer.from(html).toString('base64')}`))}) {+ const frame = document.createElement('iframe')+ frame.setAttribute('sandbox', 'allow-scripts')+ frame.src = url+ document.body.append(frame)+}+</script></body></html>`++test('in Chrome, every published or stored design keeps its CSP in <head> and cannot open nested frames', async () => {+ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)+ const all = cases()+ const dir = await mkdtemp(join(tmpdir(), 'fx0-design-csp-'))+ try {+ const file = join(dir, 'page.html')+ await writeFile(file, page(all))+ const { stdout } = await promisify(execFile)(CHROME, [+ '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',+ `--user-data-dir=${join(dir, 'profile')}`, '--virtual-time-budget=5000', '--dump-dom', pathToFileURL(file).href,+ ], { timeout: 60_000, maxBuffer: 16 * 1024 * 1024 })+ const results = JSON.parse(stdout.match(/<pre id="out">([^<]*)<\/pre>/)[1])+ for (const [name] of all) {+ const expected = name.startsWith('control') ? { csp: 'none', frame: 'loaded' } : { csp: 'HEAD', frame: 'blocked' }+ assert.deepEqual(results[name], expected, name)+ }+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+})diff --git a/tests/design-publish.test.mjs b/tests/design-publish.test.mjsnew file mode 100644index 0000000..0203f21--- /dev/null+++ b/tests/design-publish.test.mjs@@ -0,0 +1,36 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { registerHooks } from 'node:module'++// publishDesignArtifact makes one Redis call, recorded here: its first argument is+// the design that gets stored.+const stored = []+globalThis.__designPublishCalls = stored+registerHooks({+ resolve(specifier, context, next) {+ if (specifier === '@upstash/redis' && context.parentURL?.endsWith('/lib/journal.ts')) {+ const fake = 'export class Redis { async eval(script, keys, args) { globalThis.__designPublishCalls.push(args[0]); return { status: "published", revision: 1 } } }'+ return { url: `data:text/javascript,${encodeURIComponent(fake)}`, shortCircuit: true }+ }+ return next(specifier, context)+ },+})+process.env.KV_REST_API_URL ??= 'https://redis.invalid'+process.env.KV_REST_API_TOKEN ??= 'test-token'+const { publishDesignArtifact } = await import('../lib/journal.ts')++const DESIGN = '<!doctype html><html><head></head><body><p>design</p></body></html>'++test('publishing stores the normalized design that passed validation, never the raw input', async () => {+ const raw = `\u00a0\ufeff<!DOCTYPE\u00a0html>${DESIGN.slice('<!doctype html>'.length)}\n\u3000`+ assert.deepEqual(await publishDesignArtifact('chat', raw, 4), { ok: true, revision: 1, changed: true, event: undefined })+ assert.deepEqual(stored, [DESIGN])++ // An invisible character that is not whitespace is spelled out for the model, and nothing is stored.+ assert.deepEqual(await publishDesignArtifact('chat', `\u200b${DESIGN}`), {+ ok: false,+ reason: 'invalid',+ error: 'design artifact must start with <!doctype html>, but it starts with "\\u200b<!doctype html><html><h…"',+ })+ assert.deepEqual(stored, [DESIGN])+})