loopable / web /src /apps /code /CodeAppFrame.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
c72f0a1 verified
Raw History Blame
4.16 kB
import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS, checkTenant } from "../../apiContract";
import { CODE_APP_SANDBOX, appDocument } from "./frameDocument";
import { attachBridgeHost } from "./bridgeHost";
import type { BridgeHostOptions } from "./bridgeHost";
import bootstrapBody from "./frame-bootstrap.html?raw";
import bootstrapAsset from "./frame-bootstrap.html?url&no-inline";
export const CODE_APP_CONNECTION_POLICY = "(); report-to=code-app";
export const CODE_APP_REFUSAL = "This App cannot run safely in this browser.";
export default function CodeAppFrame({ applicationId, html, css, name, onReady, onRefused, confirmDelete, confirmTool, bootstrapBase = API_V1 }: {
applicationId: string; html: string; css: string; name: string;
onReady: () => void; onRefused: (message: string) => void;
bootstrapBase?: string;
confirmDelete: BridgeHostOptions["confirmDelete"];
confirmTool: BridgeHostOptions["confirmTool"];
}) {
const document = useMemo(() => appDocument(html, css), [html, css]);
const frame = useRef<HTMLIFrameElement>(null);
const callbacks = useRef({ onReady, onRefused });
callbacks.current = { onReady, onRefused };
const [source, setSource] = useState<string | null>(null);
useLayoutEffect(() => {
const controller = new AbortController();
setSource(null);
let verified = false;
let sent = false;
let mounted = false;
let detachBridge = () => {};
const refuse = () => {
if (controller.signal.aborted) return;
controller.abort();
window.clearTimeout(timeout);
detachBridge();
setSource(null);
callbacks.current.onRefused(CODE_APP_REFUSAL);
};
const timeout = window.setTimeout(refuse, 5000);
const receive = (event: MessageEvent) => {
if (controller.signal.aborted || !verified || !frame.current?.contentWindow || event.source !== frame.current.contentWindow
|| event.data?.type !== "code-app-bootstrap") return;
if (event.data.phase === "refused") { refuse(); return; }
if (event.data.phase === "ready" && !sent) {
sent = true;
detachBridge = attachBridgeHost(() => {
try {
const outer = frame.current?.contentWindow;
return outer && outer.length === 1 ? outer.frames[0] : null;
}
catch { return null; }
}, { applicationId, confirmDelete, confirmTool });
try { event.source.postMessage({ type: "code-app-bootstrap", phase: "mount", document, name }, "*"); }
catch { refuse(); }
} else if (event.data.phase === "mounted" && sent && !mounted) {
mounted = true;
window.clearTimeout(timeout);
callbacks.current.onReady();
} else {
refuse();
}
};
window.addEventListener("message", receive);
void (async () => {
try {
const url = `${bootstrapBase}/applications/${encodeURIComponent(applicationId)}/code-frame?bootstrap=${crypto.randomUUID()}`;
const response = await fetch(url, { credentials: CREDENTIALS, signal: controller.signal, cache: "no-store", redirect: "error" });
if (!response.ok || checkTenant(response) || response.headers.get("Connection-Allowlist") !== CODE_APP_CONNECTION_POLICY
|| response.headers.get("Content-Type")?.split(";")[0].trim() !== "text/html"
|| await response.text() !== bootstrapBody) { refuse(); return; }
if (!controller.signal.aborted) {
verified = true;
setSource(url);
}
} catch { refuse(); }
})();
return () => {
controller.abort();
window.clearTimeout(timeout);
window.removeEventListener("message", receive);
detachBridge();
};
}, [applicationId, document, name, bootstrapBase, confirmDelete, confirmTool]);
if (!source) return null;
return <iframe
ref={frame}
data-code-app-frame
title={name}
sandbox={CODE_APP_SANDBOX}
referrerPolicy="no-referrer"
src={source}
data-code-app-bootstrap-asset={bootstrapAsset}
style={{ display: "block", width: "100%", height: "100%", flex: 1, minHeight: 0, border: 0 }}
/>;
}