feat(plugins): per-plugin graphics engine grant for unsafe-eval CSP

This commit is contained in:
miracle authored and GitHub committed 2026-10-05 14:32:59 +08:00
1 parent de265287e0
commit 38ce7b5dd2
23 files changed
+333 -9

No files matched your search

@@ -15,6 +15,7 @@ import { useToast } from "@/composables/useToast";
import PluginShortcutSettings from "./PluginShortcutSettings.vue";
import PluginIcon from "@/components/plugins/PluginIcon.vue";
import PluginAiAccessSection from "@/components/plugins/PluginAiAccessSection.vue";
import PluginGraphicsEngineSection from "@/components/plugins/PluginGraphicsEngineSection.vue";
import * as api from "@/lib/backend/api";
import { clearPluginIconCache } from "@/lib/plugins/pluginIconResolver";
import { loadPinnedPluginIds, savePinnedPluginIds, sortPluginsPinnedFirst } from "@/lib/plugins/pluginPinning";
@@ -43,6 +44,7 @@ import { formatBytes } from "@/lib/database/serverMetrics";
import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore";
import type { InstalledPlugin, PluginInstallResult, PluginRepository, PluginRepositoryCatalogResult, PluginTrustedKey } from "@/types/database";
import { useI18n } from "vue-i18n";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
@@ -84,6 +86,15 @@ const { t, locale: appLocale } = useI18n();
const { toast } = useToast();
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
const settingsStore = useSettingsStore();
// A reinstall must start without consent: drop any graphics-engine (unsafe-eval) grant
// when the plugin is uninstalled, mirroring the backend's forget_plugin_permissions.
function forgetGraphicsEngineGrant(pluginId: string) {
const granted = settingsStore.editorSettings.pluginGraphicsEngineIds;
if (!granted.includes(pluginId)) return;
settingsStore.updateEditorSettings({ pluginGraphicsEngineIds: granted.filter((id) => id !== pluginId) });
}
const activeSection = ref<"marketplace" | "installed" | "settings">("marketplace");
const installedPlugins = ref<InstalledPlugin[]>([]);
const trustedKeys = ref<PluginTrustedKey[]>([]);
@@ -653,6 +664,7 @@ async function runBatchUninstall() {
(definition) => definition.plugin.manifest.name,
async (definition) => {
await api.uninstallPlugin(definition.plugin.manifest.id);
forgetGraphicsEngineGrant(definition.plugin.manifest.id);
},
(definition) => definition.plugin.manifest.id,
);
@@ -1034,6 +1046,7 @@ async function uninstallSelectedPlugin() {
operating.value = true;
try {
applyInstalledPlugins(await api.uninstallPlugin(definition.plugin.manifest.id));
forgetGraphicsEngineGrant(definition.plugin.manifest.id);
retireBatchFailure(definition.plugin.manifest.id);
notifyComponentUpdatesChanged();
window.dispatchEvent(new CustomEvent("dbx:plugins-changed"));
@@ -1569,6 +1582,8 @@ onBeforeUnmount(() => {
<PluginAiAccessSection :key="selectedDefinition.plugin.manifest.id" :plugin="selectedDefinition.plugin" />
<PluginGraphicsEngineSection :key="`graphics-${selectedDefinition.plugin.manifest.id}`" :plugin="selectedDefinition.plugin" />
<div v-if="connectionProviders.some((entry) => entry.plugin.manifest.id === selectedPluginId)" class="space-y-3">
<div class="flex flex-wrap gap-2">
<Button
@@ -0,0 +1,72 @@
// @vitest-environment happy-dom
import { createApp, h, reactive } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import PluginGraphicsEngineSection from "./PluginGraphicsEngineSection.vue";
import type { InstalledPlugin } from "@/types/database";
const mocks = vi.hoisted(() => ({ state: null as any, save: vi.fn(), toast: vi.fn() }));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => mocks.state }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
function plugin(id: string, withUi: boolean): InstalledPlugin {
return {
manifest: { id, version: "1.0.0", name: id, drivers: [], entrypoints: withUi ? { ui: { root: "ui", entry: "ui/index.html" } } : undefined },
} as unknown as InstalledPlugin;
}
let app: ReturnType<typeof createApp>;
let container: HTMLDivElement;
function mount(target: InstalledPlugin) {
container = document.createElement("div");
document.body.append(container);
app = createApp({ render: () => h(PluginGraphicsEngineSection, { plugin: target }) });
app.mount(container);
}
beforeEach(() => {
vi.clearAllMocks();
mocks.state = reactive({
isEditorSettingsLoaded: true,
editorSettings: { pluginGraphicsEngineIds: [] },
updateEditorSettingsAndPersist: mocks.save,
});
mocks.save.mockImplementation(async (partial: any) => {
Object.assign(mocks.state.editorSettings, partial);
});
});
afterEach(() => {
app.unmount();
container.remove();
});
describe("plugin graphics engine section", () => {
it("stays hidden for plugins without a ui entrypoint", () => {
mount(plugin("io.dbx.backend-only", false));
expect(container.querySelector("[data-plugin-graphics-engine]")).toBeNull();
});
it("grants and revokes the plugin without touching other grants", async () => {
mocks.state.editorSettings.pluginGraphicsEngineIds = ["io.dbx.other"];
mount(plugin("io.github.t8y2.s3", true));
const toggle = container.querySelector<HTMLElement>('[role="switch"]')!;
expect(toggle.getAttribute("aria-checked")).toBe("false");
toggle.click();
await vi.waitFor(() => expect(mocks.state.editorSettings.pluginGraphicsEngineIds).toEqual(["io.dbx.other", "io.github.t8y2.s3"]));
await vi.waitFor(() => expect(container.querySelector<HTMLElement>('[role="switch"]')!.getAttribute("aria-checked")).toBe("true"));
container.querySelector<HTMLElement>('[role="switch"]')!.click();
await vi.waitFor(() => expect(mocks.state.editorSettings.pluginGraphicsEngineIds).toEqual(["io.dbx.other"]));
});
it("toasts when persisting the grant fails", async () => {
mount(plugin("io.github.t8y2.s3", true));
mocks.save.mockRejectedValueOnce(new Error("disk full"));
container.querySelector<HTMLElement>('[role="switch"]')!.click();
await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalled());
expect(mocks.state.editorSettings.pluginGraphicsEngineIds).toEqual([]);
});
});
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { Palette } from "@lucide/vue";
import { Switch } from "@/components/ui/switch";
import { useToast } from "@/composables/useToast";
import { useSettingsStore } from "@/stores/settingsStore";
import { isPluginGraphicsEngineEnabled, withPluginGraphicsEngineEnabled } from "@/lib/plugins/pluginGraphicsEngine";
import type { InstalledPlugin } from "@/types/database";
const props = defineProps<{ plugin: InstalledPlugin }>();
const { t } = useI18n();
const { toast } = useToast();
const settings = useSettingsStore();
const pluginId = computed(() => props.plugin.manifest.id);
// Only a plugin that ships a UI can render through a graphics engine.
const hasUi = computed(() => !!props.plugin.manifest.entrypoints?.ui);
const enabled = computed(() => isPluginGraphicsEngineEnabled(settings.editorSettings.pluginGraphicsEngineIds, pluginId.value));
const saving = ref(false);
async function setEnabled(next: boolean) {
if (saving.value) return;
saving.value = true;
try {
await settings.updateEditorSettingsAndPersist({
pluginGraphicsEngineIds: withPluginGraphicsEngineEnabled(settings.editorSettings.pluginGraphicsEngineIds, pluginId.value, next),
});
} catch (error) {
toast(t("pluginPlatform.graphicsEngine.saveFailed", { message: error instanceof Error ? error.message : String(error) }), 5000);
} finally {
saving.value = false;
}
}
</script>
<template>
<section v-if="hasUi" class="space-y-3 rounded-lg border p-4" data-plugin-graphics-engine>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-start gap-2">
<Palette class="mt-0.5 size-4 shrink-0 text-primary" />
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("pluginPlatform.graphicsEngine.title") }}</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.graphicsEngine.description") }}</p>
</div>
</div>
<Switch :model-value="enabled" :disabled="saving" :aria-label="t('pluginPlatform.graphicsEngine.title')" @update:model-value="setEnabled($event === true)" />
</div>
<div class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-[11px] leading-4 text-muted-foreground">{{ t("pluginPlatform.graphicsEngine.securityNote") }}</div>
</section>
</template>
@@ -19,6 +19,7 @@ import {
type PluginAiRecommendationHostUpdate,
} from "@/lib/plugins/pluginHostBridge";
import { getCachedPluginUiHtml, getOrLoadPluginUiHtml } 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";
import { buildPluginEditorAppearance } from "@/lib/plugins/pluginAppearance";
@@ -56,6 +57,9 @@ const { t, locale: appLocale } = useI18n();
const { isDark, themeRevision } = useTheme();
const settingsStore = useSettingsStore();
const openAiConversation = inject(OPEN_PLUGIN_AI_CONVERSATION, undefined);
// Per-plugin grant for `script-src 'unsafe-eval'`; flipping it rebuilds the
// sandbox document (and must not reuse a doc cached under the other setting).
const graphicsEngineEnabled = computed(() => isPluginGraphicsEngineEnabled(settingsStore.editorSettings.pluginGraphicsEngineIds, props.plugin.manifest.id));
// --- Plugin AI generation consent (E2) --------------------------------------
// Every host.ai.generateText send is consented through this in-app dialog: it
@@ -711,12 +715,17 @@ async function loadWorkbench() {
const { html, entryDirectory } = cachedHtml;
// The final sandbox document is cached alongside the html: generating it
// re-runs megabyte-scale string surgery on every boot.
if (!cachedHtml.sandboxDoc) {
cachedHtml.sandboxDoc = pluginSandboxDocument(html, props.plugin.manifest.permissions, currentBridgeTheme(), {
baseUrl: pluginUiBaseUrl(props.plugin.manifest.id, entryDirectory),
});
const allowUnsafeEval = graphicsEngineEnabled.value;
if (!cachedHtml.sandboxDoc || cachedHtml.sandboxDoc.allowUnsafeEval !== allowUnsafeEval) {
cachedHtml.sandboxDoc = {
allowUnsafeEval,
doc: pluginSandboxDocument(html, props.plugin.manifest.permissions, currentBridgeTheme(), {
baseUrl: pluginUiBaseUrl(props.plugin.manifest.id, entryDirectory),
allowUnsafeEval,
}),
};
}
source.value = cachedHtml.sandboxDoc;
source.value = cachedHtml.sandboxDoc.doc;
await nextTick();
if (disposed || generation !== loadGeneration) return;
createBridge();
@@ -773,7 +782,7 @@ onMounted(async () => {
// Identity changes require rebuilding the sandbox document; context and locale
// changes are pushed through the bridge so plugin UI state survives them.
watch(
() => [props.plugin.manifest.id, props.plugin.manifest.version, props.contribution.id] as const,
() => [props.plugin.manifest.id, props.plugin.manifest.version, props.contribution.id, graphicsEngineEnabled.value] as const,
() => void loadWorkbench(),
);
watch(
@@ -30,6 +30,9 @@ vi.mock("@/lib/backend/api", () => mocks);
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ connections: [] }) }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({}) }));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({ editorSettings: { pluginGraphicsEngineIds: [] }, updateEditorSettings: vi.fn() }),
}));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: mocks.isTauriRuntime }));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => vi.fn()) }));
vi.mock("@tauri-apps/plugin-shell", () => ({ open: mocks.openExternal }));
@@ -61,6 +64,9 @@ vi.mock("@/components/plugins/PluginIcon.vue", async () => ({ default: (await im
// Shortcut preferences have their own component/store tests. Keep this batch
// harness scoped to plugin mutations and their exact backend call counts.
vi.mock("@/components/plugins/PluginShortcutSettings.vue", async () => ({ default: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("PluginShortcutSettings") }));
// The graphics-engine grant lives in the settings store; this batch harness has
// no pinia, so the section is stubbed like the other store-backed child panels.
vi.mock("@/components/plugins/PluginGraphicsEngineSection.vue", async () => ({ default: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("PluginGraphicsEngineSection") }));
import PluginContributionsPanel from "@/components/plugins/PluginContributionsPanel.vue";
+6
View File
@@ -76,6 +76,12 @@ export default withEnglishFallback({
needsApproval: "Təsdiq tələb olunur",
saveFailed: "Ayar saxlanılmadı: {message}",
},
graphicsEngine: {
title: "Qrafika mühərriki",
description: "Bu plaginin interfeysinə WebGL qrafika mühərrikini (PixiJS və bənzərləri) işə salmağa icazə verir. Bağlı olduqda ona ehtiyac duyan vizual elementlər işə düşmür və plagin qrafika mühərrikinin əlçatmaz olduğunu bildirir.",
securityNote: "Açıq olduqda bu plaginin skriptləri icra zamanı kod tərtib edə bilər (CSP unsafe-eval). Güzəşt yalnız bu plaginə şamil olunur.",
saveFailed: "Ayar saxlanılmadı: {message}",
},
dataAccess: {
title: "Məlumat girişi",
description: "Bu plaginin yalnız oxuma sorğuları ilə oxuya biləcəyi bağlantılar. Plagin bağlantıya ilk dəfə ehtiyac duyanda sizdən soruşur; girişi burada istənilən vaxt ləğv edə bilərsiniz.",
+6
View File
@@ -183,6 +183,12 @@ export default {
needsApproval: "Needs approval",
saveFailed: "Could not save the setting: {message}",
},
graphicsEngine: {
title: "Graphics engine",
description: "Lets this plugin's interface run a WebGL graphics engine (PixiJS and similar). While this is off, visuals that need one cannot start and the plugin reports that its graphics engine is unavailable.",
securityNote: "On means this plugin's scripts may compile code at runtime (CSP unsafe-eval). The relaxation applies to this plugin only.",
saveFailed: "Could not save the setting: {message}",
},
dataAccess: {
title: "Data access",
description: "Connections this plugin may read with read-only queries. The plugin asks you the first time it needs a connection; you can revoke access here at any time.",
+6
View File
@@ -185,6 +185,12 @@ export default withEnglishFallback({
needsApproval: "Requiere aprobación",
saveFailed: "No se pudo guardar la configuración: {message}",
},
graphicsEngine: {
title: "Motor gráfico",
description: "Permite que la interfaz de este plugin ejecute un motor gráfico WebGL (PixiJS y similares). Mientras esté desactivado, los elementos visuales que lo necesiten no podrán iniciarse y el plugin indicará que el motor gráfico no está disponible.",
securityNote: "Activarlo permite que los scripts de este plugin compilen código en tiempo de ejecución (CSP unsafe-eval). La relajación se aplica solo a este plugin.",
saveFailed: "No se pudo guardar la configuración: {message}",
},
dataAccess: {
title: "Acceso a datos",
description: "Conexiones que este plugin puede leer con consultas de solo lectura. El plugin te pregunta la primera vez que necesita una conexión; puedes revocar el acceso aquí en cualquier momento.",
+6
View File
@@ -105,6 +105,12 @@ export default withEnglishFallback({
needsApproval: "Perlu persetujuan",
saveFailed: "Tidak dapat menyimpan pengaturan: {message}",
},
graphicsEngine: {
title: "Mesin grafis",
description: "Mengizinkan antarmuka plugin ini menjalankan mesin grafis WebGL (PixiJS dan sejenisnya). Saat nonaktif, visual yang membutuhkannya tidak dapat dimulai dan plugin melaporkan mesin grafis tidak tersedia.",
securityNote: "Jika aktif, skrip plugin ini dapat mengompilasi kode saat runtime (CSP unsafe-eval). Pelonggaran hanya berlaku untuk plugin ini.",
saveFailed: "Tidak dapat menyimpan pengaturan: {message}",
},
dataAccess: {
title: "Akses data",
description: "Koneksi yang boleh dibaca plugin ini dengan kueri read-only. Plugin akan meminta izin saat pertama kali membutuhkan koneksi; Anda dapat mencabut akses ini kapan saja.",
+6
View File
@@ -183,6 +183,12 @@ export default withEnglishFallback({
needsApproval: "Richiede approvazione",
saveFailed: "Impossibile salvare l'impostazione: {message}",
},
graphicsEngine: {
title: "Motore grafico",
description: "Consente all'interfaccia di questo plugin di eseguire un motore grafico WebGL (PixiJS e simili). Quando è disattivato, gli elementi visivi che ne hanno bisogno non si avviano e il plugin segnala che il motore grafico non è disponibile.",
securityNote: "Attivandolo, gli script di questo plugin possono compilare codice in fase di esecuzione (CSP unsafe-eval). L'allentamento vale solo per questo plugin.",
saveFailed: "Impossibile salvare l'impostazione: {message}",
},
dataAccess: {
title: "Accesso ai dati",
description: "Connessioni che questo plugin può leggere con query di sola lettura. Il plugin te lo chiede la prima volta che gli serve una connessione; puoi revocare l'accesso qui in qualsiasi momento.",
+6
View File
@@ -184,6 +184,12 @@ export default withEnglishFallback({
needsApproval: "承認が必要",
saveFailed: "設定を保存できませんでした: {message}",
},
graphicsEngine: {
title: "グラフィックスエンジン",
description: "このプラグインの UI が WebGL グラフィックスエンジン(PixiJS など)を使えるようにします。オフのときは、それを必要とする表示は開始できず、プラグインはグラフィックスエンジンを利用できないと報告します。",
securityNote: "オンにすると、このプラグインのスクリプトが実行時にコードを生成できます(CSP unsafe-eval)。緩和はこのプラグインにのみ適用されます。",
saveFailed: "設定を保存できませんでした: {message}",
},
dataAccess: {
title: "データアクセス",
description: "このプラグインが読み取り専用クエリを実行できる接続です。プラグインが初めて接続を必要とするときに確認を求めます。ここでいつでも取り消せます。",
+6
View File
@@ -183,6 +183,12 @@ export default withEnglishFallback({
needsApproval: "승인 필요",
saveFailed: "설정을 저장할 수 없습니다: {message}",
},
graphicsEngine: {
title: "그래픽 엔진",
description: "이 플러그인 인터페이스가 WebGL 그래픽 엔진(PixiJS 등)을 실행할 수 있게 합니다. 꺼져 있으면 해당 엔진이 필요한 화면은 시작되지 않으며 플러그인이 그래픽 엔진을 사용할 수 없다고 표시합니다.",
securityNote: "켜면 이 플러그인 스크립트가 런타임에 코드를 컴파일할 수 있습니다(CSP unsafe-eval). 완화는 이 플러그인에만 적용됩니다.",
saveFailed: "설정을 저장할 수 없습니다: {message}",
},
dataAccess: {
title: "데이터 액세스",
description: "이 플러그인이 읽기 전용 쿼리로 읽을 수 있는 연결입니다. 플러그인이 처음 연결이 필요할 때 동의를 요청하며, 여기에서 언제든지 취소할 수 있습니다.",
+6
View File
@@ -184,6 +184,12 @@ export default withEnglishFallback({
needsApproval: "Requer aprovação",
saveFailed: "Não foi possível salvar a configuração: {message}",
},
graphicsEngine: {
title: "Motor gráfico",
description: "Permite que a interface deste plugin execute um motor gráfico WebGL (PixiJS e similares). Enquanto estiver desativado, os visuais que dependem dele não iniciam e o plugin informa que o motor gráfico está indisponível.",
securityNote: "Ativado, os scripts deste plugin podem compilar código em tempo de execução (CSP unsafe-eval). O abrandamento vale apenas para este plugin.",
saveFailed: "Não foi possível salvar a configuração: {message}",
},
dataAccess: {
title: "Acesso a dados",
description: "Conexões que este plugin pode ler com consultas somente leitura. O plugin pergunta a você na primeira vez que precisa de uma conexão; você pode revogar o acesso aqui a qualquer momento.",
+6
View File
@@ -154,6 +154,12 @@ export default withEnglishFallback({
needsApproval: "Нужно подтверждение",
saveFailed: "Не удалось сохранить настройку: {message}",
},
graphicsEngine: {
title: "Графический движок",
description: "Позволяет интерфейсу этого плагина использовать WebGL-движок (PixiJS и подобные). Когда выключено, зависящие от него визуализации не запускаются, и плагин сообщает, что графический движок недоступен.",
securityNote: "Во включённом виде скрипты плагина могут компилировать код во время выполнения (CSP unsafe-eval). Ослабление действует только для этого плагина.",
saveFailed: "Не удалось сохранить настройку: {message}",
},
dataAccess: {
title: "Доступ к данным",
description: "Подключения, которые этот плагин может читать запросами только на чтение. Плагин спрашивает разрешение, когда подключение понадобится ему впервые; отозвать доступ можно здесь в любой момент.",
+6
View File
@@ -76,6 +76,12 @@ export default withEnglishFallback({
needsApproval: "Onay gerekir",
saveFailed: "Ayar kaydedilemedi: {message}",
},
graphicsEngine: {
title: "Grafik motoru",
description: "Bu eklentinin arayüzünün bir WebGL grafik motoru (PixiJS ve benzerleri) çalıştırmasına izin verir. Kapalıyken buna ihtiyaç duyan görseller başlamaz ve eklenti grafik motorunun kullanılamadığını bildirir.",
securityNote: "Açıkken bu eklentinin betikleri çalışma zamanında kod derleyebilir (CSP unsafe-eval). Gevşetme yalnızca bu eklenti için geçerlidir.",
saveFailed: "Ayar kaydedilemedi: {message}",
},
dataAccess: {
title: "Veri erişimi",
description: "Bu eklentinin salt okunur sorgularla okuyabileceği bağlantılar. Eklenti bir bağlantıya ilk kez ihtiyaç duyduğunda size sorar; erişimi burada istediğiniz zaman iptal edebilirsiniz.",
+6
View File
@@ -129,6 +129,12 @@ export default withEnglishFallback({
needsApproval: "需确认",
saveFailed: "保存设置失败:{message}",
},
graphicsEngine: {
title: "图形引擎",
description: "允许此插件的界面运行 WebGL 图形引擎(PixiJS 一类)。关闭时依赖它的画面无法启动,插件会提示图形引擎不可用。",
securityNote: "开启后此插件的脚本可以在运行时编译代码(CSP unsafe-eval),放宽只作用于这一个插件。",
saveFailed: "保存设置失败:{message}",
},
dataAccess: {
title: "数据访问",
description: "该插件可以执行只读查询的连接。插件首次需要某个连接时会征求你的同意,你可以随时在这里撤销。",
+6
View File
@@ -186,6 +186,12 @@ export default withEnglishFallback({
needsApproval: "需確認",
saveFailed: "儲存設定失敗:{message}",
},
graphicsEngine: {
title: "圖形引擎",
description: "允許此外掛的介面執行 WebGL 圖形引擎(PixiJS 一類)。關閉時依賴它的畫面無法啟動,外掛會提示圖形引擎不可用。",
securityNote: "開啟後此外掛的指令碼可以在執行期編譯程式碼(CSP unsafe-eval),放寬只作用於這一個外掛。",
saveFailed: "儲存設定失敗:{message}",
},
dataAccess: {
title: "資料存取",
description: "此外掛可以執行唯讀查詢的連線。外掛首次需要某個連線時會徵求你的同意,你可以隨時在這裡撤銷。",
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { isPluginGraphicsEngineEnabled, normalizePluginGraphicsEngineIds, withPluginGraphicsEngineEnabled } from "./pluginGraphicsEngine";
describe("pluginGraphicsEngine", () => {
it("defaults to no grants and drops junk entries", () => {
expect(normalizePluginGraphicsEngineIds(undefined)).toEqual([]);
expect(normalizePluginGraphicsEngineIds("io.github.t8y2.s3")).toEqual([]);
expect(normalizePluginGraphicsEngineIds([null, 7, "", " ", "io.github.t8y2.s3", " io.github.t8y2.s3 "])).toEqual(["io.github.t8y2.s3"]);
});
it("grants and revokes a single plugin without touching the others", () => {
const granted = withPluginGraphicsEngineEnabled(["io.dbx.chart"], "io.github.t8y2.s3", true);
expect(granted).toEqual(["io.dbx.chart", "io.github.t8y2.s3"]);
expect(isPluginGraphicsEngineEnabled(granted, "io.github.t8y2.s3")).toBe(true);
expect(isPluginGraphicsEngineEnabled(granted, "io.dbx.other")).toBe(false);
const revoked = withPluginGraphicsEngineEnabled(granted, "io.github.t8y2.s3", false);
expect(revoked).toEqual(["io.dbx.chart"]);
expect(isPluginGraphicsEngineEnabled(revoked, "io.github.t8y2.s3")).toBe(false);
});
it("never grants an empty plugin id", () => {
expect(withPluginGraphicsEngineEnabled([], "", true)).toEqual([]);
expect(isPluginGraphicsEngineEnabled([""], "")).toBe(false);
});
it("keeps a re-grant idempotent", () => {
const once = withPluginGraphicsEngineEnabled([], "io.dbx.chart", true);
expect(withPluginGraphicsEngineEnabled(once, "io.dbx.chart", true)).toEqual(once);
});
});
@@ -0,0 +1,35 @@
/**
* Per-plugin opt-in for `script-src 'unsafe-eval'` in the workbench sandbox.
*
* WebGL graphics engines generate their uniform/UBO sync code with
* `new Function` (PixiJS 8 refuses to even construct a renderer when that
* throws), so a plugin whose UI renders through such an engine needs
* unsafe-eval or its visual surfaces never initialize. The sandbox keeps the
* directive off by default and the user grants it one plugin at a time, the
* same way AI tool access and data reads are granted.
*/
const MAX_GRANTED_PLUGINS = 64;
export function normalizePluginGraphicsEngineIds(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const ids = new Set<string>();
for (const entry of value) {
if (typeof entry !== "string") continue;
const id = entry.trim();
if (!id) continue;
ids.add(id);
if (ids.size >= MAX_GRANTED_PLUGINS) break;
}
return [...ids];
}
export function isPluginGraphicsEngineEnabled(ids: readonly string[] | undefined, pluginId: string): boolean {
return !!pluginId && (ids || []).includes(pluginId);
}
export function withPluginGraphicsEngineEnabled(ids: readonly string[] | undefined, pluginId: string, enabled: boolean): string[] {
const current = normalizePluginGraphicsEngineIds(ids).filter((id) => id !== pluginId);
if (!enabled || !pluginId) return current;
return [...current, pluginId].slice(0, MAX_GRANTED_PLUGINS);
}
+16
View File
@@ -1059,6 +1059,22 @@ describe("PluginHostBridge", () => {
expect(document).not.toContain("<base ");
});
it("adds unsafe-eval to script-src only for the granted plugin", () => {
const granted = pluginSandboxDocument("<html><head></head><body></body></html>", [], undefined, {
baseUrl: "http://dbx-plugin.localhost/io.github.t8y2.s3/assets/",
allowUnsafeEval: true,
});
expect(granted).toContain("script-src 'unsafe-inline' 'unsafe-eval' blob: http://dbx-plugin.localhost;");
// The grant is scoped to script-src; no other directive picks it up.
expect(granted).toContain("style-src 'unsafe-inline' blob:;");
expect(granted).not.toContain("img-src data: blob: http://dbx-plugin.localhost 'unsafe-eval'");
const withheld = pluginSandboxDocument("<html><head></head><body></body></html>", [], undefined, {
baseUrl: "http://dbx-plugin.localhost/io.github.t8y2.s3/assets/",
});
expect(withheld).not.toContain("unsafe-eval");
});
it("pre-seeds the current theme as the sandbox first paint", () => {
const themed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events"], { appearance: "dark", tokens: { "--color-background": "#131416", "--color-foreground": "rgb(215 215 219)" } });
expect(themed).toContain("color-scheme: dark");
@@ -1097,13 +1097,21 @@ export interface PluginSandboxOptions {
* hosts without the plugin asset protocol (the web host).
*/
baseUrl?: string;
/**
* Adds `'unsafe-eval'` to `script-src`. WebGL graphics engines codegen their
* uniform sync with `new Function` and refuse to initialize without it, so
* the user grants this per plugin (see `pluginGraphicsEngine.ts`). Off by
* default: the sandbox stays eval-free for every other plugin.
*/
allowUnsafeEval?: boolean;
}
export function pluginSandboxDocument(html: string, permissions?: readonly string[], theme?: PluginBridgeTheme, options?: PluginSandboxOptions): string {
const networkOrigins = pluginNetworkOrigins(permissions);
const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
const assetSource = pluginAssetCspSource(options?.baseUrl);
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:${assetSource}; style-src 'unsafe-inline' blob:; img-src data: blob:${assetSource}; font-src data: blob:${assetSource}; ${connectSrc} media-src data: blob:${assetSource};">`;
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.
const base = options?.baseUrl && assetSource ? `<base href="${escapeHtmlAttribute(options.baseUrl)}">` : "";
@@ -12,8 +12,10 @@ export interface PluginUiHtml {
/** Final sandbox document (html + CSP/SDK/theme injection); built lazily once
* per plugin version — regenerating it re-runs megabyte-scale string surgery
* on every panel/tab boot. The embedded appearance only affects the pre-init
* first paint; the init message pushes the live theme right after. */
sandboxDoc?: string;
* first paint; the init message pushes the live theme right after. Carries the
* `unsafe-eval` grant it was built with: that grant is a user setting that can
* flip while the html stays valid, and it changes the CSP. */
sandboxDoc?: { allowUnsafeEval: boolean; doc: string };
}
const cache = new Map<string, PluginUiHtml>();
+6
View File
@@ -1,4 +1,5 @@
import { normalizeModelTemplates, type ModelTemplate } from "@/lib/model/modelTemplates";
import { normalizePluginGraphicsEngineIds } from "@/lib/plugins/pluginGraphicsEngine";
import { normalizePluginShortcutSettings, type PluginShortcutSettings } from "@/lib/plugins/pluginShortcuts";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
@@ -1085,6 +1086,8 @@ export interface EditorSettings {
updateDownloadSource: UpdateDownloadSource;
ignoredUpdateVersion: string;
pluginShortcuts: PluginShortcutSettings;
/** Plugin ids the user granted `script-src 'unsafe-eval'` in the workbench sandbox. */
pluginGraphicsEngineIds: string[];
toolbarItems: ToolbarItems;
objectBrowserShowCheckbox: boolean;
objectBrowserViewMode: "list" | "grid";
@@ -1393,6 +1396,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
updateDownloadSource: "official",
ignoredUpdateVersion: "",
pluginShortcuts: normalizePluginShortcutSettings(undefined),
pluginGraphicsEngineIds: [],
toolbarItems: { ...DEFAULT_TOOLBAR_ITEMS },
objectBrowserShowCheckbox: false,
objectBrowserViewMode: "list",
@@ -2066,6 +2070,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
updateDownloadSource: normalizeUpdateDownloadSource(settings.updateDownloadSource),
ignoredUpdateVersion: typeof settings.ignoredUpdateVersion === "string" ? settings.ignoredUpdateVersion : DEFAULT_EDITOR_SETTINGS.ignoredUpdateVersion,
pluginShortcuts: normalizePluginShortcutSettings(settings.pluginShortcuts),
pluginGraphicsEngineIds: normalizePluginGraphicsEngineIds(settings.pluginGraphicsEngineIds),
toolbarItems: normalizeToolbarItems(settings.toolbarItems),
objectBrowserShowCheckbox: typeof settings.objectBrowserShowCheckbox === "boolean" ? settings.objectBrowserShowCheckbox : DEFAULT_EDITOR_SETTINGS.objectBrowserShowCheckbox,
objectBrowserViewMode: settings.objectBrowserViewMode === "grid" ? "grid" : DEFAULT_EDITOR_SETTINGS.objectBrowserViewMode,
@@ -2895,6 +2900,7 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.updateDownloadSource !== undefined) editorSettings.value.updateDownloadSource = normalizeUpdateDownloadSource(partial.updateDownloadSource);
if (partial.ignoredUpdateVersion !== undefined) editorSettings.value.ignoredUpdateVersion = typeof partial.ignoredUpdateVersion === "string" ? partial.ignoredUpdateVersion : "";
if (partial.pluginShortcuts !== undefined) editorSettings.value.pluginShortcuts = normalizePluginShortcutSettings(partial.pluginShortcuts);
if (partial.pluginGraphicsEngineIds !== undefined) editorSettings.value.pluginGraphicsEngineIds = normalizePluginGraphicsEngineIds(partial.pluginGraphicsEngineIds);
if (partial.toolbarItems !== undefined) editorSettings.value.toolbarItems = normalizeToolbarItems(partial.toolbarItems);
if (partial.objectBrowserShowCheckbox !== undefined) editorSettings.value.objectBrowserShowCheckbox = partial.objectBrowserShowCheckbox === true;
if (partial.objectBrowserViewMode !== undefined) editorSettings.value.objectBrowserViewMode = partial.objectBrowserViewMode === "grid" ? "grid" : "list";