Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6485: isolate hosted plugin surfaces (#7329)

Jiayuan Zhangbedad9e222fc
diff --git a/.env.example b/.env.example
index a2b86f5e05..b6ecf96422 100644
--- a/.env.example
+++ b/.env.example
@@ -533,18 +533,26 @@ MULTICA_VCS_SECRET_KEY=
# Plugins (Settings → Plugins). A plugin's frontend is an artifact its author
# uploads; Multica stores it and serves it into a sandboxed iframe, and an
# installation is bound to one immutable version. Hook endpoints and MCP servers
-# stay on the author's own infrastructure. Two optional settings:
+# stay on the author's own infrastructure. Settings:
# 1. MULTICA_PLUGIN_SECRET_KEY — a base64-encoded 32-byte key that encrypts
-# `secret` config values at rest. Without it, saving a secret field fails
-# closed rather than storing plaintext. Generate one with:
+# `secret` config values at rest and seals short-lived surface launch URLs.
+# Without it, saving a secret field and launching a surface both fail
+# closed. Generate one with:
# openssl rand -base64 32
-# 2. MULTICA_PLUGIN_DIR — an absolute path to a directory of plugin folders,
+# 2. MULTICA_PLUGIN_SURFACE_ORIGIN — a dedicated browser origin routed to this
+# backend (for example https://plugins.example.com). It must differ from
+# the app/API origins and carry no app session cookies. The proxy must
+# preserve Host. The backend serves
+# only /plugin-surfaces/* there; a Host check refuses the same URL on the
+# ordinary API origin.
+# 3. MULTICA_PLUGIN_DIR — an absolute path to a directory of plugin folders,
# each containing a multica.plugin.json. It is the development publish
# channel: an author iterating on a surface publishes straight from disk
# instead of zipping and uploading after every edit. It still produces an
# ordinary immutable version, so there is no second way for plugin code to
# reach a browser. Leave empty to accept uploads only.
MULTICA_PLUGIN_SECRET_KEY=
+MULTICA_PLUGIN_SURFACE_ORIGIN=
MULTICA_PLUGIN_DIR=
# Lark / Feishu bot integration (Settings → Integrations "Bind to Lark")
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 4026656506..eb3e3a1175 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -176,6 +176,9 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state の署名シークレット。`JWT_SECRET` から派生可能 |
| セルフホスト Git | `MULTICA_VCS_INTEGRATION_ENABLED` | Forgejo/Gitea/GitLab 連携のスイッチ。compose ではデフォルトで有効 |
| セルフホスト Git | `MULTICA_VCS_SECRET_KEY` | base64 エンコードされた 32 バイトの暗号化キー(`openssl rand -base64 32`)。未設定の場合、この機能全体が利用できません |
+| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | 保存済み secret と surface 起動 URL を暗号化する base64 形式の 32 バイト鍵 |
+| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | バックエンドへルーティングする Cookie なしの専用 origin。app/API origin と分離し、`Host` を保持すること |
+| Plugins | `MULTICA_PLUGIN_DIR` | 開発時にローカル plugin bundle を公開するための任意の絶対ディレクトリ |
`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージによる done への遷移は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 349165156d..8804b427ec 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -176,6 +176,9 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state 서명 키. `JWT_SECRET`에서 파생 가능 |
| 자체 호스팅 Git | `MULTICA_VCS_INTEGRATION_ENABLED` | Forgejo/Gitea/GitLab 연동 스위치. compose에서는 기본 활성화 |
| 자체 호스팅 Git | `MULTICA_VCS_SECRET_KEY` | base64로 인코딩한 32바이트 암호화 키(`openssl rand -base64 32`). 없으면 전체 기능을 사용할 수 없음 |
+| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | 저장된 secret과 surface 실행 URL을 암호화하는 base64 인코딩 32바이트 키 |
+| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 백엔드로 라우팅되는 쿠키 없는 전용 origin. app/API origin과 달라야 하며 `Host`를 보존해야 함 |
+| Plugins | `MULTICA_PLUGIN_DIR` | 개발 중 로컬 plugin bundle을 게시하는 선택적 절대 디렉터리 |
`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 done 전환은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index e1cfe89250..3671a7c1d2 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -176,6 +176,9 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state signing secret; can be derived from `JWT_SECRET` |
| Self-hosted Git | `MULTICA_VCS_INTEGRATION_ENABLED` | Forgejo/Gitea/GitLab integration switch; enabled by default in compose |
| Self-hosted Git | `MULTICA_VCS_SECRET_KEY` | Base64-encoded 32-byte encryption key (`openssl rand -base64 32`); the feature is entirely unavailable without it |
+| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | Base64-encoded 32-byte key for stored secrets and encrypted surface launch URLs |
+| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | Dedicated cookie-free browser origin routed to this backend; must differ from app/API origins and preserve `Host` |
+| Plugins | `MULTICA_PLUGIN_DIR` | Optional absolute directory used to publish local plugin bundles during development |
Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and trigger merge-to-done normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index c37c31e855..7ece129bea 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -176,6 +176,9 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state 签名密钥;可从 `JWT_SECRET` 派生 |
| 自托管 Git | `MULTICA_VCS_INTEGRATION_ENABLED` | Forgejo/Gitea/GitLab 集成开关,compose 默认开启 |
| 自托管 Git | `MULTICA_VCS_SECRET_KEY` | base64 编码的 32 字节加密密钥(`openssl rand -base64 32`);未配置时该功能整体不可用 |
+| 插件 | `MULTICA_PLUGIN_SECRET_KEY` | base64 编码的 32 字节密钥,用于加密已存 secret 和 surface 启动 URL |
+| 插件 | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 路由到后端的独立无 Cookie 浏览器 origin;必须不同于 app/API origin,并保留 `Host` |
+| 插件 | `MULTICA_PLUGIN_DIR` | 开发时用于发布本地插件包的可选绝对目录 |
不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像和触发合并转 done,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 952821b811..8bdb9dc7c1 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -134,6 +134,12 @@ services:
# intentionally NOT used to derive this value, to avoid Host /
# X-Forwarded-Host spoofing on misconfigured proxies.
MULTICA_PUBLIC_URL: ${MULTICA_PUBLIC_URL:-}
+ # Surface HTML must use a second, cookie-free browser origin routed to
+ # this backend. Both settings are optional only in the sense that leaving
+ # either empty disables plugin surfaces rather than weakening isolation.
+ MULTICA_PLUGIN_SECRET_KEY: ${MULTICA_PLUGIN_SECRET_KEY:-}
+ MULTICA_PLUGIN_SURFACE_ORIGIN: ${MULTICA_PLUGIN_SURFACE_ORIGIN:-}
+ MULTICA_PLUGIN_DIR: ${MULTICA_PLUGIN_DIR:-}
# Comma-separated CIDRs whose source IP is allowed to set
# X-Forwarded-For / X-Real-IP for the webhook per-IP rate limiter.
# Empty default = headers ignored, RemoteAddr used. Set e.g.
diff --git a/e2e/plugin-surface-security.spec.ts b/e2e/plugin-surface-security.spec.ts
new file mode 100644
index 0000000000..efbcab90d3
--- /dev/null
+++ b/e2e/plugin-surface-security.spec.ts
@@ -0,0 +1,104 @@
+import { expect, test } from "@playwright/test";
+import { buildSurfaceFrameDocument } from "../packages/views/plugins/surface-document";
+
+test.describe("plugin surface browser boundary", () => {
+ test("a normal hosted document relays exactly one guest-created port", async ({ page }) => {
+ await page.route("https://plugin-content.example.test/**", async (route) => {
+ await route.fulfill({
+ contentType: "text/html",
+ headers: { "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'" },
+ body: `<!doctype html><script>
+ const channel = new MessageChannel();
+ parent.postMessage({
+ type: "multica:plugin-bridge-connect",
+ version: 2,
+ challenge: "proof"
+ }, "*", [channel.port1]);
+ </script>`,
+ });
+ });
+ const wrapper = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque",
+ bridgeToken: "proof",
+ });
+ await page.setContent(`<script>window.bridgeCount = 0; addEventListener("message", event => {
+ if (event.data?.type === "multica:plugin-bridge-connect" && event.ports[0]) window.bridgeCount += 1;
+ });</script><iframe id="host" sandbox="allow-scripts allow-same-origin"></iframe>`);
+ await page.locator("#host").evaluate((frame, srcdoc) => {
+ (frame as HTMLIFrameElement).srcdoc = srcdoc as string;
+ }, wrapper);
+
+ await expect.poll(() => page.evaluate(() => (window as unknown as { bridgeCount: number }).bridgeCount)).toBe(1);
+ });
+
+ test("a first-line external navigation sends no request and cannot retain a bridge", async ({ page }) => {
+ let attackerRequests = 0;
+ await page.route("https://plugin-content.example.test/**", async (route) => {
+ await route.fulfill({
+ contentType: "text/html",
+ headers: {
+ "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'",
+ },
+ body: `<!doctype html><script>
+ const channel = new MessageChannel();
+ channel.port2.onmessage = () => channel.port2.postMessage("still-alive");
+ parent.postMessage({
+ type: "multica:plugin-bridge-connect",
+ version: 2,
+ challenge: "proof"
+ }, "*", [channel.port1]);
+ location.replace("https://attacker.example.test/stolen");
+ const blockedUntil = performance.now() + 150;
+ while (performance.now() < blockedUntil) {}
+ </script>`,
+ });
+ });
+ await page.route("https://attacker.example.test/**", async (route) => {
+ attackerRequests += 1;
+ await route.fulfill({ body: "should never load" });
+ });
+
+ const wrapper = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque",
+ bridgeToken: "proof",
+ });
+ await page.setContent(`<script>window.bridgeCount = 0; window.blockedCount = 0; window.bridgeReply = false; addEventListener("message", event => {
+ if (event.data?.type === "multica:plugin-bridge-connect" && event.ports[0]) {
+ window.bridgeCount += 1;
+ window.bridgePort = event.ports[0];
+ window.bridgePort.onmessage = () => { window.bridgeReply = true; };
+ window.bridgePort.start();
+ }
+ if (event.data?.type === "multica:plugin-surface-navigation-blocked") {
+ window.blockedCount += 1;
+ window.bridgePort?.close();
+ }
+ });</script><iframe id="host" sandbox="allow-scripts allow-same-origin"></iframe>`);
+ await page.locator("#host").evaluate((frame, srcdoc) => {
+ (frame as HTMLIFrameElement).srcdoc = srcdoc as string;
+ }, wrapper);
+
+ await expect.poll(() => page.evaluate(() => (window as unknown as { blockedCount: number }).blockedCount)).toBe(1);
+ await page.evaluate(() => (window as unknown as { bridgePort?: MessagePort }).bridgePort?.postMessage("ping"));
+ await page.waitForTimeout(100);
+ expect(await page.evaluate(() => (window as unknown as { bridgeReply: boolean }).bridgeReply)).toBe(false);
+ expect(attackerRequests).toBe(0);
+ });
+
+ test("two script-capable plugin frames cannot inspect each other", async ({ page }) => {
+ await page.setContent(`
+ <script>
+ window.results = [];
+ addEventListener("message", event => window.results.push(event.data));
+ </script>
+ <iframe name="pluginA" sandbox="allow-scripts" srcdoc="<script>
+ try { parent.frames[1].document.body; parent.postMessage('leaked', '*'); }
+ catch (error) { parent.postMessage(error.name, '*'); }
+ <\/script>"></iframe>
+ <iframe name="pluginB" sandbox="allow-scripts" srcdoc="<div id='private'>secret</div>"></iframe>
+ `);
+
+ await expect.poll(() => page.evaluate(() => (window as unknown as { results: string[] }).results)).toContain("SecurityError");
+ expect(await page.evaluate(() => (window as unknown as { results: string[] }).results)).not.toContain("leaked");
+ });
+});
diff --git a/examples/plugins/deploy-sentinel/ui/main.js b/examples/plugins/deploy-sentinel/ui/main.js
index 26283e59ad..3f4f540d55 100644
--- a/examples/plugins/deploy-sentinel/ui/main.js
+++ b/examples/plugins/deploy-sentinel/ui/main.js
@@ -8,50 +8,30 @@
// user and checks the scopes this plugin was granted.
//
// A surface entry is ONE script with no module graph. Multica stores and serves
-// the published artifact and inlines it into the document it generates, so
-// there is no origin for a static `import` to resolve against — and that is the
+// the published artifact and serves it in a generated content document, so
+// there is no module graph for a static `import` to resolve against — and that is the
// point: a surface cannot reach its author's server just by loading. In a real
// plugin you would bundle `@multica/plugin-sdk` in; this file inlines the few
// calls it needs so the example stays readable and has nothing to install.
const pending = new Map();
-let port = null;
+const port = globalThis.__multicaPluginBridgePortV2;
let sequence = 0;
-window.addEventListener("message", (event) => {
- const data = event.data;
- if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;
- // Only the embedder may hand this frame a port, and only once. Sibling frames
- // are mutually opaque but `parent.frames[i]` is an allowed cross-origin
- // access, so another plugin on this page could otherwise deliver its own port
- // and become this surface's "host". Origin is useless here (a sandboxed frame
- // sees "null"), so identity is the window reference.
- if (event.source !== window.parent || port) return;
- port = event.ports[0];
- port.onmessage = (message) => {
- const payload = message.data;
- if (payload?.kind === "theme") return applyTheme(payload.theme);
- const entry = pending.get(payload?.id);
- if (!entry) return;
- pending.delete(payload.id);
- if (payload.ok) entry.resolve(payload.data);
- else entry.reject(new Error(payload.error));
- };
- port.start();
- applyTheme(data.theme);
- resize(360);
- correlate();
-});
-
-// Announce until the host answers with a port. One announcement is not enough
-// in either direction: this frame can finish executing before the embedder's
-// effect attaches its listener, and a host waiting on the iframe load event can
-// miss that event entirely.
-(function announce(attempts) {
- if (port || attempts > 50) return;
- window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");
- setTimeout(() => announce(attempts + 1), 120);
-})(0);
+if (!(port instanceof MessagePort)) throw new Error("Multica surface bridge is unavailable");
+delete globalThis.__multicaPluginBridgePortV2;
+port.onmessage = (message) => {
+ const payload = message.data;
+ if (payload?.kind === "theme") return applyTheme(payload.theme);
+ const entry = pending.get(payload?.id);
+ if (!entry) return;
+ pending.delete(payload.id);
+ if (payload.ok) entry.resolve(payload.data);
+ else entry.reject(new Error(payload.error));
+};
+port.start();
+resize(360);
+correlate();
function applyTheme(theme) {
for (const [name, value] of Object.entries(theme ?? {})) {
diff --git a/examples/plugins/hello-panel/README.md b/examples/plugins/hello-panel/README.md
index 029e7a52ee..b2102d4a63 100644
--- a/examples/plugins/hello-panel/README.md
+++ b/examples/plugins/hello-panel/README.md
@@ -23,9 +23,9 @@ artifact, serves the panel script from it, and binds your installation to that
one immutable version.
`ui/main.js` is one file with no `import`. That is the contract, not a
-simplification for the example: the host inlines the entry into the sandboxed
-document it generates, so there is no origin a module specifier could resolve
-against. Bundle your dependencies in.
+simplification for the example: Multica serves the entry inside one generated
+document with no module graph, so a bare module specifier has nowhere to
+resolve. Bundle your dependencies in.
While you are iterating, `MULTICA_PLUGIN_DIR` publishes straight from disk
instead of asking you to zip and upload after every edit. It still produces an
diff --git a/examples/plugins/hello-panel/ui/main.js b/examples/plugins/hello-panel/ui/main.js
index 941bf22608..e80f32af2c 100644
--- a/examples/plugins/hello-panel/ui/main.js
+++ b/examples/plugins/hello-panel/ui/main.js
@@ -10,44 +10,22 @@
// file with nothing to install.
const pending = new Map();
-let port = null;
+const port = globalThis.__multicaPluginBridgePortV2;
let sequence = 0;
-window.addEventListener("message", (event) => {
- const data = event.data;
- if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;
- // Only the embedder may hand this frame a port, and only once. Sibling frames
- // are mutually opaque but `parent.frames[i]` is an allowed cross-origin
- // access, so another plugin on this page could otherwise deliver its own port
- // and become this surface's "host" — reading everything it writes. Origin is
- // useless here (a sandboxed frame sees "null"), so identity is the window
- // reference.
- if (event.source !== window.parent || port) return;
- port = event.ports[0];
- port.onmessage = (message) => {
- const payload = message.data;
- if (payload?.kind === "theme") return applyTheme(payload.theme);
- const entry = pending.get(payload?.id);
- if (!entry) return;
- pending.delete(payload.id);
- if (payload.ok) entry.resolve(payload.data);
- else entry.reject(new Error(payload.error));
- };
- port.start();
- applyTheme(data.theme);
- start();
-});
-
-// Announce until the host answers with a port. One announcement is not enough
-// in either direction: this frame can finish executing before the embedder's
-// effect attaches its listener, and a host waiting on the iframe load event can
-// miss that event entirely. Repeating makes the handshake independent of who is
-// ready first — the one ordering neither side controls.
-(function announce(attempts) {
- if (port || attempts > 50) return;
- window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");
- setTimeout(() => announce(attempts + 1), 120);
-})(0);
+if (!(port instanceof MessagePort)) throw new Error("Multica surface bridge is unavailable");
+delete globalThis.__multicaPluginBridgePortV2;
+port.onmessage = (message) => {
+ const payload = message.data;
+ if (payload?.kind === "theme") return applyTheme(payload.theme);
+ const entry = pending.get(payload?.id);
+ if (!entry) return;
+ pending.delete(payload.id);
+ if (payload.ok) entry.resolve(payload.data);
+ else entry.reject(new Error(payload.error));
+};
+port.start();
+start();
function applyTheme(theme) {
for (const [name, value] of Object.entries(theme ?? {})) {
diff --git a/examples/plugins/release-checklist/ui/main.js b/examples/plugins/release-checklist/ui/main.js
index b373e3514a..0f9172e664 100644
--- a/examples/plugins/release-checklist/ui/main.js
+++ b/examples/plugins/release-checklist/ui/main.js
@@ -10,44 +10,22 @@
// the user's own session.
const pending = new Map();
-let port = null;
+const port = globalThis.__multicaPluginBridgePortV2;
let sequence = 0;
-window.addEventListener("message", (event) => {
- const data = event.data;
- if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;
- // Only the embedder may hand this frame a port, and only once. Sibling frames
- // are mutually opaque but `parent.frames[i]` is an allowed cross-origin
- // access, so another plugin on this page could otherwise deliver its own port
- // and become this surface's "host" — reading everything it writes. Origin is
- // useless here (a sandboxed frame sees "null"), so identity is the window
- // reference.
- if (event.source !== window.parent || port) return;
- port = event.ports[0];
- port.onmessage = (message) => {
- const payload = message.data;
- if (payload?.kind === "theme") return applyTheme(payload.theme);
- const entry = pending.get(payload?.id);
- if (!entry) return;
- pending.delete(payload.id);
- if (payload.ok) entry.resolve(payload.data);
- else entry.reject(Object.assign(new Error(payload.error), { status: payload.status }));
- };
- port.start();
- applyTheme(data.theme);
- boot();
-});
-
-// Announce until the host answers with a port. One announcement is not enough
-// in either direction: this frame can finish executing before the embedder's
-// effect attaches its listener, and a host waiting on the iframe load event can
-// miss that event entirely. Repeating makes the handshake independent of who is
-// ready first — the one ordering neither side controls.
-(function announce(attempts) {
- if (port || attempts > 50) return;
- window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");
- setTimeout(() => announce(attempts + 1), 120);
-})(0);
+if (!(port instanceof MessagePort)) throw new Error("Multica surface bridge is unavailable");
+delete globalThis.__multicaPluginBridgePortV2;
+port.onmessage = (message) => {
+ const payload = message.data;
+ if (payload?.kind === "theme") return applyTheme(payload.theme);
+ const entry = pending.get(payload?.id);
+ if (!entry) return;
+ pending.delete(payload.id);
+ if (payload.ok) entry.resolve(payload.data);
+ else entry.reject(Object.assign(new Error(payload.error), { status: payload.status }));
+};
+port.start();
+boot();
function applyTheme(theme) {
for (const [name, value] of Object.entries(theme ?? {})) {
diff --git a/examples/plugins/triage-notify/ui/main.js b/examples/plugins/triage-notify/ui/main.js
index 0a9e68d390..4ec17593f0 100644
--- a/examples/plugins/triage-notify/ui/main.js
+++ b/examples/plugins/triage-notify/ui/main.js
@@ -11,38 +11,22 @@
// that it happened at all.
const pending = new Map();
-let port = null;
+const port = globalThis.__multicaPluginBridgePortV2;
let sequence = 0;
-window.addEventListener("message", (event) => {
- const data = event.data;
- if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;
- // Only the embedder may hand this frame a port, and only once. Sibling frames
- // are mutually opaque but `parent.frames[i]` is an allowed cross-origin
- // access, so another plugin on this page could otherwise deliver its own port
- // and become this surface's "host". Origin is useless here — a sandboxed
- // frame sees "null" — so identity is the window reference.
- if (event.source !== window.parent || port) return;
- port = event.ports[0];
- port.onmessage = (message) => {
- const payload = message.data;
- if (payload?.kind === "theme") return applyTheme(payload.theme);
- const entry = pending.get(payload?.id);
- if (!entry) return;
- pending.delete(payload.id);
- if (payload.ok) entry.resolve(payload.data);
- else entry.reject(Object.assign(new Error(payload.error), { status: payload.status }));
- };
- port.start();
- applyTheme(data.theme);
- boot();
-});
-
-(function announce(attempts) {
- if (port || attempts > 50) return;
- window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");
- setTimeout(() => announce(attempts + 1), 120);
-})(0);
+if (!(port instanceof MessagePort)) throw new Error("Multica surface bridge is unavailable");
+delete globalThis.__multicaPluginBridgePortV2;
+port.onmessage = (message) => {
+ const payload = message.data;
+ if (payload?.kind === "theme") return applyTheme(payload.theme);
+ const entry = pending.get(payload?.id);
+ if (!entry) return;
+ pending.delete(payload.id);
+ if (payload.ok) entry.resolve(payload.data);
+ else entry.reject(Object.assign(new Error(payload.error), { status: payload.status }));
+};
+port.start();
+boot();
function applyTheme(theme) {
for (const [name, value] of Object.entries(theme ?? {})) {
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index ce278c72d8..19a8328dbf 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY, clientErrorMessage } from "./client";
-import { EMPTY_PLUGIN_PACKAGE_LIST, EMPTY_PLUGIN_PREVIEW, EMPTY_PLUGIN_SURFACE_SCRIPT } from "./schemas";
+import { EMPTY_PLUGIN_PACKAGE_LIST, EMPTY_PLUGIN_PREVIEW, EMPTY_PLUGIN_SURFACE_LAUNCH } from "./schemas";
afterEach(() => {
vi.unstubAllGlobals();
@@ -157,25 +157,23 @@ describe("ApiClient Plugin preview response schema", () => {
)).resolves.toEqual(EMPTY_PLUGIN_PREVIEW);
});
- // A surface's code is what the host inlines into a sandboxed frame. A
- // malformed response must fall back to an EMPTY script, which the frame
- // renders as "could not load" — not to a partial one that runs.
- it("falls back to an empty surface script when the response is malformed", async () => {
+ // A malformed launch must not become a partly trusted frame URL.
+ it("falls back to an empty surface launch when the response is malformed", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ code: 42 }), {
+ new Response(JSON.stringify({ url: 42, bridge_token: "proof" }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
),
);
- await expect(new ApiClient("https://api.example.test").getPluginSurfaceScript(
+ await expect(new ApiClient("https://api.example.test").getPluginSurfaceLaunch(
"workspace-1",
"installation-1",
"hello",
- )).resolves.toEqual(EMPTY_PLUGIN_SURFACE_SCRIPT);
+ )).resolves.toEqual(EMPTY_PLUGIN_SURFACE_LAUNCH);
});
it("falls back to an empty package list when the response is malformed", async () => {
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index e4c8bd7990..867a29d1b0 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -153,7 +153,7 @@ import type {
PluginInstallationListResponse,
PluginPackage,
PluginPackageListResponse,
- PluginSurfaceScript,
+ PluginSurfaceLaunch,
PluginInvocation,
PluginMCPTool,
PluginPreview,
@@ -412,12 +412,12 @@ import {
EMPTY_PLUGIN_PREVIEW,
EMPTY_PLUGIN_PACKAGE,
EMPTY_PLUGIN_PACKAGE_LIST,
- EMPTY_PLUGIN_SURFACE_SCRIPT,
+ EMPTY_PLUGIN_SURFACE_LAUNCH,
PluginHookResultSchema,
PluginInstallationListResponseSchema,
PluginPackageListResponseSchema,
PluginPackageSchema,
- PluginSurfaceScriptSchema,
+ PluginSurfaceLaunchSchema,
PluginInvocationListSchema,
PluginMCPToolListSchema,
PluginTokenIssueSchema,
@@ -2603,17 +2603,13 @@ export class ApiClient {
await this.fetch<void>(`/api/workspaces/${workspaceId}/plugins/packages/${packageId}`, { method: "DELETE" });
}
- /**
- * The code one surface runs, read from the version the workspace installed.
- * The host inlines it into the sandboxed document, so nothing is fetched from
- * the plugin author's infrastructure to render a panel.
- */
- async getPluginSurfaceScript(workspaceId: string, installationId: string, surfaceKey: string): Promise<PluginSurfaceScript> {
+ /** Mint one hosted document URL and its single-use bridge proof. */
+ async getPluginSurfaceLaunch(workspaceId: string, installationId: string, surfaceKey: string): Promise<PluginSurfaceLaunch> {
const raw = await this.fetch<unknown>(
- `/api/workspaces/${workspaceId}/plugins/${installationId}/surfaces/${encodeURIComponent(surfaceKey)}/script`,
+ `/api/workspaces/${workspaceId}/plugins/${installationId}/surfaces/${encodeURIComponent(surfaceKey)}/launch`,
);
- return parseWithFallback(raw, PluginSurfaceScriptSchema, EMPTY_PLUGIN_SURFACE_SCRIPT, {
- endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/surfaces/{surfaceKey}/script",
+ return parseWithFallback(raw, PluginSurfaceLaunchSchema, EMPTY_PLUGIN_SURFACE_LAUNCH, {
+ endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/surfaces/{surfaceKey}/launch",
});
}
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index c114607887..83db108440 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -70,7 +70,7 @@ import type {
PluginPackage,
PluginPackageListResponse,
PluginPreview,
- PluginSurfaceScript,
+ PluginSurfaceLaunch,
ResourceLabelsResponse,
RuntimeModelListRequest,
SearchIssuesResponse,
@@ -297,19 +297,17 @@ export const EMPTY_PLUGIN_PACKAGE: PluginPackage = {
created_at: "",
};
-/**
- * A surface's code. The empty default is what the frame renders as "this panel
- * could not load" — an unparseable response must never become an empty script
- * that looks like a working but silent panel.
- */
-export const PluginSurfaceScriptSchema = z.object({
- code: z.string().default(""),
+/** A malformed launch becomes unavailable, never a partly trusted frame. */
+export const PluginSurfaceLaunchSchema = z.object({
+ url: z.string().default(""),
+ bridge_token: z.string().default(""),
version: z.string().default(""),
digest: z.string().default(""),
}).loose();
-export const EMPTY_PLUGIN_SURFACE_SCRIPT: PluginSurfaceScript = {
- code: "",
+export const EMPTY_PLUGIN_SURFACE_LAUNCH: PluginSurfaceLaunch = {
+ url: "",
+ bridge_token: "",
version: "",
digest: "",
};
diff --git a/packages/core/plugins/queries.test.ts b/packages/core/plugins/queries.test.ts
new file mode 100644
index 0000000000..b6f929a3ef
--- /dev/null
+++ b/packages/core/plugins/queries.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { pluginSurfaceLaunchOptions } from "./queries";
+
+describe("pluginSurfaceLaunchOptions", () => {
+ it("uses a new cache entry when a mounted panel moves to another issue", () => {
+ const issueOne = pluginSurfaceLaunchOptions(
+ "workspace-1",
+ "installation-1",
+ "panel",
+ "version-1",
+ "frame-1",
+ "issue-1",
+ );
+ const issueTwo = pluginSurfaceLaunchOptions(
+ "workspace-1",
+ "installation-1",
+ "panel",
+ "version-1",
+ "frame-1",
+ "issue-2",
+ );
+
+ expect(issueOne.queryKey).not.toEqual(issueTwo.queryKey);
+ expect(issueOne.queryKey.at(-1)).toBe("issue-1");
+ expect(issueTwo.queryKey.at(-1)).toBe("issue-2");
+ });
+});
diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.ts
index 623cc00f5d..da83a83e3e 100644
--- a/packages/core/plugins/queries.ts
+++ b/packages/core/plugins/queries.ts
@@ -24,26 +24,26 @@ export function pluginPackagesOptions(wsId: string) {
});
}
-/**
- * The code one surface runs.
- *
- * A published version is immutable, so this is keyed by the version rather than
- * the installation and never goes stale on its own: an upgrade changes the key.
- * `staleTime: Infinity` is a statement about the artifact, not a cache tuning
- * choice — the same version id can only ever return the same bytes.
- */
-export function pluginSurfaceScriptOptions(
+/** One non-cacheable launch for one mounted surface frame. */
+export function pluginSurfaceLaunchOptions(
wsId: string,
installationId: string,
surfaceKey: string,
packageVersionId: string,
+ launchInstance: string,
+ issueId?: string,
) {
return queryOptions({
- queryKey: [...pluginKeys.all(wsId), installationId, "surface", surfaceKey, packageVersionId] as const,
- queryFn: () => api.getPluginSurfaceScript(wsId, installationId, surfaceKey),
+ // A launch contains a single-use bridge token. Two mounted panels must not
+ // share one merely because React Query deduplicated their requests. Moving
+ // the same mounted panel to another issue also needs a fresh launch because
+ // the issue-scoped bridge is replaced with it.
+ queryKey: [...pluginKeys.all(wsId), installationId, "surface-launch", surfaceKey, packageVersionId, launchInstance, issueId ?? ""] as const,
+ queryFn: () => api.getPluginSurfaceLaunch(wsId, installationId, surfaceKey),
enabled: wsId.length > 0 && installationId.length > 0 && surfaceKey.length > 0,
- staleTime: Infinity,
- gcTime: 30 * 60 * 1000,
+ staleTime: 0,
+ gcTime: 0,
+ refetchOnMount: "always",
retry: false,
});
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 4cfddcfcd9..9068f46d11 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -98,7 +98,7 @@ export type {
PluginPackage,
PluginPackageVersion,
PluginPackageListResponse,
- PluginSurfaceScript,
+ PluginSurfaceLaunch,
PluginPreview,
PluginPreviewRequest,
PluginInstallRequest,
diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.ts
index e58ca106fb..134cfb2de4 100644
--- a/packages/core/types/plugin.ts
+++ b/packages/core/types/plugin.ts
@@ -142,15 +142,12 @@ export interface PluginPackageListResponse {
packages: PluginPackage[];
}
-/**
- * The code one surface runs, read from the version the workspace installed.
- *
- * The host inlines it into the sandboxed document it generates, so the surface
- * loads nothing over the network and its CSP names no third-party script origin
- * at all.
- */
-export interface PluginSurfaceScript {
- code: string;
+/** One short-lived, installation-bound launch of a hosted surface. */
+export interface PluginSurfaceLaunch {
+ /** Multica's cookie-free content URL, never the plugin author's server. */
+ url: string;
+ /** Single-use proof the generated document must present to this frame. */
+ bridge_token: string;
version: string;
digest: string;
}
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index 85a6e7bcd3..a446981164 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -17,8 +17,9 @@ multica.ui.resize(320);
**One** script in a sandboxed iframe.
Bundle this SDK and everything else your surface needs into a single file. There
-is no module graph: you publish an artifact, Multica stores it and inlines your
-entry into the document it generates, so there is no origin for a top-level
+is no module graph: you publish an artifact, Multica stores it and serves your
+entry inside a generated document on its dedicated plugin-content origin. There
+is no path back to the author's server and no top-level module graph for a bare
`import` to resolve against. Publishing refuses an entry that has one rather
than letting it fail later in a reader's browser.
@@ -31,7 +32,7 @@ before you write one:
or per member, and survives the frame.
- **`Origin: null` on your own requests.** If your surface calls your backend
directly, that backend must accept a null origin in CORS.
-- **A CSP you did not write.** The host generates the document and derives
+- **A CSP you did not write.** Multica generates the response and derives
`connect-src` from the `net:` scopes in your manifest. Declare every host you
intend to reach; with no `net:` scope your surface cannot issue a network
request at all, including back to your own origin, which is no longer in the
@@ -66,7 +67,7 @@ cannot start agent runs as a side effect of posting text.
## Theme
-The host pushes design tokens in at init and again on every theme switch, and
+The host pushes design tokens over the private port and again on every theme switch, and
the SDK writes them as custom properties on `:root`. Use `var(--foreground)`,
`var(--background)`, `var(--border)`, `var(--radius)` and friends and your
surface will look native without shipping a stylesheet.
diff --git a/packages/plugin-sdk/index.ts b/packages/plugin-sdk/index.ts
index 4410f67874..dfb8a8e093 100644
--- a/packages/plugin-sdk/index.ts
+++ b/packages/plugin-sdk/index.ts
@@ -13,9 +13,7 @@
*/
import {
- BRIDGE_INIT_MESSAGE,
- BRIDGE_PROTOCOL_VERSION,
- BRIDGE_READY_MESSAGE,
+ BRIDGE_PORT_GLOBAL,
isBridgeEvent,
isBridgeResponse,
type BridgeMethod,
@@ -83,9 +81,6 @@ export class MulticaPluginError extends Error {
}
const DEFAULT_TIMEOUT_MS = 15_000;
-const ANNOUNCE_INTERVAL_MS = 120;
-const ANNOUNCE_ATTEMPTS = 50;
-
type Pending = {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
@@ -106,66 +101,20 @@ class Bridge {
this.ready = new Promise((resolve) => {
this.markReady = resolve;
});
- if (typeof window !== "undefined") {
- window.addEventListener("message", this.onWindowMessage);
- this.announce();
+ const guestPort = (globalThis as Record<string, unknown>)[BRIDGE_PORT_GLOBAL];
+ if (guestPort && typeof (guestPort as MessagePort).postMessage === "function" &&
+ typeof (guestPort as MessagePort).close === "function") {
+ // First reader wins. The port is not a credential, but leaving a second
+ // global reference around makes accidental competing SDK instances much
+ // harder to diagnose and weakens the one-channel invariant.
+ delete (globalThis as Record<string, unknown>)[BRIDGE_PORT_GLOBAL];
+ this.port = guestPort as MessagePort;
+ this.port.onmessage = this.onPortMessage;
+ this.port.start?.();
+ this.markReady();
}
}
- /**
- * Announces until the host answers with a port.
- *
- * One announcement is not enough in either direction: a srcdoc frame can
- * finish executing before the embedder's effect attaches its listener, and a
- * host that waits on the iframe load event can miss it entirely. Repeating
- * until the port arrives makes the handshake independent of who is ready
- * first, which is the only ordering nobody controls.
- */
- private announce() {
- if (typeof window === "undefined" || !window.parent) return;
- let attempts = 0;
- const beat = () => {
- if (this.port || attempts++ > ANNOUNCE_ATTEMPTS) return;
- // targetOrigin "*" because this frame has an opaque origin and cannot
- // know the embedder's. The message carries nothing but the signal.
- window.parent.postMessage({ type: BRIDGE_READY_MESSAGE }, "*");
- setTimeout(beat, ANNOUNCE_INTERVAL_MS);
- };
- beat();
- }
-
- private onWindowMessage = (event: MessageEvent) => {
- const data = event.data as { type?: string; version?: number; theme?: ThemeTokens } | null;
- if (!data || data.type !== BRIDGE_INIT_MESSAGE) return;
- const port = event.ports?.[0];
- if (!port) return;
- // Only the embedder may hand this frame a port.
- //
- // Sibling frames are mutually opaque, but `parent.frames[i]` is an indexed
- // cross-origin access the spec allows, so another plugin on the same page
- // can postMessage into this one. Without this check it could deliver its own
- // MessagePort and become this surface's "host": feed it fabricated issue
- // data and read everything the surface writes, including whatever it puts in
- // storage:user. Origin cannot be compared — a sandboxed frame sees "null" —
- // so the embedder is identified by window reference, mirroring the host's
- // own check on the readiness signal.
- if (event.source !== window.parent) return;
- // First init wins. A hijacker that lost the race could otherwise send a
- // second init and take the channel over afterwards.
- if (this.port) return;
- if (data.version !== BRIDGE_PROTOCOL_VERSION) {
- // A host newer or older than this SDK: fail loudly rather than guess at a
- // shape neither side agreed on.
- return;
- }
- this.port = port;
- port.onmessage = this.onPortMessage;
- port.start?.();
- if (data.theme) this.applyTheme(data.theme);
- for (const request of this.queued.splice(0)) port.postMessage(request);
- this.markReady();
- };
-
private onPortMessage = (event: MessageEvent) => {
const message = event.data;
if (isBridgeEvent(message)) {
diff --git a/packages/plugin-sdk/protocol.ts b/packages/plugin-sdk/protocol.ts
index a87446afd4..2ec537ee35 100644
--- a/packages/plugin-sdk/protocol.ts
+++ b/packages/plugin-sdk/protocol.ts
@@ -9,35 +9,22 @@
*
* - Identity is bound by a MessagePort, not by `event.origin`. A surface runs
* in a sandboxed iframe with no `allow-same-origin`, so its origin is the
- * opaque string "null" — every surface would look identical. The host hands
- * each iframe its own port at init and only ever listens on that port, so
- * "which plugin sent this" is answered by which channel it arrived on.
+ * opaque string "null" — every surface would look identical. The generated
+ * guest bootstrap creates one channel, and the host accepts its peer only
+ * after source, protocol and single-use launch checks. From then on, "which
+ * plugin sent this" is answered by which private channel it arrived on.
* - No credential crosses this boundary. The surface asks; the host performs
* the call on the user's session and returns the result.
*/
-export const BRIDGE_PROTOCOL_VERSION = 1;
-
-/** Marks the single window message that carries the port. */
-export const BRIDGE_INIT_MESSAGE = "multica:plugin-bridge-init";
+export const BRIDGE_PROTOCOL_VERSION = 2;
/**
- * Posted by the surface to its embedder once its message listener is attached.
- *
- * The handshake has to start from the guest. A srcdoc frame can finish loading
- * before the embedder's React `onLoad` handler is even attached, so a host that
- * connects on load either misses the event entirely or sends the port before
- * anything is listening for it — both look identical from outside: a blank
- * panel. The host answers this signal instead, and matches `event.source`
- * against the iframe it created so another frame cannot claim the port.
+ * Installed by Multica's bootstrap before any plugin code executes. The guest
+ * creates this port; the trusted wrapper transfers its peer to the host only
+ * after the launch challenge and navigation policy have passed.
*/
-export const BRIDGE_READY_MESSAGE = "multica:plugin-surface-ready";
-
-export type BridgeInitMessage = {
- type: typeof BRIDGE_INIT_MESSAGE;
- version: number;
- theme: ThemeTokens;
-};
+export const BRIDGE_PORT_GLOBAL = "__multicaPluginBridgePortV2";
/** Design tokens the host pushes so a surface matches the product it sits in. */
export type ThemeTokens = Record<string, string>;
diff --git a/packages/views/plugins/index.ts b/packages/views/plugins/index.ts
index ed218b987e..61ac097576 100644
--- a/packages/views/plugins/index.ts
+++ b/packages/views/plugins/index.ts
@@ -1,6 +1,6 @@
export { PluginPanelSection } from "./plugin-panel-section";
export { PluginSurfaceFrame } from "./plugin-surface-frame";
-export { buildSurfaceCSP, buildSurfaceDocument, surfaceConnectSources } from "./surface-document";
+export { buildSurfaceFrameDocument } from "./surface-document";
export {
PluginHookMenuItems,
collectManualHookActions,
diff --git a/packages/views/plugins/plugin-modal-surface.tsx b/packages/views/plugins/plugin-modal-surface.tsx
index bfece67ec2..1fd85a1b3d 100644
--- a/packages/views/plugins/plugin-modal-surface.tsx
+++ b/packages/views/plugins/plugin-modal-surface.tsx
@@ -20,9 +20,9 @@ import { PluginSurfaceFrame } from "./plugin-surface-frame";
/**
* The mount point for `modal` surfaces.
*
- * A modal is the same sandboxed iframe as a panel — `allow-scripts` without
- * `allow-same-origin`, host-generated srcdoc, CSP derived from the granted
- * `net:` scopes — differing only in where it appears. What it is NOT is a way
+ * A modal is the same hosted, opaque inner iframe as a panel — with a CSP
+ * derived from the granted `net:` scopes — differing only in where it appears.
+ * What it is NOT is a way
* for a plugin to interrupt somebody: it opens because a person picked it from
* the issue menu, never on the plugin's own initiative.
*/
diff --git a/packages/views/plugins/plugin-panel-section.test.tsx b/packages/views/plugins/plugin-panel-section.test.tsx
index 7d513f2c86..fd58dacbe1 100644
--- a/packages/views/plugins/plugin-panel-section.test.tsx
+++ b/packages/views/plugins/plugin-panel-section.test.tsx
@@ -7,9 +7,12 @@ import enIssues from "../locales/en/issues.json";
const data = vi.hoisted(() => ({
installed: { plugins: [] as Array<Record<string, unknown>> },
- // A surface's code now comes from us, over a second query. `null` is what a
- // frame that has nothing to run sees.
- script: { code: "console.log('hi');", version: "1.0.0", digest: "abc" } as Record<string, unknown> | null,
+ launch: {
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque",
+ bridge_token: "single-use-proof",
+ version: "1.0.0",
+ digest: "abc",
+ } as Record<string, unknown> | null,
flagEnabled: true,
}));
@@ -19,12 +22,12 @@ vi.mock("@tanstack/react-query", () => ({
// carries, so a test can make the code unavailable without touching the list.
useQuery: (options: { queryKey?: readonly unknown[] }) =>
options?.queryKey?.[0] === "surface"
- ? { data: data.script, isPending: false, isError: data.script === null }
+ ? { data: data.launch, isPending: false, isError: data.launch === null }
: { data: data.installed, isLoading: false, isError: false },
}));
vi.mock("@multica/core/plugins", () => ({
pluginInstallationsOptions: () => ({ queryKey: ["plugins"] }),
- pluginSurfaceScriptOptions: () => ({ queryKey: ["surface"] }),
+ pluginSurfaceLaunchOptions: () => ({ queryKey: ["surface"] }),
}));
vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "workspace-1", name: "Acme", slug: "acme" }) }));
vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => data.flagEnabled }));
@@ -62,23 +65,28 @@ function installation(overrides: Record<string, unknown> = {}) {
describe("PluginPanelSection", () => {
beforeEach(() => {
data.installed.plugins = [];
- data.script = { code: "console.log('hi');", version: "1.0.0", digest: "abc" };
+ data.launch = {
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque",
+ bridge_token: "single-use-proof",
+ version: "1.0.0",
+ digest: "abc",
+ };
data.flagEnabled = true;
});
- it("mounts an enabled issue_panel in a sandbox that never gets allow-same-origin", () => {
+ it("mounts an enabled issue_panel with an opaque nested plugin frame", () => {
data.installed.plugins = [installation()];
render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });
const frame = screen.getByTitle("Hello Panel — Hello");
- // allow-scripts WITHOUT allow-same-origin is the entire isolation boundary.
- // The pairing is what the HTML spec calls out as defeating the sandbox, so
- // this assertion is the regression guard for the whole surface model.
- expect(frame).toHaveAttribute("sandbox", "allow-scripts");
- expect(frame.getAttribute("sandbox")).not.toContain("allow-same-origin");
- // srcDoc, not src: the host generates the document so it can set the CSP.
+ // The visible iframe is trusted host code. Its srcdoc creates the actual
+ // plugin iframe with allow-scripts and deliberately no allow-same-origin.
+ expect(frame).toHaveAttribute("sandbox", "allow-scripts allow-same-origin");
expect(frame).toHaveAttribute("srcdoc");
expect(frame).not.toHaveAttribute("src");
+ const srcdoc = frame.getAttribute("srcdoc") ?? "";
+ expect(srcdoc).toContain('child.setAttribute("sandbox", "allow-scripts")');
+ expect(srcdoc).not.toContain('child.setAttribute("sandbox", "allow-scripts allow-same-origin")');
});
it("does not mount a disabled installation", () => {
@@ -121,7 +129,7 @@ describe("PluginPanelSection", () => {
it("says the surface could not load instead of showing an empty frame", () => {
// An empty body is what a malformed response parses to. Mounting a frame
// for it would look like a working panel that renders nothing.
- data.script = null;
+ data.launch = null;
data.installed.plugins = [installation()];
render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });
@@ -129,30 +137,25 @@ describe("PluginPanelSection", () => {
expect(screen.getByText(/could not load its interface/i)).toBeInTheDocument();
});
- it("loads a surface's code from Multica, never from the plugin author", () => {
- // The frame's document carries the code inline. If anything here starts
- // emitting a remote <script src>, every panel open becomes a request to a
- // third party again.
+ it("loads only Multica's dedicated content origin", () => {
data.installed.plugins = [installation()];
render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });
const srcdoc = screen.getByTitle("Hello Panel — Hello").getAttribute("srcdoc") ?? "";
- expect(srcdoc).not.toContain("<script src=");
- expect(srcdoc).toContain("script-src 'unsafe-inline'");
+ expect(srcdoc).toContain("frame-src https://plugin-content.example.test");
+ expect(srcdoc).not.toContain("frame-src https:;");
});
- it("acknowledges a plugin bootstrap error and shows a useful failure", () => {
+ it("shows a useful plugin bootstrap failure", () => {
data.installed.plugins = [installation()];
render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });
const frame = screen.getByTitle("Hello Panel — Hello") as HTMLIFrameElement;
- const postMessage = vi.spyOn(frame.contentWindow!, "postMessage");
const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-error" } });
Object.defineProperty(event, "source", { value: frame.contentWindow, configurable: true });
act(() => window.dispatchEvent(event));
expect(screen.getByText("Hello Panel could not load its interface.")).toBeInTheDocument();
- expect(postMessage).toHaveBeenCalledWith({ type: "multica:plugin-surface-error-ack" }, "*");
});
it("clears a previous surface failure when the issue changes", () => {
@@ -181,7 +184,12 @@ describe("PluginPanelSection", () => {
act(() => window.dispatchEvent(event));
expect(screen.getByText("Hello Panel could not load its interface.")).toBeInTheDocument();
- data.script = { code: "console.log('replacement');", version: "1.0.1", digest: "def" };
+ data.launch = {
+ url: "https://plugin-content.example.test/plugin-surfaces/replacement",
+ bridge_token: "replacement-proof",
+ version: "1.0.1",
+ digest: "def",
+ };
rerender(<PluginPanelSection issueId="issue-1" />);
expect(screen.queryByText("Hello Panel could not load its interface.")).not.toBeInTheDocument();
expect(screen.getByTitle("Hello Panel — Hello").getAttribute("srcdoc")).not.toBe(originalDocument);
diff --git a/packages/views/plugins/plugin-sdk-handshake.test.ts b/packages/views/plugins/plugin-sdk-handshake.test.ts
index 37c2f0b6d5..e0d1c6295f 100644
--- a/packages/views/plugins/plugin-sdk-handshake.test.ts
+++ b/packages/views/plugins/plugin-sdk-handshake.test.ts
@@ -1,65 +1,16 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
-// Lives here rather than beside the SDK on purpose: @multica/plugin-sdk ships
-// as TypeScript source to third parties and carries no test runner of its own,
-// and packages/views is its only consumer in this repo.
-//
-// The guest half of the handshake. Sibling surfaces are mutually opaque but
-// `parent.frames[i]` is an allowed cross-origin access, so another plugin on the
-// same page can postMessage into this one. What stops it from becoming this
-// surface's "host" is the two checks below — neither is visible from reading a
-// plugin's own code, which is exactly why they are pinned here.
-//
-// Runs on a hand-built window rather than jsdom: the SDK touches exactly
-// `addEventListener` and `parent`, and a package that ships to third parties is
-// better off with no test-only dependency at all.
-
-class FakeWindow extends EventTarget {
- parent: FakeWindow = this;
- readonly sent: unknown[] = [];
- postMessage(message: unknown) {
- this.sent.push(message);
- }
-}
-
-let fakeWindow: FakeWindow;
-
-async function loadSdk() {
+async function loadSdk(port: MessagePort | null) {
vi.resetModules();
- fakeWindow = new FakeWindow();
- vi.stubGlobal("window", fakeWindow);
- // The SDK writes theme tokens to documentElement when a host sends them; no
- // theme is sent here, so a document is never touched.
- vi.stubGlobal("document", undefined);
+ if (port) vi.stubGlobal("__multicaPluginBridgePortV2", port);
return import("@multica/plugin-sdk");
}
-function initFrom(source: unknown, port: MessagePort) {
- const event = new MessageEvent("message", {
- data: { type: "multica:plugin-bridge-init", version: 1 },
- });
- Object.defineProperty(event, "source", { value: source, configurable: true });
- Object.defineProperty(event, "ports", { value: [port], configurable: true });
- fakeWindow.dispatchEvent(event);
-}
+describe("surface SDK guest port", () => {
+ beforeEach(() => vi.unstubAllGlobals());
-/**
- * Waits out a turn for a delivery that must never come.
- *
- * Only sound for an assertion that stays true forever: a port delivers on an
- * event-loop drain rather than as a DOM task, so a timer is no barrier for one
- * that IS coming. Wait on the traffic itself in that case — see the third test.
- */
-const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
-
-describe("surface bridge handshake", () => {
- beforeEach(() => {
- vi.useRealTimers();
- });
-
- it("accepts a port from the embedder and answers on it", async () => {
- const { multica } = await loadSdk();
+ it("takes the guest-created bootstrap port and answers on it", async () => {
const channel = new MessageChannel();
const asked: unknown[] = [];
channel.port2.onmessage = (event) => {
@@ -69,51 +20,22 @@ describe("surface bridge handshake", () => {
};
channel.port2.start();
- initFrom(fakeWindow.parent, channel.port1);
+ const { multica } = await loadSdk(channel.port1);
await multica.context.get(true);
expect(asked).toHaveLength(1);
expect(asked[0]).toMatchObject({ kind: "action", method: "GET", path: "/context" });
+ expect((globalThis as Record<string, unknown>).__multicaPluginBridgePortV2).toBeUndefined();
});
- it("ignores an init from a window that is not the embedder", async () => {
- const { multica } = await loadSdk();
- const hostile = new MessageChannel();
- const seen: unknown[] = [];
- hostile.port2.onmessage = (event) => seen.push(event.data);
- hostile.port2.start();
-
- // A sibling plugin frame shouting an init with its own port.
- initFrom(new FakeWindow(), hostile.port1);
- void multica.context.get(true);
- await settle();
-
- expect(seen).toHaveLength(0);
- });
-
- it("keeps the first port when a second init arrives", async () => {
- const { multica } = await loadSdk();
- const real = new MessageChannel();
- const hijack = new MessageChannel();
- const onReal: unknown[] = [];
- const onHijack: unknown[] = [];
- real.port2.onmessage = (event) => onReal.push(event.data);
- hijack.port2.onmessage = (event) => onHijack.push(event.data);
- real.port2.start();
- hijack.port2.start();
-
- initFrom(fakeWindow.parent, real.port1);
- // Even from the embedder's own window: a hijacker that lost the race must
- // not be able to take the channel over afterwards.
- initFrom(fakeWindow.parent, hijack.port1);
- void multica.context.get(true);
- // The request arriving on the first port is the barrier: until it does,
- // "the hijacker got nothing" is true of a channel nobody has used yet.
- await vi.waitFor(() => expect(onReal.length).toBeGreaterThan(0));
+ it("applies theme events delivered before a plugin makes its first request", async () => {
+ const style = { setProperty: vi.fn() };
+ vi.stubGlobal("document", { documentElement: { style } });
+ const channel = new MessageChannel();
+ const { multica } = await loadSdk(channel.port1);
+ channel.port2.postMessage({ kind: "theme", theme: { "--background": "black" } });
- // The property under test is that the second init cannot capture the
- // channel — traffic keeps going to the port bound first, and the hijacker's
- // port stays silent.
- expect(onHijack).toHaveLength(0);
+ await vi.waitFor(() => expect(style.setProperty).toHaveBeenCalledWith("--background", "black"));
+ expect(typeof multica.ui.onThemeChange).toBe("function");
});
});
diff --git a/packages/views/plugins/plugin-surface-frame.tsx b/packages/views/plugins/plugin-surface-frame.tsx
index ae69cca180..f2648d1b18 100644
--- a/packages/views/plugins/plugin-surface-frame.tsx
+++ b/packages/views/plugins/plugin-surface-frame.tsx
@@ -1,12 +1,12 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useId, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { pluginSurfaceScriptOptions } from "@multica/core/plugins";
+import { pluginSurfaceLaunchOptions } from "@multica/core/plugins";
import type { PluginInstallation, PluginSurface } from "@multica/core/types";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../i18n";
-import { buildSurfaceDocument, readThemeTokens } from "./surface-document";
+import { buildSurfaceFrameDocument, readThemeTokens } from "./surface-document";
import { createSurfaceBridge } from "./surface-bridge";
const DEFAULT_HEIGHT = 220;
@@ -22,77 +22,93 @@ interface PluginSurfaceFrameProps {
/**
* Mounts one plugin surface.
*
- * `sandbox="allow-scripts"` WITHOUT `allow-same-origin` is the whole isolation
- * boundary and must never be loosened: the pairing is called out in the HTML
- * spec as defeating the sandbox, and it is what would hand a third-party script
- * our cookies and storage. Same rule, same reason as
- * `packages/views/editor/code-block-iframe.tsx`.
+ * This element is a TRUSTED wrapper. Its nested plugin iframe is the isolation
+ * boundary and is always `sandbox="allow-scripts"` without
+ * `allow-same-origin`; see buildSurfaceFrameDocument.
*/
export function PluginSurfaceFrame({ wsId, installation, surface, issueId, className }: PluginSurfaceFrameProps) {
const frameRef = useRef<HTMLIFrameElement>(null);
const anchorRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(DEFAULT_HEIGHT);
+ const launchInstance = useId();
- // The code comes from us, not from the plugin author's server. It is keyed by
- // the installed version, which is immutable — so this is fetched once and an
- // upgrade is what changes the key.
- const { data: script, isPending, isError } = useQuery(
- pluginSurfaceScriptOptions(wsId, installation.id, surface.key, installation.package_version_id),
+ // Every mounted frame gets its own launch. The artifact is immutable, but the
+ // bridge proof is deliberately neither cacheable nor shareable.
+ const { data: launch, isPending, isError } = useQuery(
+ pluginSurfaceLaunchOptions(wsId, installation.id, surface.key, installation.package_version_id, launchInstance, issueId),
);
- // Tokens are read off a mounted element, so the frame inherits whatever theme
- // the app is actually in rather than a hardcoded copy that drifts. It has to
- // happen after mount: on first render the ref is still null and the surface
- // would be built with no theme at all.
- const [theme, setTheme] = useState<Record<string, string>>({});
- useEffect(() => setTheme(readThemeTokens(anchorRef.current)), []);
-
const surfaceDocument = useMemo(() => {
- // An empty body is what a malformed response parses to. Rendering it would
- // mount a frame that runs nothing and looks like a working, silent panel.
- if (!script?.code) return null;
- return buildSurfaceDocument({ code: script.code, grantedScopes: installation.granted_scopes, theme });
- }, [script?.code, installation.granted_scopes, theme]);
+ if (!launch?.url || !launch.bridge_token) return null;
+ try {
+ return buildSurfaceFrameDocument({ url: launch.url, bridgeToken: launch.bridge_token });
+ } catch {
+ return null;
+ }
+ }, [launch?.url, launch?.bridge_token]);
- // A failure belongs to one rendered document on one issue. Keeping a plain
- // boolean makes the banner survive an issue change or a version/code reload
- // even though the replacement iframe is running normally.
+ // Terminal state belongs to one rendered document on one issue. Comparing
+ // the instance keeps an old failure/navigation from surviving a replacement
+ // launch even though the new iframe is running normally.
const surfaceInstance = useMemo(() => ({ issueId, surfaceDocument }), [issueId, surfaceDocument]);
const [failedSurfaceInstance, setFailedSurfaceInstance] = useState<typeof surfaceInstance | null>(null);
+ const [navigatedSurfaceInstance, setNavigatedSurfaceInstance] = useState<typeof surfaceInstance | null>(null);
const failed = failedSurfaceInstance === surfaceInstance;
+ const navigated = navigatedSurfaceInstance === surfaceInstance;
// One bridge per rendered document. srcDoc changing reloads the frame — and
// therefore restarts the guest's handshake — so the old bridge is finished:
// close() is terminal, and reusing a closed one across a document change is
// exactly how the panel ends up permanently blank.
const bridge = useMemo(
- () => createSurfaceBridge({ installationId: installation.id, issueId, onResize: setHeight }),
- [installation.id, issueId, surfaceDocument],
+ () => createSurfaceBridge({
+ installationId: installation.id,
+ bridgeToken: launch?.bridge_token ?? "",
+ issueId,
+ onResize: setHeight,
+ }),
+ [installation.id, launch?.bridge_token, issueId],
);
- // Arm as soon as the frame element exists. The surface announces itself once
- // its listener is attached, so there is no load event to race.
- useEffect(() => {
- if (frameRef.current) bridge.connect(frameRef.current, readThemeTokens(anchorRef.current));
- return () => bridge.close();
- }, [bridge]);
-
+ // The listener is armed BEFORE srcdoc is assigned. That makes the guest-first
+ // one-shot port transfer race-free without retries or a reusable token.
useEffect(() => {
+ const frame = frameRef.current;
+ if (!frame || !surfaceDocument) return () => bridge.close();
const onMessage = (event: MessageEvent) => {
const type = (event.data as { type?: string } | null)?.type;
- if (type !== "multica:plugin-surface-error") return;
+ if (type !== "multica:plugin-surface-error" &&
+ type !== "multica:plugin-surface-navigated" &&
+ type !== "multica:plugin-surface-navigation-blocked") return;
// Same window-identity rule as the bridge: without it any frame on the
// page could light up the failure banner on every other panel.
- if (!frameRef.current?.contentWindow || event.source !== frameRef.current.contentWindow) return;
- // A surface whose script throws on its first line posts the error rather
- // than rendering blank. Acknowledge it so the guest can stop repeating
- // the signal it started before this effect was guaranteed to be mounted.
- frameRef.current.contentWindow.postMessage({ type: "multica:plugin-surface-error-ack" }, "*");
- setFailedSurfaceInstance(surfaceInstance);
+ if (!frame.contentWindow || event.source !== frame.contentWindow) return;
+ if (type === "multica:plugin-surface-error") setFailedSurfaceInstance(surfaceInstance);
+ else setNavigatedSurfaceInstance(surfaceInstance);
};
+ // Terminal events and the bridge are both armed before srcdoc is assigned,
+ // so even a first-line plugin failure or navigation cannot outrun the host.
window.addEventListener("message", onMessage);
- return () => window.removeEventListener("message", onMessage);
- }, [surfaceInstance]);
+ bridge.connect(frame, readThemeTokens(anchorRef.current));
+ frame.srcdoc = surfaceDocument;
+ return () => {
+ window.removeEventListener("message", onMessage);
+ bridge.close();
+ frame.removeAttribute("srcdoc");
+ };
+ }, [bridge, surfaceDocument, surfaceInstance]);
+
+ useEffect(() => {
+ if (navigated) bridge.close();
+ }, [navigated, bridge]);
+
+ if (navigated) {
+ return (
+ <div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>
+ <PluginSurfaceNotice installation={installation} kind="navigated" />
+ </div>
+ );
+ }
if (!surfaceDocument) {
return (
@@ -121,8 +137,9 @@ export function PluginSurfaceFrame({ wsId, installation, surface, issueId, class
key={`${installation.id}:${surface.key}:${issueId ?? ""}`}
ref={frameRef}
title={`${installation.name} — ${surface.name}`}
- srcDoc={surfaceDocument}
- sandbox="allow-scripts"
+ // This is the host-authored wrapper, so same-origin is intentional. Its
+ // nested plugin iframe remains opaque and owns no app credential.
+ sandbox="allow-scripts allow-same-origin"
className="w-full border-0 bg-transparent"
style={{ height }}
/>
@@ -135,10 +152,11 @@ function PluginSurfaceNotice({
kind,
}: {
installation: PluginInstallation;
- kind: "unavailable" | "failed" | "loading";
+ kind: "unavailable" | "failed" | "loading" | "navigated";
}) {
const { t } = useT("issues");
if (kind === "failed") return <>{t(($) => $.plugins.surface_failed, { name: installation.name })}</>;
if (kind === "loading") return <>{t(($) => $.plugins.surface_loading, { name: installation.name })}</>;
+ if (kind === "navigated") return <>{t(($) => $.plugins.surface_navigated, { name: installation.name })}</>;
return <>{t(($) => $.plugins.surface_unavailable, { name: installation.name })}</>;
}
diff --git a/packages/views/plugins/surface-bridge.test.ts b/packages/views/plugins/surface-bridge.test.ts
index 24f8af8dbb..0be2a427b3 100644
--- a/packages/views/plugins/surface-bridge.test.ts
+++ b/packages/views/plugins/surface-bridge.test.ts
@@ -5,61 +5,36 @@ vi.mock("@multica/core/api", () => ({ api: { callPluginAction: mockCall } }));
import { createSurfaceBridge } from "./surface-bridge";
-// The bridge is the only path from a surface into Multica, so what it refuses
-// matters more than what it forwards. None of this is visible from the
-// component: it only holds if the guards run before the fetch.
+const TOKEN = "single-use-launch-proof";
-function connectedBridge(options: Parameters<typeof createSurfaceBridge>[0] = { installationId: "installation-1" }) {
+function connectMessage(source: Window | null, port: MessagePort, challenge = TOKEN, version = 2) {
+ const event = new MessageEvent("message", {
+ data: { type: "multica:plugin-bridge-connect", version, challenge },
+ });
+ Object.defineProperty(event, "source", { value: source, configurable: true });
+ Object.defineProperty(event, "ports", { value: [port], configurable: true });
+ window.dispatchEvent(event);
+}
+
+function connectedBridge(
+ options: Parameters<typeof createSurfaceBridge>[0] = { installationId: "installation-1", bridgeToken: TOKEN },
+) {
const bridge = createSurfaceBridge(options);
const posted: unknown[] = [];
- const frame = {
- contentWindow: {
- postMessage: (_message: unknown, _origin: string, transfer: MessagePort[]) => {
- const port = transfer[0];
- if (!port) throw new Error("bridge did not transfer a port");
- port.onmessage = (event: MessageEvent) => posted.push(event.data);
- port.start();
- (frame as unknown as { port: MessagePort }).port = port;
- },
- },
- } as unknown as HTMLIFrameElement & { port: MessagePort };
-
+ const frame = { contentWindow: {} } as unknown as HTMLIFrameElement;
+ const channel = new MessageChannel();
+ channel.port2.onmessage = (event) => {
+ if ((event.data as { kind?: string } | null)?.kind !== "theme") posted.push(event.data);
+ };
+ channel.port2.start();
bridge.connect(frame, {});
- // The guest announces itself; the host answers that, not the iframe's load
- // event. `source` has to be the frame's own window or the host must ignore it.
- announce(frame.contentWindow as unknown as Window);
- return { bridge, frame, posted };
-}
-
-/**
- * Fires the surface's readiness signal as if it came from `source`.
- *
- * `MessageEvent.source` is getter-only, so it is redefined on the instance. The
- * host reads it by identity, which is exactly the check being exercised.
- */
-function announce(source: Window | null) {
- const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-ready" } });
- Object.defineProperty(event, "source", { value: source, configurable: true });
- window.dispatchEvent(event);
+ connectMessage(frame.contentWindow, channel.port1, options.bridgeToken);
+ return { bridge, frame, port: channel.port2, posted };
}
-/**
- * Resolves once the bridge has answered everything posted before this call.
- *
- * Nothing here may wait by timer. jsdom has no MessageChannel, so `frame.port`
- * is Node's, and a port delivers on an event-loop drain rather than as a DOM
- * task — `setTimeout(0)` can fire first. That is how this suite failed in CI:
- * the assertions ran before the bridge saw anything, and the handler landed in
- * the *next* test, which then failed on a call it never made.
- *
- * A port is FIFO, so a request posted last and answered proves every earlier
- * one was handled. This probe names a path outside the Action API, which the
- * bridge refuses without awaiting anything. Its answer is not the test's, so it
- * is dropped from `posted` before returning.
- */
-async function answered(frame: { port: MessagePort }, posted: unknown[]) {
- const id = "probe:has-the-bridge-caught-up";
- frame.port.postMessage({ id, kind: "action", method: "GET", path: "/probe" });
+async function answered(port: MessagePort, posted: unknown[]) {
+ const id = "probe:bridge-drained";
+ port.postMessage({ id, kind: "action", method: "GET", path: "/probe" });
const sent = (message: unknown) => (message as { id?: string } | null)?.id === id;
await vi.waitFor(() => {
if (!posted.some(sent)) throw new Error("bridge has not answered the probe yet");
@@ -67,25 +42,16 @@ async function answered(frame: { port: MessagePort }, posted: unknown[]) {
posted.splice(posted.findIndex(sent), 1);
}
-/**
- * Waits out one event-loop port drain — the cycle any pending delivery rides.
- *
- * Only for the closed-bridge case, where the assertion is that a message is
- * never delivered and there is therefore no answer to wait for. A drain of our
- * own is the closest available clock: a delivery the closed port wrongly made
- * would have come through on the same one.
- */
-const portDrain = () =>
- new Promise<void>((resolve) => {
- const channel = new MessageChannel();
- channel.port1.onmessage = () => {
- channel.port1.close();
- channel.port2.close();
- resolve();
- };
- channel.port1.start();
- channel.port2.postMessage(0);
- });
+const portDrain = () => new Promise<void>((resolve) => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => {
+ channel.port1.close();
+ channel.port2.close();
+ resolve();
+ };
+ channel.port1.start();
+ channel.port2.postMessage(0);
+});
describe("surface bridge", () => {
beforeEach(() => {
@@ -93,105 +59,87 @@ describe("surface bridge", () => {
mockCall.mockResolvedValue({ ok: true });
});
- it("forwards an allowed path with the installation that owns the channel", async () => {
- const { frame } = connectedBridge({ installationId: "installation-1", issueId: "issue-1" });
- frame.port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });
+ it("forwards an allowed request with the installation that owns the channel", async () => {
+ const { port } = connectedBridge({ installationId: "installation-1", bridgeToken: TOKEN, issueId: "issue-1" });
+ port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });
- await vi.waitFor(() => {
- expect(mockCall).toHaveBeenCalledWith("installation-1", expect.objectContaining({
- method: "GET",
- path: "/context",
- issueId: "issue-1",
- }));
- });
+ await vi.waitFor(() => expect(mockCall).toHaveBeenCalledWith("installation-1", expect.objectContaining({
+ method: "GET",
+ path: "/context",
+ issueId: "issue-1",
+ })));
});
- it("refuses a path outside the Action API before it reaches the network", async () => {
- // A surface asking for /me or ../admin must never turn into a real request:
- // the Action API's scope checks only exist on the paths it defines.
- const { frame, posted } = connectedBridge();
- for (const path of ["/me", "/workspaces/w1/plugins", "/../admin", "/issues/i1/comments/extra"]) {
- frame.port.postMessage({ id: `bad-${path}`, kind: "action", method: "GET", path });
- }
- await vi.waitFor(() => expect(posted).toHaveLength(4));
+ it("refuses paths and methods outside the Action API before fetch", async () => {
+ const { port, posted } = connectedBridge();
+ port.postMessage({ id: "bad-path", kind: "action", method: "GET", path: "/me" });
+ port.postMessage({ id: "bad-method", kind: "action", method: "TRACE", path: "/context" });
+ await answered(port, posted);
expect(mockCall).not.toHaveBeenCalled();
- for (const response of posted as Array<{ ok: boolean; status: number }>) {
- expect(response.ok).toBe(false);
- expect(response.status).toBe(400);
- }
+ expect(posted).toContainEqual(expect.objectContaining({ id: "bad-path", ok: false, status: 400 }));
});
- it("passes the refusal status through so a surface can tell 403 from 404", async () => {
- // 403 means "the admin did not grant this scope" — a different fix for a
- // plugin author than a missing resource, so it must not be flattened.
- mockCall.mockRejectedValue(Object.assign(new Error("not granted comments:write"), { status: 403 }));
- const { frame, posted } = connectedBridge();
- frame.port.postMessage({ id: "r1", kind: "action", method: "POST", path: "/issues/i1/comments", body: {} });
+ it("passes a refusal status through to the plugin", async () => {
+ mockCall.mockRejectedValue(Object.assign(new Error("not granted"), { status: 403 }));
+ const { port, posted } = connectedBridge();
+ port.postMessage({ id: "r1", kind: "action", method: "POST", path: "/issues/i1/comments", body: {} });
await vi.waitFor(() => expect(posted).toHaveLength(1));
-
expect(posted[0]).toMatchObject({ id: "r1", ok: false, status: 403 });
});
- it("refuses a method outside the allowlist before it reaches fetch", async () => {
- const { frame, posted } = connectedBridge();
- frame.port.postMessage({ id: "r1", kind: "action", method: "TRACE", path: "/context" });
- frame.port.postMessage({ id: "r2", kind: "action", method: "get", path: "/context" });
- await answered(frame, posted);
-
- expect(mockCall).not.toHaveBeenCalled();
- expect(posted).toHaveLength(0);
- });
-
- it("ignores messages that are not bridge requests", async () => {
- const { frame, posted } = connectedBridge();
- frame.port.postMessage({ hello: "world" });
- frame.port.postMessage({ id: 7, kind: "action", method: "GET", path: "/context" });
- await answered(frame, posted);
-
- expect(mockCall).not.toHaveBeenCalled();
- expect(posted).toHaveLength(0);
- });
-
- it("clamps a resize so a surface cannot push the page out of view", async () => {
+ it("clamps resize requests", async () => {
const heights: number[] = [];
- const { frame, posted } = connectedBridge({ installationId: "installation-1", onResize: (h) => heights.push(h) });
- frame.port.postMessage({ id: "r1", kind: "ui.resize", height: 10_000_000 });
- frame.port.postMessage({ id: "r2", kind: "ui.resize", height: -5 });
- frame.port.postMessage({ id: "r3", kind: "ui.resize", height: 320 });
- await answered(frame, posted);
-
- expect(heights).toEqual([4000, 0, 320]);
+ const { port, posted } = connectedBridge({
+ installationId: "installation-1",
+ bridgeToken: TOKEN,
+ onResize: (height) => heights.push(height),
+ });
+ port.postMessage({ id: "large", kind: "ui.resize", height: 10_000_000 });
+ port.postMessage({ id: "small", kind: "ui.resize", height: -5 });
+ await answered(port, posted);
+ expect(heights).toEqual([4000, 0]);
});
- it("ignores a readiness signal from a window it does not own", () => {
- // Every sandboxed frame reports the opaque origin "null", so the window
- // reference is the only thing that distinguishes this surface from any
- // other frame on the page — including a hostile one shouting the signal.
- // Nothing to wait for: the host answers the signal on the dispatch itself.
- const bridge = createSurfaceBridge({ installationId: "installation-1" });
- let transferred = false;
- const frame = {
- contentWindow: { postMessage: () => { transferred = true; } },
- } as unknown as HTMLIFrameElement;
+ it("refuses the wrong frame, protocol, challenge, and a replay", async () => {
+ const bridge = createSurfaceBridge({ installationId: "installation-1", bridgeToken: TOKEN });
+ const frame = { contentWindow: {} } as unknown as HTMLIFrameElement;
bridge.connect(frame, {});
- announce({} as Window);
- expect(transferred).toBe(false);
+ const wrongSource = new MessageChannel();
+ const wrongVersion = new MessageChannel();
+ const wrongChallenge = new MessageChannel();
+ connectMessage({} as Window, wrongSource.port1);
+ connectMessage(frame.contentWindow, wrongVersion.port1, TOKEN, 1);
+ connectMessage(frame.contentWindow, wrongChallenge.port1, "wrong");
+
+ const accepted = new MessageChannel();
+ const replay = new MessageChannel();
+ const acceptedMessages: unknown[] = [];
+ const replayMessages: unknown[] = [];
+ accepted.port2.onmessage = (event) => acceptedMessages.push(event.data);
+ replay.port2.onmessage = (event) => replayMessages.push(event.data);
+ accepted.port2.start();
+ replay.port2.start();
+ connectMessage(frame.contentWindow, accepted.port1);
+ connectMessage(frame.contentWindow, replay.port1);
+ accepted.port2.postMessage({ id: "real", kind: "action", method: "GET", path: "/context" });
+ replay.port2.postMessage({ id: "replay", kind: "action", method: "GET", path: "/context" });
+
+ await vi.waitFor(() => expect(mockCall).toHaveBeenCalledTimes(1));
+ expect(mockCall).toHaveBeenCalledWith("installation-1", expect.objectContaining({ path: "/context" }));
+ expect(replayMessages).toHaveLength(0);
+ expect(acceptedMessages).toContainEqual(expect.objectContaining({ kind: "theme" }));
bridge.close();
});
it("stops answering once closed", async () => {
- // Answer one request first. Without that, a bridge that answered nothing at
- // all — closed or not — would pass this test.
- const { bridge, frame } = connectedBridge();
- frame.port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });
+ const { bridge, port } = connectedBridge();
+ port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });
await vi.waitFor(() => expect(mockCall).toHaveBeenCalledTimes(1));
-
bridge.close();
- frame.port.postMessage({ id: "r2", kind: "action", method: "GET", path: "/context" });
+ port.postMessage({ id: "r2", kind: "action", method: "GET", path: "/context" });
await portDrain();
-
expect(mockCall).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/views/plugins/surface-bridge.ts b/packages/views/plugins/surface-bridge.ts
index dd0d4f2303..b88a946581 100644
--- a/packages/views/plugins/surface-bridge.ts
+++ b/packages/views/plugins/surface-bridge.ts
@@ -7,17 +7,13 @@ import { api } from "@multica/core/api";
* session and returns the result. The plugin holds no credential, so this is
* the only path from a surface into Multica.
*
- * Identity is bound by the MessagePort, not by `event.origin`. A sandboxed
- * frame without `allow-same-origin` has the opaque origin "null" — every
- * surface would present the same string, so comparing it would authenticate
- * nothing. Instead the host creates one channel per iframe, transfers one end
- * in, and only ever listens on the other; which plugin sent a message is
- * answered by which channel it arrived on.
+ * Identity is bound by three things together: the expected outer frame window,
+ * a single-use launch challenge, and the guest-created MessagePort. Origin is
+ * not useful for the inner plugin frame because its sandbox makes it opaque.
*/
-const BRIDGE_PROTOCOL_VERSION = 1;
-const BRIDGE_INIT_MESSAGE = "multica:plugin-bridge-init";
-const BRIDGE_READY_MESSAGE = "multica:plugin-surface-ready";
+const BRIDGE_PROTOCOL_VERSION = 2;
+const BRIDGE_CONNECT_MESSAGE = "multica:plugin-bridge-connect";
type BridgeMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
@@ -63,6 +59,8 @@ function isBridgeRequest(value: unknown): value is BridgeRequest {
export interface SurfaceBridgeOptions {
installationId: string;
+ /** Single-use proof returned with this exact hosted document URL. */
+ bridgeToken: string;
/** Mounted-on issue, forwarded to /context so the surface knows where it is. */
issueId?: string;
onResize?: (height: number) => void;
@@ -70,12 +68,9 @@ export interface SurfaceBridgeOptions {
export interface SurfaceBridge {
/**
- * Waits for the surface to announce itself, then hands it a port.
- *
- * Driven by the guest rather than by the iframe's load event: a srcdoc frame
- * can finish loading before React attaches `onLoad`, so a load-driven host
- * either never fires or sends the port before the guest is listening. Both
- * failures look the same from outside — a blank panel.
+ * Arms the listener before the trusted outer document is assigned. The guest
+ * creates the channel; the host accepts its port only once all launch proofs
+ * match.
*/
connect(frame: HTMLIFrameElement, theme: Record<string, string>): void;
/** Pushes a theme change to an already-connected frame. */
@@ -84,9 +79,10 @@ export interface SurfaceBridge {
}
export function createSurfaceBridge(options: SurfaceBridgeOptions): SurfaceBridge {
- let channel: MessageChannel | null = null;
+ let port: MessagePort | null = null;
let closed = false;
- const readyListeners: Array<(event: MessageEvent) => void> = [];
+ let connected = false;
+ const connectListeners: Array<(event: MessageEvent) => void> = [];
const handle = async (request: BridgeRequest, port: MessagePort) => {
if (request.kind === "ui.resize") {
@@ -121,43 +117,37 @@ export function createSurfaceBridge(options: SurfaceBridgeOptions): SurfaceBridg
return {
connect(frame, theme) {
if (closed) return;
- const onReady = (event: MessageEvent) => {
- if ((event.data as { type?: string } | null)?.type !== BRIDGE_READY_MESSAGE) return;
- // The only check that matters: the signal came from the window this
- // bridge owns. Origin cannot be used — every sandboxed frame reports
- // "null" — so identity is the window reference plus, from here on, the
- // private port.
+ const onConnect = (event: MessageEvent) => {
+ const data = event.data as { type?: string; version?: number; challenge?: string } | null;
+ if (data?.type !== BRIDGE_CONNECT_MESSAGE) return;
+ // The outer frame is trusted host code. It forwards an inner port only
+ // after its own source, protocol and challenge checks have passed.
if (!frame.contentWindow || event.source !== frame.contentWindow) return;
- window.removeEventListener("message", onReady);
- if (closed) return;
-
- channel?.port1.close();
- channel = new MessageChannel();
- channel.port1.onmessage = (portEvent) => {
+ if (data.version !== BRIDGE_PROTOCOL_VERSION || data.challenge !== options.bridgeToken) return;
+ const guestPort = event.ports?.[0];
+ if (!guestPort || closed || connected) return;
+
+ connected = true;
+ window.removeEventListener("message", onConnect);
+ port = guestPort;
+ port.onmessage = (portEvent) => {
if (!isBridgeRequest(portEvent.data)) return;
- void handle(portEvent.data, channel!.port1);
+ void handle(portEvent.data, guestPort);
};
- channel.port1.start();
- // targetOrigin "*" is required, not lax: an opaque origin can never
- // match a string. The message carries no secret, and the port is
- // transferred into this specific contentWindow.
- frame.contentWindow.postMessage(
- { type: BRIDGE_INIT_MESSAGE, version: BRIDGE_PROTOCOL_VERSION, theme },
- "*",
- [channel.port2],
- );
+ port.start();
+ port.postMessage({ kind: "theme", theme });
};
- readyListeners.push(onReady);
- window.addEventListener("message", onReady);
+ connectListeners.push(onConnect);
+ window.addEventListener("message", onConnect);
},
pushTheme(theme) {
- channel?.port1.postMessage({ kind: "theme", theme });
+ port?.postMessage({ kind: "theme", theme });
},
close() {
closed = true;
- for (const listener of readyListeners.splice(0)) window.removeEventListener("message", listener);
- channel?.port1.close();
- channel = null;
+ for (const listener of connectListeners.splice(0)) window.removeEventListener("message", listener);
+ port?.close();
+ port = null;
},
};
}
diff --git a/packages/views/plugins/surface-document.test.ts b/packages/views/plugins/surface-document.test.ts
index e58911f162..9edd39f933 100644
--- a/packages/views/plugins/surface-document.test.ts
+++ b/packages/views/plugins/surface-document.test.ts
@@ -1,130 +1,65 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import {
- buildSurfaceCSP,
- buildSurfaceDocument,
- surfaceConnectSources,
-} from "./surface-document";
+import { buildSurfaceFrameDocument } from "./surface-document";
-// The document the host generates IS the sandbox policy. These pin the parts a
-// reviewer cannot verify by reading the component: what a surface is allowed to
-// talk to, and that nothing about the plugin can escape into the markup.
+describe("plugin surface frame document", () => {
+ it("allows the nested frame to navigate only to the hosted content origin", () => {
+ const document = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque-token",
+ bridgeToken: "one-use-proof",
+ });
-describe("surface connect-src", () => {
- it("derives the allowlist from granted net: scopes only", () => {
- expect(surfaceConnectSources(["issues:read", "net:example.com", "storage:user", "net:api.example.com"]))
- .toEqual(["https://example.com", "https://api.example.com"]);
+ expect(document).toContain("frame-src https://plugin-content.example.test");
+ expect(document).not.toContain("frame-src https:;");
+ expect(document).toContain("connect-src 'none'");
});
- it("names no remote origin when no net: scope was granted", () => {
- // While the code loaded from the author's server, script-src had to name
- // that origin, so a surface could always reach its author back. The code is
- // ours to serve now, so this policy names no remote origin of any kind.
- //
- // That bounds what the DOCUMENT can request. It is not the same claim as
- // "a surface cannot reach its author": the sandbox still permits the frame
- // to navigate itself, which no CSP directive covers. See the known gap in
- // surface-document.ts.
- const csp = buildSurfaceCSP(["issues:read"]);
- expect(csp).toContain("connect-src 'none'");
- expect(csp).toContain("script-src 'unsafe-inline'");
- expect(csp).not.toContain("https://");
- });
+ it("keeps the untrusted inner frame opaque", () => {
+ const document = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque-token",
+ bridgeToken: "one-use-proof",
+ });
- it("keeps the cheapest side channels closed", () => {
- // <img> and webfont URLs are the two exfiltration paths that need no
- // scripting at all.
- const csp = buildSurfaceCSP(["net:example.com"]);
- expect(csp).toContain("img-src data: blob:");
- expect(csp).toContain("font-src data:");
+ expect(document).toContain('child.setAttribute("sandbox", "allow-scripts")');
+ expect(document).not.toContain('child.setAttribute("sandbox", "allow-scripts allow-same-origin")');
});
- it("allows only the domains that were granted", () => {
- const csp = buildSurfaceCSP(["net:example.com"]);
- expect(csp).toContain("connect-src https://example.com");
- expect(csp).not.toContain("https://cdn.example.com");
- });
+ it("checks source, protocol, challenge and one-time use before relaying a guest port", () => {
+ const document = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque-token",
+ bridgeToken: "one-use-proof",
+ });
- it("denies everything by default and allows no plugin-controlled framing", () => {
- const csp = buildSurfaceCSP([]);
- expect(csp).toContain("default-src 'none'");
- // frame-ancestors is intentionally absent — <meta> ignores it, and the
- // sandbox already denies this document the ability to frame anything.
- expect(csp).not.toContain("frame-ancestors");
- expect(csp).toContain("base-uri 'none'");
- expect(csp).toContain("form-action 'none'");
+ expect(document).toContain("event.source !== child.contentWindow");
+ expect(document).toContain("data.version !== 2");
+ expect(document).toContain("data.challenge !== config.bridgeToken");
+ expect(document).toContain('state !== "launching"');
+ expect(document).toContain('state = "connected"');
});
-});
-describe("surface document", () => {
- it("puts the policy before anything it governs", () => {
- const document = buildSurfaceDocument({
- code: "console.log('hi');",
- grantedScopes: ["net:example.com"],
- theme: {},
+ it("uses terminal state instead of guessing when CSP reports navigation", () => {
+ const document = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/opaque-token",
+ bridgeToken: "one-use-proof",
});
- const cspIndex = document.indexOf("Content-Security-Policy");
- const scriptIndex = document.indexOf("<script");
- expect(cspIndex).toBeGreaterThan(-1);
- expect(cspIndex).toBeLessThan(scriptIndex);
- });
- it("fetches nothing to render a surface", () => {
- // The point of hosting the artifact: rendering the panel issues no request,
- // so a well-behaved plugin's author learns nothing about who opened it.
- const document = buildSurfaceDocument({ code: "console.log('hi');", grantedScopes: [], theme: {} });
- expect(document).not.toContain("<script src=");
+ expect(document).toContain("securitypolicyviolation");
+ expect(document).toContain("multica:plugin-surface-navigation-blocked");
+ expect(document).toContain('if (state === "terminal") return');
+ expect(document).not.toContain("setTimeout(");
});
- it("does not mistake an ordinary host reload for hostile navigation", () => {
- // pagehide fires for both self-navigation and a host-authored srcDoc reload,
- // so it cannot be used as a security signal. The real Chromium regression
- // test reloads the document; this pins that no beacon is generated at all.
- const document = buildSurfaceDocument({ code: "console.log('hi');", grantedScopes: [], theme: {} });
- expect(document).not.toContain("pagehide");
- expect(document).not.toContain("multica:plugin-surface-navigated");
- });
-
- it("installs browser error listeners before plugin code runs", () => {
- const document = buildSurfaceDocument({ code: "throw new Error('boom');", grantedScopes: [], theme: {} });
- const executeIndex = document.indexOf("document.body.appendChild(element)");
- expect(document.indexOf('addEventListener("error"')).toBeLessThan(executeIndex);
- expect(document.indexOf('addEventListener("unhandledrejection"')).toBeLessThan(executeIndex);
- expect(document).toContain("multica:plugin-surface-error-ack");
- });
+ it("never interpolates the launch URL or proof into executable source", () => {
+ const document = buildSurfaceFrameDocument({
+ url: "https://plugin-content.example.test/plugin-surfaces/%3C/script%3E",
+ bridgeToken: `proof</script><script>alert(1)</script>`,
+ });
- it("carries code that would otherwise close the script element early", () => {
- // A surface that contains the literal end tag inside a string is ordinary
- // JavaScript. Base64 is what makes it impossible for the HTML tokenizer to
- // react to a plugin's source at all.
- const code = `const html = "</script><script>alert(1)</script>";`;
- const document = buildSurfaceDocument({ code, grantedScopes: [], theme: {} });
expect(document).not.toContain("alert(1)");
- expect(document).not.toContain('"</script>');
-
- const encoded = /id="multica-surface-code">([^<]*)</.exec(document)?.[1] ?? "";
- expect(encoded).not.toBe("");
- expect(new TextDecoder().decode(Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0))))
- .toBe(code);
+ expect(document).not.toContain("proof</script>");
});
- it("round-trips non-ASCII source", () => {
- // Encoding through latin1 would corrupt this silently, and the surface
- // would fail at runtime with a message pointing nowhere near the cause.
- const code = `const 消息 = "部署已完成 ✅";`;
- const document = buildSurfaceDocument({ code, grantedScopes: [], theme: {} });
- const encoded = /id="multica-surface-code">([^<]*)</.exec(document)?.[1] ?? "";
- expect(new TextDecoder().decode(Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0))))
- .toBe(code);
- });
-
- it("forwards theme tokens as custom properties so a surface looks native untouched", () => {
- const document = buildSurfaceDocument({
- code: "console.log('hi');",
- grantedScopes: [],
- theme: { "--background": "oklch(1 0 0)", "--radius": "6px" },
- });
- expect(document).toContain("--background: oklch(1 0 0);");
- expect(document).toContain("--radius: 6px;");
+ it("rejects a non-HTTP launch", () => {
+ expect(() => buildSurfaceFrameDocument({ url: "javascript:alert(1)", bridgeToken: "proof" })).toThrow();
});
});
diff --git a/packages/views/plugins/surface-document.ts b/packages/views/plugins/surface-document.ts
index 1cf8881cce..16861061b4 100644
--- a/packages/views/plugins/surface-document.ts
+++ b/packages/views/plugins/surface-document.ts
@@ -1,26 +1,4 @@
-/**
- * The host generates the document a surface runs in, and now supplies the code
- * that runs in it. That is the point: CSP is a response-header/meta decision
- * made by whoever emits the document, so if the plugin author's server emitted
- * it, the `net:` scopes the admin approved would be a claim we never check. Here
- * they become a `connect-src` the browser enforces.
- *
- * The script is INLINED rather than loaded from an origin. When it came from
- * the author's server, `script-src` had to name that origin, which meant a
- * surface could always reach its author back — and it meant every panel open
- * told the author who was reading which issue. Now Multica stores the published
- * artifact and hands it to the frame, so the policy names no remote script
- * origin at all.
- *
- * The frame is mounted with `sandbox="allow-scripts"` and NOT
- * `allow-same-origin` — the pairing the HTML spec calls out as defeating the
- * sandbox. That gives the document an opaque origin: no cookies, no
- * localStorage, no access to the embedder, and no shared storage between two
- * plugins. It is the same model `packages/views/editor/code-block-iframe.tsx`
- * already uses for untrusted HTML.
- */
-
-/** Design tokens forwarded into the frame so a surface looks native for free. */
+/** Design tokens forwarded over the bridge so a surface looks native. */
export const SURFACE_THEME_TOKENS = [
"--background",
"--foreground",
@@ -35,6 +13,9 @@ export const SURFACE_THEME_TOKENS = [
"--text-body",
] as const;
+export const SURFACE_BRIDGE_CONNECT_MESSAGE = "multica:plugin-bridge-connect";
+export const SURFACE_BRIDGE_PROTOCOL_VERSION = 2;
+
export function readThemeTokens(element: Element | null): Record<string, string> {
if (!element || typeof getComputedStyle !== "function") return {};
const computed = getComputedStyle(element);
@@ -50,101 +31,55 @@ function escapeAttribute(value: string): string {
return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
-/**
- * Builds the `connect-src` list from the granted scopes only — never from the
- * manifest the source URL serves today. `net:` is an exact host by contract, so
- * a plugin that needs a subdomain declares it.
- */
-export function surfaceConnectSources(grantedScopes: string[]): string[] {
- return grantedScopes
- .filter((scope) => scope.startsWith("net:"))
- .map((scope) => `https://${scope.slice("net:".length)}`);
-}
-
-export function buildSurfaceCSP(grantedScopes: string[]): string {
- const connect = surfaceConnectSources(grantedScopes);
- return [
- "default-src 'none'",
- // Inline only, and no remote origin at all. The surface's code is supplied
- // by us, so the generated document has nothing left for `script-src` to
- // fetch. Under the previous model the author's own origin was always in
- // this list.
- "script-src 'unsafe-inline'",
- "style-src 'unsafe-inline'",
- // Inline data only. An <img> or webfont URL is the cheapest possible side
- // channel, and a surface that needs artwork inlines it.
- "img-src data: blob:",
- "font-src data:",
- // With no net: scope, connection APIs in the generated document cannot
- // reach an origin. Self-navigation is a separate sandbox gap documented
- // below and tracked outside this change.
- `connect-src ${connect.length > 0 ? connect.join(" ") : "'none'"}`,
- // A sandboxed frame cannot navigate the top level anyway; saying so keeps
- // the policy honest if the sandbox attribute is ever loosened.
- "form-action 'none'",
- "base-uri 'none'",
- // frame-ancestors is deliberately absent: it is ignored when delivered via
- // <meta>, and the browser logs a warning for it. Nothing is lost — the
- // sandbox already denies this document the ability to frame anything.
- ].join("; ");
-}
-
-export interface SurfaceDocumentInput {
- /** The surface's entry script, as published. */
- code: string;
- grantedScopes: string[];
- theme: Record<string, string>;
-}
-
-/**
- * Encodes the surface's code so it can be carried inside an HTML document.
- *
- * Base64 rather than escaping `</script`: the alphabet cannot contain anything
- * the HTML tokenizer reacts to, so there is no sequence in a plugin's source
- * that can end the script element early or shift the parser into another state.
- * Escaping works too, but it is a rule about JavaScript syntax enforced by a
- * string replace, and getting it subtly wrong looks like a plugin bug.
- */
-function encodeSurfaceCode(code: string): string {
- const bytes = new TextEncoder().encode(code);
+function encodeUTF8(value: string): string {
+ const bytes = new TextEncoder().encode(value);
let binary = "";
- // Chunked: String.fromCharCode(...bytes) blows the argument limit somewhere
- // around a hundred kilobytes, which a real surface reaches.
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return btoa(binary);
}
+export interface SurfaceFrameDocumentInput {
+ /** Short-lived URL on Multica's dedicated, cookie-free content origin. */
+ url: string;
+ /** Single-use proof embedded in both trusted documents, never plugin code. */
+ bridgeToken: string;
+}
+
/**
- * The srcdoc a surface iframe renders.
+ * Builds the trusted outer frame around one untrusted plugin document.
*
- * The plugin's code arrives as base64 in a non-executable element and is
- * activated by a small bootstrap. Everything executable is inline, and rendering
- * this document fetches nothing.
+ * The outer frame exists so its `frame-src` applies to only this plugin. A
+ * page-wide policy would also have to allow every attachment preview origin;
+ * that wider list would let a hostile surface navigate to those origins. Here
+ * the only network navigation an inner frame may make is back to the exact
+ * Multica content origin that served it.
*
- * KNOWN GAP — a sandboxed frame may navigate ITSELF. `allow-scripts` without
- * `allow-top-navigation` stops a surface navigating the top level or a sibling,
- * but the HTML sandbox deliberately permits `_self`, and no shipped CSP
- * directive covers it (`navigate-to` was dropped from CSP3, and `connect-src` /
- * `form-action` govern other things). So a HOSTILE artifact can still run
- * `location.replace("https://author.example/live.html")`, which reaches the
- * author's server once and replaces this document with one whose CSP we do not
- * write. Closing it needs either an embedder `frame-src` policy or a handshake
- * the navigated document cannot complete. Tracked separately; do not describe
- * a surface as unable to reach its author until that lands. In particular, do
- * not use lifecycle events from this document as a security signal: a normal
- * host-driven `srcDoc` reload fires the same events.
+ * The outer frame is host-authored and same-origin with the app. The INNER
+ * frame is still `sandbox="allow-scripts"` without `allow-same-origin`, so two
+ * plugins receive distinct opaque origins and cannot inspect each other.
*/
-export function buildSurfaceDocument({ code, grantedScopes, theme }: SurfaceDocumentInput): string {
- const csp = buildSurfaceCSP(grantedScopes);
- const themeCss = Object.entries(theme)
- .map(([name, value]) => `${name}: ${value};`)
- .join(" ");
+export function buildSurfaceFrameDocument({ url, bridgeToken }: SurfaceFrameDocumentInput): string {
+ const parsed = new URL(url);
+ if ((parsed.protocol !== "https:" && parsed.protocol !== "http:") || !bridgeToken) {
+ throw new Error("invalid plugin surface launch");
+ }
+
+ const config = encodeUTF8(JSON.stringify({ url: parsed.toString(), bridgeToken }));
+ const csp = [
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ `frame-src ${parsed.origin}`,
+ "connect-src 'none'",
+ "img-src 'none'",
+ "font-src 'none'",
+ "object-src 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ ].join("; ");
- // The meta CSP must precede anything it governs, so it is the first child of
- // <head>. Note srcdoc documents also inherit the embedder's policy — this
- // narrows, it cannot widen.
return `<!doctype html>
<html>
<head>
@@ -152,67 +87,68 @@ export function buildSurfaceDocument({ code, grantedScopes, theme }: SurfaceDocu
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
-:root { ${themeCss} color-scheme: light dark; }
-* { box-sizing: border-box; }
-html, body { margin: 0; padding: 0; }
-body {
- background: var(--background, transparent);
- color: var(--foreground, inherit);
- font: 400 var(--text-body, 14px)/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
-}
+html, body, #multica-plugin-root, iframe { width: 100%; height: 100%; margin: 0; padding: 0; border: 0; }
+body { overflow: hidden; background: transparent; }
</style>
</head>
<body>
-<div id="root"></div>
-<script type="text/plain" id="multica-surface-code">${encodeSurfaceCode(code)}</script>
+<div id="multica-plugin-root"></div>
<script>
(function () {
- var errorReportAttempts = 0;
- var errorReportTimer = null;
+ var encoded = ${JSON.stringify(config)};
+ var binary = atob(encoded);
+ var bytes = new Uint8Array(binary.length);
+ for (var index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
+ var config = JSON.parse(new TextDecoder().decode(bytes));
+ var child = document.createElement("iframe");
+ child.title = "Plugin content";
+ child.setAttribute("sandbox", "allow-scripts");
- function emitSurfaceError() {
- parent.postMessage({ type: 'multica:plugin-surface-error' }, '*');
- errorReportAttempts++;
- if (errorReportAttempts >= 50 && errorReportTimer !== null) {
- clearInterval(errorReportTimer);
- errorReportTimer = null;
- }
- }
+ var state = "launching";
+ var loadCount = 0;
- function reportSurfaceError() {
- if (errorReportAttempts > 0) return;
- emitSurfaceError();
- if (errorReportAttempts < 50) errorReportTimer = setInterval(emitSurfaceError, 120);
+ function stopSurface(type) {
+ if (state === "terminal") return;
+ state = "terminal";
+ // After connection the host owns the transferred port; this terminal
+ // signal makes it close the bridge and unmount this wrapper.
+ parent.postMessage({ type: type }, "*");
}
- // A srcdoc document may execute before the host component's effect attaches
- // its listener. Repeat a failure until the host acknowledges it, bounded to
- // the same six-second window as the SDK bridge handshake.
- window.addEventListener("message", function (event) {
- if (event.source !== parent) return;
- if (!event.data || event.data.type !== 'multica:plugin-surface-error-ack') return;
- errorReportAttempts = 50;
- if (errorReportTimer !== null) clearInterval(errorReportTimer);
- errorReportTimer = null;
+ document.addEventListener("securitypolicyviolation", function (event) {
+ if (event.effectiveDirective === "frame-src" || event.effectiveDirective === "child-src") {
+ stopSurface("multica:plugin-surface-navigation-blocked");
+ }
});
- // Installed before plugin code executes. Dynamically appending an inline
- // script does not rethrow its syntax/runtime errors from appendChild; the
- // browser reports them through these global events instead.
- window.addEventListener("error", reportSurfaceError);
- window.addEventListener("unhandledrejection", reportSurfaceError);
+ child.addEventListener("load", function () {
+ loadCount += 1;
+ if (loadCount > 1) stopSurface("multica:plugin-surface-navigated");
+ });
- try {
- var encoded = document.getElementById("multica-surface-code").textContent;
- var binary = atob(encoded);
- var bytes = new Uint8Array(binary.length);
- for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
- var element = document.createElement("script");
- element.textContent = new TextDecoder().decode(bytes);
- document.body.appendChild(element);
- } catch (error) {
- reportSurfaceError();
- }
+ window.addEventListener("message", function (event) {
+ if (!child.contentWindow || event.source !== child.contentWindow) return;
+ var data = event.data || {};
+ if (data.type === "multica:plugin-surface-error" || data.type === "multica:plugin-surface-navigated") {
+ stopSurface(data.type);
+ return;
+ }
+ if (data.type !== ${JSON.stringify(SURFACE_BRIDGE_CONNECT_MESSAGE)} ||
+ data.version !== ${SURFACE_BRIDGE_PROTOCOL_VERSION} ||
+ data.challenge !== config.bridgeToken || state !== "launching" || !event.ports[0]) return;
+
+ state = "connected";
+ parent.postMessage({
+ type: ${JSON.stringify(SURFACE_BRIDGE_CONNECT_MESSAGE)},
+ version: ${SURFACE_BRIDGE_PROTOCOL_VERSION},
+ challenge: config.bridgeToken
+ }, "*", [event.ports[0]]);
+ config.bridgeToken = "";
+ });
+
+ child.src = config.url;
+ config.url = "";
+ document.getElementById("multica-plugin-root").appendChild(child);
})();
</script>
</body>
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d66beafd5e..8486c8e835 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -344,12 +344,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
DisableWorkspaceCreation: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",
VCSIntegrationEnabled: os.Getenv("MULTICA_VCS_INTEGRATION_ENABLED") == "true",
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),
+ AppURL: appURLFromEnv(),
TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),
CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),
AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
AttachmentFrameAncestors: origins,
+ PluginSurfaceOrigin: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_SURFACE_ORIGIN")), "/"),
LLMAPIKey: strings.TrimSpace(os.Getenv("MULTICA_LLM_API_KEY")),
LLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),
LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),
@@ -1083,6 +1085,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// is derived from this rather than stored, so no row holds a usable
// one.
h.PluginService.DeploymentKey = pluginKey
+ h.PluginSurfaceTokens, err = handler.NewPluginSurfaceTokenBox(pluginKey)
+ if err != nil {
+ slog.Error("plugins: surface token key derivation failed; surfaces disabled", "error", err)
+ }
slog.Info("Plugin secret encryption enabled")
}
} else {
@@ -1163,6 +1169,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Use(opts.HTTPMetrics.Middleware)
}
r.Use(chimw.Recoverer)
+ r.Use(h.PluginSurfaceHostBoundary)
r.Use(middleware.ContentSecurityPolicy)
// Share allowed origins with WebSocket origin checker.
@@ -1242,6 +1249,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// #6024).
r.Get("/api/avatars/{sig}/*", h.ServeAvatar)
+ // Hosted plugin documents are capability-authenticated and intentionally
+ // outside the session middleware: the configured content origin must stay
+ // cookie-free. The encrypted path token binds the installation, immutable
+ // version, surface and one bridge challenge.
+ r.Get("/plugin-surfaces/{token}", h.ServePluginSurface)
+
// Auth (public) — per-IP rate limiting.
if rdb == nil {
slog.Warn("auth rate limiting disabled: REDIS_URL not configured")
@@ -1470,10 +1483,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// see what is mounted in their workspace and which scopes
// it holds; install / configure / remove stay admin-only.
r.Get("/plugins", h.ListPlugins)
- // A surface's code, read from the version the workspace
- // installed. Member-visible because opening an issue is
- // what asks for it.
- r.Get("/plugins/{installationId}/surfaces/{surfaceKey}/script", h.GetPluginSurfaceScript)
+ // One short-lived hosted surface launch. Member-visible
+ // because opening an issue is what asks for it; executable
+ // bytes stay off the authenticated app/API origin.
+ r.Get("/plugins/{installationId}/surfaces/{surfaceKey}/launch", h.GetPluginSurfaceLaunch)
})
// Admin-level access
r.Group(func(r chi.Router) {
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index fb678d6eb6..4b8dea97bf 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -95,6 +95,10 @@ type Config struct {
// the server into minting webhook URLs pointing at an attacker-controlled
// host.
PublicURL string
+ // AppURL is the browser application's canonical origin, resolved from
+ // MULTICA_APP_URL (falling back to FRONTEND_ORIGIN). It is kept separate
+ // from PublicURL because split app/API deployments use different origins.
+ AppURL string
// TrustedProxies are CIDRs whose source IP we trust to set
// X-Forwarded-For / X-Real-IP. Empty means "trust nothing": the rate
// limiter uses r.RemoteAddr exclusively. Populated via the
@@ -115,6 +119,10 @@ type Config struct {
// frontend/CORS origin allowlist so split app/api self-hosted deployments
// can frame API-hosted PDFs without allowing arbitrary third-party frames.
AttachmentFrameAncestors []string
+ // PluginSurfaceOrigin is the dedicated, cookie-free browser origin that
+ // routes /plugin-surfaces/* back to this server. It must not be the app/API
+ // origin: the route serves stored third-party JavaScript as HTML.
+ PluginSurfaceOrigin string
// LLM* configure the basic LLM API layer (MUL-4238). They back the
// server-internal LLM helpers in pkg/llm (e.g. chat title generation).
// The generic OpenAI-compatible passthrough endpoints were removed in
@@ -361,6 +369,9 @@ type Handler struct {
// error rather than silently storing plaintext. Wired in
// cmd/server/router.go after New.
VCSSecretBox *secretbox.Box
+ // PluginSurfaceTokens seal short-lived launch claims. Nil disables surface
+ // launches; wired from a domain-separated MULTICA_PLUGIN_SECRET_KEY at boot.
+ PluginSurfaceTokens *secretbox.Box
// PRRefresh drives the GitHub API snapshot pipeline for PR cards (MUL-5265):
// webhook / page-visit / TTL triggers → authenticated GraphQL fetch →
// head-SHA-guarded atomic snapshot write. Always non-nil, but inert (every
diff --git a/server/internal/handler/plugin_package.go b/server/internal/handler/plugin_package.go
index 69e1cd12a0..2e647ec78e 100644
--- a/server/internal/handler/plugin_package.go
+++ b/server/internal/handler/plugin_package.go
@@ -149,49 +149,3 @@ func (h *Handler) DeletePluginPackage(w http.ResponseWriter, r *http.Request) {
}
w.WriteHeader(http.StatusNoContent)
}
-
-// GetPluginSurfaceScript — GET /api/workspaces/{id}/plugins/{installationId}/surfaces/{surfaceKey}/script
-//
-// The code one surface runs, read from the installed version's stored files. The
-// host inlines it into the sandboxed document it generates, which is what lets
-// that document's CSP name no third-party script origin at all: a surface can no
-// longer reach its author's server just by existing.
-//
-// Member-visible, because opening an issue is what triggers it. It returns code
-// the workspace already consented to install, to a member who can already see
-// that the Plugin is mounted.
-func (h *Handler) GetPluginSurfaceScript(w http.ResponseWriter, r *http.Request) {
- if !h.requirePluginsV1(w, r) {
- return
- }
- workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")
- if !ok {
- return
- }
- installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, chi.URLParam(r, "installationId"))
- if err != nil {
- writePluginError(w, err, "failed to load the Plugin")
- return
- }
- if !installation.Enabled {
- // A disabled installation renders nothing. Serving its code anyway would
- // make "disabled" a UI state rather than a decision.
- writeError(w, http.StatusForbidden, "this Plugin is disabled")
- return
- }
- script, err := h.PluginService.SurfaceScript(r.Context(), installation, chi.URLParam(r, "surfaceKey"))
- if err != nil {
- writePluginError(w, err, "failed to load the Plugin surface")
- return
- }
- // The bytes are immutable for the life of the version, and the surface key is
- // part of the URL, so this is safely cacheable per client. Private: it is
- // workspace content behind a session.
- w.Header().Set("Cache-Control", "private, max-age=300")
- w.Header().Set("ETag", `"`+script.Digest+`"`)
- if strings.Contains(r.Header.Get("If-None-Match"), script.Digest) {
- w.WriteHeader(http.StatusNotModified)
- return
- }
- writeJSON(w, http.StatusOK, script)
-}
diff --git a/server/internal/handler/plugin_package_test.go b/server/internal/handler/plugin_package_test.go
index 2d0d189bb1..878d1c93a5 100644
--- a/server/internal/handler/plugin_package_test.go
+++ b/server/internal/handler/plugin_package_test.go
@@ -4,10 +4,12 @@ import (
"archive/zip"
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
+ "regexp"
"strings"
"testing"
@@ -121,19 +123,45 @@ func installPublishedVersion(t *testing.T, versionID string) string {
func surfaceScript(t *testing.T, installationID, surfaceKey string) (*httptest.ResponseRecorder, service.PluginSurfaceScript) {
t.Helper()
+ previousOrigin := testHandler.cfg.PluginSurfaceOrigin
+ previousTokens := testHandler.PluginSurfaceTokens
+ testHandler.cfg.PluginSurfaceOrigin = "https://plugin-content.example.test"
+ testHandler.PluginSurfaceTokens, _ = NewPluginSurfaceTokenBox(bytes.Repeat([]byte{7}, 32))
+ t.Cleanup(func() {
+ testHandler.cfg.PluginSurfaceOrigin = previousOrigin
+ testHandler.PluginSurfaceTokens = previousTokens
+ })
+
recorder := httptest.NewRecorder()
- testHandler.GetPluginSurfaceScript(recorder, pluginHandlerRequest(http.MethodGet, "/script", nil, map[string]string{
+ testHandler.GetPluginSurfaceLaunch(recorder, pluginHandlerRequest(http.MethodGet, "/launch", nil, map[string]string{
"id": testWorkspaceID,
"installationId": installationID,
"surfaceKey": surfaceKey,
}))
- var script service.PluginSurfaceScript
- if recorder.Code == http.StatusOK {
- if err := json.Unmarshal(recorder.Body.Bytes(), &script); err != nil {
- t.Fatalf("decode surface script: %v", err)
- }
+ if recorder.Code != http.StatusOK {
+ return recorder, service.PluginSurfaceScript{}
+ }
+ var launch pluginSurfaceLaunch
+ if err := json.Unmarshal(recorder.Body.Bytes(), &launch); err != nil {
+ t.Fatalf("decode surface launch: %v", err)
+ }
+ token := launch.URL[strings.LastIndex(launch.URL, "/")+1:]
+ documentRecorder := httptest.NewRecorder()
+ documentRequest := pluginHandlerRequest(http.MethodGet, "/plugin-surfaces/"+token, nil, map[string]string{"token": token})
+ documentRequest.Host = "plugin-content.example.test"
+ testHandler.ServePluginSurface(documentRecorder, documentRequest)
+ if documentRecorder.Code != http.StatusOK {
+ t.Fatalf("serve hosted surface: status=%d body=%s", documentRecorder.Code, documentRecorder.Body.String())
+ }
+ encoded := regexp.MustCompile(`id="multica-surface-code">([^<]+)</script>`).FindStringSubmatch(documentRecorder.Body.String())
+ if len(encoded) != 2 {
+ t.Fatal("hosted surface did not contain stored code")
+ }
+ code, err := base64.StdEncoding.DecodeString(encoded[1])
+ if err != nil {
+ t.Fatalf("decode hosted surface code: %v", err)
}
- return recorder, script
+ return recorder, service.PluginSurfaceScript{Code: string(code), Version: launch.Version, Digest: launch.Digest}
}
// An author with no server of their own publishes a panel plugin by upload, an
diff --git a/server/internal/handler/plugin_surface.go b/server/internal/handler/plugin_surface.go
new file mode 100644
index 0000000000..7202aff173
--- /dev/null
+++ b/server/internal/handler/plugin_surface.go
@@ -0,0 +1,362 @@
+package handler
+
+import (
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+const (
+ pluginSurfaceLaunchTTL = 2 * time.Minute
+ pluginSurfaceProtocolVersion = 2
+ pluginSurfaceConnectMessage = "multica:plugin-bridge-connect"
+ pluginSurfacePortGlobal = "__multicaPluginBridgePortV2"
+)
+
+var errInvalidPluginSurfaceOrigin = errors.New("plugin surface origin must be an absolute HTTP(S) origin without a path")
+
+type pluginSurfaceLaunchClaims struct {
+ WorkspaceID string `json:"workspace_id"`
+ InstallationID string `json:"installation_id"`
+ VersionID string `json:"version_id"`
+ SurfaceKey string `json:"surface_key"`
+ Digest string `json:"digest"`
+ Challenge string `json:"challenge"`
+ ExpiresAt int64 `json:"expires_at"`
+}
+
+type pluginSurfaceLaunch struct {
+ URL string `json:"url"`
+ BridgeToken string `json:"bridge_token"`
+ Version string `json:"version"`
+ Digest string `json:"digest"`
+}
+
+// NewPluginSurfaceTokenBox derives a separate AES-GCM key from the plugin
+// deployment key. A surface URL can never be opened as a stored config secret,
+// even though operators rotate both with one deployment setting.
+func NewPluginSurfaceTokenBox(deploymentKey []byte) (*secretbox.Box, error) {
+ if len(deploymentKey) != secretbox.KeySize {
+ return nil, secretbox.ErrInvalidKey
+ }
+ mac := hmac.New(sha256.New, deploymentKey)
+ _, _ = mac.Write([]byte("multica/plugin-surface-launch/v1"))
+ return secretbox.New(mac.Sum(nil))
+}
+
+func parsePluginSurfaceOrigin(raw string) (*url.URL, error) {
+ parsed, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || parsed.Host == "" || (parsed.Scheme != "https" && parsed.Scheme != "http") ||
+ (parsed.Path != "" && parsed.Path != "/") || parsed.RawQuery != "" || parsed.Fragment != "" || parsed.User != nil {
+ return nil, errInvalidPluginSurfaceOrigin
+ }
+ parsed.Path = ""
+ return parsed, nil
+}
+
+func (h *Handler) pluginSurfaceOriginIsDedicated(origin *url.URL) bool {
+ candidates := make([]string, 0, len(h.cfg.AttachmentFrameAncestors)+2)
+ candidates = append(candidates, h.cfg.PublicURL)
+ candidates = append(candidates, h.cfg.AppURL)
+ candidates = append(candidates, h.cfg.AttachmentFrameAncestors...)
+ for _, candidate := range candidates {
+ appOrigin, err := parsePluginSurfaceOrigin(candidate)
+ if err == nil && strings.EqualFold(appOrigin.Host, origin.Host) {
+ return false
+ }
+ }
+ return true
+}
+
+// PluginSurfaceHostBoundary turns the configured content host into a one-route
+// origin. Reusing the API process is operationally convenient; exposing its
+// login, JSON API, uploads or redirects under the plugin host is not part of
+// that bargain.
+func (h *Handler) PluginSurfaceHostBoundary(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ origin, err := parsePluginSurfaceOrigin(h.cfg.PluginSurfaceOrigin)
+ if err == nil && h.pluginSurfaceOriginIsDedicated(origin) && strings.EqualFold(r.Host, origin.Host) &&
+ !strings.HasPrefix(r.URL.Path, "/plugin-surfaces/") {
+ http.NotFound(w, r)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func randomPluginSurfaceChallenge() (string, error) {
+ value := make([]byte, 32)
+ if _, err := rand.Read(value); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(value), nil
+}
+
+func (h *Handler) mintPluginSurfaceToken(claims pluginSurfaceLaunchClaims) (string, error) {
+ if h.PluginSurfaceTokens == nil {
+ return "", errors.New("plugin surface token encryption is not configured")
+ }
+ payload, err := json.Marshal(claims)
+ if err != nil {
+ return "", fmt.Errorf("marshal plugin surface launch: %w", err)
+ }
+ sealed, err := h.PluginSurfaceTokens.Seal(payload)
+ if err != nil {
+ return "", fmt.Errorf("seal plugin surface launch: %w", err)
+ }
+ return base64.RawURLEncoding.EncodeToString(sealed), nil
+}
+
+func (h *Handler) openPluginSurfaceToken(token string) (pluginSurfaceLaunchClaims, error) {
+ if h.PluginSurfaceTokens == nil {
+ return pluginSurfaceLaunchClaims{}, errors.New("plugin surface token encryption is not configured")
+ }
+ sealed, err := base64.RawURLEncoding.DecodeString(token)
+ if err != nil {
+ return pluginSurfaceLaunchClaims{}, errors.New("invalid plugin surface token encoding")
+ }
+ payload, err := h.PluginSurfaceTokens.Open(sealed)
+ if err != nil {
+ return pluginSurfaceLaunchClaims{}, errors.New("invalid plugin surface token")
+ }
+ var claims pluginSurfaceLaunchClaims
+ if err := json.Unmarshal(payload, &claims); err != nil {
+ return pluginSurfaceLaunchClaims{}, errors.New("invalid plugin surface claims")
+ }
+ if claims.WorkspaceID == "" || claims.InstallationID == "" || claims.VersionID == "" ||
+ claims.SurfaceKey == "" || claims.Digest == "" || claims.Challenge == "" ||
+ claims.ExpiresAt <= time.Now().Unix() {
+ return pluginSurfaceLaunchClaims{}, errors.New("expired or incomplete plugin surface claims")
+ }
+ return claims, nil
+}
+
+// GetPluginSurfaceLaunch returns no executable bytes. It mints one short-lived
+// hosted URL plus the proof that exact document must present to the exact frame
+// which requested it.
+func (h *Handler) GetPluginSurfaceLaunch(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ origin, err := parsePluginSurfaceOrigin(h.cfg.PluginSurfaceOrigin)
+ if err != nil || h.PluginSurfaceTokens == nil {
+ writeError(w, http.StatusServiceUnavailable, "Plugin surfaces are unavailable: MULTICA_PLUGIN_SURFACE_ORIGIN and MULTICA_PLUGIN_SECRET_KEY must be configured")
+ return
+ }
+ if !h.pluginSurfaceOriginIsDedicated(origin) {
+ writeError(w, http.StatusServiceUnavailable, "Plugin surfaces require a dedicated content origin separate from the app and API origins")
+ return
+ }
+
+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, chi.URLParam(r, "installationId"))
+ if err != nil {
+ writePluginError(w, err, "failed to load the Plugin")
+ return
+ }
+ if !installation.Enabled {
+ writeError(w, http.StatusForbidden, "this Plugin is disabled")
+ return
+ }
+ script, err := h.PluginService.SurfaceScript(r.Context(), installation, chi.URLParam(r, "surfaceKey"))
+ if err != nil {
+ writePluginError(w, err, "failed to load the Plugin surface")
+ return
+ }
+ challenge, err := randomPluginSurfaceChallenge()
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create the Plugin surface launch")
+ return
+ }
+ claims := pluginSurfaceLaunchClaims{
+ WorkspaceID: util.UUIDToString(workspaceID),
+ InstallationID: util.UUIDToString(installation.ID),
+ VersionID: util.UUIDToString(installation.PackageVersionID),
+ SurfaceKey: chi.URLParam(r, "surfaceKey"),
+ Digest: script.Digest,
+ Challenge: challenge,
+ ExpiresAt: time.Now().Add(pluginSurfaceLaunchTTL).Unix(),
+ }
+ token, err := h.mintPluginSurfaceToken(claims)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create the Plugin surface launch")
+ return
+ }
+ w.Header().Set("Cache-Control", "private, no-store")
+ writeJSON(w, http.StatusOK, pluginSurfaceLaunch{
+ URL: origin.String() + "/plugin-surfaces/" + token,
+ BridgeToken: challenge,
+ Version: script.Version,
+ Digest: script.Digest,
+ })
+}
+
+// ServePluginSurface renders stored plugin code only on the configured content
+// host. The path credential is encrypted, authenticated, short-lived and bound
+// to the installation's immutable version, so this route needs no session and
+// receives no app cookie.
+func (h *Handler) ServePluginSurface(w http.ResponseWriter, r *http.Request) {
+ origin, err := parsePluginSurfaceOrigin(h.cfg.PluginSurfaceOrigin)
+ if err != nil || !h.pluginSurfaceOriginIsDedicated(origin) || !strings.EqualFold(r.Host, origin.Host) {
+ http.NotFound(w, r)
+ return
+ }
+ // Enforce the deployment promise at the request boundary. A broad parent-
+ // domain auth cookie must make the surface fail visibly, not quietly arrive
+ // on a host that was supposed to be cookie-free.
+ if r.Header.Get("Cookie") != "" || r.Header.Get("Authorization") != "" {
+ writeError(w, http.StatusBadRequest, "the Plugin content origin must not receive app credentials")
+ return
+ }
+ claims, err := h.openPluginSurfaceToken(chi.URLParam(r, "token"))
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ workspaceID, err := util.ParseUUID(claims.WorkspaceID)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, claims.InstallationID)
+ if err != nil || !installation.Enabled || util.UUIDToString(installation.PackageVersionID) != claims.VersionID {
+ http.NotFound(w, r)
+ return
+ }
+ script, err := h.PluginService.SurfaceScript(r.Context(), installation, claims.SurfaceKey)
+ if err != nil || !hmac.Equal([]byte(script.Digest), []byte(claims.Digest)) {
+ http.NotFound(w, r)
+ return
+ }
+ var scopes []string
+ if err := json.Unmarshal(installation.GrantedScopes, &scopes); err != nil {
+ http.NotFound(w, r)
+ return
+ }
+
+ document := buildPluginSurfaceDocument(script.Code, claims.Challenge)
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "private, no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()")
+ w.Header().Set("Cross-Origin-Resource-Policy", "cross-origin")
+ w.Header().Set("Content-Security-Policy", pluginSurfaceCSP(scopes))
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(document))
+}
+
+func pluginSurfaceCSP(scopes []string) string {
+ connect := make([]string, 0)
+ for _, domain := range plugincontract.NetDomains(scopes) {
+ // Installation scopes are validated when written, but the CSP remains a
+ // boundary if a row is corrupted or restored from an older database.
+ if plugincontract.ValidateScope(plugincontract.ScopeNetPrefix+domain) != nil {
+ continue
+ }
+ connect = append(connect, "https://"+domain)
+ }
+ connectSource := "'none'"
+ if len(connect) > 0 {
+ connectSource = strings.Join(connect, " ")
+ }
+ return strings.Join([]string{
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ "img-src data: blob:",
+ "font-src data:",
+ "connect-src " + connectSource,
+ "frame-src 'none'",
+ "object-src 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ }, "; ")
+}
+
+func buildPluginSurfaceDocument(code, challenge string) string {
+ encodedCode := base64.StdEncoding.EncodeToString([]byte(code))
+ bootstrap := fmt.Sprintf(`(function () {
+ var challenge = %s;
+ var codeElement = document.getElementById("multica-surface-code");
+ var bootstrapElement = document.currentScript;
+ var failed = false;
+ function reportSurfaceError() {
+ if (failed) return;
+ failed = true;
+ parent.postMessage({ type: "multica:plugin-surface-error" }, "*");
+ }
+ window.addEventListener("error", reportSurfaceError);
+ window.addEventListener("unhandledrejection", reportSurfaceError);
+ try {
+ var channel = new MessageChannel();
+ Object.defineProperty(globalThis, %s, {
+ value: channel.port2,
+ configurable: true,
+ enumerable: false,
+ writable: false
+ });
+ window.addEventListener("pagehide", function () {
+ parent.postMessage({ type: "multica:plugin-surface-navigated" }, "*");
+ });
+ parent.postMessage({
+ type: %s,
+ version: %d,
+ challenge: challenge
+ }, "*", [channel.port1]);
+ challenge = "";
+
+ var binary = atob(codeElement.textContent || "");
+ var bytes = new Uint8Array(binary.length);
+ for (var index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
+ codeElement.remove();
+ bootstrapElement.remove();
+ var plugin = document.createElement("script");
+ plugin.textContent = new TextDecoder().decode(bytes);
+ document.body.appendChild(plugin);
+ } catch (error) {
+ reportSurfaceError();
+ }
+})();`, strconv.Quote(challenge), strconv.Quote(pluginSurfacePortGlobal), strconv.Quote(pluginSurfaceConnectMessage), pluginSurfaceProtocolVersion)
+
+ return `<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<style>
+:root { color-scheme: light dark; }
+* { box-sizing: border-box; }
+html, body { margin: 0; padding: 0; }
+body {
+ background: var(--background, transparent);
+ color: var(--foreground, inherit);
+ font: 400 var(--text-body, 14px)/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+}
+</style>
+</head>
+<body>
+<div id="root"></div>
+<script type="text/plain" id="multica-surface-code">` + html.EscapeString(encodedCode) + `</script>
+<script>` + bootstrap + `</script>
+</body>
+</html>`
+}
diff --git a/server/internal/handler/plugin_surface_test.go b/server/internal/handler/plugin_surface_test.go
new file mode 100644
index 0000000000..f2ac4aa614
--- /dev/null
+++ b/server/internal/handler/plugin_surface_test.go
@@ -0,0 +1,202 @@
+package handler
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func pluginSurfaceTokenHandler(t *testing.T) *Handler {
+ t.Helper()
+ box, err := NewPluginSurfaceTokenBox(bytes.Repeat([]byte{9}, 32))
+ if err != nil {
+ t.Fatalf("NewPluginSurfaceTokenBox: %v", err)
+ }
+ return &Handler{PluginSurfaceTokens: box}
+}
+
+func validSurfaceClaims() pluginSurfaceLaunchClaims {
+ return pluginSurfaceLaunchClaims{
+ WorkspaceID: "01900000-0000-7000-8000-000000000001",
+ InstallationID: "01900000-0000-7000-8000-000000000002",
+ VersionID: "01900000-0000-7000-8000-000000000003",
+ SurfaceKey: "panel",
+ Digest: "sha256",
+ Challenge: "bridge-proof-must-stay-opaque",
+ ExpiresAt: time.Now().Add(time.Minute).Unix(),
+ }
+}
+
+func TestPluginSurfaceTokenIsOpaqueAuthenticatedAndExpiring(t *testing.T) {
+ h := pluginSurfaceTokenHandler(t)
+ claims := validSurfaceClaims()
+ token, err := h.mintPluginSurfaceToken(claims)
+ if err != nil {
+ t.Fatalf("mintPluginSurfaceToken: %v", err)
+ }
+ if strings.Contains(token, claims.Challenge) || strings.Contains(token, claims.InstallationID) {
+ t.Fatalf("launch token exposed plaintext claims: %q", token)
+ }
+ opened, err := h.openPluginSurfaceToken(token)
+ if err != nil {
+ t.Fatalf("openPluginSurfaceToken: %v", err)
+ }
+ if opened != claims {
+ t.Fatalf("opened claims = %+v, want %+v", opened, claims)
+ }
+
+ replacement := byte('A')
+ if token[10] == replacement {
+ replacement = 'B'
+ }
+ tampered := token[:10] + string(replacement) + token[11:]
+ if _, err := h.openPluginSurfaceToken(tampered); err == nil {
+ t.Fatal("tampered launch token was accepted")
+ }
+ claims.ExpiresAt = time.Now().Add(-time.Second).Unix()
+ expired, err := h.mintPluginSurfaceToken(claims)
+ if err != nil {
+ t.Fatalf("mint expired token: %v", err)
+ }
+ if _, err := h.openPluginSurfaceToken(expired); err == nil {
+ t.Fatal("expired launch token was accepted")
+ }
+}
+
+func TestPluginSurfaceTokenKeyFailsClosed(t *testing.T) {
+ if _, err := NewPluginSurfaceTokenBox(nil); err == nil {
+ t.Fatal("empty deployment key enabled surface tokens")
+ }
+}
+
+func TestPluginSurfaceOriginMustBeOnlyAnHTTPOrigin(t *testing.T) {
+ for _, value := range []string{"", "plugin.example.test", "javascript:alert(1)", "https://plugin.example.test/path", "https://plugin.example.test?x=1"} {
+ if _, err := parsePluginSurfaceOrigin(value); err == nil {
+ t.Fatalf("parsePluginSurfaceOrigin(%q) succeeded", value)
+ }
+ }
+ parsed, err := parsePluginSurfaceOrigin("https://plugin.example.test/")
+ if err != nil || parsed.String() != "https://plugin.example.test" {
+ t.Fatalf("valid origin = %v, %v", parsed, err)
+ }
+}
+
+func TestPluginSurfaceOriginMustDifferFromEveryAppOrigin(t *testing.T) {
+ h := &Handler{cfg: Config{
+ PublicURL: "https://api.example.test",
+ AppURL: "https://canonical-app.example.test",
+ AttachmentFrameAncestors: []string{"https://app.example.test"},
+ }}
+ for _, value := range []string{"https://api.example.test", "https://canonical-app.example.test", "https://app.example.test"} {
+ origin, err := parsePluginSurfaceOrigin(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h.pluginSurfaceOriginIsDedicated(origin) {
+ t.Fatalf("%s was accepted as a dedicated content origin", value)
+ }
+ }
+ content, _ := parsePluginSurfaceOrigin("https://plugin-content.example.test")
+ if !h.pluginSurfaceOriginIsDedicated(content) {
+ t.Fatal("separate content origin was rejected")
+ }
+}
+
+func TestServePluginSurfaceRejectsConfiguredAppOriginBeforeOpeningToken(t *testing.T) {
+ h := pluginSurfaceTokenHandler(t)
+ h.cfg.AppURL = "https://app.example.test"
+ h.cfg.PluginSurfaceOrigin = "https://app.example.test"
+ token, err := h.mintPluginSurfaceToken(validSurfaceClaims())
+ if err != nil {
+ t.Fatalf("mintPluginSurfaceToken: %v", err)
+ }
+
+ request := pluginHandlerRequest(http.MethodGet, "/plugin-surfaces/"+token, nil, map[string]string{"token": token})
+ request.Host = "app.example.test"
+ recorder := httptest.NewRecorder()
+ h.ServePluginSurface(recorder, request)
+
+ if recorder.Code != http.StatusNotFound {
+ t.Fatalf("shared app/content origin: status=%d, want %d", recorder.Code, http.StatusNotFound)
+ }
+}
+
+func TestPluginSurfaceHostExposesOnlySurfaceDocuments(t *testing.T) {
+ h := &Handler{cfg: Config{PluginSurfaceOrigin: "https://plugin-content.example.test"}}
+ called := false
+ boundary := h.PluginSurfaceHostBoundary(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusNoContent)
+ }))
+
+ blocked := httptest.NewRequest(http.MethodGet, "https://plugin-content.example.test/api/config", nil)
+ blocked.Host = "plugin-content.example.test"
+ blockedRecorder := httptest.NewRecorder()
+ boundary.ServeHTTP(blockedRecorder, blocked)
+ if blockedRecorder.Code != http.StatusNotFound || called {
+ t.Fatalf("content host API request: status=%d called=%v", blockedRecorder.Code, called)
+ }
+
+ allowed := httptest.NewRequest(http.MethodGet, "https://plugin-content.example.test/plugin-surfaces/token", nil)
+ allowed.Host = "plugin-content.example.test"
+ allowedRecorder := httptest.NewRecorder()
+ boundary.ServeHTTP(allowedRecorder, allowed)
+ if allowedRecorder.Code != http.StatusNoContent || !called {
+ t.Fatalf("content document request: status=%d called=%v", allowedRecorder.Code, called)
+ }
+}
+
+func TestPluginSurfaceCSPComesOnlyFromGrantedNetScopes(t *testing.T) {
+ csp := pluginSurfaceCSP([]string{"issues:read", "net:api.example.test", "storage:user", "net:evil.test; script-src *"})
+ for _, directive := range []string{
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "connect-src https://api.example.test",
+ "frame-src 'none'",
+ "form-action 'none'",
+ } {
+ if !strings.Contains(csp, directive) {
+ t.Fatalf("CSP missing %q: %s", directive, csp)
+ }
+ }
+ if strings.Contains(csp, "issues:read") || strings.Contains(csp, "connect-src https:;") {
+ t.Fatalf("CSP widened beyond net grants: %s", csp)
+ }
+ if strings.Contains(csp, "evil.test") || strings.Contains(csp, "script-src *") {
+ t.Fatalf("invalid stored net scope escaped into CSP: %s", csp)
+ }
+ if noNetwork := pluginSurfaceCSP([]string{"issues:read"}); !strings.Contains(noNetwork, "connect-src 'none'") {
+ t.Fatalf("no-network CSP = %s", noNetwork)
+ }
+}
+
+func TestPluginSurfaceDocumentHidesBootstrapProofBeforePluginCode(t *testing.T) {
+ code := `const html = "</script><script>alert(1)</script>";`
+ document := buildPluginSurfaceDocument(code, "bridge-proof")
+ if strings.Contains(document, "alert(1)") || strings.Contains(document, `"</script>`) {
+ t.Fatal("plugin source escaped its inert base64 element")
+ }
+ for _, required := range []string{
+ "new MessageChannel()",
+ pluginSurfacePortGlobal,
+ pluginSurfaceConnectMessage,
+ "challenge = \"\"",
+ `window.addEventListener("error", reportSurfaceError)`,
+ `window.addEventListener("unhandledrejection", reportSurfaceError)`,
+ "codeElement.remove()",
+ "bootstrapElement.remove()",
+ } {
+ if !strings.Contains(document, required) {
+ t.Fatalf("surface document missing %q", required)
+ }
+ }
+ if strings.Index(document, "bootstrapElement.remove()") > strings.Index(document, "document.body.appendChild(plugin)") {
+ t.Fatal("plugin code runs before its launch proof is removed from the DOM")
+ }
+ if strings.Index(document, `window.addEventListener("error", reportSurfaceError)`) > strings.Index(document, "document.body.appendChild(plugin)") {
+ t.Fatal("plugin code runs before browser error reporting is armed")
+ }
+}