Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(plugins): add host.copy bridge for plugin clipboard writes

t8y2048b9ed2912d
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue
index 49914cb187..5b8dc240af 100644
--- a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue
@@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
import { AlertTriangle, Loader2 } from "@lucide/vue";
import * as api from "@/lib/backend/api";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { copyToClipboard } from "@/lib/common/clipboard";
import { PluginHostBridge, pluginSandboxDocument, type PluginBridgeTheme, type PluginSaveFileRequest, type PluginSaveFileResult, type PluginWorkbenchContext } from "@/lib/plugins/pluginHostBridge";
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
import { useI18n } from "vue-i18n";
@@ -73,6 +74,7 @@ function createBridge() {
openFilesystem: async (pluginId, providerId, context) => emit("openFilesystem", pluginId, providerId, context),
closeTab: () => emit("closeTab"),
saveFile: (_pluginId, request, data) => savePluginFile(request, data),
+ copyText: (_pluginId, text) => copyToClipboard(text),
},
appLocale.value,
currentBridgeTheme(),
@@ -253,7 +255,7 @@ onBeforeUnmount(() => {
<span>{{ error }}</span>
</div>
<template v-else>
- <iframe ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
+ <iframe ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" allow="clipboard-write" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
<!-- Cover until the frame has actually painted: the iframe stays mounted
underneath so its load event can fire (v-else on the overlay would
deadlock), it just isn't visible yet. Fully opaque so the covered
diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts
index 6a9b56fc4d..82cc2aa5cc 100644
--- a/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts
+++ b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts
@@ -292,6 +292,7 @@ describe("PluginHostBridge", () => {
expect(document).toContain("get locale() { return locale; }");
expect(document).toContain("openFilesystem");
expect(document).toContain("saveFile");
+ expect(document).toContain("copy");
expect(document).toContain("document.dispatchEvent(new CustomEvent('dbx-plugin-env'");
expect(document).toContain("shortcut: 'closeTab'");
expect(document).toContain("connect-src 'none'");
@@ -408,6 +409,59 @@ describe("PluginHostBridge", () => {
expect(messages[1]).toMatchObject({ type: "response", id: "save2", result: null });
});
+ it("routes host.copy through the host clipboard and rejects bad payloads", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const copyText = vi.fn().mockResolvedValue(undefined);
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ copyText,
+ });
+
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "copy1", method: "host.copy", params: { text: "https://example.com/share?sig=1" } },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+ expect(copyText).toHaveBeenCalledWith("sample", "https://example.com/share?sig=1");
+ expect(messages[0]).toMatchObject({ type: "response", id: "copy1", result: { success: true } });
+
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "copy2", method: "host.copy", params: { text: "" } },
+ } as MessageEvent);
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "copy3", method: "host.copy", params: { text: "x".repeat(2 * 1024 * 1024 + 1) } },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(3));
+ const byId = new Map(messages.map((message) => [(message as { id?: string }).id, message]));
+ expect(byId.get("copy2")).toMatchObject({ id: "copy2", error: "host.copy requires text" });
+ // Oversized text is stopped by the generic bridge payload guard before the handler cap.
+ expect(String((byId.get("copy3") as { error?: string }).error)).toMatch(/too large|exceeds/);
+ });
+
+ it("rejects host.copy when the host has no clipboard support", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "nocopy", method: "host.copy", params: { text: "hello" } },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+ expect(messages[0]).toMatchObject({ id: "nocopy", error: "Host clipboard is unavailable" });
+ });
+
it("rejects host.saveFile without payload or host support", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.ts
index 164e40b7fc..28269350d4 100644
--- a/apps/desktop/src/lib/plugins/pluginHostBridge.ts
+++ b/apps/desktop/src/lib/plugins/pluginHostBridge.ts
@@ -43,6 +43,8 @@ export interface PluginHostBridgeApi {
closeTab?(): Promise<void> | void;
/** Persist plugin bytes through the host's native save dialog. Resolves null when the user cancels. */
saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): Promise<PluginSaveFileResult | null>;
+ /** Write text to the system clipboard on behalf of the sandboxed plugin iframe. */
+ copyText?(pluginId: string, text: string): Promise<void>;
}
interface PluginRequestMessage {
@@ -207,6 +209,17 @@ export class PluginHostBridge {
if (!this.api.saveFile) throw new Error("Host file saving is unavailable");
return this.api.saveFile(this.plugin.manifest.id, { fileName: optionalTrimmedString(input.fileName), contentType: optionalTrimmedString(input.contentType) }, bytes);
}
+ if (method === "host.copy") {
+ const input = isRecord(params) ? params : {};
+ // The sandboxed workbench iframe has an opaque origin and no clipboard
+ // permission, so every scripted copy path is denied there; the host
+ // writes the system clipboard instead.
+ if (typeof input.text !== "string" || !input.text) throw new Error("host.copy requires text");
+ if (input.text.length > MAX_BRIDGE_PAYLOAD_BYTES) throw new Error(`Plugin copy payload exceeds ${MAX_BRIDGE_PAYLOAD_BYTES} characters`);
+ if (!this.api.copyText) throw new Error("Host clipboard is unavailable");
+ await this.api.copyText(this.plugin.manifest.id, input.text);
+ return { success: true };
+ }
throw new Error(`Unsupported plugin host method '${method}'`);
}
@@ -493,6 +506,7 @@ export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
const bytes = data instanceof ArrayBuffer ? data : (data instanceof Uint8Array ? data.buffer : new Uint8Array(data).buffer);
return request('host.saveFile', options, { transfer: bytes });
},
+ copy: (text) => request('host.copy', { text }),
onEvent: (listener) => { listeners.event.add(listener); return () => listeners.event.delete(listener); },
onBinary: (listener) => { listeners.binary.add(listener); return () => listeners.binary.delete(listener); },
onContext: (listener) => { listeners.context.add(listener); return () => listeners.context.delete(listener); },
diff --git a/plugins/sdk/dev-host/browser-bridge.mjs b/plugins/sdk/dev-host/browser-bridge.mjs
index cb93bb7efd..fdd1edff64 100644
--- a/plugins/sdk/dev-host/browser-bridge.mjs
+++ b/plugins/sdk/dev-host/browser-bridge.mjs
@@ -123,6 +123,7 @@ function installBridge(channel) {
},
openWorkbench: (contributionId, context) => request("host.openWorkbench", { contributionId, context }),
openFilesystem: (providerId, context) => request("host.openFilesystem", { providerId, context }),
+ copy: (text) => request("host.copy", { text }),
onContext: (fn) => listen("context", fn),
onEvent: (fn) => listen("event", fn),
onBinary: (fn) => listen("binary", fn),
diff --git a/plugins/sdk/dev-host/ui/App.vue b/plugins/sdk/dev-host/ui/App.vue
index cea9cb1170..df0b9db2df 100644
--- a/plugins/sdk/dev-host/ui/App.vue
+++ b/plugins/sdk/dev-host/ui/App.vue
@@ -304,6 +304,22 @@ async function onMessage(event) {
}
if (m.type !== "request") return;
const channel = f.channel;
+ // The sandboxed plugin iframe cannot write the clipboard; the debug page is
+ // a normal top-level document, so it performs the copy like the DBX host.
+ if (m.method === "host.copy") {
+ const text = m.params?.text;
+ if (typeof text !== "string" || !text) {
+ post(f, { type: "response", id: m.id, error: { message: "host.copy requires text" } });
+ return;
+ }
+ if (text.length > 2 * 1024 * 1024) {
+ post(f, { type: "response", id: m.id, error: { message: "Plugin copy payload exceeds 2097152 characters" } });
+ return;
+ }
+ const ok = await copyTextToClipboard(text);
+ post(f, ok ? { type: "response", id: m.id, result: { success: true } } : { type: "response", id: m.id, error: { message: "Host clipboard is unavailable" } });
+ return;
+ }
try {
const result = await api("bridge", { frameId: f.id, channel, method: m.method, params: m.params });
if (f.channel !== channel || !windows.has(f.id)) return;
@@ -315,6 +331,29 @@ async function onMessage(event) {
if (f.channel === channel) post(f, { type: "response", id: m.id, error: { message: e.message, code: e.code, data: e.data } });
}
}
+async function copyTextToClipboard(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ // Fall through to the legacy path for engines without the async API.
+ }
+ const helper = document.createElement("textarea");
+ helper.value = text;
+ helper.setAttribute("readonly", "");
+ helper.style.position = "fixed";
+ helper.style.opacity = "0";
+ document.body.appendChild(helper);
+ helper.select();
+ let ok = false;
+ try {
+ ok = document.execCommand("copy");
+ } catch {
+ ok = false;
+ }
+ helper.remove();
+ return ok;
+}
onMounted(async () => {
window.addEventListener("message", onMessage);
await run(async () => {
@@ -415,7 +454,7 @@ onBeforeUnmount(() => {
</div>
</div>
<div class="relative min-h-0 flex-1">
- <iframe v-for="f in frames" v-show="active === f.id" :key="f.id" :ref="(el) => (el ? windows.set(f.id, el) : windows.delete(f.id))" :srcdoc="f.html" sandbox="allow-scripts" referrerpolicy="no-referrer" :title="frameName(f)" class="absolute inset-0" @load="init(f)" />
+ <iframe v-for="f in frames" v-show="active === f.id" :key="f.id" :ref="(el) => (el ? windows.set(f.id, el) : windows.delete(f.id))" :srcdoc="f.html" sandbox="allow-scripts" allow="clipboard-write" referrerpolicy="no-referrer" :title="frameName(f)" class="absolute inset-0" @load="init(f)" />
<div v-if="!frames.length" class="grid h-full place-items-center text-sm text-base-content/50">
<div class="flex items-center gap-2"><Settings2 :size="18" />{{ t("尚未打开工作台") }}</div>
</div>