Файли
openidea/e2e/mdxPreview.spec.ts
T
Deng Liuтаdengliu 85cbc6bacd feat(mdx): add side-by-side MDX preview with opt-in sandboxed JSX execution (#6881)
Adds Editor Only / Editor and Preview / Preview Only layouts for .mdx files.

- Safe Static Mode on open: frontmatter, GFM, math, Mermaid, MDX comments and documentation tags (Steps, CardGroup, Note, Tabs, Accordion) render through the sanitized Markdown pipeline with scroll sync and no script execution.
- Run JSX (or Trust Project in Restricted Mode) lazy-loads @mdx-js/mdx and sucrase and evaluates JSX, workspace/tsconfig/node_modules imports, .mdx transclusions, stylesheets, assets and custom layouts inside an opaque-origin sandboxed iframe with its own CSP, no network and no IPC.
- The host-guest bridge is a per-document MessagePort; image, media, module and link resolution stay inside the window's project roots, checked lexically and after canonicalization (new fs_canonicalize command, which rejects parent traversal).
- Execution requires a current, affirmative trust result for the file's owning project, including attached workspace members, whose trust changes now emit ProjectTrustChanged.
- External links open only from a real click on an anchor in the frame and always go through a confirmation dialog showing the parsed destination.
- Settings > Languages & Frameworks > Markdown adds MDX component execution (Ask before running / Run automatically in trusted projects / Disabled), a user-only setting that project settings cannot enable.

Closes #6876

Co-authored-by: dengliu <[email protected]>
2026-12-02 08:39:22 +08:00

382 рядки
17 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
import { readFileSync } from "node:fs";
import path from "node:path";
import { expect, test } from "./fixtures";
test("previews MDX safely on open, opts into sandboxed JSX execution, and configures MDX execution in Settings", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set(
"/dev/acme-api/Counter.tsx",
[
'import { useState } from "react";',
"export function Counter({ initial = 1 }: { initial?: number }) {",
" const [count, setCount] = useState(initial);",
" return (",
' <button type="button" onClick={() => setCount((c) => c + 1)}>',
" Clicks: {count}",
" </button>",
" );",
"}",
].join("\n"),
);
docBackend().files.set("/dev/acme-api/Part.mdx", "Transcluded **MDX** snippet from `./Part.mdx`.");
docBackend().files.set(
"/dev/acme-api/guide.mdx",
[
"---",
'title: "Interactive Guide"',
"---",
"",
"{/* Stripped MDX comment */}",
'import { Counter } from "./Counter";',
'import Part from "./Part.mdx";',
"",
"# {frontmatter.title}",
"",
"<Steps>",
' <Step title="Safe static preview">',
" Documentation tags render immediately.",
" </Step>",
"</Steps>",
"",
'<Note title="Sandbox">Runs inside an isolated frame.</Note>',
"",
"<Part />",
"",
"<Counter initial={3} />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/guide.mdx");
});
// 1. Safe static preview renders immediately without executing JSX, and shows the opt-in banner.
await expect(page.getByRole("button", { name: "Editor Only", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Editor and Preview", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Preview Only", exact: true })).toBeVisible();
await expect(page.getByText("This MDX file contains JSX components or imports.")).toBeVisible();
const staticPreview = page.getByRole("document", { name: "Markdown preview" });
await expect(staticPreview).toContainText("Safe static preview");
await expect(staticPreview).toContainText("Runs inside an isolated frame.");
await expect(staticPreview).not.toContainText("Stripped MDX comment");
// 2. Dynamic opt-in launches the sandboxed iframe and evaluates imported TSX + transcluded MDX.
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
const sandboxFrame = page.frameLocator('iframe[title="MDX preview"]');
await expect(sandboxFrame.getByRole("heading", { name: "Interactive Guide" })).toBeVisible();
await expect(sandboxFrame.getByText("Transcluded MDX snippet from ./Part.mdx.")).toBeVisible();
const counterBtn = sandboxFrame.getByRole("button", { name: "Clicks: 3" });
await expect(counterBtn).toBeVisible();
await counterBtn.click();
await expect(sandboxFrame.getByRole("button", { name: "Clicks: 4" })).toBeVisible();
// 3. Stepping back to Safe Mode restores the static sanitized preview.
await page.getByRole("button", { name: "Safe Mode", exact: true }).click();
await expect(page.getByText("This MDX file contains JSX components or imports.")).toBeVisible();
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
// 4. Settings › Languages & Frameworks › Markdown exposes MDX component execution.
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Markdown");
await settings.getByRole("treeitem", { name: "Markdown", exact: true, level: 2 }).click();
const mdxSelect = settings.getByRole("button", { name: "MDX component execution", exact: true });
await expect(mdxSelect).toBeVisible();
await expect(mdxSelect).toContainText("Ask before running");
await mdxSelect.click();
await page.getByRole("option", { name: "Disabled", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
});
test("renders OpenIDEA docs/en/introduction.mdx with Run JSX and docs/plugins.mdx with ambient React hooks", async ({
workbench: page,
}) => {
const repoRoot = path.resolve(import.meta.dirname, "..");
const docsFiles: Record<string, string> = {
"/dev/acme-api/docs/docs.json": readFileSync(path.join(repoRoot, "docs/docs.json"), "utf8"),
"/dev/acme-api/docs/home.css": readFileSync(path.join(repoRoot, "docs/home.css"), "utf8"),
"/dev/acme-api/docs/plugins.mdx": readFileSync(path.join(repoRoot, "docs/plugins.mdx"), "utf8"),
"/dev/acme-api/docs/snippets/marketplace.jsx": readFileSync(
path.join(repoRoot, "docs/snippets/marketplace.jsx"),
"utf8",
),
"/dev/acme-api/docs/snippets/plugin-catalog.jsx": readFileSync(
path.join(repoRoot, "docs/snippets/plugin-catalog.jsx"),
"utf8",
),
"/dev/acme-api/docs/en/introduction.mdx": readFileSync(path.join(repoRoot, "docs/en/introduction.mdx"), "utf8"),
};
await page.evaluate(async (seed) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
for (const [k, v] of Object.entries(seed)) {
docBackend().files.set(k, v);
}
await editorService().openFile("/dev/acme-api/docs/en/introduction.mdx");
}, docsFiles);
// 1. en/introduction.mdx shows the Run JSX button and runs <CardGroup> + <Note> in sandbox.
await expect(page.getByRole("button", { name: "Run JSX", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
const introFrame = page.frameLocator('iframe[title="MDX preview"]');
await expect(introFrame.getByRole("heading", { name: "Where to go next" })).toBeVisible();
await expect(introFrame.getByRole("link", { name: "Install" })).toBeVisible();
// 2. docs/plugins.mdx imports /snippets/marketplace.jsx (which uses ambient useState/useEffect without imports)
// and auto-loads docs/home.css.
await page.evaluate(async () => {
const servicePath = "/src/workbench/contributions.ts";
const { editorService } = await import(servicePath);
await editorService().openFile("/dev/acme-api/docs/plugins.mdx");
});
await expect(page.getByRole("button", { name: "Run JSX", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByRole("alert")).toHaveCount(0);
const marketFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/docs/plugins.mdx"]');
await expect(marketFrame.getByRole("heading", { name: "Make OpenIDEA yours." })).toBeVisible();
const searchInput = marketFrame.getByRole("searchbox", { name: "Search plugins" });
await expect(searchInput).toBeVisible();
await searchInput.fill("Graphviz");
await expect(marketFrame.getByRole("heading", { name: "Graphviz" })).toBeVisible();
});
test("renders Mermaid diagrams and docs-root <video> elements in both Safe Mode and sandboxed Run JSX mode", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set("/dev/acme-api/docs/docs.json", "{}");
// Minimal ftyp box bytes encoded as a data URL in the in-memory workspace
docBackend().files.set(
"/dev/acme-api/docs/videos/agent-resources-lifecycle.mp4",
"data:video/mp4;base64,AAAAGGZ0eXBtcDQyAAAAAGlzb21tcDQy",
);
docBackend().files.set(
"/dev/acme-api/docs/en/guide/agent-resources.mdx",
[
"---",
'title: "Agent resources and lifecycle"',
"---",
"",
'<video controls className="w-full aspect-video rounded-xl" src="/videos/agent-resources-lifecycle.mp4" />',
"",
"## Architecture and data flow",
"",
"```mermaid",
"flowchart LR",
' Host["OpenIDEA Host"] --> MCP["Built-in MCP Server"]',
"```",
"",
"<Steps>",
' <Step title="Phase 1">',
" Host startup.",
" </Step>",
"</Steps>",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/docs/en/guide/agent-resources.mdx");
});
// 1. Safe Static Mode renders the Mermaid diagram as SVG and resolves the docs-root <video> to a blob: URL.
const staticPreview = page.getByRole("document", { name: "Markdown preview" });
await expect(staticPreview.locator('[data-mermaid-state="ok"] .mermaid-output svg')).toBeVisible();
await expect(staticPreview.locator("video")).toHaveAttribute("src", /^blob:/);
// 2. Clicking Run JSX renders both the Mermaid SVG and the <video> blob: URL inside the sandboxed frame.
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/docs/en/guide/agent-resources.mdx"]');
await expect(liveFrame.getByRole("heading", { name: "Architecture and data flow" })).toBeVisible();
await expect(liveFrame.locator('[data-mdx-mermaid="ok"] svg')).toBeVisible();
await expect(liveFrame.locator("video")).toHaveAttribute("src", /^blob:/);
});
test("confirms external links only on a real browser click in the MDX frame and blocks scripted/focus attempts", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
(window as { __openedExternalUrls?: string[] }).__openedExternalUrls = [];
window.open = ((url?: string | URL) => {
(window as { __openedExternalUrls?: string[] }).__openedExternalUrls!.push(String(url ?? ""));
return null;
}) as typeof window.open;
docBackend().files.set(
"/dev/acme-api/links.mdx",
[
'import { useEffect, useRef } from "react";',
"",
"export function LinkProbe() {",
" const linkRef = useRef(null);",
" useEffect(() => {",
' window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/on-mount", clickId: 1 }, "*");',
" linkRef.current?.click();",
" const onFocus = () => {",
' window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/on-focus", clickId: 2 }, "*");',
" linkRef.current?.click();",
" };",
' window.addEventListener("focus", onFocus);',
' return () => window.removeEventListener("focus", onFocus);',
" }, []);",
" return (",
" <div>",
' <button type="button" onClick={() => { linkRef.current?.click(); window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/hijack", clickId: 3 }, "*"); }}>Benign Button</button>',
' <a ref={linkRef} href="https://[email protected]/docs?q=1">External Docs</a>',
" </div>",
" );",
"}",
"",
"# Link Guard",
"",
"<LinkProbe />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/links.mdx");
});
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
const iframe = page.locator('iframe[data-mdx-path="/dev/acme-api/links.mdx"]');
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/links.mdx"]');
await expect(liveFrame.getByRole("link", { name: "External Docs" })).toBeVisible();
// 1. Mount-time postMessage + synthetic link.click() must not open the confirmation dialog.
const dialog = page.getByRole("dialog", { name: "Open External Link?" });
await expect(dialog).toHaveCount(0);
// 2. Focusing the iframe without clicking the link must not open the confirmation dialog.
await iframe.focus();
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
// 3. Clicking a benign button whose handler calls synthetic link.click() / postMessage must not open the dialog.
await liveFrame.getByRole("button", { name: "Benign Button" }).click();
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
// 4. A real browser click on the link opens the confirmation showing parsed scheme+host prominently.
await liveFrame.getByRole("link", { name: "External Docs" }).click();
await expect(dialog).toBeVisible();
await expect(page.getByTestId("mdx-external-link-destination")).toHaveText("https://evil.example");
await expect(page.getByTestId("mdx-external-link-full")).toHaveText("https://[email protected]/docs?q=1");
// Dismissing with Cancel keeps the URL unopened and does not re-open on focus/script.
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toHaveCount(0);
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
expect(await page.evaluate(() => (window as { __openedExternalUrls?: string[] }).__openedExternalUrls)).toEqual([]);
// 5. Clicking the link a second time with real input opens confirmation again; clicking Open opens the parsed URL.
await liveFrame.getByRole("link", { name: "External Docs" }).click();
await expect(dialog).toBeVisible();
await dialog.getByRole("button", { name: "Open", exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await page.evaluate(() => (window as { __openedExternalUrls?: string[] }).__openedExternalUrls)).toEqual([
"https://[email protected]/docs?q=1",
]);
});
test("does not open the external link prompt for hover, forged link handlers, or a stolen bridge port", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set(
"/dev/acme-api/forged-links.mdx",
[
'import { useEffect } from "react";',
"",
"export const portThief = { port: null };",
'export const dataGetter = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data").get;',
'export const patched = Object.defineProperty(MessageEvent.prototype, "data", {',
" configurable: true,",
" get() {",
" if (this.target instanceof MessagePort) portThief.port = this.target;",
" return dataGetter.call(this);",
" },",
"});",
"",
"export function Probe({ A }) {",
" useEffect(() => {",
" let n = 100;",
" const forge = (ev) => {",
' const el = A({ href: "https://evil.example/forged", children: "x" });',
" el.props.onClick({ preventDefault() {}, defaultPrevented: false, nativeEvent: ev });",
' portThief.port?.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/port", clickId: n++ });',
" };",
' document.addEventListener("mousemove", forge);',
' document.addEventListener("click", forge);',
" return () => {",
' document.removeEventListener("mousemove", forge);',
' document.removeEventListener("click", forge);',
" };",
" }, []);",
" return (",
" <div style={{ height: 300 }}>",
' <button type="button">Benign Button</button>',
" </div>",
" );",
"}",
"",
"# Forged Links",
"",
"<Probe A={props.components.a} />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/forged-links.mdx");
});
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
const iframe = page.locator('iframe[data-mdx-path="/dev/acme-api/forged-links.mdx"]');
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/forged-links.mdx"]');
await expect(liveFrame.getByRole("button", { name: "Benign Button" })).toBeVisible();
const dialog = page.getByRole("dialog", { name: "Open External Link?" });
const box = (await iframe.boundingBox())!;
for (let i = 0; i < 5; i++) await page.mouse.move(box.x + 100 + i * 10, box.y + 150);
await page.waitForTimeout(200);
await expect(dialog).toHaveCount(0);
await liveFrame.getByRole("button", { name: "Benign Button" }).click();
await page.waitForTimeout(200);
await expect(dialog).toHaveCount(0);
});