fix(plugin): preserve nested dynamic import URLs in packaged workbench

This commit is contained in:
jearhe authored and GitHub committed 2026-10-07 01:05:28 +08:00
1 parent 090e9037a8
commit 1da95288c6
6 files changed
+187 -36

No files matched your search

@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
writePluginLocalFileChunk: vi.fn(),
closePluginLocalFile: vi.fn(),
openPluginWorkbench: vi.fn(),
isTauriRuntime: vi.fn(),
}));
vi.mock("@/lib/backend/tauri", () => ({
@@ -32,7 +33,7 @@ vi.mock("@/lib/backend/api", () => ({
readPluginUiAsset: mocks.readPluginUiAsset,
subscribePluginEvents: mocks.subscribePluginEvents,
}));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: mocks.isTauriRuntime }));
vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: vi.fn() }));
vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: ref(false), themeRevision: ref(0) }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { uiFontFamily: "", fontFamily: "", fontSize: 14 } }) }));
@@ -45,6 +46,7 @@ vi.mock("@/stores/connectionStore", () => ({
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ openPluginWorkbench: mocks.openPluginWorkbench }) }));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ locale: ref("en"), t: (key: string) => key }) }));
import { clearPluginUiHtmlCache } from "@/lib/plugins/pluginUiHtmlCache";
import PluginWorkbenchHost from "./PluginWorkbenchHost.vue";
const plugin: InstalledPlugin = {
@@ -72,7 +74,13 @@ describe("PluginWorkbenchHost initialization", () => {
let root: HTMLDivElement;
beforeEach(() => {
clearPluginUiHtmlCache();
vi.clearAllMocks();
mocks.isTauriRuntime.mockReturnValue(false);
const settings = (window as unknown as { happyDOM: { settings: Record<string, boolean> } }).happyDOM.settings;
settings.disableJavaScriptFileLoading = true;
settings.disableCSSFileLoading = true;
settings.handleDisabledFileLoadingAsSuccess = true;
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => window.setTimeout(() => callback(0), 0));
vi.stubGlobal("getComputedStyle", () => Object.assign([], { getPropertyValue: () => "" }));
mocks.readPluginUiEntry.mockResolvedValue({ dataBase64: btoa("<!doctype html><html><body></body></html>"), contentType: "text/html" });
@@ -107,6 +115,23 @@ describe("PluginWorkbenchHost initialization", () => {
return { frame: frame!, postMessage, ready };
}
it("passes the packaged module URL and existing asset CSP into srcdoc", async () => {
mocks.isTauriRuntime.mockReturnValue(true);
vi.stubEnv("PROD", true);
vi.stubGlobal("location", { protocol: "tauri:" });
mocks.readPluginUiEntry.mockResolvedValue({
dataBase64: btoa('<!doctype html><html><head></head><body><script type="module" src="./entry/app.mjs"></script></body></html>'),
contentType: "text/html",
});
const { frame } = await mountHost();
const srcdoc = frame.getAttribute("srcdoc") ?? "";
expect(srcdoc).toContain('<script type="module" src="dbx-plugin://localhost/sample/entry/app.mjs"></script>');
expect(srcdoc).toContain('<base href="dbx-plugin://localhost/sample/entry/">');
expect(srcdoc).toContain("script-src 'unsafe-inline' blob: dbx-plugin:;");
expect(mocks.readPluginUiAsset).not.toHaveBeenCalled();
});
it("runs reinit before one init when load precedes ready", async () => {
const firstReinit = deferred();
const { frame, postMessage, ready } = await mountHost();
@@ -18,7 +18,7 @@ import {
type PluginWorkbenchContext,
type PluginAiRecommendationHostUpdate,
} from "@/lib/plugins/pluginHostBridge";
import { getCachedPluginUiHtml, getOrLoadPluginUiHtml } from "@/lib/plugins/pluginUiHtmlCache";
import { getCachedPluginUiHtml, getOrLoadPluginUiHtml, pluginUiAssetBaseUrl } from "@/lib/plugins/pluginUiHtmlCache";
import { isPluginGraphicsEngineEnabled } from "@/lib/plugins/pluginGraphicsEngine";
import { beginFloatingWindowDrag, closeFloatingWindows, endFloatingWindowDrag, openFloatingWindow, setFloatingWindowSize } from "@/lib/plugins/pluginFloatingWindow";
import { isFloatingPluginWindow } from "@/lib/app/windowContext";
@@ -673,18 +673,6 @@ async function savePluginFile(request: PluginSaveFileRequest, data: Uint8Array):
return { path: fileName };
}
/**
* Base URL prefix for lazy-loaded plugin UI assets. wry serves custom schemes
* natively on WKWebView/webkit2gtk but maps them onto http(s) subdomains on
* WebView2, so the host page's own protocol picks the form the webview will
* actually request. The web host has no plugin asset protocol.
*/
function pluginUiBaseUrl(pluginId: string, entryDirectory: string): string | undefined {
if (!isTauriRuntime()) return undefined;
const origin = location.protocol === "http:" || location.protocol === "https:" ? `${location.protocol}//dbx-plugin.localhost/${pluginId}/` : `dbx-plugin://localhost/${pluginId}/`;
return entryDirectory ? `${origin}${entryDirectory}/` : origin;
}
async function loadWorkbench() {
const generation = ++loadGeneration;
// An identity rebuild swaps the plugin this component serves; retire the
@@ -720,7 +708,7 @@ async function loadWorkbench() {
cachedHtml.sandboxDoc = {
allowUnsafeEval,
doc: pluginSandboxDocument(html, props.plugin.manifest.permissions, currentBridgeTheme(), {
baseUrl: pluginUiBaseUrl(props.plugin.manifest.id, entryDirectory),
baseUrl: pluginUiAssetBaseUrl(props.plugin.manifest.id, entryDirectory),
allowUnsafeEval,
}),
};
+8 -2
View File
@@ -1032,18 +1032,24 @@ describe("PluginHostBridge", () => {
});
it("injects a <base> and widens resource CSP sources for the plugin asset origin", () => {
const document = pluginSandboxDocument("<html><head></head><body></body></html>", [], undefined, { baseUrl: "dbx-plugin://localhost/io.github.t8y2.s3/assets/" });
const document = pluginSandboxDocument('<html><head></head><body><script type="module" src="dbx-plugin://localhost/io.github.t8y2.s3/entry/app.mjs"></script><script type="module" src="https://cdn.example.test/app.mjs"></script></body></html>', [], undefined, {
baseUrl: "dbx-plugin://localhost/io.github.t8y2.s3/assets/",
});
expect(document).toContain('<base href="dbx-plugin://localhost/io.github.t8y2.s3/assets/">');
expect(document).toContain("script-src 'unsafe-inline' blob: dbx-plugin:;");
expect(document).toContain("font-src data: blob: dbx-plugin:;");
expect(document).toContain('src="dbx-plugin://localhost/io.github.t8y2.s3/entry/app.mjs"');
const scriptPolicy = document.match(/script-src[^;]+;/)?.[0] ?? "";
expect(scriptPolicy).not.toContain("https://cdn.example.test");
// <base> leads the head injection so inlined CSS url() resolves against it.
expect(document.indexOf("<base ")).toBeLessThan(document.indexOf("<style>"));
});
it("allows the WebView2-mapped asset origin exactly", () => {
const document = pluginSandboxDocument("<html><head></head><body></body></html>", [], undefined, { baseUrl: "http://dbx-plugin.localhost/io.github.t8y2.s3/assets/" });
const document = pluginSandboxDocument('<html><head></head><body><script type="module" src="http://dbx-plugin.localhost/io.github.t8y2.s3/entry/app.mjs"></script></body></html>', [], undefined, { baseUrl: "http://dbx-plugin.localhost/io.github.t8y2.s3/assets/" });
expect(document).toContain("script-src 'unsafe-inline' blob: http://dbx-plugin.localhost;");
expect(document).toContain('<base href="http://dbx-plugin.localhost/io.github.t8y2.s3/assets/">');
expect(document).toContain('src="http://dbx-plugin.localhost/io.github.t8y2.s3/entry/app.mjs"');
});
it("rejects malformed asset base URLs without touching the CSP", () => {
@@ -1089,12 +1089,13 @@ export function pluginNetworkOrigins(permissions: readonly string[] | undefined)
export interface PluginSandboxOptions {
/**
* Base URL under which the workbench document may fetch further plugin UI
* assets (code-split chunks, fonts) — `dbx-plugin://localhost/<id>/assets/`
* on native custom schemes, `http(s)://dbx-plugin.localhost/<id>/assets/`
* where WebView2 maps the scheme to an http subdomain. Injected as the
* document `<base>` and allowed in the resource CSP directives. Omit on
* hosts without the plugin asset protocol (the web host).
* Base URL for plugin UI resources resolved relative to the srcdoc document
* (for example, inlined CSS `url()` references) — `dbx-plugin://localhost/<id>/`
* on native custom schemes, `http(s)://dbx-plugin.localhost/<id>/` where
* WebView2 maps the scheme to an http subdomain. Injected as the document
* `<base>` and allowed in resource CSP directives. External module imports
* resolve from their own preserved URLs. Omit on hosts without the plugin
* asset protocol (the web host).
*/
baseUrl?: string;
/**
@@ -1112,8 +1113,8 @@ export function pluginSandboxDocument(html: string, permissions?: readonly strin
const assetSource = pluginAssetCspSource(options?.baseUrl);
const scriptSrc = options?.allowUnsafeEval ? "script-src 'unsafe-inline' 'unsafe-eval'" : "script-src 'unsafe-inline'";
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; ${scriptSrc} blob:${assetSource}; style-src 'unsafe-inline' blob:; img-src data: blob:${assetSource}; font-src data: blob:${assetSource}; ${connectSrc} media-src data: blob:${assetSource};">`;
// <base> must precede every relative URL the document resolves (inlined CSS
// url(), dynamic import specifiers), so it leads the injection.
// <base> must precede relative URLs resolved from the srcdoc itself (such as
// inlined CSS url() references), so it leads the injection.
const base = options?.baseUrl && assetSource ? `<base href="${escapeHtmlAttribute(options.baseUrl)}">` : "";
const sdk = `<script>${pluginSdkSource(theme)}</script>`;
const uiKit = `<style>${pluginUiKitCss()}</style>`;
+91 -1
View File
@@ -1,15 +1,17 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
readPluginUiEntry: vi.fn(),
readPluginUiAsset: vi.fn(),
isTauriRuntime: vi.fn(),
}));
vi.mock("@/lib/backend/api", () => ({
readPluginUiEntry: mocks.readPluginUiEntry,
readPluginUiAsset: mocks.readPluginUiAsset,
}));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: mocks.isTauriRuntime }));
import { COMPONENT_PLUGINS_UPDATED_EVENT } from "@/lib/updates/componentUpdateEvents";
import { clearPluginUiHtmlCache, getCachedPluginUiHtml, getOrLoadPluginUiHtml, setCachedPluginUiHtml } from "./pluginUiHtmlCache";
@@ -22,8 +24,15 @@ describe("pluginUiHtmlCache", () => {
beforeEach(() => {
clearPluginUiHtmlCache();
vi.resetAllMocks();
mocks.isTauriRuntime.mockReturnValue(false);
const settings = (window as unknown as { happyDOM: { settings: Record<string, boolean> } }).happyDOM.settings;
settings.disableJavaScriptFileLoading = true;
settings.disableCSSFileLoading = true;
settings.handleDisabledFileLoadingAsSuccess = true;
});
afterEach(() => vi.unstubAllGlobals());
it("returns the stored document for the same plugin id+version key", () => {
setCachedPluginUiHtml("io.dbx.ssh@0.4.88", { html: "<html>a</html>", entryDirectory: "" });
expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.88")).toEqual({ html: "<html>a</html>", entryDirectory: "" });
@@ -52,6 +61,87 @@ describe("pluginUiHtmlCache", () => {
expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.89")).toBeUndefined();
});
it.each([
{ protocol: "tauri:", prefix: "dbx-plugin://localhost/sample/" },
{ protocol: "http:", prefix: "http://dbx-plugin.localhost/sample/" },
{ protocol: "https:", prefix: "https://dbx-plugin.localhost/sample/" },
])("preserves packaged module URL identity and nested import bases for $protocol", async ({ protocol, prefix }) => {
mocks.isTauriRuntime.mockReturnValue(true);
vi.stubEnv("PROD", true);
vi.stubGlobal("location", { protocol });
mocks.readPluginUiEntry.mockResolvedValueOnce(
uiEntryPayload(`<!doctype html><html><head>
<link rel="stylesheet" href="./styles/theme.css" data-theme="dark" disabled>
</head><body>
<script src="./legacy.js" defer data-legacy="true"></script>
<script type="module" src="./entry/app.mjs?rev=1#app" data-test="foo" crossorigin="anonymous"></script>
</body></html>`),
);
mocks.readPluginUiAsset.mockImplementation(async (_pluginId: string, path: string) => ({
dataBase64: btoa(path.endsWith(".css") ? "body{color:red}" : "window.legacyLoaded = true;"),
}));
const result = await getOrLoadPluginUiHtml("sample@1.0.0", "sample");
const document = new DOMParser().parseFromString(result.html, "text/html");
const entry = document.querySelector<HTMLScriptElement>('script[type="module"]');
expect(result.entryDirectory).toBe("styles");
expect(entry?.getAttribute("src")).toBe(`${prefix}entry/app.mjs?rev=1#app`);
expect(entry?.getAttribute("data-test")).toBe("foo");
expect(entry?.getAttribute("crossorigin")).toBe("anonymous");
expect(entry?.textContent).toBe("");
// Model the browser's URL resolution through entry → child → deeper. The
// external module URL, not the document's CSS-oriented <base>, owns each
// relative import's resolution base.
if (!entry) throw new Error("Packaged module entry is missing");
const entryUrl = entry.src;
const childUrl = new URL("./child/app.mjs", entryUrl).href;
const deeperUrl = new URL("./deeper/module.mjs", childUrl).href;
expect(childUrl).toBe(`${prefix}entry/child/app.mjs`);
expect(deeperUrl).toBe(`${prefix}entry/child/deeper/module.mjs`);
const legacy = document.querySelector<HTMLScriptElement>('script[data-legacy="true"]');
expect(legacy?.hasAttribute("src")).toBe(false);
expect(legacy?.hasAttribute("defer")).toBe(true);
expect(legacy?.textContent).toBe("window.legacyLoaded = true;");
const stylesheet = document.querySelector<HTMLStyleElement>("style[data-theme=dark]");
expect(stylesheet?.hasAttribute("disabled")).toBe(true);
expect(stylesheet?.textContent).toBe("body{color:red}");
expect(mocks.readPluginUiAsset.mock.calls.map(([, path]) => path)).toEqual(["styles/theme.css", "legacy.js"]);
});
it("keeps the inline fallback for module scripts in dev despite the tauri runtime", async () => {
// `tauri dev` serves the app from the devUrl (http(s):), where the module
// URL rewrite would land on the WebView2-only subdomain form that
// WKWebView/webkit2gtk never serve — the entry must stay inline in dev.
mocks.isTauriRuntime.mockReturnValue(true);
vi.stubEnv("PROD", false);
vi.stubGlobal("location", { protocol: "http:" });
mocks.readPluginUiEntry.mockResolvedValueOnce(uiEntryPayload('<html><body><script type="module" src="./entry/app.mjs" data-dev="1"></script></body></html>'));
mocks.readPluginUiAsset.mockResolvedValueOnce({ dataBase64: btoa('await import("./child/app.mjs");') });
const result = await getOrLoadPluginUiHtml("sample@dev", "sample");
const document = new DOMParser().parseFromString(result.html, "text/html");
const module = document.querySelector<HTMLScriptElement>('script[type="module"]');
expect(module?.hasAttribute("src")).toBe(false);
expect(module?.getAttribute("data-dev")).toBe("1");
expect(module?.textContent).toBe('await import("./child/app.mjs");');
expect(mocks.readPluginUiAsset).toHaveBeenCalledWith("sample", "entry/app.mjs");
});
it("keeps inline fallback for hosts without the plugin asset protocol", async () => {
mocks.readPluginUiEntry.mockResolvedValueOnce(uiEntryPayload('<html><body><script type="module" src="./entry/app.mjs" data-test="web"></script></body></html>'));
mocks.readPluginUiAsset.mockResolvedValueOnce({ dataBase64: btoa('await import("./child/app.mjs");') });
const result = await getOrLoadPluginUiHtml("sample@web", "sample");
const document = new DOMParser().parseFromString(result.html, "text/html");
const module = document.querySelector<HTMLScriptElement>('script[type="module"]');
expect(module?.hasAttribute("src")).toBe(false);
expect(module?.getAttribute("data-test")).toBe("web");
expect(module?.textContent).toBe('await import("./child/app.mjs");');
expect(mocks.readPluginUiAsset).toHaveBeenCalledWith("sample", "entry/app.mjs");
});
it("invalidates on dbx:plugins-changed so a same-version reinstall re-reads the build", async () => {
setCachedPluginUiHtml("io.dbx.ssh@0.4.88", { html: "stale", entryDirectory: "" });
window.dispatchEvent(new CustomEvent("dbx:plugins-changed"));
@@ -1,9 +1,10 @@
// The inlined plugin ui document is multiple megabytes; rebuilding it per
// The processed plugin UI document is multiple megabytes; rebuilding it per
// workbench instance (every dock panel, every tab) re-reads the entry through
// the bridge and re-parses it each time. Module scope is the point: the cache
// is shared by every PluginWorkbenchHost instance, so only the first boot of a
// plugin version pays the read/decode/inline pipeline.
import * as api from "@/lib/backend/api";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { COMPONENT_PLUGINS_UPDATED_EVENT } from "@/lib/updates/componentUpdateEvents";
export interface PluginUiHtml {
@@ -45,7 +46,30 @@ export function clearPluginUiHtmlCache(): void {
inFlight.clear();
}
// --- First-boot pipeline (read → decode → inline local assets) -------------
// --- First-boot pipeline (read → decode → prepare local assets) -------------
/** Base URL for packaged plugin UI resources on desktop hosts. */
export function pluginUiAssetBaseUrl(pluginId: string, entryDirectory = ""): string | undefined {
if (!isTauriRuntime()) return undefined;
const origin = location.protocol === "http:" || location.protocol === "https:" ? `${location.protocol}//dbx-plugin.localhost/${pluginId}/` : `dbx-plugin://localhost/${pluginId}/`;
return entryDirectory ? `${origin}${entryDirectory}/` : origin;
}
function pluginUiAssetUrl(pluginId: string, path: string, source: string): string | undefined {
const baseUrl = pluginUiAssetBaseUrl(pluginId);
if (!baseUrl) return undefined;
const assetUrl = new URL(
path
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/"),
baseUrl,
);
const sourceUrl = new URL(source.trim(), "https://dbx-plugin.invalid/");
assetUrl.search = sourceUrl.search;
assetUrl.hash = sourceUrl.hash;
return assetUrl.href;
}
function localUiAssetPath(source: string): string | undefined {
const trimmed = source.trim();
@@ -70,22 +94,39 @@ async function inlineLocalUiAssets(html: string, pluginId: string): Promise<Plug
}
const document = new DOMParser().parseFromString(html, "text/html");
const resources = [...document.querySelectorAll("script[src], link[rel='stylesheet'][href]")];
// Dynamic-import chunks and CSS url() references live next to the entry
// script; its directory is the <base> the sandbox document needs to resolve
// them through the dbx-plugin scheme.
// Keep the existing first-local-resource directory for the sandbox <base>
// used by document-relative assets such as inlined CSS url(). External
// module imports resolve from their own preserved module URLs instead.
let entryDirectory = "";
// Fetch every referenced asset concurrently — these are bridge round-trips
// into the sidecar, and panels reopen this path on every workbench (re)load.
const fetched = await Promise.all(
resources.map((resource) => {
resources.map(async (resource) => {
const source = resource.getAttribute(resource.tagName === "SCRIPT" ? "src" : "href");
const path = source ? localUiAssetPath(source) : undefined;
if (!path) return Promise.resolve({ resource, content: null });
if (!source || !path) return { resource, content: null };
if (!entryDirectory) entryDirectory = path.split("/").slice(0, -1).join("/");
return api.readPluginUiAsset(pluginId, path).then((asset) => ({
const isModuleScript = resource.tagName === "SCRIPT" && resource.getAttribute("type")?.trim().toLowerCase() === "module";
// Keep the external module URL only in packaged builds: `tauri dev` serves
// the app from the devUrl (http(s):), which maps module URLs onto the
// WebView2-only http-subdomain form that WKWebView/webkit2gtk never serve,
// so the entry module would fail to load at all in dev there. Dev keeps
// the inline fallback below (nested imports resolve relative to the
// srcdoc <base>, as they did before the packaged fix).
if (isModuleScript && import.meta.env.PROD) {
const url = pluginUiAssetUrl(pluginId, path, source);
if (url) {
// Keep the module's real URL: browsers resolve its static and dynamic
// imports from this URL, not from the srcdoc document's <base>.
resource.setAttribute("src", url);
return { resource, content: null };
}
}
const asset = await api.readPluginUiAsset(pluginId, path);
return {
resource,
content: new TextDecoder().decode(Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0))),
}));
};
}),
);
for (const { resource, content } of fetched) {
@@ -117,7 +158,7 @@ async function inlineLocalUiAssets(html: string, pluginId: string): Promise<Plug
return { html: document.documentElement.outerHTML, entryDirectory };
}
/** Full first-boot pipeline: read the ui entry through the bridge, decode, inline local assets. */
/** Full first-boot pipeline: read the ui entry through the bridge, decode, and prepare local assets. */
export async function loadPluginUiHtml(pluginId: string): Promise<PluginUiHtml> {
const asset = await api.readPluginUiEntry(pluginId);
const bytes = Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0));