A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Let published designs show their embedded images, fonts and media
Esteban Suarez415d500dcfc0
diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.tsindex eb84c1e..cc77782 100644--- a/app/api/artifact-frame/route.ts+++ b/app/api/artifact-frame/route.ts@@ -1,4 +1,4 @@-import { DESIGN_ARTIFACT_EMBEDDED_CSP, prepareDesignArtifactHtml } from '../../../lib/design-artifact'+import { DESIGN_ARTIFACT_EMBEDDED_CSP, DESIGN_FRAME_CSP, prepareDesignArtifactHtml } from '../../../lib/design-artifact'import { readDesignArtifactAt } from '../../../lib/journal'import { readGeneration } from '../../../lib/history'import { withSessionRoute } from '../../../lib/route-auth'@@ -33,16 +33,6 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>: past ? 'This version is not in the history.' : 'No design artifact has been published for this session.'}</p></body></html>`const artifactUrl = `data:text/html;base64,${Buffer.from(preparedArtifact, 'utf8').toString('base64')}`- const csp = [- "default-src 'none'",- 'frame-src data:',- "script-src 'unsafe-inline'",- "style-src 'unsafe-inline'",- "object-src 'none'",- "base-uri 'none'",- "form-action 'none'",- "frame-ancestors 'self'",- ].join('; ')const serializedArtifactUrl = JSON.stringify(artifactUrl)const serializedReadyToken = JSON.stringify(readyToken)// The wrapper paints nothing of its own, so a design that has not painted yet@@ -101,7 +91,7 @@ document.querySelector('#frame-root').append(frame);headers: {'cache-control': etag ? 'private, no-cache' : 'private, no-store',...(etag ? { etag } : {}),- 'content-security-policy': csp,+ 'content-security-policy': DESIGN_FRAME_CSP,'content-type': 'text/html; charset=utf-8','permissions-policy':'accelerometer=(), camera=(), clipboard-read=(), clipboard-write=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=()',diff --git a/lib/design-artifact.ts b/lib/design-artifact.tsindex 7c4b5f3..3cc227c 100644--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@ -17,6 +17,22 @@ export const DESIGN_ARTIFACT_EMBEDDED_CSP = ["form-action 'none'",].join('; ')+// The wrapper that frames the design. Its data: frame inherits this policy on top of+// the embedded one, so anything the design may load must be allowed here too.+export const DESIGN_FRAME_CSP = [+ "default-src 'none'",+ 'frame-src data:',+ "script-src 'unsafe-inline'",+ "style-src 'unsafe-inline'",+ 'img-src data:',+ 'font-src data:',+ 'media-src data:',+ "object-src 'none'",+ "base-uri 'none'",+ "form-action 'none'",+ "frame-ancestors 'self'",+].join('; ')+function designArtifactBootstrap(readyToken?: string): string {// The sandbox grants no popups, so a clicked https link asks the app to open it// (see app/api/artifact-frame): the app shows the address and opens it only on thediff --git a/tests/design-artifact.browser.mjs b/tests/design-artifact.browser.mjsindex 618af47..616f250 100644--- a/tests/design-artifact.browser.mjs+++ b/tests/design-artifact.browser.mjs@@ -7,7 +7,7 @@ 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'+import { DESIGN_ARTIFACT_EMBEDDED_CSP, DESIGN_FRAME_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'@@ -92,3 +92,49 @@ test('in Chrome, every published or stored design keeps its CSP in <head> and caawait rm(dir, { recursive: true, force: true })}})++// The wrapper's own policy reaches the design's data: frame, so a design is rendered+// here under both policies, as in production. An embedded image must load; a remote+// one must still be refused by the policy, not merely fail to connect.+const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='+const imageDesign = `<!doctype html><html><head><title>design</title></head><body>+<img id="embedded" alt="" src="data:image/png;base64,${PIXEL}">+<script>+const results = {}+const report = (name, value) => { results[name] ??= value; parent.postMessage(results, '*') }+addEventListener('securitypolicyviolation', (event) => {+ if (event.blockedURI.startsWith('data:')) report('embedded', 'blocked')+ if (event.blockedURI.startsWith('http:')) report('remote', 'blocked')+})+const embedded = document.getElementById('embedded')+embedded.complete && embedded.naturalWidth ? report('embedded', 'loaded') : embedded.addEventListener('load', () => report('embedded', 'loaded'))+const remote = new Image()+remote.onload = () => report('remote', 'loaded')+remote.src = 'http://127.0.0.1:9/pixel.png'+</script></body></html>`++test('in Chrome, a published design shows embedded images inside the wrapper and still refuses remote ones', async () => {+ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)+ const dir = await mkdtemp(join(tmpdir(), 'fx0-design-frame-csp-'))+ try {+ const url = `data:text/html;base64,${Buffer.from(published('image', imageDesign)).toString('base64')}`+ const frameCsp = DESIGN_FRAME_CSP.replace(/; frame-ancestors[^;]*/, '')+ const file = join(dir, 'page.html')+ await writeFile(file, `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${frameCsp}"><title>frame CSP</title></head><body><pre id="out">{}</pre><script>+addEventListener('message', ({ data }) => { if (!data.token) document.getElementById('out').textContent = JSON.stringify(data) })+const frame = document.createElement('iframe')+frame.setAttribute('sandbox', 'allow-scripts')+frame.setAttribute('credentialless', '')+frame.src = ${JSON.stringify(url)}+document.body.append(frame)+</script></body></html>`)+ 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])+ assert.deepEqual(results, { embedded: 'loaded', remote: 'blocked' })+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+})