Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Open design links only after the user confirms them in fx0

Pranit556d93f3aa05
diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.ts
index 3f790fe..eb84c1e 100644
--- a/app/api/artifact-frame/route.ts
+++ b/app/api/artifact-frame/route.ts
@@ -77,13 +77,11 @@ addEventListener('message',event=>{
// The design paints in its own process, after this wrapper's load event; the app
// swaps a new revision on screen only once it has.
if(event.data.type==='painted')parent.postMessage({type:'fx0-artifact-painted'},location.origin);
- // The design cannot open popups itself; a clicked https link is opened here, without
- // an opener, and only during the click's user activation (it propagates to this frame).
+ // The design can only ask to open a link: its scripts can read the token and send
+ // this at any time. The app shows the address and opens it on the user's own click
+ // there. Recent user activation only filters out asks nobody prompted; it is not proof.
if(event.data.type==='open'&&typeof event.data.url==='string'&&navigator.userActivation?.isActive!==false){
- try{
- const url=new URL(event.data.url);
- if(url.protocol==='https:'&&!url.username&&!url.password)window.open(url.href,'_blank','noopener,noreferrer');
- }catch{}
+ parent.postMessage({type:'fx0-artifact-open',url:event.data.url},location.origin);
}
});
frame.addEventListener('load',()=>setTimeout(()=>{
diff --git a/components/design-link-dialog.tsx b/components/design-link-dialog.tsx
new file mode 100644
index 0000000..a77d43b
--- /dev/null
+++ b/components/design-link-dialog.tsx
@@ -0,0 +1,65 @@
+'use client'
+
+import { useEffect, useRef, useState } from 'react'
+import { fastClick } from '../lib/fast-click'
+import { Button, buttonVariants } from './ui/button'
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from './ui/dialog'
+
+// A click already under way when the dialog appears must not land on Open link.
+const ARM_MS = 500
+
+// A design asked to open `url`. Only a real click on this dialog's link opens it,
+// in a new tab with no opener or referrer; the design cannot reach this dialog.
+export default function DesignLinkDialog({ url, onClose }: { url: string | null; onClose: () => void }) {
+ const [armed, setArmed] = useState(false)
+ const cancel = useRef<HTMLButtonElement>(null)
+ useEffect(() => {
+ setArmed(false)
+ if (!url) return
+ const timer = setTimeout(() => setArmed(true), ARM_MS)
+ return () => clearTimeout(timer)
+ }, [url])
+ const parsed = url ? new URL(url) : null
+ const origin = parsed ? `${parsed.protocol}//${parsed.host}` : ''
+ return (
+ <Dialog open={url != null} onOpenChange={(open) => { if (!open) onClose() }}>
+ <DialogContent
+ className="max-w-md"
+ // Cancel takes focus, so Enter never opens the link by default.
+ onOpenAutoFocus={(event) => { event.preventDefault(); cancel.current?.focus() }}
+ >
+ <DialogTitle className="text-lg font-medium">Open this link?</DialogTitle>
+ <DialogDescription className="mt-2 text-sm text-muted-foreground">
+ The design wants to open this page in a new tab. Open it only if you expect it.
+ </DialogDescription>
+ {url && (
+ <p className="mt-4 max-h-40 overflow-y-auto break-all bg-secondary px-3 py-2 font-mono text-xs text-foreground-secondary">
+ <span className="font-semibold text-foreground">{origin}</span>
+ {url.slice(origin.length)}
+ </p>
+ )}
+ <div className="mt-5 flex flex-wrap gap-2">
+ <a
+ href={url ?? undefined}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-disabled={!armed || undefined}
+ onClick={(event) => {
+ if (!armed) {
+ event.preventDefault()
+ return
+ }
+ // Close after the browser follows the link: a link removed during its
+ // own click does not navigate.
+ setTimeout(onClose, 0)
+ }}
+ className={buttonVariants({ className: armed ? undefined : 'pointer-events-none opacity-60' })}
+ >
+ Open link
+ </a>
+ <Button ref={cancel} variant="outline" {...fastClick(onClose)}>Cancel</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/preview-pane.tsx b/components/preview-pane.tsx
index cb8e07b..ec1c6e0 100644
--- a/components/preview-pane.tsx
+++ b/components/preview-pane.tsx
@@ -1,9 +1,15 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
+import { designLinkUrl } from '../lib/design-link'
import { EMPTY_DRAFT_DOCUMENT, patchDraftDocument } from '../lib/draft-preview'
+import DesignLinkDialog from './design-link-dialog'
import { HowItWorksPanel } from './how-it-works'
+// After the link dialog closes, a design's asks are ignored this long: the click
+// that closed it is a fresh gesture the design could otherwise spend at once.
+const LINK_PAUSE_MS = 2000
+
export type PreviewSource = { kind: 'design'; sessionId: string; revision: number }
export default function PreviewPane({
@@ -69,9 +75,31 @@ export default function PreviewPane({
// fires before that and swapping then showed the wrapper's white page. Documents
// that never report (a missing revision) swap a while after loading.
const frames = useRef<(HTMLIFrameElement | null)[]>([null, null])
+ const frontIndex = useRef(front)
+ frontIndex.current = front
+ // A link the design on screen asked to open, waiting for the user's own click.
+ const [linkRequest, setLinkRequest] = useState<string | null>(null)
+ const linksPausedUntil = useRef(0)
+ const closeLinkRequest = useCallback(() => {
+ linksPausedUntil.current = Date.now() + LINK_PAUSE_MS
+ setLinkRequest(null)
+ }, [])
+ useEffect(() => {
+ setLinkRequest(null)
+ }, [source.sessionId])
useEffect(() => {
const onMessage = (event: MessageEvent) => {
- if (event.origin !== window.location.origin || event.data?.type !== 'fx0-artifact-painted') return
+ if (event.origin !== window.location.origin) return
+ if (event.data?.type === 'fx0-artifact-open') {
+ // Only the design on screen may ask, never one loading underneath; one ask
+ // at a time, and none just after the last one closed.
+ const shown = frontIndex.current == null ? null : frames.current[frontIndex.current]
+ const url = designLinkUrl(event.data.url)
+ if (!url || !shown || shown.contentWindow !== event.source || Date.now() < linksPausedUntil.current) return
+ setLinkRequest((current) => current ?? url)
+ return
+ }
+ if (event.data?.type !== 'fx0-artifact-painted') return
const index = frames.current.findIndex((frame) => frame?.contentWindow === event.source)
if (index >= 0) bringToFront(index)
}
@@ -143,6 +171,7 @@ export default function PreviewPane({
) : (
<div className="flex-1" />
)}
+ <DesignLinkDialog url={linkRequest} onClose={closeLinkRequest} />
</section>
)
}
diff --git a/lib/design-artifact.ts b/lib/design-artifact.ts
index 8b86192..7c4b5f3 100644
--- a/lib/design-artifact.ts
+++ b/lib/design-artifact.ts
@@ -18,8 +18,9 @@ export const DESIGN_ARTIFACT_EMBEDDED_CSP = [
].join('; ')
function designArtifactBootstrap(readyToken?: string): string {
- // The sandbox grants no popups, so a clicked https link asks the trusted wrapper to
- // open it (see app/api/artifact-frame) instead of navigating the preview away.
+ // 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 the
+ // user's own click there, instead of the design navigating the preview away.
const heartbeat = readyToken
? `const token=${JSON.stringify(readyToken)};const send=type=>parent.postMessage({type,token},"*");send("heartbeat");setInterval(()=>send("heartbeat"),500);addEventListener("load",()=>{send("ready");requestAnimationFrame(()=>requestAnimationFrame(()=>send("painted")))},{once:true});addEventListener("click",event=>{const link=event.target instanceof Element&&event.target.closest("a[href]");const url=link?link.getAttribute("href")||"":"";if(/^https:/i.test(url)){event.preventDefault();parent.postMessage({type:"open",token,url},"*")}},true);`
: ''
diff --git a/lib/design-link.ts b/lib/design-link.ts
new file mode 100644
index 0000000..e85767e
--- /dev/null
+++ b/lib/design-link.ts
@@ -0,0 +1,18 @@
+// The longest address a design may ask to open: the confirmation shows all of it,
+// so anything the design packed into the address is visible before it is sent.
+export const MAX_DESIGN_LINK_LENGTH = 2048
+
+// A design can only ask the app to open a link; the user opens it from the app's
+// own dialog. This is the address that dialog may offer, or null: an https page,
+// with no username or password, short enough to show whole.
+export function designLinkUrl(value: unknown): string | null {
+ if (typeof value !== 'string' || value.length > MAX_DESIGN_LINK_LENGTH) return null
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ return null
+ }
+ if (url.protocol !== 'https:' || url.username || url.password) return null
+ return url.href.length <= MAX_DESIGN_LINK_LENGTH ? url.href : null
+}
diff --git a/tests/core.test.mjs b/tests/core.test.mjs
index 97faac4..d0f6df5 100644
--- a/tests/core.test.mjs
+++ b/tests/core.test.mjs
@@ -21,6 +21,25 @@ import {
} from '../components/chat-state.ts'
import { createTools } from '../lib/tools.ts'
import { featuredModels } from '../lib/featured-models.ts'
+import { designLinkUrl, MAX_DESIGN_LINK_LENGTH } from '../lib/design-link.ts'
+
+test('a design may only ask to open a whole https address, shown in full before it opens', () => {
+ assert.equal(designLinkUrl('https://vercel.com/blog?ref=design#top'), 'https://vercel.com/blog?ref=design#top')
+ assert.equal(designLinkUrl('https://EXAMPLE.com'), 'https://example.com/', 'the dialog shows the address the browser opens')
+ for (const value of [
+ 'http://example.com', 'javascript:alert(1)', 'data:text/html,hi', 'https://user:[email protected]',
+ 'https://[email protected]', '//example.com', 'not a url', '', null, undefined, 42, { href: 'https://example.com' },
+ ]) {
+ assert.equal(designLinkUrl(value), null, JSON.stringify(value) ?? String(value))
+ }
+ const longest = `https://example.com/?q=${'a'.repeat(MAX_DESIGN_LINK_LENGTH - 'https://example.com/?q='.length)}`
+ assert.equal(designLinkUrl(longest), longest)
+ assert.equal(designLinkUrl(`${longest}a`), null, 'too long to show whole')
+ // An address that only grows past the limit once the browser encodes it is refused too.
+ const spaced = `https://example.com/?q=a${' '.repeat(1000)}b`
+ assert.ok(spaced.length <= MAX_DESIGN_LINK_LENGTH && new URL(spaced).href.length > MAX_DESIGN_LINK_LENGTH)
+ assert.equal(designLinkUrl(spaced), null)
+})
import { readFileSync } from 'node:fs'
import { DESIGN_MD_CATALOG, DESIGN_MD_MAX_BYTES, parseDesignMdRequest } from '../lib/design-md.ts'
diff --git a/tests/route-security.test.mjs b/tests/route-security.test.mjs
index 8c0c252..6e45448 100644
--- a/tests/route-security.test.mjs
+++ b/tests/route-security.test.mjs
@@ -447,7 +447,11 @@ test('the artifact preview permits iframe origins but preserves opaque credentia
assert.equal(frame.status, 200)
const html = await frame.text()
assert.match(html, /setAttribute\('sandbox','allow-scripts'\)/)
- assert.match(html, /url\.protocol==='https:'&&!url\.username&&!url\.password\)window\.open\(url\.href,'_blank','noopener,noreferrer'\)/)
+ // The design only asks to open a link; the wrapper passes the ask to the app on this
+ // origin, which shows the address and opens it on the user's own click.
+ assert.doesNotMatch(html, /window\.open/)
+ assert.match(html, /if\(event\.source!==frame\.contentWindow\|\|event\.data\?\.token!==token\)return;/)
+ assert.match(html, /parent\.postMessage\(\{type:'fx0-artifact-open',url:event\.data\.url\},location\.origin\)/)
assert.match(html, /navigator\.userActivation\?\.isActive!==false/)
assert.doesNotMatch(html, /allow-popups/)
assert.match(html, /setAttribute\('credentialless',''\)/)