diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts b/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts index 97e71578aa..a6acd44b29 100644 --- a/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts +++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts @@ -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 } }).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(""), 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(''), + contentType: "text/html", + }); + + const { frame } = await mountHost(); + const srcdoc = frame.getAttribute("srcdoc") ?? ""; + expect(srcdoc).toContain(''); + expect(srcdoc).toContain(''); + 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(); diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue index 8f4c905cb4..58e7a8a34f 100644 --- a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue +++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue @@ -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, }), }; diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts index c8a0553ae3..65afd106e8 100644 --- a/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts +++ b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts @@ -1032,18 +1032,24 @@ describe("PluginHostBridge", () => { }); it("injects a and widens resource CSP sources for the plugin asset origin", () => { - const document = pluginSandboxDocument("", [], undefined, { baseUrl: "dbx-plugin://localhost/io.github.t8y2.s3/assets/" }); + const document = pluginSandboxDocument('', [], undefined, { + baseUrl: "dbx-plugin://localhost/io.github.t8y2.s3/assets/", + }); expect(document).toContain(''); 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"); // leads the head injection so inlined CSS url() resolves against it. expect(document.indexOf("")); }); it("allows the WebView2-mapped asset origin exactly", () => { - const document = pluginSandboxDocument("", [], undefined, { baseUrl: "http://dbx-plugin.localhost/io.github.t8y2.s3/assets/" }); + const document = pluginSandboxDocument('', [], 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(''); + 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", () => { diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.ts index 62684f9f2e..df08ba3cf6 100644 --- a/apps/desktop/src/lib/plugins/pluginHostBridge.ts +++ b/apps/desktop/src/lib/plugins/pluginHostBridge.ts @@ -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//assets/` - * on native custom schemes, `http(s)://dbx-plugin.localhost//assets/` - * where WebView2 maps the scheme to an http subdomain. Injected as the - * document `` 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//` + * on native custom schemes, `http(s)://dbx-plugin.localhost//` where + * WebView2 maps the scheme to an http subdomain. Injected as the document + * `` 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 = ``; - // must precede every relative URL the document resolves (inlined CSS - // url(), dynamic import specifiers), so it leads the injection. + // 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 ? `` : ""; const sdk = ``; const uiKit = ``; diff --git a/apps/desktop/src/lib/plugins/pluginUiHtmlCache.spec.ts b/apps/desktop/src/lib/plugins/pluginUiHtmlCache.spec.ts index c52d10ddab..ce02a40b6c 100644 --- a/apps/desktop/src/lib/plugins/pluginUiHtmlCache.spec.ts +++ b/apps/desktop/src/lib/plugins/pluginUiHtmlCache.spec.ts @@ -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 } }).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: "a", entryDirectory: "" }); expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.88")).toEqual({ html: "a", 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(` + + + + + `), + ); + 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('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 , 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('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("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('')); + 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('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('')); + 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('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")); diff --git a/apps/desktop/src/lib/plugins/pluginUiHtmlCache.ts b/apps/desktop/src/lib/plugins/pluginUiHtmlCache.ts index 6c2b8ee16d..38e85293f7 100644 --- a/apps/desktop/src/lib/plugins/pluginUiHtmlCache.ts +++ b/apps/desktop/src/lib/plugins/pluginUiHtmlCache.ts @@ -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 the sandbox document needs to resolve - // them through the dbx-plugin scheme. + // Keep the existing first-local-resource directory for the sandbox + // 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 , 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 . + 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 { const asset = await api.readPluginUiEntry(pluginId); const bytes = Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0));