File size: 4,164 Bytes
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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 }}
  />;
}