Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

sandbox_proxy.html

194 lines7.2 KB

1<!doctype html>
2<html>
3 <head>
4 <meta charset="utf-8" />
5 <meta name="color-scheme" content="light dark" />
6 <!-- CSP is set via HTTP headers by serve.ts (based on ?csp= query param).
7 The inner iframe inherits this CSP since we use document.write(). -->
8 <title>MCP-UI Proxy</title>
9 <style>
10 html,
11 body {
12 margin: 0;
13 height: 100vh;
14 width: 100vw;
15 /* Transparent background allows parent page to show through */
16 background-color: transparent;
17 }
18 body {
19 display: flex;
20 flex-direction: column;
21 }
22 * {
23 box-sizing: border-box;
24 }
25 iframe {
26 background-color: transparent;
27 border: 0px none transparent;
28 padding: 0px;
29 overflow: hidden;
30 flex-grow: 1;
31 /* Inherit color scheme from parent for consistent transparency */
32 color-scheme: inherit;
33 }
34 </style>
35 </head>
36 <body>
37 <script>
38 function buildAllowAttribute(permissions) {
39 if (!permissions) return ''
40​
41 const allowList = []
42 if (permissions['camera']) allowList.push('camera')
43 if (permissions['microphone']) allowList.push('microphone')
44 if (permissions['geolocation']) allowList.push('geolocation')
45 if (permissions['clipboardWrite']) allowList.push('clipboard-write')
46​
47 return allowList.join('; ')
48 }
49​
50 const ALLOWED_REFERRER_PATTERN =
51 /^http:\/\/(localhost|127\.0\.0\.1)(:|\/|$)/
52​
53 if (window.self === window.top) {
54 throw new Error('This file is only to be used in an iframe sandbox.')
55 }
56​
57 if (!document.referrer) {
58 throw new Error('No referrer, cannot validate embedding site.')
59 }
60​
61 if (!document.referrer.match(ALLOWED_REFERRER_PATTERN)) {
62 throw new Error(
63 `Embedding domain not allowed in referrer ${document.referrer}. (Consider updating the validation logic to allow your domain.)`,
64 )
65 }
66​
67 // Extract the expected host origin from the referrer for origin validation.
68 // This is the origin we expect all parent messages to come from.
69 const EXPECTED_HOST_ORIGIN = new URL(document.referrer).origin
70​
71 const OWN_ORIGIN = new URL(window.location.href).origin
72​
73 // Security self-test: verify iframe isolation is working correctly.
74 // This MUST throw a SecurityError -- if `window.top` is accessible, the sandbox
75 // configuration is dangerously broken and untrusted content could escape.
76 try {
77 window.top?.alert('If you see this, the sandbox is not setup securely.')
78 throw 'FAIL'
79 } catch (e) {
80 if (e === 'FAIL') {
81 throw new Error('The sandbox is not setup securely.')
82 }
83​
84 // Expected: SecurityError confirms proper sandboxing.
85 }
86​
87 // Double-iframe sandbox architecture: THIS file is the outer sandbox proxy
88 // iframe on a separate origin. It creates an inner iframe for untrusted HTML
89 // content. Per the specification, the Host and the Sandbox MUST have different
90 // origins.
91 const inner = document.createElement('iframe')
92 inner.style = 'width:100%; height:100%; border:none;'
93 inner.setAttribute(
94 'sandbox',
95 'allow-scripts allow-same-origin allow-forms',
96 )
97 // Note: allow attribute is set later when receiving sandbox-resource-ready notification
98 // based on the permissions requested by the app
99 document.body.appendChild(inner)
100​
101 const RESOURCE_READY_NOTIFICATION =
102 'ui/notifications/sandbox-resource-ready'
103 const PROXY_READY_NOTIFICATION = 'ui/notifications/sandbox-proxy-ready'
104​
105 // Message relay: This Sandbox (outer iframe) acts as a bidirectional bridge,
106 // forwarding messages between:
107 //
108 // Host (parent window) ↔ Sandbox (outer frame) ↔ View (inner iframe)
109 //
110 // Reason: the parent window and inner iframe have different origins and can't
111 // communicate directly, so the outer iframe forwards messages in both
112 // directions to connect them.
113 //
114 // Special case: The "ui/notifications/sandbox-proxy-ready" message is
115 // intercepted here (not relayed) because the Sandbox uses it to configure and
116 // load the inner iframe with the view HTML content.
117 //
118 // Security: CSP is enforced via HTTP headers on sandbox.html (set by serve.ts
119 // based on ?csp= query param). This is tamper-proof unlike meta tags.
120​
121 window.addEventListener('message', async (event) => {
122 if (event.source === window.parent) {
123 // Validate that messages from parent come from the expected host origin.
124 // This prevents malicious pages from sending messages to this sandbox.
125 if (event.origin !== EXPECTED_HOST_ORIGIN) {
126 console.error(
127 '[Sandbox] Rejecting message from unexpected origin:',
128 event.origin,
129 'expected:',
130 EXPECTED_HOST_ORIGIN,
131 )
132 return
133 }
134​
135 if (event.data && event.data.method === RESOURCE_READY_NOTIFICATION) {
136 const { html, sandbox, permissions } = event.data.params
137 if (typeof sandbox === 'string') {
138 inner.setAttribute('sandbox', sandbox)
139 }
140 // Set Permission Policy allow attribute if permissions are requested
141 const allowAttribute = buildAllowAttribute(permissions)
142 if (allowAttribute) {
143 console.log('[Sandbox] Setting allow attribute:', allowAttribute)
144 inner.setAttribute('allow', allowAttribute)
145 }
146 if (typeof html === 'string') {
147 // Use document.write instead of srcdoc (which the CesiumJS Map won't work with)
148 const doc = inner.contentDocument || inner.contentWindow?.document
149 if (doc) {
150 doc.open()
151 doc.write(html)
152 doc.close()
153 } else {
154 // Fallback to srcdoc if document is not accessible
155 console.warn(
156 '[Sandbox] document.write not available, falling back to srcdoc',
157 )
158 inner.srcdoc = html
159 }
160 }
161 } else {
162 if (inner && inner.contentWindow) {
163 inner.contentWindow.postMessage(event.data, '*')
164 }
165 }
166 } else if (event.source === inner.contentWindow) {
167 if (event.origin !== OWN_ORIGIN) {
168 console.error(
169 '[Sandbox] Rejecting message from inner iframe with unexpected origin:',
170 event.origin,
171 'expected:',
172 OWN_ORIGIN,
173 )
174 return
175 }
176 // Relay messages from inner frame to parent window.
177 // Use specific origin instead of "*" to prevent message interception.
178 window.parent.postMessage(event.data, EXPECTED_HOST_ORIGIN)
179 }
180 })
181​
182 // Notify the Host that the Sandbox is ready to receive view HTML.
183 // Use specific origin instead of "*" to ensure only the expected host receives this.
184 window.parent.postMessage(
185 {
186 jsonrpc: '2.0',
187 method: PROXY_READY_NOTIFICATION,
188 params: {},
189 },
190 EXPECTED_HOST_ORIGIN,
191 )
192 </script>
193 </body>
194</html>