fix: load sandboxed raw apps behind a cookie-authenticated proxy (#12787)

* fix: load sandboxed raw app bundles behind a cookie-authenticated proxy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: recover the script through the embedder when the stylesheet was refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-12-02 01:28:38 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 994f9b8b27
commit 9312b08e9a
2 changed files with 73 additions and 6 deletions
+49 -6
View File
@@ -1030,7 +1030,8 @@ async fn get_raw_app_data(
/// HTML wrapper that hosts a raw-app bundle inside a sandboxed, opaque-origin
/// iframe. Served by [`get_raw_app_data`] for the `.html` "file type". It loads
/// the bundle `.js`/`.css` as same-path subresources, shims web storage (which
/// the bundle `.js`/`.css` as same-path subresources (from the embedder when those
/// requests are refused), shims web storage (which
/// an opaque origin disallows), and waits for the embedder's handshake before
/// evaluating the bundle, so `window.ctx` — and `window.process.env` when the
/// viewer approved SDK scopes — is set synchronously when it runs. That token is
@@ -1040,7 +1041,7 @@ fn raw_app_wrapper_html(secret: &str) -> String {
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="./__SECRET__.css" />
<link id="__wm_css" rel="stylesheet" href="./__SECRET__.css" onerror="this.wmFailed = true" />
<script>
(function () {
// Storage shim: an opaque-origin (sandboxed) document has no localStorage and
@@ -1107,11 +1108,54 @@ fn raw_app_wrapper_html(secret: &str) -> String {
// synchronously when the bundle runs. The bundle <script> is injected only
// after this, never inline, so it always observes a ready context.
var loaded = false;
var hs;
try { hs = new URLSearchParams(window.location.search).get('wm_hs') || undefined; } catch (_) {}
// Requests from an opaque origin are cross-site, so a cookie-authenticated proxy
// can refuse the .js/.css below. The embedder's own requests carry the cookie, so
// it is asked for what failed. Never the first choice: a bundle run from a blob:
// URL cannot resolve URLs against document.currentScript.src.
function askEmbedder(ext) {
return new Promise(function (resolve) {
if (!hs) return resolve();
var ch = new MessageChannel();
ch.port1.onmessage = function (e) { resolve(e.data); };
window.parent.postMessage({ type: 'windmill:asset', ext: ext, nonce: hs }, '*', [ch.port2]);
});
}
var cssRecovery;
function recoverCss() {
cssRecovery = askEmbedder('css').then(function (css) {
if (typeof css !== 'string') return;
var st = document.createElement('style');
st.textContent = css;
link.replaceWith(st);
});
}
var link = document.getElementById('__wm_css');
// The stylesheet can fail before this script runs.
if (link.wmFailed) recoverCss(); else link.onerror = recoverCss;
function runScript(src) {
var s = document.createElement('script');
s.src = src;
document.body.appendChild(s);
return s;
}
function loadByUrl() { return runScript('./__SECRET__.js'); }
function recoverBundle(otherwise) {
Promise.all([askEmbedder('js'), cssRecovery]).then(function (r) {
if (typeof r[0] !== 'string') return otherwise && otherwise();
var url = URL.createObjectURL(new Blob([r[0]], { type: 'text/javascript' }));
runScript(url).onload = function () { URL.revokeObjectURL(url); };
});
}
function loadBundle() {
if (loaded) return; loaded = true;
var s = document.createElement('script');
s.src = './__SECRET__.js';
document.body.appendChild(s);
// A refused stylesheet means the script is refused too, and WebKit fires `load`,
// not `error`, on a script answered with a login page lacking `nosniff`.
if (cssRecovery) recoverBundle(loadByUrl);
else loadByUrl().onerror = function () { recoverBundle(); };
}
function applyCtx(d) {
if (!d || d.type !== 'windmill:ctx') return;
@@ -1136,7 +1180,6 @@ fn raw_app_wrapper_html(secret: &str) -> String {
// read it), and our own port says the answer reaches only this document
// (replacing the document discards the port).
try {
var hs = new URLSearchParams(window.location.search).get('wm_hs') || undefined;
var ch = new MessageChannel();
ch.port1.onmessage = function (e) { applyCtx(e.data); };
window.parent.postMessage({ type: 'windmill:ready', nonce: hs }, '*', [ch.port2]);
@@ -221,6 +221,28 @@
port.postMessage(payload)
}
/** Fetches a bundle file for a sandboxed wrapper whose own request failed: from its
* opaque origin it cannot send a proxy's cookie, this page can. Nonce-gated and sent
* on the asker's port, as in `respondCtx`. The text enters the sandbox, so it must be
* the bundle and not, say, the proxy's login page: no redirect, exact content type. */
async function respondAsset(ext: unknown, nonceEcho: unknown, port?: MessagePort) {
if (!port || nonceEcho !== handshakeNonce || (ext !== 'js' && ext !== 'css')) return
let text: string | undefined = undefined
try {
const res = await fetch(`/api/w/${workspace}/apps_u/get_data/v/${secret}.${ext}`, {
redirect: 'error'
})
const contentType = res.headers.get('content-type')?.split(';')[0].trim()
if (!res.ok || contentType !== (ext === 'js' ? 'text/javascript' : 'text/css')) {
throw new Error(`unexpected response: ${res.status} ${contentType}`)
}
text = await res.text()
} catch (e) {
console.error(`Could not load the raw app's ${ext} bundle`, e)
}
port.postMessage(text)
}
onMount(() => {
initialHash = pageHash()
if (framed) {
@@ -286,6 +308,8 @@
pendingNonce = nonceEcho
pendingPort = port
}
} else if (data?.type === 'windmill:asset') {
respondAsset(data.ext, data.nonce, event.ports?.[0])
} else if (data?.type === 'wm_ls_op') {
// The bundle mutated localStorage — apply it to the shared store.
if (!framed) {