Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6469: host plugin artifacts, bind installs to immutable versions (#7321)
Jiayuan Zhangf45b591623bf
diff --git a/.env.example b/.env.exampleindex ab8778ec1d..2520e75769 100644--- a/.env.example+++ b/.env.example@@ -524,18 +524,20 @@ GITHUB_APP_PRIVATE_KEY=MULTICA_VCS_INTEGRATION_ENABLED=MULTICA_VCS_SECRET_KEY=-# Plugins (Settings → Plugins). Multica never executes plugin code: a plugin-# runs only inside a sandboxed iframe in the user's browser, or on the plugin-# author's own server. Two optional settings:+# Plugins (Settings → Plugins). A plugin's frontend is an artifact its author+# uploads; Multica stores it and serves it into a sandboxed iframe, and an+# installation is bound to one immutable version. Hook endpoints and MCP servers+# stay on the author's own infrastructure. Two optional settings:# 1. MULTICA_PLUGIN_SECRET_KEY — a base64-encoded 32-byte key that encrypts# `secret` config values at rest. Without it, saving a secret field fails# closed rather than storing plaintext. Generate one with:# openssl rand -base64 32# 2. MULTICA_PLUGIN_DIR — an absolute path to a directory of plugin folders,-# each containing a multica.plugin.json. A self-hosted operator or plugin-# author can then install with the source URL `local:<folder-name>`-# instead of publishing to a public HTTPS host first. Leave empty to-# accept only public HTTPS manifest URLs.+# each containing a multica.plugin.json. It is the development publish+# channel: an author iterating on a surface publishes straight from disk+# instead of zipping and uploading after every edit. It still produces an+# ordinary immutable version, so there is no second way for plugin code to+# reach a browser. Leave empty to accept uploads only.MULTICA_PLUGIN_SECRET_KEY=MULTICA_PLUGIN_DIR=diff --git a/e2e/plugin-surface-document.spec.ts b/e2e/plugin-surface-document.spec.tsnew file mode 100644index 0000000000..d9d230ef40--- /dev/null+++ b/e2e/plugin-surface-document.spec.ts@@ -0,0 +1,89 @@+import { expect, test } from "@playwright/test";+import { buildSurfaceDocument } from "../packages/views/plugins/surface-document";++/**+ * Real Chromium coverage for behavior jsdom does not implement: executing a+ * sandboxed srcdoc document, reporting errors from a dynamically inserted+ * script, and firing page lifecycle events when the host rewrites srcdoc.+ */++test.describe("plugin surface document (real Chromium, sandboxed srcdoc)", () => {+ test("a host-authored srcdoc reload is not reported as hostile navigation", async ({ page }) => {+ const first = buildSurfaceDocument({+ code: "parent.postMessage({ type: 'plugin-test-ran' }, '*');",+ grantedScopes: [],+ theme: {},+ });+ const themed = buildSurfaceDocument({+ code: "parent.postMessage({ type: 'plugin-test-ran' }, '*');",+ grantedScopes: [],+ theme: { "--background": "white" },+ });++ await page.setContent("<!doctype html><body></body>");+ await page.evaluate((srcdoc) => {+ const state = { ran: 0, navigated: 0 };+ (window as unknown as { __surfaceState: typeof state }).__surfaceState = state;+ window.addEventListener("message", (event) => {+ const type = (event.data as { type?: string } | null)?.type;+ if (type === "plugin-test-ran") state.ran++;+ if (type === "multica:plugin-surface-navigated") state.navigated++;+ });+ const frame = document.createElement("iframe");+ frame.id = "surface";+ frame.sandbox.add("allow-scripts");+ frame.srcdoc = srcdoc;+ document.body.appendChild(frame);+ }, first);++ await expect.poll(() => page.evaluate(() =>+ (window as unknown as { __surfaceState: { ran: number } }).__surfaceState.ran,+ )).toBe(1);++ await page.evaluate((srcdoc) => {+ document.querySelector<HTMLIFrameElement>("#surface")!.srcdoc = srcdoc;+ }, themed);+ await expect.poll(() => page.evaluate(() =>+ (window as unknown as { __surfaceState: { ran: number } }).__surfaceState.ran,+ )).toBe(2);++ expect(await page.evaluate(() =>+ (window as unknown as { __surfaceState: { navigated: number } }).__surfaceState.navigated,+ )).toBe(0);+ });++ test("reports a synchronous plugin error even when the host listener mounts late", async ({ page }) => {+ const documentWithError = buildSurfaceDocument({+ code: "throw new Error('plugin failed during bootstrap');",+ grantedScopes: [],+ theme: {},+ });++ await page.setContent("<!doctype html><body></body>");+ await page.evaluate((srcdoc) => {+ const frame = document.createElement("iframe");+ frame.id = "surface";+ frame.sandbox.add("allow-scripts");+ frame.srcdoc = srcdoc;+ document.body.appendChild(frame);+ }, documentWithError);++ // The guest has already executed and failed before the host starts+ // listening. A one-shot postMessage is lost in this ordering.+ await page.waitForTimeout(300);+ await page.evaluate(() => {+ (window as unknown as { __surfaceErrors: number }).__surfaceErrors = 0;+ window.addEventListener("message", (event) => {+ if ((event.data as { type?: string } | null)?.type !== "multica:plugin-surface-error") return;+ const frame = document.querySelector<HTMLIFrameElement>("#surface")!;+ if (event.source !== frame.contentWindow) return;+ (window as unknown as { __surfaceErrors: number }).__surfaceErrors++;+ frame.contentWindow!.postMessage({ type: "multica:plugin-surface-error-ack" }, "*");+ });+ });++ await expect.poll(() => page.evaluate(() =>+ (window as unknown as { __surfaceErrors: number }).__surfaceErrors,+ )).toBe(1);+ });+});diff --git a/examples/plugins/deploy-sentinel/README.md b/examples/plugins/deploy-sentinel/README.mdindex 07bd0f61fe..9bd9f3d79c 100644--- a/examples/plugins/deploy-sentinel/README.md+++ b/examples/plugins/deploy-sentinel/README.md@@ -73,10 +73,15 @@ export MULTICA_PLUGIN_DEV_ORIGINS=https://127.0.0.1:8788,https://127.0.0.1:8789export MULTICA_PLUGIN_DEV_CA=/path/to/your-dev-ca.pem```-Install it as `local:deploy-sentinel`, fill in the config form, then open the-`metrics` approval panel and tick the tools you want agents to reach. Nothing-under `metrics` is callable until you do — that is the whole difference between-the `mcp` transport and an `http` hook.+Publish it from `MULTICA_PLUGIN_DIR` as `deploy-sentinel`, install the version+that appears, fill in the config form, then open the `metrics` approval panel+and tick the tools you want agents to reach. Nothing under `metrics` is callable+until you do — that is the whole difference between the `mcp` transport and an+`http` hook.++Note what `MULTICA_PLUGIN_DIR` does and does not cover. It is a publishing+shortcut for the FRONTEND artifact only; the two servers above are still yours+to run, and the `net:` scopes are still what authorises reaching them.Both endpoints must be HTTPS even locally: the manifest validator requires it,and `MULTICA_PLUGIN_DEV_CA` is how you get a self-signed certificate trusted.diff --git a/examples/plugins/deploy-sentinel/ui/main.js b/examples/plugins/deploy-sentinel/ui/main.jsindex 951a2c0a5c..26283e59ad 100644--- a/examples/plugins/deploy-sentinel/ui/main.js+++ b/examples/plugins/deploy-sentinel/ui/main.js@@ -6,13 +6,84 @@// origin: no host cookies, no host storage, and no credential of any kind. Every// call below goes over the bridge, where the host re-issues it as the signed-in// user and checks the scopes this plugin was granted.+//+// A surface entry is ONE script with no module graph. Multica stores and serves+// the published artifact and inlines it into the document it generates, so+// there is no origin for a static `import` to resolve against — and that is the+// point: a surface cannot reach its author's server just by loading. In a real+// plugin you would bundle `@multica/plugin-sdk` in; this file inlines the few+// calls it needs so the example stays readable and has nothing to install.++const pending = new Map();+let port = null;+let sequence = 0;++window.addEventListener("message", (event) => {+ const data = event.data;+ if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;+ // Only the embedder may hand this frame a port, and only once. Sibling frames+ // are mutually opaque but `parent.frames[i]` is an allowed cross-origin+ // access, so another plugin on this page could otherwise deliver its own port+ // and become this surface's "host". Origin is useless here (a sandboxed frame+ // sees "null"), so identity is the window reference.+ if (event.source !== window.parent || port) return;+ port = event.ports[0];+ port.onmessage = (message) => {+ const payload = message.data;+ if (payload?.kind === "theme") return applyTheme(payload.theme);+ const entry = pending.get(payload?.id);+ if (!entry) return;+ pending.delete(payload.id);+ if (payload.ok) entry.resolve(payload.data);+ else entry.reject(new Error(payload.error));+ };+ port.start();+ applyTheme(data.theme);+ resize(360);+ correlate();+});++// Announce until the host answers with a port. One announcement is not enough+// in either direction: this frame can finish executing before the embedder's+// effect attaches its listener, and a host waiting on the iframe load event can+// miss that event entirely.+(function announce(attempts) {+ if (port || attempts > 50) return;+ window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");+ setTimeout(() => announce(attempts + 1), 120);+})(0);++function applyTheme(theme) {+ for (const [name, value] of Object.entries(theme ?? {})) {+ document.documentElement.style.setProperty(name, value);+ }+}++function call(method, path, body) {+ const id = `r${++sequence}`;+ return new Promise((resolve, reject) => {+ pending.set(id, { resolve, reject });+ port.postMessage({ id, kind: "action", method, path, body });+ });+}-import { multica } from "https://esm.sh/@multica/plugin-sdk@1";+function resize(height) {+ port.postMessage({ id: `resize${Date.now()}`, kind: "ui.resize", height });+}++// One of THIS plugin's own hooks, over the `ui` trigger. The host signs the+// outbound call and applies the rate limit; the frame never sees the endpoint.+async function invokeHook(hookKey, input) {+ const result = await call("POST", `/hooks/${encodeURIComponent(hookKey)}`, { trigger: "ui", input });+ if (result?.status !== "ok") throw new Error(result?.error ?? "The hook did not answer.");+ return result.output;+}const root = document.getElementById("root");function render(html) {root.innerHTML = html;+ resize(document.body.scrollHeight + 16);}function escapeHTML(value) {@@ -36,16 +107,17 @@ function deployRow(deploy) {async function correlate() {render(`<p class="muted">Looking for recent deploys…</p>`);try {- const issue = await multica.issue.get();+ const context = await call("GET", "/context");+ const issue = context.issue+ ? await call("GET", `/issues/${encodeURIComponent(context.issue.id)}`)+ : null;// The service name is a workspace-level setting rather than something// typed per issue: everyone investigating the same service should get the// same answer.- const service = (await multica.storage.workspace.get("default_service")) ?? "checkout-api";+ const stored = await call("GET", "/storage/workspace/default_service").catch(() => null);+ const service = stored?.value ?? "checkout-api";- const result = await multica.hooks.invoke("correlate_deploys", {- service,- window_minutes: 120,- });+ const result = await invokeHook("correlate_deploys", { service, window_minutes: 120 });if (!result?.deploys?.length) {render(`<p>${escapeHTML(result?.summary ?? "No deploys found.")}</p>`);@@ -72,7 +144,7 @@ root.addEventListener("click", async (event) => {event.target.disabled = true;try {- const result = await multica.hooks.invoke("request_rollback", { deploy_id: deployId, reason });+ const result = await invokeHook("request_rollback", { deploy_id: deployId, reason });render(result.status === "filed"? `<p>Filed <code>${escapeHTML(result.change_id)}</code>. ${escapeHTML(result.next_step)}</p>`: `<p class="error">${escapeHTML(result.reason)}</p>`);@@ -80,6 +152,3 @@ root.addEventListener("click", async (event) => {render(`<p class="error">${escapeHTML(error.message)}</p>`);}});--multica.ui.resize(360);-correlate();diff --git a/examples/plugins/hello-panel/README.md b/examples/plugins/hello-panel/README.mdindex 5e11739fb9..029e7a52ee 100644--- a/examples/plugins/hello-panel/README.md+++ b/examples/plugins/hello-panel/README.md@@ -17,14 +17,20 @@ boring — it should demonstrate the contract, not the framework of the week.## Running it-The manifest and `ui/main.js` must be served over public HTTPS from the same-directory, because `entry` resolves relative to the manifest URL and Multica-never re-hosts plugin code. Install by pasting the manifest URL into-**Settings → Plugins**.--`MULTICA_PLUGIN_DIR` installs (`local:hello-panel`) are for developing the-manifest itself: the install and consent flow work, but the panel cannot load a-script from the server's filesystem and says so instead of rendering blank.+Zip this folder — the manifest plus every file it names — and upload it in+**Settings → Plugins**. You need no server of your own: Multica stores the+artifact, serves the panel script from it, and binds your installation to that+one immutable version.++`ui/main.js` is one file with no `import`. That is the contract, not a+simplification for the example: the host inlines the entry into the sandboxed+document it generates, so there is no origin a module specifier could resolve+against. Bundle your dependencies in.++While you are iterating, `MULTICA_PLUGIN_DIR` publishes straight from disk+instead of asking you to zip and upload after every edit. It still produces an+ordinary version — re-publishing an unchanged version number lands as+`1.0.0+dev.N` — so a panel always runs code somebody consented to.## Note on scopesdiff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 785ead4a50..ce278c72d8 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY, clientErrorMessage } from "./client";-import { EMPTY_PLUGIN_PREVIEW } from "./schemas";+import { EMPTY_PLUGIN_PACKAGE_LIST, EMPTY_PLUGIN_PREVIEW, EMPTY_PLUGIN_SURFACE_SCRIPT } from "./schemas";afterEach(() => {vi.unstubAllGlobals();@@ -153,9 +153,45 @@ describe("ApiClient Plugin preview response schema", () => {await expect(new ApiClient("https://api.example.test").previewPlugin("workspace-1",- { source_url: "https://example.test/multica.plugin.json" },+ { version_id: "version-1" },)).resolves.toEqual(EMPTY_PLUGIN_PREVIEW);});++ // A surface's code is what the host inlines into a sandboxed frame. A+ // malformed response must fall back to an EMPTY script, which the frame+ // renders as "could not load" — not to a partial one that runs.+ it("falls back to an empty surface script when the response is malformed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ code: 42 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ await expect(new ApiClient("https://api.example.test").getPluginSurfaceScript(+ "workspace-1",+ "installation-1",+ "hello",+ )).resolves.toEqual(EMPTY_PLUGIN_SURFACE_SCRIPT);+ });++ it("falls back to an empty package list when the response is malformed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ packages: "nope" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ await expect(new ApiClient("https://api.example.test").listPluginPackages("workspace-1"))+ .resolves.toEqual(EMPTY_PLUGIN_PACKAGE_LIST);+ });});describe("ApiClient server Table query", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex d8a3ce2f9a..7980116c86 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -151,6 +151,9 @@ import type {PluginHookResult,PluginInstallation,PluginInstallationListResponse,+ PluginPackage,+ PluginPackageListResponse,+ PluginSurfaceScript,PluginInvocation,PluginMCPTool,PluginPreview,@@ -401,8 +404,14 @@ import {EMPTY_WORKSPACE_MCP_SERVER,EMPTY_PLUGIN_INSTALLATION_LIST,EMPTY_PLUGIN_PREVIEW,+ EMPTY_PLUGIN_PACKAGE,+ EMPTY_PLUGIN_PACKAGE_LIST,+ EMPTY_PLUGIN_SURFACE_SCRIPT,PluginHookResultSchema,PluginInstallationListResponseSchema,+ PluginPackageListResponseSchema,+ PluginPackageSchema,+ PluginSurfaceScriptSchema,PluginInvocationListSchema,PluginMCPToolListSchema,PluginTokenIssueSchema,@@ -2483,6 +2492,75 @@ export class ApiClient {});}+ /** Everything published into this workspace, with its versions. */+ async listPluginPackages(workspaceId: string): Promise<PluginPackageListResponse> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/packages`);+ return parseWithFallback(raw, PluginPackageListResponseSchema, EMPTY_PLUGIN_PACKAGE_LIST, {+ endpoint: "GET /api/workspaces/{id}/plugins/packages",+ });+ }++ /**+ * Publishes an artifact bundle: a zip holding the manifest and every file it+ * names. This is the whole publishing path — a plugin author needs no server+ * of their own, and nothing about a published version changes afterwards.+ *+ * Not routed through `this.fetch`, for the same reason uploadFile is not: the+ * browser has to set the multipart boundary itself.+ */+ async publishPluginPackage(workspaceId: string, bundle: File): Promise<PluginPackage> {+ const formData = new FormData();+ formData.append("bundle", bundle);++ const res = await fetch(`${this.baseUrl}/api/workspaces/${workspaceId}/plugins/packages`, {+ method: "POST",+ headers: this.authHeaders(),+ body: formData,+ credentials: "include",+ });+ if (!res.ok) {+ if (res.status === 401) this.handleUnauthorized();+ throw new Error(await this.parseErrorMessage(res, `Publishing failed: ${res.status}`));+ }+ const raw = (await res.json()) as unknown;+ return parseWithFallback(raw, PluginPackageSchema, EMPTY_PLUGIN_PACKAGE, {+ endpoint: "POST /api/workspaces/{id}/plugins/packages",+ });+ }++ /**+ * Publishes from a directory the operator hosts (MULTICA_PLUGIN_DIR) — the+ * development channel, so iterating on a surface does not mean zipping and+ * uploading after every edit. It still produces an immutable version.+ */+ async publishLocalPluginPackage(workspaceId: string, name: string): Promise<PluginPackage> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/packages/local`, {+ method: "POST",+ body: JSON.stringify({ name }),+ });+ return parseWithFallback(raw, PluginPackageSchema, EMPTY_PLUGIN_PACKAGE, {+ endpoint: "POST /api/workspaces/{id}/plugins/packages/local",+ });+ }++ async deletePluginPackage(workspaceId: string, packageId: string): Promise<void> {+ await this.fetch<void>(`/api/workspaces/${workspaceId}/plugins/packages/${packageId}`, { method: "DELETE" });+ }++ /**+ * The code one surface runs, read from the version the workspace installed.+ * The host inlines it into the sandboxed document, so nothing is fetched from+ * the plugin author's infrastructure to render a panel.+ */+ async getPluginSurfaceScript(workspaceId: string, installationId: string, surfaceKey: string): Promise<PluginSurfaceScript> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/plugins/${installationId}/surfaces/${encodeURIComponent(surfaceKey)}/script`,+ );+ return parseWithFallback(raw, PluginSurfaceScriptSchema, EMPTY_PLUGIN_SURFACE_SCRIPT, {+ endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/surfaces/{surfaceKey}/script",+ });+ }+/*** Step one of the two-step install. Nothing is written: the response is what* the consent screen shows before an installation exists.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5a36a52ea8..4af75e0ff5 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -65,7 +65,10 @@ import type {NotificationPreferenceResponse,PluginInstallation,PluginInstallationListResponse,+ PluginPackage,+ PluginPackageListResponse,PluginPreview,+ PluginSurfaceScript,ResourceLabelsResponse,RuntimeModelListRequest,SearchIssuesResponse,@@ -122,7 +125,7 @@ export const PluginInstallationSchema = z.object({name: z.string().default(""),description: z.string().optional(),version: z.string().default(""),- source_url: z.string().default(""),+ package_version_id: z.string().default(""),enabled: z.boolean().default(false),granted_scopes: z.array(z.string()).default([]),config_schema: z.array(PluginConfigFieldSchema).default([]),@@ -140,7 +143,7 @@ export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {plugin_key: "",name: "",version: "",- source_url: "",+ package_version_id: "",enabled: false,granted_scopes: [],config_schema: [],@@ -235,6 +238,9 @@ export const PluginPreviewSchema = z.object({manifest: PluginManifestSummarySchema,scopes: z.array(z.string()).default([]),config_schema: z.array(PluginConfigFieldSchema).default([]),+ version_id: z.string().default(""),+ version: z.string().default(""),+ digest: z.string().default(""),installed: z.boolean().default(false),installed_version: z.string().optional(),added_scopes: z.array(z.string()).default([]),@@ -244,10 +250,68 @@ export const EMPTY_PLUGIN_PREVIEW: PluginPreview = {manifest: { key: "", name: "", version: "", author: { name: "" } },scopes: [],config_schema: [],+ version_id: "",+ version: "",+ digest: "",installed: false,added_scopes: [],};+/**+ * A published version. `installed` is the marker the settings page reads to+ * answer "which one am I on"; it defaults to false so a malformed response can+ * never claim a version is running that is not.+ */+export const PluginPackageVersionSchema = z.object({+ id: z.string().default(""),+ version: z.string().default(""),+ digest: z.string().default(""),+ size_bytes: z.number().default(0),+ published_at: z.string().default(""),+ installed: z.boolean().default(false),+}).loose();++export const PluginPackageSchema = z.object({+ id: z.string().default(""),+ plugin_key: z.string().default(""),+ name: z.string().default(""),+ versions: z.array(PluginPackageVersionSchema).default([]),+ created_at: z.string().default(""),+}).loose();++export const PluginPackageListResponseSchema = z.object({+ packages: z.array(PluginPackageSchema).default([]),+}).loose();++export const EMPTY_PLUGIN_PACKAGE_LIST: PluginPackageListResponse = {+ packages: [],+};++export const EMPTY_PLUGIN_PACKAGE: PluginPackage = {+ id: "",+ plugin_key: "",+ name: "",+ versions: [],+ created_at: "",+};++/**+ * A surface's code. The empty default is what the frame renders as "this panel+ * could not load" — an unparseable response must never become an empty script+ * that looks like a working but silent panel.+ */+export const PluginSurfaceScriptSchema = z.object({+ code: z.string().default(""),+ version: z.string().default(""),+ digest: z.string().default(""),+}).loose();++export const EMPTY_PLUGIN_SURFACE_SCRIPT: PluginSurfaceScript = {+ code: "",+ version: "",+ digest: "",+};+export const GitHubInstallationSchema = z.object({id: z.string(),workspace_id: z.string(),diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.tsindex d26ad6cb0b..3946067c97 100644--- a/packages/core/plugins/mutations.ts+++ b/packages/core/plugins/mutations.ts@@ -9,9 +9,9 @@ function useInvalidatePlugins(wsId: string) {}/**- * Preview is deliberately a mutation, not a query: it performs an outbound- * fetch of a URL the administrator just typed, so it must run on an explicit- * action and never be replayed by a cache refetch.+ * Preview is deliberately a mutation, not a query: it is the first half of a+ * consent flow the administrator started, so it must run on an explicit action+ * rather than be replayed by a cache refetch.*/export function usePreviewPlugin(wsId: string) {return useMutation({@@ -19,6 +19,35 @@ export function usePreviewPlugin(wsId: string) {});}+/**+ * Publishes an artifact bundle. A published version is immutable, so this only+ * ever adds one — it can never change what an installed workspace is running.+ */+export function usePublishPluginPackage(wsId: string) {+ const invalidate = useInvalidatePlugins(wsId);+ return useMutation({+ mutationFn: (bundle: File) => api.publishPluginPackage(wsId, bundle),+ onSettled: invalidate,+ });+}++/** The development channel: publish from MULTICA_PLUGIN_DIR instead of a zip. */+export function usePublishLocalPluginPackage(wsId: string) {+ const invalidate = useInvalidatePlugins(wsId);+ return useMutation({+ mutationFn: (name: string) => api.publishLocalPluginPackage(wsId, name),+ onSettled: invalidate,+ });+}++export function useDeletePluginPackage(wsId: string) {+ const invalidate = useInvalidatePlugins(wsId);+ return useMutation({+ mutationFn: (packageId: string) => api.deletePluginPackage(wsId, packageId),+ onSettled: invalidate,+ });+}+export function useInstallPlugin(wsId: string) {const invalidate = useInvalidatePlugins(wsId);return useMutation({diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.tsindex c3c88ffb7c..623cc00f5d 100644--- a/packages/core/plugins/queries.ts+++ b/packages/core/plugins/queries.ts@@ -4,6 +4,7 @@ import { api } from "../api";export const pluginKeys = {all: (wsId: string) => ["workspaces", wsId, "plugins"] as const,installed: (wsId: string) => [...pluginKeys.all(wsId), "installed"] as const,+ packages: (wsId: string) => [...pluginKeys.all(wsId), "packages"] as const,};export function pluginInstallationsOptions(wsId: string) {@@ -14,6 +15,39 @@ export function pluginInstallationsOptions(wsId: string) {});}+/** What this workspace has published, with each plugin's versions. */+export function pluginPackagesOptions(wsId: string) {+ return queryOptions({+ queryKey: pluginKeys.packages(wsId),+ queryFn: () => api.listPluginPackages(wsId),+ enabled: wsId.length > 0,+ });+}++/**+ * The code one surface runs.+ *+ * A published version is immutable, so this is keyed by the version rather than+ * the installation and never goes stale on its own: an upgrade changes the key.+ * `staleTime: Infinity` is a statement about the artifact, not a cache tuning+ * choice — the same version id can only ever return the same bytes.+ */+export function pluginSurfaceScriptOptions(+ wsId: string,+ installationId: string,+ surfaceKey: string,+ packageVersionId: string,+) {+ return queryOptions({+ queryKey: [...pluginKeys.all(wsId), installationId, "surface", surfaceKey, packageVersionId] as const,+ queryFn: () => api.getPluginSurfaceScript(wsId, installationId, surfaceKey),+ enabled: wsId.length > 0 && installationId.length > 0 && surfaceKey.length > 0,+ staleTime: Infinity,+ gcTime: 30 * 60 * 1000,+ retry: false,+ });+}+/*** A hook's recent calls, for the author staring at a failing endpoint.*diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 6897551ce7..cea78fc777 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -95,6 +95,10 @@ export type {PluginResource,PluginInstallationListResponse,PluginManifestSummary,+ PluginPackage,+ PluginPackageVersion,+ PluginPackageListResponse,+ PluginSurfaceScript,PluginPreview,PluginPreviewRequest,PluginInstallRequest,diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.tsindex 61e59175d9..e58ca106fb 100644--- a/packages/core/types/plugin.ts+++ b/packages/core/types/plugin.ts@@ -52,7 +52,12 @@ export interface PluginInstallation {name: string;description?: string;version: string;- source_url: string;+ /**+ * The published version this installation is bound to. Publishing a new+ * version does not touch it — upgrading is an explicit second consent, which+ * is what makes "the admin approved this code" true rather than aspirational.+ */+ package_version_id: string;enabled: boolean;granted_scopes: string[];config_schema: PluginConfigField[];@@ -82,11 +87,16 @@ export interface PluginManifestSummary {/*** What the consent screen renders. There is no signature and no trust tier in* this model: an administrator reading the scope list IS the trust decision.+ *+ * It describes one published version, and installing names that same version.*/export interface PluginPreview {manifest: PluginManifestSummary;scopes: string[];config_schema: PluginConfigField[];+ version_id: string;+ version: string;+ digest: string;installed: boolean;installed_version?: string;/** Scopes this install would add on top of what is already granted. */@@ -94,14 +104,57 @@ export interface PluginPreview {}export interface PluginPreviewRequest {- source_url: string;+ version_id: string;}export interface PluginInstallRequest {- source_url: string;+ version_id: string;granted_scopes: string[];}+/** One immutable published version of a plugin package. */+export interface PluginPackageVersion {+ id: string;+ version: string;+ /** sha256 of the artifact's contents, so two people can confirm they match. */+ digest: string;+ size_bytes: number;+ published_at: string;+ /** True for the version this workspace currently runs, if any. */+ installed: boolean;+}++/**+ * A plugin published into this workspace. Publishing is workspace-private: a+ * public directory needs review, reporting and takedown, which is a separate+ * decision from where the artifact lives.+ */+export interface PluginPackage {+ id: string;+ plugin_key: string;+ name: string;+ /** Newest first. */+ versions: PluginPackageVersion[];+ created_at: string;+}++export interface PluginPackageListResponse {+ packages: PluginPackage[];+}++/**+ * The code one surface runs, read from the version the workspace installed.+ *+ * The host inlines it into the sandboxed document it generates, so the surface+ * loads nothing over the network and its CSP names no third-party script origin+ * at all.+ */+export interface PluginSurfaceScript {+ code: string;+ version: string;+ digest: string;+}+export interface PluginConfigRequest {values: Record<string, unknown>;}diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.mdindex ef784d3d55..85a6e7bcd3 100644--- a/packages/plugin-sdk/README.md+++ b/packages/plugin-sdk/README.md@@ -14,7 +14,13 @@ multica.ui.resize(320);## What a surface is-An ordinary script in a sandboxed iframe.+**One** script in a sandboxed iframe.++Bundle this SDK and everything else your surface needs into a single file. There+is no module graph: you publish an artifact, Multica stores it and inlines your+entry into the document it generates, so there is no origin for a top-level+`import` to resolve against. Publishing refuses an entry that has one rather+than letting it fail later in a reader's browser.The frame is mounted with `sandbox="allow-scripts"` and **not**`allow-same-origin`, so it has an opaque origin. Consequences worth knowing@@ -27,9 +33,20 @@ before you write one:directly, that backend must accept a null origin in CORS.- **A CSP you did not write.** The host generates the document and derives`connect-src` from the `net:` scopes in your manifest. Declare every host you- intend to reach; a surface with no `net:` scope cannot make network requests- at all. `net:` is an exact host — declare `net:api.example.com` separately from- `net:example.com`.+ intend to reach; with no `net:` scope your surface cannot issue a network+ request at all, including back to your own origin, which is no longer in the+ policy now that Multica serves your code. `net:` is an exact host, so declare+ `net:api.example.com` separately from `net:example.com`.++## Publishing++Zip the manifest with every file it names and upload it in **Settings →+Plugins**. You need no server of your own for the frontend; hook endpoints and+MCP servers are still yours to run.++A published version is immutable. Installing binds a workspace to one version,+and publishing a new one changes nothing there until an administrator upgrades —+so what they approved on the consent screen is what their browsers run.## What you can do, and what bounds itdiff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 28ece67bd2..a5441facad 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -809,11 +809,13 @@"plugins": {"panels": "Plugins","surface_failed": "{{name}} could not load its interface.",- "surface_local_only": "{{name}} was installed from a local source, so its interface cannot be loaded in the browser.","hook_succeeded": "{{name}} finished.","hook_failed": "{{name}} failed.","hook_refused": "{{name}} was not run.","hook_activity": "Recent calls",- "hook_never_run": "This hook has not run yet."+ "hook_never_run": "This hook has not run yet.",+ "surface_loading": "Loading {{name}}…",+ "surface_unavailable": "{{name}} could not load its interface. The installed version may not include it.",+ "surface_navigated": "{{name}} tried to replace its panel with a page loaded from elsewhere. It has been stopped and disconnected — tell your workspace admin."}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex ee2247a091..fbae029871 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -331,7 +331,7 @@},"plugins": {"title": "Plugins",- "description": "Install plugins by URL and review exactly what each one is allowed to reach.",+ "description": "Publish plugins into this workspace, then install a specific version and review exactly what it is allowed to reach.","loading": "Loading Plugins","load_failed": "Plugins couldn't be loaded","load_failed_description": "Try again. Installed Plugins are unaffected.",@@ -348,22 +348,15 @@"contributes": "Contributes","version": "v{{version}}","byline": "{{author}} · v{{version}}",- "source": "Source","states": {"disabled": "Disabled"},- "install": {- "title": "Install a Plugin",- "description": "Paste the URL of a plugin manifest. You'll see what it asks for before anything is installed.",- "placeholder": "https://example.com/multica.plugin.json",- "review": "Review"- },"installed": {"title": "Installed"},"consent": {"title": "This Plugin is asking for the following access",- "description": "Multica never runs plugin code on its servers. A Plugin can only do what these scopes allow, and never more than the person using it can already do.",+ "description": "You are approving one specific version. Its code is stored by Multica and will not change until you upgrade. A Plugin can only do what these scopes allow, and never more than the person using it can already do.","cancel": "Cancel","confirm": "Grant and install","confirm_upgrade": "Grant and upgrade",@@ -402,6 +395,19 @@"drifted": "Schema changed","save": "Save approvals","approved": "Approved tools updated."+ },+ "publish": {+ "title": "Publish a Plugin",+ "description": "Upload a plugin package. Multica stores and serves it, so a plugin author needs no server of their own.",+ "hint": "A .zip holding multica.plugin.json and every file it names.",+ "upload": "Upload package",+ "published": "Published {{name}} {{version}}",+ "empty": "Nothing has been published in this workspace yet.",+ "delete": "Delete published Plugin",+ "deleted": "Published Plugin deleted",+ "installed_version": "In use",+ "review_install": "Review and install",+ "review_upgrade": "Review and upgrade"}},"properties": {diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 6bb51cf450..fd87d7db6d 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -778,11 +778,13 @@"plugins": {"panels": "Plugins","surface_failed": "{{name}} のインターフェースを読み込めませんでした。",- "surface_local_only": "{{name}} はローカルソースからインストールされているため、ブラウザでインターフェースを読み込めません。","hook_succeeded": "{{name}} が完了しました。","hook_failed": "{{name}} が失敗しました。","hook_refused": "{{name}} は実行されませんでした。","hook_activity": "最近の呼び出し",- "hook_never_run": "このフックはまだ実行されていません。"+ "hook_never_run": "このフックはまだ実行されていません。",+ "surface_loading": "{{name}} を読み込んでいます…",+ "surface_unavailable": "{{name}} のインターフェースを読み込めません。インストール済みのバージョンに含まれていない可能性があります。",+ "surface_navigated": "{{name}} がパネルを外部から読み込んだページに置き換えようとしました。停止して接続を切りました。ワークスペース管理者に知らせてください。"}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 015ec0494c..7e2732ecd1 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -331,7 +331,7 @@},"plugins": {"title": "Plugins",- "description": "URL から Plugin をインストールし、各 Plugin が何にアクセスできるかを確認します。",+ "description": "このワークスペースにプラグインを公開し、特定のバージョンをインストールして、何にアクセスできるかを確認します。","loading": "Plugins を読み込み中","load_failed": "Plugins を読み込めませんでした","load_failed_description": "再試行してください。インストール済みの Plugin には影響しません。",@@ -348,22 +348,15 @@"contributes": "提供する機能","version": "v{{version}}","byline": "{{author}} · v{{version}}",- "source": "ソース","states": {"disabled": "無効"},- "install": {- "title": "Plugin をインストール",- "description": "Plugin manifest の URL を貼り付けてください。インストール前に要求される権限を確認できます。",- "placeholder": "https://example.com/multica.plugin.json",- "review": "権限を確認"- },"installed": {"title": "インストール済み"},"consent": {"title": "この Plugin は次のアクセスを要求しています",- "description": "Multica はサーバー上で Plugin のコードを実行しません。Plugin はこれらの権限の範囲内でのみ動作し、利用者本人の権限を超えることはありません。",+ "description": "承認するのは特定のバージョンです。そのコードは Multica が保存し、アップグレードするまで変わりません。Plugin はこれらの権限の範囲内でのみ動作し、利用者本人の権限を超えることはありません。","cancel": "キャンセル","confirm": "許可してインストール","confirm_upgrade": "許可してアップグレード",@@ -402,6 +395,19 @@"drifted": "スキーマが変更されました","save": "承認を保存","approved": "承認済みツールを更新しました。"+ },+ "publish": {+ "title": "プラグインを公開",+ "description": "プラグインパッケージをアップロードします。Multica が保存と配信を行うため、作者自身のサーバーは不要です。",+ "hint": "multica.plugin.json とそれが参照するすべてのファイルを含む .zip。",+ "upload": "パッケージをアップロード",+ "published": "{{name}} {{version}} を公開しました",+ "empty": "このワークスペースではまだ何も公開されていません。",+ "delete": "公開したプラグインを削除",+ "deleted": "公開したプラグインを削除しました",+ "installed_version": "使用中",+ "review_install": "確認してインストール",+ "review_upgrade": "確認してアップグレード"}},"properties": {diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 771c5ec918..1c504f1a81 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -778,11 +778,13 @@"plugins": {"panels": "Plugins","surface_failed": "{{name}}의 인터페이스를 불러오지 못했습니다.",- "surface_local_only": "{{name}}은(는) 로컬 소스에서 설치되어 브라우저에서 인터페이스를 불러올 수 없습니다.","hook_succeeded": "{{name}} 완료됨.","hook_failed": "{{name}} 실패함.","hook_refused": "{{name}}이(가) 실행되지 않았습니다.","hook_activity": "최근 호출",- "hook_never_run": "이 훅은 아직 실행되지 않았습니다."+ "hook_never_run": "이 훅은 아직 실행되지 않았습니다.",+ "surface_loading": "{{name}} 불러오는 중…",+ "surface_unavailable": "{{name}}의 인터페이스를 불러올 수 없습니다. 설치된 버전에 포함되어 있지 않을 수 있습니다.",+ "surface_navigated": "{{name}}이(가) 패널을 외부에서 불러온 페이지로 바꾸려 했습니다. 중지하고 연결을 끊었습니다. 워크스페이스 관리자에게 알리세요."}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 30fd867204..2d64208581 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -331,7 +331,7 @@},"plugins": {"title": "Plugins",- "description": "URL로 Plugin을 설치하고 각 Plugin이 무엇에 접근할 수 있는지 확인합니다.",+ "description": "이 워크스페이스에 플러그인을 게시하고 특정 버전을 설치하며, 무엇에 접근할 수 있는지 확인합니다.","loading": "Plugins 불러오는 중","load_failed": "Plugins를 불러올 수 없습니다","load_failed_description": "다시 시도하세요. 설치된 Plugin에는 영향이 없습니다.",@@ -348,22 +348,15 @@"contributes": "제공 기능","version": "v{{version}}","byline": "{{author}} · v{{version}}",- "source": "출처","states": {"disabled": "비활성"},- "install": {- "title": "Plugin 설치",- "description": "Plugin manifest의 URL을 붙여넣으세요. 설치 전에 요청하는 권한을 확인할 수 있습니다.",- "placeholder": "https://example.com/multica.plugin.json",- "review": "권한 확인"- },"installed": {"title": "설치됨"},"consent": {"title": "이 Plugin이 요청하는 접근 권한",- "description": "Multica는 서버에서 Plugin 코드를 실행하지 않습니다. Plugin은 이 권한 범위 안에서만 동작하며, 사용자 본인의 권한을 넘어설 수 없습니다.",+ "description": "승인하는 것은 특정 버전입니다. 해당 코드는 Multica가 저장하며 업그레이드하기 전까지 변하지 않습니다. Plugin은 이 권한 범위 안에서만 동작하며, 사용자 본인의 권한을 넘어설 수 없습니다.","cancel": "취소","confirm": "허용하고 설치","confirm_upgrade": "허용하고 업그레이드",@@ -402,6 +395,19 @@"drifted": "스키마가 변경됨","save": "승인 저장","approved": "승인된 도구를 업데이트했습니다."+ },+ "publish": {+ "title": "플러그인 게시",+ "description": "플러그인 패키지를 업로드하세요. Multica가 저장하고 제공하므로 작성자에게 별도의 서버가 필요하지 않습니다.",+ "hint": "multica.plugin.json과 그것이 참조하는 모든 파일이 담긴 .zip입니다.",+ "upload": "패키지 업로드",+ "published": "{{name}} {{version}} 게시됨",+ "empty": "이 워크스페이스에는 아직 게시된 것이 없습니다.",+ "delete": "게시된 플러그인 삭제",+ "deleted": "게시된 플러그인을 삭제했습니다",+ "installed_version": "사용 중",+ "review_install": "확인 후 설치",+ "review_upgrade": "확인 후 업그레이드"}},"properties": {diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex deb23e67ad..0dd9219099 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -778,11 +778,13 @@"plugins": {"panels": "Plugins","surface_failed": "{{name}} 的界面加载失败。",- "surface_local_only": "{{name}} 是从本地源安装的,界面无法在浏览器里加载。","hook_succeeded": "{{name}} 已完成。","hook_failed": "{{name}} 执行失败。","hook_refused": "{{name}} 未被执行。","hook_activity": "最近调用",- "hook_never_run": "该 hook 尚未运行过。"+ "hook_never_run": "该 hook 尚未运行过。",+ "surface_loading": "正在加载 {{name}}…",+ "surface_unavailable": "{{name}} 的界面无法加载,已安装的版本可能不包含它。",+ "surface_navigated": "{{name}} 试图把面板替换成从别处加载的页面。已经拦下并断开连接,建议告知工作区管理员。"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 1f50d18a7b..f60cb8c33d 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -331,7 +331,7 @@},"plugins": {"title": "Plugins",- "description": "通过 URL 安装 Plugin,并逐条查看它能访问什么。",+ "description": "在这个工作区里发布插件,然后安装某个具体版本,并逐条确认它能访问什么。","loading": "正在加载 Plugins","load_failed": "无法加载 Plugins","load_failed_description": "请重试。已安装的 Plugin 不受影响。",@@ -348,22 +348,15 @@"contributes": "提供的能力","version": "v{{version}}","byline": "{{author}} · v{{version}}",- "source": "来源","states": {"disabled": "已停用"},- "install": {- "title": "安装 Plugin",- "description": "粘贴 Plugin manifest 的 URL。安装前你会先看到它请求的全部权限。",- "placeholder": "https://example.com/multica.plugin.json",- "review": "查看权限"- },"installed": {"title": "已安装"},"consent": {"title": "该 Plugin 请求以下访问权限",- "description": "Multica 从不在服务器上运行 Plugin 代码。Plugin 只能做这些权限允许的事,且永远不会超过使用者本人的权限。",+ "description": "你批准的是某个具体版本。它的代码由 Multica 存储,在你升级之前不会变化。Plugin 只能做这些权限允许的事,且永远不会超过使用者本人的权限。","cancel": "取消","confirm": "授权并安装","confirm_upgrade": "授权并升级",@@ -402,6 +395,19 @@"drifted": "schema 已变更","save": "保存批准","approved": "已更新批准的工具。"+ },+ "publish": {+ "title": "发布插件",+ "description": "上传插件产物包。Multica 负责存储和分发,作者不需要自己的服务器。",+ "hint": "一个 .zip,包含 multica.plugin.json 和它引用的所有文件。",+ "upload": "上传产物包",+ "published": "已发布 {{name}} {{version}}",+ "empty": "这个工作区还没有发布过插件。",+ "delete": "删除已发布的插件",+ "deleted": "已删除发布的插件",+ "installed_version": "使用中",+ "review_install": "查看并安装",+ "review_upgrade": "查看并升级"}},"properties": {diff --git a/packages/views/plugins/index.ts b/packages/views/plugins/index.tsindex caec317119..ed218b987e 100644--- a/packages/views/plugins/index.ts+++ b/packages/views/plugins/index.ts@@ -1,6 +1,6 @@export { PluginPanelSection } from "./plugin-panel-section";export { PluginSurfaceFrame } from "./plugin-surface-frame";-export { buildSurfaceCSP, buildSurfaceDocument, resolveSurfaceEntry, surfaceConnectSources } from "./surface-document";+export { buildSurfaceCSP, buildSurfaceDocument, surfaceConnectSources } from "./surface-document";export {PluginHookMenuItems,collectManualHookActions,diff --git a/packages/views/plugins/plugin-hook-actions.test.ts b/packages/views/plugins/plugin-hook-actions.test.tsindex 32c55e959b..4d6f794425 100644--- a/packages/views/plugins/plugin-hook-actions.test.ts+++ b/packages/views/plugins/plugin-hook-actions.test.ts@@ -12,7 +12,7 @@ function installation(overrides: Partial<PluginInstallation> = {}): PluginInstalplugin_key: "com.example.one",name: "Example",version: "1.0.0",- source_url: "https://example.com/multica.plugin.json",+ package_version_id: "version-1",enabled: true,granted_scopes: [],config_schema: [],diff --git a/packages/views/plugins/plugin-modal-surface.test.ts b/packages/views/plugins/plugin-modal-surface.test.tsindex 49a9b09ca7..fcbfa2c00e 100644--- a/packages/views/plugins/plugin-modal-surface.test.ts+++ b/packages/views/plugins/plugin-modal-surface.test.ts@@ -12,7 +12,7 @@ function installation(overrides: Partial<PluginInstallation> = {}): PluginInstalplugin_key: "com.example.one",name: "Example",version: "1.0.0",- source_url: "https://example.com/multica.plugin.json",+ package_version_id: "version-1",enabled: true,granted_scopes: [],config_schema: [],diff --git a/packages/views/plugins/plugin-modal-surface.tsx b/packages/views/plugins/plugin-modal-surface.tsxindex 4f1c672137..bfece67ec2 100644--- a/packages/views/plugins/plugin-modal-surface.tsx+++ b/packages/views/plugins/plugin-modal-surface.tsx@@ -76,6 +76,9 @@ interface PluginModalSurfaceProps {}export function PluginModalSurface({ target, issueId, onOpenChange }: PluginModalSurfaceProps) {+ // Same source as usePluginModalSurfaces above: a modal only ever opens from+ // the issue menu, which is inside the workspace route.+ const workspace = useCurrentWorkspace();if (!target) return null;return (<Dialog open onOpenChange={onOpenChange}>@@ -95,6 +98,7 @@ export function PluginModalSurface({ target, issueId, onOpenChange }: PluginModa// issue into its context call, and an unchanged document would not// reload for a different one.key={`${pluginModalKey(target)}:${issueId ?? ""}`}+ wsId={workspace?.id ?? ""}installation={target.installation}surface={target.surface}issueId={issueId}diff --git a/packages/views/plugins/plugin-panel-section.test.tsx b/packages/views/plugins/plugin-panel-section.test.tsxindex b15cb847b3..7d513f2c86 100644--- a/packages/views/plugins/plugin-panel-section.test.tsx+++ b/packages/views/plugins/plugin-panel-section.test.tsx@@ -1,19 +1,31 @@import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { act, render, screen } from "@testing-library/react";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";import enIssues from "../locales/en/issues.json";const data = vi.hoisted(() => ({installed: { plugins: [] as Array<Record<string, unknown>> },+ // A surface's code now comes from us, over a second query. `null` is what a+ // frame that has nothing to run sees.+ script: { code: "console.log('hi');", version: "1.0.0", digest: "abc" } as Record<string, unknown> | null,flagEnabled: true,}));vi.mock("@tanstack/react-query", () => ({- useQuery: () => ({ data: data.installed, isLoading: false, isError: false }),+ // Two different queries reach this mock: the installation list and one+ // surface's code. They are told apart by the query key the options object+ // carries, so a test can make the code unavailable without touching the list.+ useQuery: (options: { queryKey?: readonly unknown[] }) =>+ options?.queryKey?.[0] === "surface"+ ? { data: data.script, isPending: false, isError: data.script === null }+ : { data: data.installed, isLoading: false, isError: false },+}));+vi.mock("@multica/core/plugins", () => ({+ pluginInstallationsOptions: () => ({ queryKey: ["plugins"] }),+ pluginSurfaceScriptOptions: () => ({ queryKey: ["surface"] }),}));-vi.mock("@multica/core/plugins", () => ({ pluginInstallationsOptions: () => ({ queryKey: ["plugins"] }) }));vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "workspace-1", name: "Acme", slug: "acme" }) }));vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => data.flagEnabled }));vi.mock("../platform/local-directory", () => ({ isDesktopShell: () => false }));@@ -32,7 +44,7 @@ function installation(overrides: Record<string, unknown> = {}) {plugin_key: "com.example.hello",name: "Hello Panel",version: "1.0.0",- source_url: "https://example.com/plugin/multica.plugin.json",+ package_version_id: "version-1",enabled: true,granted_scopes: ["issues:read"],config_schema: [],@@ -50,6 +62,7 @@ function installation(overrides: Record<string, unknown> = {}) {describe("PluginPanelSection", () => {beforeEach(() => {data.installed.plugins = [];+ data.script = { code: "console.log('hi');", version: "1.0.0", digest: "abc" };data.flagEnabled = true;});@@ -105,11 +118,72 @@ describe("PluginPanelSection", () => {expect(container).toBeEmptyDOMElement();});- it("says why a local install cannot render instead of showing an empty frame", () => {- data.installed.plugins = [installation({ source_url: "local:hello" })];+ it("says the surface could not load instead of showing an empty frame", () => {+ // An empty body is what a malformed response parses to. Mounting a frame+ // for it would look like a working panel that renders nothing.+ data.script = null;+ data.installed.plugins = [installation()];render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });expect(screen.queryByTitle("Hello Panel — Hello")).not.toBeInTheDocument();- expect(screen.getByText(/installed from a local source/i)).toBeInTheDocument();+ expect(screen.getByText(/could not load its interface/i)).toBeInTheDocument();+ });++ it("loads a surface's code from Multica, never from the plugin author", () => {+ // The frame's document carries the code inline. If anything here starts+ // emitting a remote <script src>, every panel open becomes a request to a+ // third party again.+ data.installed.plugins = [installation()];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ const srcdoc = screen.getByTitle("Hello Panel — Hello").getAttribute("srcdoc") ?? "";+ expect(srcdoc).not.toContain("<script src=");+ expect(srcdoc).toContain("script-src 'unsafe-inline'");+ });++ it("acknowledges a plugin bootstrap error and shows a useful failure", () => {+ data.installed.plugins = [installation()];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ const frame = screen.getByTitle("Hello Panel — Hello") as HTMLIFrameElement;+ const postMessage = vi.spyOn(frame.contentWindow!, "postMessage");+ const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-error" } });+ Object.defineProperty(event, "source", { value: frame.contentWindow, configurable: true });+ act(() => window.dispatchEvent(event));++ expect(screen.getByText("Hello Panel could not load its interface.")).toBeInTheDocument();+ expect(postMessage).toHaveBeenCalledWith({ type: "multica:plugin-surface-error-ack" }, "*");+ });++ it("clears a previous surface failure when the issue changes", () => {+ data.installed.plugins = [installation()];+ const { rerender } = render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ const frame = screen.getByTitle("Hello Panel — Hello") as HTMLIFrameElement;+ const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-error" } });+ Object.defineProperty(event, "source", { value: frame.contentWindow, configurable: true });+ act(() => window.dispatchEvent(event));+ expect(screen.getByText("Hello Panel could not load its interface.")).toBeInTheDocument();++ rerender(<PluginPanelSection issueId="issue-2" />);+ expect(screen.queryByText("Hello Panel could not load its interface.")).not.toBeInTheDocument();+ expect(screen.getByTitle("Hello Panel — Hello")).toBeInTheDocument();+ });++ it("clears a previous surface failure when its document changes", () => {+ data.installed.plugins = [installation()];+ const { rerender } = render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ const frame = screen.getByTitle("Hello Panel — Hello") as HTMLIFrameElement;+ const originalDocument = frame.getAttribute("srcdoc");+ const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-error" } });+ Object.defineProperty(event, "source", { value: frame.contentWindow, configurable: true });+ act(() => window.dispatchEvent(event));+ expect(screen.getByText("Hello Panel could not load its interface.")).toBeInTheDocument();++ data.script = { code: "console.log('replacement');", version: "1.0.1", digest: "def" };+ rerender(<PluginPanelSection issueId="issue-1" />);+ expect(screen.queryByText("Hello Panel could not load its interface.")).not.toBeInTheDocument();+ expect(screen.getByTitle("Hello Panel — Hello").getAttribute("srcdoc")).not.toBe(originalDocument);});});diff --git a/packages/views/plugins/plugin-panel-section.tsx b/packages/views/plugins/plugin-panel-section.tsxindex 95e1dc5620..bf21492f0d 100644--- a/packages/views/plugins/plugin-panel-section.tsx+++ b/packages/views/plugins/plugin-panel-section.tsx@@ -49,6 +49,7 @@ export function PluginPanelSection({ issueId }: { issueId: string }) {{panels.map(({ installation, surface }) => (<PluginSurfaceFramekey={`${installation.id}:${surface.key}`}+ wsId={wsId}installation={installation}surface={surface}issueId={issueId}diff --git a/packages/views/plugins/plugin-surface-frame.tsx b/packages/views/plugins/plugin-surface-frame.tsxindex c26d9de152..ae69cca180 100644--- a/packages/views/plugins/plugin-surface-frame.tsx+++ b/packages/views/plugins/plugin-surface-frame.tsx@@ -1,15 +1,18 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { pluginSurfaceScriptOptions } from "@multica/core/plugins";import type { PluginInstallation, PluginSurface } from "@multica/core/types";import { cn } from "@multica/ui/lib/utils";import { useT } from "../i18n";-import { buildSurfaceDocument, readThemeTokens, resolveSurfaceEntry } from "./surface-document";+import { buildSurfaceDocument, readThemeTokens } from "./surface-document";import { createSurfaceBridge } from "./surface-bridge";const DEFAULT_HEIGHT = 220;interface PluginSurfaceFrameProps {+ wsId: string;installation: PluginInstallation;surface: PluginSurface;issueId?: string;@@ -25,13 +28,17 @@ interface PluginSurfaceFrameProps {* our cookies and storage. Same rule, same reason as* `packages/views/editor/code-block-iframe.tsx`.*/-export function PluginSurfaceFrame({ installation, surface, issueId, className }: PluginSurfaceFrameProps) {+export function PluginSurfaceFrame({ wsId, installation, surface, issueId, className }: PluginSurfaceFrameProps) {const frameRef = useRef<HTMLIFrameElement>(null);const anchorRef = useRef<HTMLDivElement>(null);const [height, setHeight] = useState(DEFAULT_HEIGHT);- const [failed, setFailed] = useState(false);- const entryUrl = useMemo(() => resolveSurfaceEntry(installation, surface), [installation, surface]);+ // The code comes from us, not from the plugin author's server. It is keyed by+ // the installed version, which is immutable — so this is fetched once and an+ // upgrade is what changes the key.+ const { data: script, isPending, isError } = useQuery(+ pluginSurfaceScriptOptions(wsId, installation.id, surface.key, installation.package_version_id),+ );// Tokens are read off a mounted element, so the frame inherits whatever theme// the app is actually in rather than a hardcoded copy that drifts. It has to@@ -41,9 +48,18 @@ export function PluginSurfaceFrame({ installation, surface, issueId, className }useEffect(() => setTheme(readThemeTokens(anchorRef.current)), []);const surfaceDocument = useMemo(() => {- if (!entryUrl) return null;- return buildSurfaceDocument({ entryUrl, grantedScopes: installation.granted_scopes, theme });- }, [entryUrl, installation.granted_scopes, theme]);+ // An empty body is what a malformed response parses to. Rendering it would+ // mount a frame that runs nothing and looks like a working, silent panel.+ if (!script?.code) return null;+ return buildSurfaceDocument({ code: script.code, grantedScopes: installation.granted_scopes, theme });+ }, [script?.code, installation.granted_scopes, theme]);++ // A failure belongs to one rendered document on one issue. Keeping a plain+ // boolean makes the banner survive an issue change or a version/code reload+ // even though the replacement iframe is running normally.+ const surfaceInstance = useMemo(() => ({ issueId, surfaceDocument }), [issueId, surfaceDocument]);+ const [failedSurfaceInstance, setFailedSurfaceInstance] = useState<typeof surfaceInstance | null>(null);+ const failed = failedSurfaceInstance === surfaceInstance;// One bridge per rendered document. srcDoc changing reloads the frame — and// therefore restarts the guest's handshake — so the old bridge is finished:@@ -62,25 +78,31 @@ export function PluginSurfaceFrame({ installation, surface, issueId, className }}, [bridge]);useEffect(() => {- // A surface whose script 404s posts this to the parent window rather than- // rendering blank — the frame has no other way to tell us.const onMessage = (event: MessageEvent) => {- if ((event.data as { type?: string } | null)?.type !== "multica:plugin-surface-error") return;+ const type = (event.data as { type?: string } | null)?.type;+ if (type !== "multica:plugin-surface-error") return;// Same window-identity rule as the bridge: without it any frame on the// page could light up the failure banner on every other panel.if (!frameRef.current?.contentWindow || event.source !== frameRef.current.contentWindow) return;- setFailed(true);+ // A surface whose script throws on its first line posts the error rather+ // than rendering blank. Acknowledge it so the guest can stop repeating+ // the signal it started before this effect was guaranteed to be mounted.+ frameRef.current.contentWindow.postMessage({ type: "multica:plugin-surface-error-ack" }, "*");+ setFailedSurfaceInstance(surfaceInstance);};window.addEventListener("message", onMessage);return () => window.removeEventListener("message", onMessage);- }, []);+ }, [surfaceInstance]);if (!surfaceDocument) {return (<div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>- {/* A local: install has no URL to load a script from — say so instead of- showing an empty box the user cannot act on. */}- <PluginSurfaceNotice installation={installation} kind="unavailable" />+ {/* Three states share this box on purpose: still loading, the request+ failed, and the installed version carries no code for this surface.+ All three mean "nothing to render yet"; only the last is permanent,+ and none of them should show an empty frame the reader cannot act+ on. */}+ <PluginSurfaceNotice installation={installation} kind={isPending && !isError ? "loading" : "unavailable"} /></div>);}@@ -108,8 +130,15 @@ export function PluginSurfaceFrame({ installation, surface, issueId, className });}-function PluginSurfaceNotice({ installation, kind }: { installation: PluginInstallation; kind: "unavailable" | "failed" }) {+function PluginSurfaceNotice({+ installation,+ kind,+}: {+ installation: PluginInstallation;+ kind: "unavailable" | "failed" | "loading";+}) {const { t } = useT("issues");if (kind === "failed") return <>{t(($) => $.plugins.surface_failed, { name: installation.name })}</>;- return <>{t(($) => $.plugins.surface_local_only, { name: installation.name })}</>;+ if (kind === "loading") return <>{t(($) => $.plugins.surface_loading, { name: installation.name })}</>;+ return <>{t(($) => $.plugins.surface_unavailable, { name: installation.name })}</>;}diff --git a/packages/views/plugins/surface-document.test.ts b/packages/views/plugins/surface-document.test.tsindex b5e42e2719..e58911f162 100644--- a/packages/views/plugins/surface-document.test.ts+++ b/packages/views/plugins/surface-document.test.ts@@ -1,10 +1,8 @@// @vitest-environment nodeimport { describe, expect, it } from "vitest";-import type { PluginInstallation, PluginSurface } from "@multica/core/types";import {buildSurfaceCSP,buildSurfaceDocument,- resolveSurfaceEntry,surfaceConnectSources,} from "./surface-document";@@ -12,65 +10,43 @@ import {// reviewer cannot verify by reading the component: what a surface is allowed to// talk to, and that nothing about the plugin can escape into the markup.-const SURFACE: PluginSurface = {- key: "hello",- type: "issue_panel",- name: "Hello",- entry: "ui/main.js",- platforms: [],-};--function installation(overrides: Partial<PluginInstallation> = {}): PluginInstallation {- return {- id: "installation-1",- plugin_key: "com.example.hello",- name: "Hello Panel",- version: "1.0.0",- source_url: "https://example.com/plugin/multica.plugin.json",- enabled: true,- granted_scopes: ["issues:read"],- config_schema: [],- config: {},- configured_secrets: [],- surfaces: [SURFACE],- hooks: [],- resources: [],- created_at: "",- updated_at: "",- ...overrides,- };-}-describe("surface connect-src", () => {it("derives the allowlist from granted net: scopes only", () => {expect(surfaceConnectSources(["issues:read", "net:example.com", "storage:user", "net:api.example.com"])).toEqual(["https://example.com", "https://api.example.com"]);});- it("gives a surface with no net: scope no third-party destination at all", () => {- // 'none', not merely an empty allowlist. This bounds THIRD-PARTY hosts; the- // author's own origin stays reachable through script-src, because the code- // has to load from somewhere. Saying otherwise would overclaim.- expect(buildSurfaceCSP(["issues:read"], "https://example.com")).toContain("connect-src 'none'");+ it("names no remote origin when no net: scope was granted", () => {+ // While the code loaded from the author's server, script-src had to name+ // that origin, so a surface could always reach its author back. The code is+ // ours to serve now, so this policy names no remote origin of any kind.+ //+ // That bounds what the DOCUMENT can request. It is not the same claim as+ // "a surface cannot reach its author": the sandbox still permits the frame+ // to navigate itself, which no CSP directive covers. See the known gap in+ // surface-document.ts.+ const csp = buildSurfaceCSP(["issues:read"]);+ expect(csp).toContain("connect-src 'none'");+ expect(csp).toContain("script-src 'unsafe-inline'");+ expect(csp).not.toContain("https://");});it("keeps the cheapest side channels closed", () => {// <img> and webfont URLs are the two exfiltration paths that need no- // scripting at all, so neither gets the script origin.- const csp = buildSurfaceCSP(["net:example.com"], "https://cdn.example.com");+ // scripting at all.+ const csp = buildSurfaceCSP(["net:example.com"]);expect(csp).toContain("img-src data: blob:");expect(csp).toContain("font-src data:");- expect(csp).not.toContain("img-src https://cdn.example.com");});- it("does not let an undeclared domain in through the script origin", () => {- const csp = buildSurfaceCSP(["net:example.com"], "https://cdn.example.com");+ it("allows only the domains that were granted", () => {+ const csp = buildSurfaceCSP(["net:example.com"]);expect(csp).toContain("connect-src https://example.com");- expect(csp).not.toContain("connect-src https://cdn.example.com");+ expect(csp).not.toContain("https://cdn.example.com");});it("denies everything by default and allows no plugin-controlled framing", () => {- const csp = buildSurfaceCSP([], "https://example.com");+ const csp = buildSurfaceCSP([]);expect(csp).toContain("default-src 'none'");// frame-ancestors is intentionally absent — <meta> ignores it, and the// sandbox already denies this document the ability to frame anything.@@ -80,41 +56,10 @@ describe("surface connect-src", () => {});});-describe("surface entry resolution", () => {- it("resolves the entry against the manifest URL, so the author's host serves the code", () => {- expect(resolveSurfaceEntry(installation(), SURFACE)).toBe("https://example.com/plugin/ui/main.js");- });-- it("refuses a local: install rather than inventing a URL", () => {- // A local source lives on the server's filesystem; there is nothing a- // browser could fetch, and guessing a URL would be worse than saying so.- expect(resolveSurfaceEntry(installation({ source_url: "local:hello" }), SURFACE)).toBeNull();- });-- it("refuses a plaintext source on a real host", () => {- expect(resolveSurfaceEntry(installation({ source_url: "http://example.com/multica.plugin.json" }), SURFACE)).toBeNull();- });-- it("allows plain HTTP from loopback so a surface can be developed locally", () => {- // Browsers already treat loopback as a secure context. Without this a- // plugin author cannot iterate on a surface at all: there is no way to- // serve one over HTTPS from a laptop.- expect(resolveSurfaceEntry(installation({ source_url: "http://localhost:8787/multica.plugin.json" }), SURFACE))- .toBe("http://localhost:8787/ui/main.js");- expect(resolveSurfaceEntry(installation({ source_url: "http://127.0.0.1:8787/multica.plugin.json" }), SURFACE))- .toBe("http://127.0.0.1:8787/ui/main.js");- });-- it("does not treat a hostname that merely contains localhost as loopback", () => {- expect(resolveSurfaceEntry(installation({ source_url: "http://localhost.evil.test/multica.plugin.json" }), SURFACE)).toBeNull();- expect(resolveSurfaceEntry(installation({ source_url: "http://notlocalhost/multica.plugin.json" }), SURFACE)).toBeNull();- });-});-describe("surface document", () => {it("puts the policy before anything it governs", () => {const document = buildSurfaceDocument({- entryUrl: "https://example.com/plugin/ui/main.js",+ code: "console.log('hi');",grantedScopes: ["net:example.com"],theme: {},});@@ -124,19 +69,58 @@ describe("surface document", () => {expect(cspIndex).toBeLessThan(scriptIndex);});- it("escapes the entry URL so a crafted manifest cannot break out of the attribute", () => {- const document = buildSurfaceDocument({- entryUrl: 'https://example.com/a"><script>alert(1)</script>.js',- grantedScopes: [],- theme: {},- });- expect(document).not.toContain('"><script>alert(1)');- expect(document).toContain(""");+ it("fetches nothing to render a surface", () => {+ // The point of hosting the artifact: rendering the panel issues no request,+ // so a well-behaved plugin's author learns nothing about who opened it.+ const document = buildSurfaceDocument({ code: "console.log('hi');", grantedScopes: [], theme: {} });+ expect(document).not.toContain("<script src=");+ });++ it("does not mistake an ordinary host reload for hostile navigation", () => {+ // pagehide fires for both self-navigation and a host-authored srcDoc reload,+ // so it cannot be used as a security signal. The real Chromium regression+ // test reloads the document; this pins that no beacon is generated at all.+ const document = buildSurfaceDocument({ code: "console.log('hi');", grantedScopes: [], theme: {} });+ expect(document).not.toContain("pagehide");+ expect(document).not.toContain("multica:plugin-surface-navigated");+ });++ it("installs browser error listeners before plugin code runs", () => {+ const document = buildSurfaceDocument({ code: "throw new Error('boom');", grantedScopes: [], theme: {} });+ const executeIndex = document.indexOf("document.body.appendChild(element)");+ expect(document.indexOf('addEventListener("error"')).toBeLessThan(executeIndex);+ expect(document.indexOf('addEventListener("unhandledrejection"')).toBeLessThan(executeIndex);+ expect(document).toContain("multica:plugin-surface-error-ack");+ });++ it("carries code that would otherwise close the script element early", () => {+ // A surface that contains the literal end tag inside a string is ordinary+ // JavaScript. Base64 is what makes it impossible for the HTML tokenizer to+ // react to a plugin's source at all.+ const code = `const html = "</script><script>alert(1)</script>";`;+ const document = buildSurfaceDocument({ code, grantedScopes: [], theme: {} });+ expect(document).not.toContain("alert(1)");+ expect(document).not.toContain('"</script>');++ const encoded = /id="multica-surface-code">([^<]*)</.exec(document)?.[1] ?? "";+ expect(encoded).not.toBe("");+ expect(new TextDecoder().decode(Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0))))+ .toBe(code);+ });++ it("round-trips non-ASCII source", () => {+ // Encoding through latin1 would corrupt this silently, and the surface+ // would fail at runtime with a message pointing nowhere near the cause.+ const code = `const 消息 = "部署已完成 ✅";`;+ const document = buildSurfaceDocument({ code, grantedScopes: [], theme: {} });+ const encoded = /id="multica-surface-code">([^<]*)</.exec(document)?.[1] ?? "";+ expect(new TextDecoder().decode(Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0))))+ .toBe(code);});it("forwards theme tokens as custom properties so a surface looks native untouched", () => {const document = buildSurfaceDocument({- entryUrl: "https://example.com/ui/main.js",+ code: "console.log('hi');",grantedScopes: [],theme: { "--background": "oklch(1 0 0)", "--radius": "6px" },});diff --git a/packages/views/plugins/surface-document.ts b/packages/views/plugins/surface-document.tsindex 5c69e5e8f8..1cf8881cce 100644--- a/packages/views/plugins/surface-document.ts+++ b/packages/views/plugins/surface-document.ts@@ -1,11 +1,16 @@-import type { PluginInstallation, PluginSurface } from "@multica/core/types";-/**- * The host generates the document a surface runs in. That is the point: CSP is- * a response-header/meta decision made by whoever emits the document, so if the- * plugin author's server emitted it, the `net:` scopes the admin approved would- * be a claim we never check. Here they become a `connect-src` the browser- * enforces.+ * The host generates the document a surface runs in, and now supplies the code+ * that runs in it. That is the point: CSP is a response-header/meta decision+ * made by whoever emits the document, so if the plugin author's server emitted+ * it, the `net:` scopes the admin approved would be a claim we never check. Here+ * they become a `connect-src` the browser enforces.+ *+ * The script is INLINED rather than loaded from an origin. When it came from+ * the author's server, `script-src` had to name that origin, which meant a+ * surface could always reach its author back — and it meant every panel open+ * told the author who was reading which issue. Now Multica stores the published+ * artifact and hands it to the frame, so the policy names no remote script+ * origin at all.** The frame is mounted with `sandbox="allow-scripts"` and NOT* `allow-same-origin` — the pairing the HTML spec calls out as defeating the@@ -41,38 +46,6 @@ export function readThemeTokens(element: Element | null): Record<string, string>return tokens;}-/**- * Resolves a surface entry to an absolute script URL.- *- * `entry` is relative to the manifest, so the plugin's own host serves its code- * — we never proxy or re-host third-party JavaScript. A `local:` source has no- * URL to resolve against; those installs are for developing the manifest and- * cannot render a surface, which the panel says out loud rather than showing an- * empty frame.- */-export function resolveSurfaceEntry(installation: PluginInstallation, surface: PluginSurface): string | null {- const source = installation.source_url ?? "";- let resolved: URL;- try {- resolved = new URL(surface.entry, source);- } catch {- // A `local:` source is not a URL at all — there is nothing a browser could- // fetch, and guessing one would be worse than saying so.- return null;- }- if (resolved.protocol === "https:") return resolved.toString();- // Plain HTTP is allowed only from loopback, matching what browsers already- // treat as a secure context. That is what makes developing a surface possible- // — serve it from a local static server and install by URL like any other —- // without opening plaintext delivery on a real deployment.- if (resolved.protocol === "http:" && isLoopbackHost(resolved.hostname)) return resolved.toString();- return null;-}--function isLoopbackHost(hostname: string): boolean {- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";-}-function escapeAttribute(value: string): string {return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");}@@ -88,28 +61,23 @@ export function surfaceConnectSources(grantedScopes: string[]): string[] {.map((scope) => `https://${scope.slice("net:".length)}`);}-export function buildSurfaceCSP(grantedScopes: string[], scriptOrigin: string): string {+export function buildSurfaceCSP(grantedScopes: string[]): string {const connect = surfaceConnectSources(grantedScopes);return ["default-src 'none'",- // The surface's own script, and nothing else executable. This origin is- // unavoidable — the code has to load from somewhere — and it is the reason- // `net:` bounds THIRD-PARTY destinations rather than exfiltration in- // general: a script served by its author can always reach its author back,- // and closing that would mean re-hosting third-party code, which this design- // deliberately does not do.- `script-src ${scriptOrigin} 'unsafe-inline'`,+ // Inline only, and no remote origin at all. The surface's code is supplied+ // by us, so the generated document has nothing left for `script-src` to+ // fetch. Under the previous model the author's own origin was always in+ // this list.+ "script-src 'unsafe-inline'","style-src 'unsafe-inline'",- // Narrowed to inline data rather than the script origin: an <img> or webfont- // URL is the cheapest possible side channel back to the author, and a- // surface that needs artwork can inline it. It does not make the channel- // impossible — a dynamic import of the author's own origin remains — but it- // removes the two that cost nothing to use.+ // Inline data only. An <img> or webfont URL is the cheapest possible side+ // channel, and a surface that needs artwork inlines it."img-src data: blob:","font-src data:",- // With no net: scope this is 'none', so a surface cannot reach any- // third-party host. Its author's own origin is still reachable via- // script-src; see above.+ // With no net: scope, connection APIs in the generated document cannot+ // reach an origin. Self-navigation is a separate sandbox gap documented+ // below and tracked outside this change.`connect-src ${connect.length > 0 ? connect.join(" ") : "'none'"}`,// A sandboxed frame cannot navigate the top level anyway; saying so keeps// the policy honest if the sandbox attribute is ever loosened.@@ -122,19 +90,54 @@ export function buildSurfaceCSP(grantedScopes: string[], scriptOrigin: string):}export interface SurfaceDocumentInput {- entryUrl: string;+ /** The surface's entry script, as published. */+ code: string;grantedScopes: string[];theme: Record<string, string>;}/**- * The srcdoc a surface iframe renders. Everything executable in it is the- * plugin's own entry script loaded cross-origin; the inline script only forwards- * load failures so a broken plugin reports itself instead of showing blank.+ * Encodes the surface's code so it can be carried inside an HTML document.+ *+ * Base64 rather than escaping `</script`: the alphabet cannot contain anything+ * the HTML tokenizer reacts to, so there is no sequence in a plugin's source+ * that can end the script element early or shift the parser into another state.+ * Escaping works too, but it is a rule about JavaScript syntax enforced by a+ * string replace, and getting it subtly wrong looks like a plugin bug.+ */+function encodeSurfaceCode(code: string): string {+ const bytes = new TextEncoder().encode(code);+ let binary = "";+ // Chunked: String.fromCharCode(...bytes) blows the argument limit somewhere+ // around a hundred kilobytes, which a real surface reaches.+ for (let index = 0; index < bytes.length; index += 0x8000) {+ binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));+ }+ return btoa(binary);+}++/**+ * The srcdoc a surface iframe renders.+ *+ * The plugin's code arrives as base64 in a non-executable element and is+ * activated by a small bootstrap. Everything executable is inline, and rendering+ * this document fetches nothing.+ *+ * KNOWN GAP — a sandboxed frame may navigate ITSELF. `allow-scripts` without+ * `allow-top-navigation` stops a surface navigating the top level or a sibling,+ * but the HTML sandbox deliberately permits `_self`, and no shipped CSP+ * directive covers it (`navigate-to` was dropped from CSP3, and `connect-src` /+ * `form-action` govern other things). So a HOSTILE artifact can still run+ * `location.replace("https://author.example/live.html")`, which reaches the+ * author's server once and replaces this document with one whose CSP we do not+ * write. Closing it needs either an embedder `frame-src` policy or a handshake+ * the navigated document cannot complete. Tracked separately; do not describe+ * a surface as unable to reach its author until that lands. In particular, do+ * not use lifecycle events from this document as a security signal: a normal+ * host-driven `srcDoc` reload fires the same events.*/-export function buildSurfaceDocument({ entryUrl, grantedScopes, theme }: SurfaceDocumentInput): string {- const scriptOrigin = new URL(entryUrl).origin;- const csp = buildSurfaceCSP(grantedScopes, scriptOrigin);+export function buildSurfaceDocument({ code, grantedScopes, theme }: SurfaceDocumentInput): string {+ const csp = buildSurfaceCSP(grantedScopes);const themeCss = Object.entries(theme).map(([name, value]) => `${name}: ${value};`).join(" ");@@ -161,7 +164,57 @@ body {</head><body><div id="root"></div>-<script src="${escapeAttribute(entryUrl)}" onerror="parent.postMessage({type:'multica:plugin-surface-error'},'*')"></script>+<script type="text/plain" id="multica-surface-code">${encodeSurfaceCode(code)}</script>+<script>+(function () {+ var errorReportAttempts = 0;+ var errorReportTimer = null;++ function emitSurfaceError() {+ parent.postMessage({ type: 'multica:plugin-surface-error' }, '*');+ errorReportAttempts++;+ if (errorReportAttempts >= 50 && errorReportTimer !== null) {+ clearInterval(errorReportTimer);+ errorReportTimer = null;+ }+ }++ function reportSurfaceError() {+ if (errorReportAttempts > 0) return;+ emitSurfaceError();+ if (errorReportAttempts < 50) errorReportTimer = setInterval(emitSurfaceError, 120);+ }++ // A srcdoc document may execute before the host component's effect attaches+ // its listener. Repeat a failure until the host acknowledges it, bounded to+ // the same six-second window as the SDK bridge handshake.+ window.addEventListener("message", function (event) {+ if (event.source !== parent) return;+ if (!event.data || event.data.type !== 'multica:plugin-surface-error-ack') return;+ errorReportAttempts = 50;+ if (errorReportTimer !== null) clearInterval(errorReportTimer);+ errorReportTimer = null;+ });++ // Installed before plugin code executes. Dynamically appending an inline+ // script does not rethrow its syntax/runtime errors from appendChild; the+ // browser reports them through these global events instead.+ window.addEventListener("error", reportSurfaceError);+ window.addEventListener("unhandledrejection", reportSurfaceError);++ try {+ var encoded = document.getElementById("multica-surface-code").textContent;+ var binary = atob(encoded);+ var bytes = new Uint8Array(binary.length);+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ var element = document.createElement("script");+ element.textContent = new TextDecoder().decode(bytes);+ document.body.appendChild(element);+ } catch (error) {+ reportSurfaceError();+ }+})();+</script></body></html>`;}diff --git a/packages/views/settings/components/plugins-tab.test.tsx b/packages/views/settings/components/plugins-tab.test.tsxindex 139ce90d9e..f9b414d3a1 100644--- a/packages/views/settings/components/plugins-tab.test.tsx+++ b/packages/views/settings/components/plugins-tab.test.tsx@@ -11,23 +11,35 @@ const mockInstall = vi.hoisted(() => vi.fn());const mockConfigure = vi.hoisted(() => vi.fn());const mockSetEnabled = vi.hoisted(() => vi.fn());const mockUninstall = vi.hoisted(() => vi.fn());+const mockPublish = vi.hoisted(() => vi.fn());+const mockDeletePackage = vi.hoisted(() => vi.fn());const data = vi.hoisted(() => ({installed: { plugins: [] as Array<Record<string, unknown>> },+ packages: { packages: [] as Array<Record<string, unknown>> },role: "owner" as "owner" | "admin" | "member",}));vi.mock("@tanstack/react-query", () => ({- useQuery: () => ({ data: data.installed, isLoading: false, isError: false }),+ // Two queries reach this tab: what is installed, and what has been published.+ // They are told apart by the query key so a test can have one without the+ // other — which is the normal state right after a publish.+ useQuery: (options: { queryKey?: readonly unknown[] }) =>+ options?.queryKey?.[1] === "packages"+ ? { data: data.packages, isLoading: false, isError: false }+ : { data: data.installed, isLoading: false, isError: false },}));vi.mock("@multica/core/plugins", () => ({pluginInstallationsOptions: () => ({ queryKey: ["plugins", "installed"] }),+ pluginPackagesOptions: () => ({ queryKey: ["plugins", "packages"] }),usePreviewPlugin: () => ({ mutateAsync: mockPreview, isPending: false }),useInstallPlugin: () => ({ mutateAsync: mockInstall, isPending: false }),useConfigurePlugin: () => ({ mutateAsync: mockConfigure, isPending: false }),useSetPluginEnabled: () => ({ mutateAsync: mockSetEnabled, isPending: false }),useUninstallPlugin: () => ({ mutateAsync: mockUninstall, isPending: false }),+ usePublishPluginPackage: () => ({ mutateAsync: mockPublish, isPending: false }),+ useDeletePluginPackage: () => ({ mutateAsync: mockDeletePackage, isPending: false }),}));vi.mock("@multica/core/paths", () => ({@@ -54,7 +66,7 @@ const INSTALLATION = {name: "Hello Panel",description: "A greeting panel.",version: "1.0.0",- source_url: "https://example.com/multica.plugin.json",+ package_version_id: "version-1",enabled: true,granted_scopes: ["issues:read", "comments:write", "net:example.com"],config_schema: [@@ -80,15 +92,47 @@ const PREVIEW = {},scopes: ["issues:read", "comments:write", "net:example.com"],config_schema: [],+ version_id: "version-1",+ version: "1.0.0",+ digest: "0123456789abcdef",installed: false,added_scopes: [],};+// One published plugin with two versions: the installed one and a newer one an+// administrator has not adopted. That gap is the normal state after a publish,+// and it is what the version list has to make legible.+const PACKAGE = {+ id: "package-1",+ plugin_key: "com.example.hello",+ name: "Hello Panel",+ created_at: "2026-08-18T00:00:00Z",+ versions: [+ {+ id: "version-2",+ version: "2.0.0",+ digest: "fedcba9876543210",+ size_bytes: 2048,+ published_at: "2026-08-20T00:00:00Z",+ installed: false,+ },+ {+ id: "version-1",+ version: "1.0.0",+ digest: "0123456789abcdef",+ size_bytes: 1024,+ published_at: "2026-08-18T00:00:00Z",+ installed: true,+ },+ ],+};+describe("PluginsTab", () => {beforeEach(() => {vi.clearAllMocks();data.role = "owner";data.installed.plugins = [];+ data.packages.packages = [PACKAGE];mockPreview.mockResolvedValue(PREVIEW);mockInstall.mockResolvedValue(INSTALLATION);mockConfigure.mockResolvedValue(INSTALLATION);@@ -97,14 +141,11 @@ describe("PluginsTab", () => {});it("shows the scope consent screen before anything is installed", async () => {+ data.packages.packages = [{ ...PACKAGE, versions: [{ ...PACKAGE.versions[0] }] }];const user = userEvent.setup();render(<PluginsTab />, { wrapper: Wrapper });- await user.type(- screen.getByPlaceholderText("https://example.com/multica.plugin.json"),- "https://example.com/multica.plugin.json",- );- await user.click(screen.getByRole("button", { name: "Review" }));+ await user.click(screen.getByRole("button", { name: "Review and install" }));// The raw scope strings are the trust model, so they must be on screen// verbatim alongside their plain-language meaning.@@ -116,12 +157,42 @@ describe("PluginsTab", () => {expect(mockInstall).not.toHaveBeenCalled();await user.click(screen.getByRole("button", { name: "Grant and install" }));+ // The version reviewed is the version installed. Anything else would put+ // the consent screen back to describing one artifact while another runs.await waitFor(() => expect(mockInstall).toHaveBeenCalledWith({- source_url: "https://example.com/multica.plugin.json",+ version_id: "version-1",granted_scopes: ["issues:read", "comments:write", "net:example.com"],}));});+ it("marks the running version and offers an upgrade only for the others", async () => {+ // A publish does not move an installed workspace, so "which one am I on"+ // has to be answerable on this screen or the guarantee is invisible.+ const user = userEvent.setup();+ render(<PluginsTab />, { wrapper: Wrapper });++ expect(screen.getByText("1.0.0")).toBeInTheDocument();+ expect(screen.getByText("2.0.0")).toBeInTheDocument();+ expect(screen.getByText("In use")).toBeInTheDocument();++ const upgrade = screen.getAllByRole("button", { name: "Review and upgrade" });+ expect(upgrade).toHaveLength(1);++ mockPreview.mockResolvedValue({ ...PREVIEW, version_id: "version-2", version: "2.0.0", installed: true, installed_version: "1.0.0" });+ await user.click(upgrade[0]!);+ await waitFor(() => expect(mockPreview).toHaveBeenCalledWith({ version_id: "version-2" }));+ });++ it("publishes an uploaded package", async () => {+ const user = userEvent.setup();+ mockPublish.mockResolvedValue({ ...PACKAGE, versions: [PACKAGE.versions[0]] });+ render(<PluginsTab />, { wrapper: Wrapper });++ const bundle = new File(["zip bytes"], "plugin.zip", { type: "application/zip" });+ await user.upload(screen.getByLabelText("Upload package"), bundle);+ await waitFor(() => expect(mockPublish).toHaveBeenCalledWith(bundle));+ });+it("renders the configuration form from the manifest and never shows a stored secret", async () => {data.installed.plugins = [INSTALLATION];const user = userEvent.setup();@@ -172,7 +243,9 @@ describe("PluginsTab", () => {render(<PluginsTab />, { wrapper: Wrapper });expect(screen.getByText("Read-only access")).toBeInTheDocument();- expect(screen.queryByRole("button", { name: "Review" })).not.toBeInTheDocument();+ // The whole publish-and-install section is admin-only.+ expect(screen.queryByRole("button", { name: "Upload package" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Review and install" })).not.toBeInTheDocument();// Base UI's Switch marks the disabled state with aria-disabled rather than// the native attribute, so assert what a screen reader actually sees.expect(screen.getByRole("switch", { name: "Enable Plugin" })).toHaveAttribute("aria-disabled", "true");diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsxindex 263fd54449..67cbb8817a 100644--- a/packages/views/settings/components/plugins-tab.tsx+++ b/packages/views/settings/components/plugins-tab.tsx@@ -1,20 +1,28 @@"use client";-import { useMemo, useState } from "react";+import { useMemo, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { AlertCircle, Loader2, Trash2 } from "lucide-react";+import { AlertCircle, Loader2, Trash2, Upload } from "lucide-react";import { toast } from "sonner";import { useCurrentMember } from "@multica/core/permissions";import {pluginInstallationsOptions,+ pluginPackagesOptions,useConfigurePlugin,+ useDeletePluginPackage,useInstallPlugin,usePreviewPlugin,+ usePublishPluginPackage,useSetPluginEnabled,useUninstallPlugin,} from "@multica/core/plugins";import { useCurrentWorkspace } from "@multica/core/paths";-import type { PluginConfigField, PluginInstallation, PluginPreview } from "@multica/core/types";+import type {+ PluginConfigField,+ PluginInstallation,+ PluginPackage,+ PluginPreview,+} from "@multica/core/types";import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";@@ -242,55 +250,116 @@ function ConfigField({);}-function InstallFlow({ wsId, canManage }: { wsId: string; canManage: boolean }) {+/**+ * Publishing, and installing what was published.+ *+ * These are one screen because they are two halves of one story: an author+ * uploads an artifact, and an administrator installs one specific version of it.+ * There is no way to install code that was not published here first — which is+ * what makes the consent screen below a statement about the code and not just+ * about the manifest.+ */+function PublishAndInstall({ wsId, canManage }: { wsId: string; canManage: boolean }) {const { t } = useT("settings");+ const { data, isLoading } = useQuery(pluginPackagesOptions(wsId));+ const publishMutation = usePublishPluginPackage(wsId);+ const deleteMutation = useDeletePluginPackage(wsId);const previewMutation = usePreviewPlugin(wsId);const installMutation = useInstallPlugin(wsId);- const [sourceUrl, setSourceUrl] = useState("");+ const fileRef = useRef<HTMLInputElement>(null);const [preview, setPreview] = useState<PluginPreview | null>(null);- const runPreview = async () => {+ const packages = useMemo(() => data?.packages ?? [], [data]);++ const reportError = (error: unknown) => {+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));+ };++ const publish = async (file: File) => {try {- const result = await previewMutation.mutateAsync({ source_url: sourceUrl.trim() });- setPreview(result);+ const published = await publishMutation.mutateAsync(file);+ toast.success(t(($) => $.plugins.publish.published, {+ name: published.name,+ version: published.versions[0]?.version ?? "",+ }));+ } catch (error) {+ reportError(error);+ } finally {+ // Cleared unconditionally so picking the same file again re-fires change,+ // which is what a person does after fixing a rejected bundle.+ if (fileRef.current) fileRef.current.value = "";+ }+ };++ const review = async (versionId: string) => {+ try {+ setPreview(await previewMutation.mutateAsync({ version_id: versionId }));} catch (error) {setPreview(null);- toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));+ reportError(error);}};const confirmInstall = async () => {if (!preview) return;try {- await installMutation.mutateAsync({ source_url: sourceUrl.trim(), granted_scopes: preview.scopes });+ await installMutation.mutateAsync({ version_id: preview.version_id, granted_scopes: preview.scopes });setPreview(null);- setSourceUrl("");toast.success(t(($) => $.plugins.consent.installed));} catch (error) {- toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));+ reportError(error);}};return (- <SettingsSection title={t(($) => $.plugins.install.title)} description={t(($) => $.plugins.install.description)}>+ <SettingsSection title={t(($) => $.plugins.publish.title)} description={t(($) => $.plugins.publish.description)}><SettingsCard>- <div className="flex flex-col gap-2 px-4 py-4 sm:flex-row sm:items-center">- <Input- className="sm:flex-1"- disabled={!canManage || previewMutation.isPending}- value={sourceUrl}- placeholder={t(($) => $.plugins.install.placeholder)}- onChange={(event) => setSourceUrl(event.target.value)}+ <div className="flex flex-col gap-2 px-4 py-4 sm:flex-row sm:items-center sm:justify-between">+ <p className="text-caption text-muted-foreground">{t(($) => $.plugins.publish.hint)}</p>+ <input+ ref={fileRef}+ type="file"+ accept=".zip,application/zip"+ className="sr-only"+ aria-label={t(($) => $.plugins.publish.upload)}+ onChange={(event) => {+ const file = event.target.files?.[0];+ if (file) void publish(file);+ }}/><Button- disabled={!canManage || previewMutation.isPending || sourceUrl.trim().length === 0}- onClick={runPreview}+ disabled={!canManage || publishMutation.isPending}+ onClick={() => fileRef.current?.click()}>- {previewMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.install.review)}+ {publishMutation.isPending ? <Loader2 className="animate-spin" /> : <Upload />}+ {t(($) => $.plugins.publish.upload)}</Button></div>+ {isLoading ? (+ <div className="border-t border-surface-border px-4 py-4">+ <Skeleton className="h-16 w-full" aria-label={t(($) => $.plugins.loading)} />+ </div>+ ) : packages.length === 0 ? (+ <p className="border-t border-surface-border px-4 py-6 text-caption text-muted-foreground">+ {t(($) => $.plugins.publish.empty)}+ </p>+ ) : (+ packages.map((pluginPackage) => (+ <PublishedPackage+ key={pluginPackage.id}+ pluginPackage={pluginPackage}+ canManage={canManage}+ busy={previewMutation.isPending || deleteMutation.isPending}+ onReview={review}+ onDelete={(packageId) => deleteMutation+ .mutateAsync(packageId)+ .then(() => toast.success(t(($) => $.plugins.publish.deleted)))+ .catch(reportError)}+ />+ ))+ )}+{preview ? (<div className="space-y-4 border-t border-surface-border px-4 py-4"><div>@@ -298,7 +367,7 @@ function InstallFlow({ wsId, canManage }: { wsId: string; canManage: boolean })<p className="text-caption text-muted-foreground">{t(($) => $.plugins.byline, {author: preview.manifest.author.name,- version: preview.manifest.version,+ version: preview.version,})}{preview.installed? t(($) => $.plugins.consent.upgrade_from, { version: preview.installed_version ?? "" })@@ -335,6 +404,72 @@ function InstallFlow({ wsId, canManage }: { wsId: string; canManage: boolean }));}+function PublishedPackage({+ pluginPackage,+ canManage,+ busy,+ onReview,+ onDelete,+}: {+ pluginPackage: PluginPackage;+ canManage: boolean;+ busy: boolean;+ onReview: (versionId: string) => void;+ onDelete: (packageId: string) => void;+}) {+ const { t } = useT("settings");+ // Versions arrive newest first, and the installed one is marked rather than+ // inferred: after a publish those are different rows, and that difference is+ // the whole reason an upgrade is a decision somebody makes.+ const installed = pluginPackage.versions.find((version) => version.installed === true);++ return (+ <div className="space-y-3 border-t border-surface-border px-4 py-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="text-body font-medium">{pluginPackage.name}</div>+ <p className="text-caption text-muted-foreground">{pluginPackage.plugin_key}</p>+ </div>+ <Button+ size="icon"+ variant="ghost"+ aria-label={t(($) => $.plugins.publish.delete)}+ disabled={!canManage || busy}+ onClick={() => onDelete(pluginPackage.id)}+ >+ <Trash2 />+ </Button>+ </div>++ <ul className="space-y-1.5">+ {pluginPackage.versions.map((version) => (+ <li key={version.id} className="flex flex-wrap items-center gap-2 text-caption">+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{version.version}</code>+ {version.installed === true ? (+ <Badge variant="secondary">{t(($) => $.plugins.publish.installed_version)}</Badge>+ ) : null}+ <span className="text-muted-foreground">{version.published_at.slice(0, 10)}</span>+ <span className="font-mono text-muted-foreground" title={version.digest}>+ {version.digest.slice(0, 12)}+ </span>+ {version.installed === true ? null : (+ <Button+ size="sm"+ variant="ghost"+ className="ml-auto"+ disabled={!canManage || busy}+ onClick={() => onReview(version.id)}+ >+ {installed ? t(($) => $.plugins.publish.review_upgrade) : t(($) => $.plugins.publish.review_install)}+ </Button>+ )}+ </li>+ ))}+ </ul>+ </div>+ );+}+function InstalledPlugin({installation,wsId,@@ -438,9 +573,6 @@ function InstalledPlugin({</div>) : null}- <p className="text-caption text-muted-foreground">- {t(($) => $.plugins.source)}: <span className="font-mono break-all">{installation.source_url}</span>- </p></div><ConfigForm installation={installation} canManage={canManage} wsId={wsId} />@@ -468,7 +600,7 @@ export function PluginsTab() {</Alert>) : null}- {canManage ? <InstallFlow wsId={wsId} canManage={canManage} /> : null}+ {canManage ? <PublishAndInstall wsId={wsId} canManage={canManage} /> : null}<SettingsSection title={t(($) => $.plugins.installed.title)}>{isLoading ? (diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 6a1c09c599..a7765cf8d9 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -245,6 +245,11 @@ var concurrentIndexCleanups = map[string]string{"363_plugin_invocation_installation_index": "idx_plugin_invocation_installation_created","364_plugin_invocation_created_at_index": "idx_plugin_invocation_created_at","390_agent_task_queue_dispatched_reclaim_v2_index": "idx_agent_task_queue_dispatched_reclaim_v2",+ "393_plugin_package_workspace_key_index": "idx_plugin_package_workspace_key",+ "394_plugin_package_version_unique_index": "idx_plugin_package_version_unique",+ "395_plugin_package_version_package_index": "idx_plugin_package_version_package",+ "396_plugin_package_file_path_index": "idx_plugin_package_file_path",+ "397_plugin_installation_package_version_index": "idx_plugin_installation_package_version",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 32d407995e..b46c2df444 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1470,6 +1470,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// see what is mounted in their workspace and which scopes// it holds; install / configure / remove stay admin-only.r.Get("/plugins", h.ListPlugins)+ // A surface's code, read from the version the workspace+ // installed. Member-visible because opening an issue is+ // what asks for it.+ r.Get("/plugins/{installationId}/surfaces/{surfaceKey}/script", h.GetPluginSurfaceScript)})// Admin-level accessr.Group(func(r chi.Router) {@@ -1496,10 +1500,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)r.Put("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)r.Delete("/runtime-profiles/{profileId}", h.DeleteRuntimeProfile)+ // Publishing. The author uploads an artifact bundle and we+ // store it; a version is immutable once published, so+ // there is no update route here by design.+ r.Get("/plugins/packages", h.ListPluginPackages)+ r.Post("/plugins/packages", h.PublishPluginPackage)+ r.Post("/plugins/packages/local", h.PublishLocalPluginPackage)+ r.Delete("/plugins/packages/{packageId}", h.DeletePluginPackage)// Installing a Plugin is two steps on purpose: preview- // parses the manifest and returns the scope list without- // writing anything, so the consent screen has something to- // show before an installation exists.+ // reads the published version's manifest and returns the+ // scope list without writing anything, so the consent+ // screen has something to show before an installation+ // exists. Both steps name the same version id, which is+ // what makes the approved manifest and the running code+ // the same artifact.r.Post("/plugins/preview", h.PreviewPlugin)r.Post("/plugins", h.InstallPlugin)r.Get("/plugins/{installationId}/invocations", h.ListPluginInvocations)diff --git a/server/go.mod b/server/go.modindex a44f1f5b7d..ecf6a9097e 100644--- a/server/go.mod+++ b/server/go.mod@@ -29,6 +29,7 @@ require (github.com/slack-go/slack v0.26.0github.com/spf13/cobra v1.10.2github.com/spf13/pflag v1.0.9+ github.com/tdewolff/parse/v2 v2.8.13github.com/yuin/goldmark v1.8.4golang.org/x/sync v0.22.0golang.org/x/sys v0.47.0diff --git a/server/go.sum b/server/go.sumindex f102f1a15d..b25db4457c 100644--- a/server/go.sum+++ b/server/go.sum@@ -146,6 +146,10 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVgithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/tdewolff/parse/v2 v2.8.13 h1:si/8rLw5BZZTWCCiMm9A3f6x+RmqYfrkEeXCgpX5ick=+github.com/tdewolff/parse/v2 v2.8.13/go.mod h1:XdsoSFThlVIRIajAuqz1evNY7bagZS8LBOPA3aVopwQ=+github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk=+github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.goindex f186c3509a..78a8e153f9 100644--- a/server/internal/handler/plugin.go+++ b/server/internal/handler/plugin.go@@ -56,12 +56,15 @@ func writePluginError(w http.ResponseWriter, err error, fallback string) {// encrypted table), and configured secrets appear as names in// `configured_secrets`.type pluginInstallationResponse struct {- ID string `json:"id"`- PluginKey string `json:"plugin_key"`- Name string `json:"name"`- Description string `json:"description,omitempty"`- Version string `json:"version"`- SourceURL string `json:"source_url"`+ ID string `json:"id"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Version string `json:"version"`+ // The published version this installation is bound to. Nothing about it can+ // change under the workspace's feet: upgrading means pointing at a different+ // version id, which is a second consent.+ PackageVersionID string `json:"package_version_id"`Enabled bool `json:"enabled"`GrantedScopes []string `json:"granted_scopes"`ConfigSchema []service.PluginConfigField `json:"config_schema"`@@ -133,7 +136,7 @@ func (h *Handler) pluginInstallationPayload(ctx context.Context, installation dbName: manifest.Name,Description: manifest.Description,Version: installation.Version,- SourceURL: installation.SourceUrl,+ PackageVersionID: uuidToString(installation.PackageVersionID),Enabled: installation.Enabled,GrantedScopes: granted,ConfigSchema: service.ConfigFieldsForManifest(manifest),@@ -176,7 +179,7 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {}type previewPluginRequest struct {- SourceURL string `json:"source_url"`+ VersionID string `json:"version_id"`}// PreviewPlugin — POST /api/workspaces/{id}/plugins/preview@@ -196,7 +199,7 @@ func (h *Handler) PreviewPlugin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "invalid request body")return}- preview, err := h.PluginService.PreviewPlugin(r.Context(), workspaceID, req.SourceURL)+ preview, err := h.PluginService.PreviewPlugin(r.Context(), workspaceID, req.VersionID)if err != nil {writePluginError(w, err, "failed to read the Plugin manifest")return@@ -205,7 +208,7 @@ func (h *Handler) PreviewPlugin(w http.ResponseWriter, r *http.Request) {}type installPluginRequest struct {- SourceURL string `json:"source_url"`+ VersionID string `json:"version_id"`GrantedScopes []string `json:"granted_scopes"`}@@ -228,7 +231,7 @@ func (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "invalid request body")return}- installation, err := h.PluginService.InstallPlugin(r.Context(), workspaceID, member.UserID, req.SourceURL, req.GrantedScopes)+ installation, err := h.PluginService.InstallPlugin(r.Context(), workspaceID, member.UserID, req.VersionID, req.GrantedScopes)if err != nil {writePluginError(w, err, "failed to install the Plugin")returndiff --git a/server/internal/handler/plugin_action_test.go b/server/internal/handler/plugin_action_test.goindex 5949d86683..a87d15a5bc 100644--- a/server/internal/handler/plugin_action_test.go+++ b/server/internal/handler/plugin_action_test.go@@ -34,9 +34,9 @@ func installPluginForAction(t *testing.T, scopes []string) string {`"scopes": ["issues:read", "comments:write", "storage:user"]`,`"scopes": `+string(encoded), 1)}- source := withLocalPluginSource(t, manifest)+ versionID := withLocalPluginSource(t, manifest)- body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": scopes})+ body, _ := json.Marshal(map[string]any{"version_id": versionID, "granted_scopes": scopes})recorder := httptest.NewRecorder()testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusCreated {diff --git a/server/internal/handler/plugin_example_test.go b/server/internal/handler/plugin_example_test.goindex 74396c3f60..377f6a8d0b 100644--- a/server/internal/handler/plugin_example_test.go+++ b/server/internal/handler/plugin_example_test.go@@ -172,8 +172,13 @@ func installExamplePlugin(t *testing.T, servers exampleServers) string {plugins.CallbackBaseURL = "https://multica.test/api/v1/plugin"t.Cleanup(func() { *plugins = previous })+ // Publishing is what validates the whole artifact: the manifest, the surface+ // script, and the SKILL.md all have to be there and be loadable. The example+ // is the file a plugin author copies, so this is the check that keeps it+ // runnable rather than merely well-formed.+ versionID := publishLocalPlugin(t, "deploy-sentinel")body, _ := json.Marshal(map[string]any{- "source_url": service.LocalSourcePrefix + "deploy-sentinel",+ "version_id": versionID,"granted_scopes": scopes,})recorder := httptest.NewRecorder()diff --git a/server/internal/handler/plugin_hook_test.go b/server/internal/handler/plugin_hook_test.goindex 93f47bb469..930e9f7730 100644--- a/server/internal/handler/plugin_hook_test.go+++ b/server/internal/handler/plugin_hook_test.go@@ -47,9 +47,9 @@ const hookHandlerTestManifest = `{func installHookPlugin(t *testing.T) string {t.Helper()- source := withLocalPluginSource(t, hookHandlerTestManifest)+ versionID := withLocalPluginSource(t, hookHandlerTestManifest)body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "net:example.com"},})recorder := httptest.NewRecorder()@@ -276,7 +276,7 @@ func TestEventDispatchRespectsTheFeatureFlagEndToEnd(t *testing.T) {`"net:example.com"`, `"net:`+host+`"`,).Replace(hookHandlerTestManifest)- source := withLocalPluginSource(t, manifest)+ versionID := withLocalPluginSource(t, manifest)// The dev-origin opt-in is what lets a loopback endpoint be dialled at all;// the granted net: scope still has to cover it, which the replace above did.previousOrigins := testHandler.PluginService.DevOrigins@@ -300,7 +300,7 @@ func TestEventDispatchRespectsTheFeatureFlagEndToEnd(t *testing.T) {})body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "net:" + host},})install := httptest.NewRecorder()diff --git a/server/internal/handler/plugin_mcp_test.go b/server/internal/handler/plugin_mcp_test.goindex 66e12b593e..bddd65ae87 100644--- a/server/internal/handler/plugin_mcp_test.go+++ b/server/internal/handler/plugin_mcp_test.go@@ -4,6 +4,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing")@@ -58,8 +59,8 @@ const httpHookManifest = `{func installMCPPlugin(t *testing.T, manifest string, scopes []string) string {t.Helper()withPluginsV1Flag(t, testHandler, true)- source := withLocalPluginSource(t, manifest)- body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": scopes})+ versionID := withLocalPluginSource(t, manifest)+ body, _ := json.Marshal(map[string]any{"version_id": versionID, "granted_scopes": scopes})recorder := httptest.NewRecorder()testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusCreated {@@ -129,19 +130,31 @@ const scopelessMCPManifest = `{}}`-// Refused at INSTALL, not at discovery: manifest validation already requires+// Refused at PUBLISH, not at discovery: manifest validation already requires// every hook transport URL to sit inside a declared `net:` scope, and that check// does not care which transport it is. The equivalent check inside// DiscoverMCPHookTools is a second layer behind this one, not the gate.-func TestMCPHookWithoutANetScopeCannotBeInstalled(t *testing.T) {+//+// The gate used to sit at install, because that was the first moment anybody+// parsed the manifest. Now the artifact is parsed when the author hands it over,+// so a manifest like this never becomes something an administrator can be shown.+func TestMCPHookWithoutANetScopeCannotBePublished(t *testing.T) {withPluginsV1Flag(t, testHandler, true)- source := withLocalPluginSource(t, scopelessMCPManifest)- body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{"issues:read"}})+ root := t.TempDir()+ writeLocalPluginManifest(t, root, scopelessMCPManifest)+ previousDir := testHandler.PluginService.LocalDir+ testHandler.PluginService.LocalDir = root+ t.Cleanup(func() { testHandler.PluginService.LocalDir = previousDir })+ body, _ := json.Marshal(map[string]string{"name": "hello"})recorder := httptest.NewRecorder()- testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ testHandler.PublishLocalPluginPackage(recorder,+ pluginHandlerRequest(http.MethodPost, "/plugins/packages/local", body, map[string]string{"id": testWorkspaceID}))if recorder.Code == http.StatusCreated {- t.Fatal("a hook pointing outside its granted net: scopes was installed")+ t.Fatal("a hook pointing outside its declared net: scopes was published")+ }+ if !strings.Contains(recorder.Body.String(), "net: scope") {+ t.Fatalf("the refusal does not name the reason: %s", recorder.Body.String())}}diff --git a/server/internal/handler/plugin_package.go b/server/internal/handler/plugin_package.gonew file mode 100644index 0000000000..69e1cd12a0--- /dev/null+++ b/server/internal/handler/plugin_package.go@@ -0,0 +1,197 @@+package handler++import (+ "encoding/json"+ "io"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// Publishing endpoints.+//+// An author uploads an artifact bundle and Multica stores it. There is no+// install-by-URL any more, and no second way for plugin code to reach a reader's+// browser: the settings page publishes here, and installing names a version this+// endpoint created.++// ListPluginPackages — GET /api/workspaces/{id}/plugins/packages+func (h *Handler) ListPluginPackages(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")+ if !ok {+ return+ }+ packages, err := h.PluginService.ListPackages(r.Context(), workspaceID)+ if err != nil {+ writePluginError(w, err, "failed to list published Plugins")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"packages": packages})+}++// PublishPluginPackage — POST /api/workspaces/{id}/plugins/packages+//+// multipart/form-data with a `bundle` file: a zip holding the manifest and every+// file it names. Validated in full before anything is stored, so a surface whose+// entry is missing fails here rather than in a reader's browser weeks later.+func (h *Handler) PublishPluginPackage(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceIDString := workspaceIDFromURL(r, "id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDString, "workspace_id")+ if !ok {+ return+ }+ member, ok := h.workspaceMember(w, r, workspaceIDString)+ if !ok {+ return+ }++ // Bounded before the multipart reader sees it: ParseMultipartForm would+ // otherwise spool an unbounded upload to a temp file first.+ r.Body = http.MaxBytesReader(w, r.Body, plugincontract.MaxBundleSize+multipartOverheadBytes)+ if err := r.ParseMultipartForm(plugincontract.MaxBundleSize + multipartOverheadBytes); err != nil {+ writeError(w, http.StatusRequestEntityTooLarge, "the Plugin package upload is too large or malformed")+ return+ }+ defer func() {+ if r.MultipartForm != nil {+ _ = r.MultipartForm.RemoveAll()+ }+ }()++ file, _, err := r.FormFile("bundle")+ if err != nil {+ writeError(w, http.StatusBadRequest, "a Plugin package file is required")+ return+ }+ defer file.Close()++ archive, err := io.ReadAll(io.LimitReader(file, plugincontract.MaxBundleSize+1))+ if err != nil {+ writeError(w, http.StatusBadRequest, "failed to read the Plugin package")+ return+ }+ if len(archive) > plugincontract.MaxBundleSize {+ writeError(w, http.StatusRequestEntityTooLarge, "the Plugin package is too large")+ return+ }++ published, err := h.PluginService.PublishBundle(r.Context(), workspaceID, member.UserID, archive)+ if err != nil {+ writePluginError(w, err, "failed to publish the Plugin")+ return+ }+ writeJSON(w, http.StatusCreated, published)+}++// multipartOverheadBytes is headroom for the form's own boundaries and headers,+// so a bundle at exactly the size limit is not rejected by the envelope around+// it.+const multipartOverheadBytes = 64 * 1024++type publishLocalPluginRequest struct {+ // Name is a directory under MULTICA_PLUGIN_DIR.+ Name string `json:"name"`+}++// PublishLocalPluginPackage — POST /api/workspaces/{id}/plugins/packages/local+//+// The development channel: publish straight from a directory the operator+// already hosts, so iterating on a surface does not mean zipping and uploading+// after every edit. It produces an ordinary immutable version — there is no+// live-reload path that would make "is this code frozen?" depend on how the+// plugin was installed.+func (h *Handler) PublishLocalPluginPackage(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceIDString := workspaceIDFromURL(r, "id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDString, "workspace_id")+ if !ok {+ return+ }+ member, ok := h.workspaceMember(w, r, workspaceIDString)+ if !ok {+ return+ }+ var req publishLocalPluginRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ published, err := h.PluginService.PublishLocalBundle(r.Context(), workspaceID, member.UserID, strings.TrimSpace(req.Name))+ if err != nil {+ writePluginError(w, err, "failed to publish the Plugin")+ return+ }+ writeJSON(w, http.StatusCreated, published)+}++// DeletePluginPackage — DELETE /api/workspaces/{id}/plugins/packages/{packageId}+func (h *Handler) DeletePluginPackage(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")+ if !ok {+ return+ }+ if err := h.PluginService.DeletePackage(r.Context(), workspaceID, chi.URLParam(r, "packageId")); err != nil {+ writePluginError(w, err, "failed to delete the published Plugin")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++// GetPluginSurfaceScript — GET /api/workspaces/{id}/plugins/{installationId}/surfaces/{surfaceKey}/script+//+// The code one surface runs, read from the installed version's stored files. The+// host inlines it into the sandboxed document it generates, which is what lets+// that document's CSP name no third-party script origin at all: a surface can no+// longer reach its author's server just by existing.+//+// Member-visible, because opening an issue is what triggers it. It returns code+// the workspace already consented to install, to a member who can already see+// that the Plugin is mounted.+func (h *Handler) GetPluginSurfaceScript(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")+ if !ok {+ return+ }+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, chi.URLParam(r, "installationId"))+ if err != nil {+ writePluginError(w, err, "failed to load the Plugin")+ return+ }+ if !installation.Enabled {+ // A disabled installation renders nothing. Serving its code anyway would+ // make "disabled" a UI state rather than a decision.+ writeError(w, http.StatusForbidden, "this Plugin is disabled")+ return+ }+ script, err := h.PluginService.SurfaceScript(r.Context(), installation, chi.URLParam(r, "surfaceKey"))+ if err != nil {+ writePluginError(w, err, "failed to load the Plugin surface")+ return+ }+ // The bytes are immutable for the life of the version, and the surface key is+ // part of the URL, so this is safely cacheable per client. Private: it is+ // workspace content behind a session.+ w.Header().Set("Cache-Control", "private, max-age=300")+ w.Header().Set("ETag", `"`+script.Digest+`"`)+ if strings.Contains(r.Header.Get("If-None-Match"), script.Digest) {+ w.WriteHeader(http.StatusNotModified)+ return+ }+ writeJSON(w, http.StatusOK, script)+}diff --git a/server/internal/handler/plugin_package_concurrency_test.go b/server/internal/handler/plugin_package_concurrency_test.gonew file mode 100644index 0000000000..10eefe9bed--- /dev/null+++ b/server/internal/handler/plugin_package_concurrency_test.go@@ -0,0 +1,158 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+)++// Publish, install and delete race each other.+//+// Relationships are application-owned by repository policy, so there is no+// foreign key making "the version this installation names still exists" true.+// The interleaving that matters is `delete counts zero installs` → `install+// reads the version` → `delete commits` → `install commits`: the installation+// survives pointing at a version that is gone, its panel 404s forever, and+// nothing in the product can explain why. A (workspace, plugin key) advisory+// lock held for each transaction is what serializes them.+//+// These run the real handlers against the real database, because the bug only+// exists at the transaction boundary — a test with a fake would assert the+// structure of the fix rather than its effect.++// TestDeleteAndInstallRaceLeavesNoDanglingInstallation is the direct regression.+// Whichever side wins, the end state has to be self-consistent: either the+// package is gone and nothing installed it, or the installation exists and its+// version is still there.+func TestDeleteAndInstallRaceLeavesNoDanglingInstallation(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ withHostCapabilities(t)++ // Repeated because a lost race is a scheduling accident: a single pass can+ // miss the window even when the lock is absent.+ for attempt := range 12 {+ cleanupPluginInstallations(t)+ published := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ versionID := published.Versions[0].ID++ var wait sync.WaitGroup+ wait.Add(2)+ go func() {+ defer wait.Done()+ body, _ := json.Marshal(map[string]any{"version_id": versionID, "granted_scopes": []string{"issues:read"}})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder,+ pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ }()+ go func() {+ defer wait.Done()+ recorder := httptest.NewRecorder()+ testHandler.DeletePluginPackage(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/packages", nil,+ map[string]string{"id": testWorkspaceID, "packageId": published.ID}))+ }()+ wait.Wait()++ var dangling int+ if err := testPool.QueryRow(context.Background(),+ `SELECT COUNT(*) FROM plugin_installation i+ WHERE i.workspace_id = $1+ AND NOT EXISTS (SELECT 1 FROM plugin_package_version v WHERE v.id = i.package_version_id)`,+ testWorkspaceID,+ ).Scan(&dangling); err != nil {+ t.Fatalf("count dangling installations: %v", err)+ }+ if dangling != 0 {+ t.Fatalf("attempt %d: %d installation(s) name a version that no longer exists", attempt, dangling)+ }+ }+}++// The mirror case: a publish racing a delete of the same plugin must not leave+// a version whose package row is gone. Such a version is unreachable — the+// settings page lists versions per package — so it would be storage nothing can+// find or clean up.+func TestPublishAndDeleteRaceLeavesNoOrphanVersion(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ withHostCapabilities(t)++ for attempt := range 12 {+ cleanupPluginInstallations(t)+ published := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")++ var wait sync.WaitGroup+ wait.Add(2)+ go func() {+ defer wait.Done()+ uploadPluginBundle(t, pluginBundleZip(t, packageManifest("2.0.0"), "console.log('v2');\n"))+ }()+ go func() {+ defer wait.Done()+ recorder := httptest.NewRecorder()+ testHandler.DeletePluginPackage(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/packages", nil,+ map[string]string{"id": testWorkspaceID, "packageId": published.ID}))+ }()+ wait.Wait()++ var orphans int+ if err := testPool.QueryRow(context.Background(),+ `SELECT COUNT(*) FROM plugin_package_version v+ WHERE v.workspace_id = $1+ AND NOT EXISTS (SELECT 1 FROM plugin_package p WHERE p.id = v.package_id)`,+ testWorkspaceID,+ ).Scan(&orphans); err != nil {+ t.Fatalf("count orphan versions: %v", err)+ }+ if orphans != 0 {+ t.Fatalf("attempt %d: %d published version(s) outlived their package", attempt, orphans)+ }+ }+}++// A failed publish must leave the package row exactly as it was. The display+// name follows the newest PUBLISHED version, so a conflicting publish that+// renamed the package would have the list describing an artifact that was never+// stored — and a first publish that failed after creating the row would leave a+// plugin with no versions at all.+func TestFailedPublishDoesNotMovePackageState(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ withHostCapabilities(t)+ cleanupPluginInstallations(t)++ publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")++ // Same version, different display name: the version insert loses the unique+ // index, so nothing about this publish may survive.+ renamed := packageManifest("1.0.0")+ renamed = replaceOnce(t, renamed, `"name": "Published Panel"`, `"name": "Renamed Panel"`)+ recorder := uploadPluginBundle(t, pluginBundleZip(t, renamed, "console.log('tampered');\n"))+ if recorder.Code != http.StatusConflict {+ t.Fatalf("republish status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ var name string+ var versions int+ if err := testPool.QueryRow(context.Background(),+ `SELECT p.name, (SELECT COUNT(*) FROM plugin_package_version v WHERE v.package_id = p.id)+ FROM plugin_package p WHERE p.workspace_id = $1`, testWorkspaceID,+ ).Scan(&name, &versions); err != nil {+ t.Fatalf("read package: %v", err)+ }+ if name != "Published Panel" {+ t.Fatalf("a failed publish renamed the package to %q", name)+ }+ if versions != 1 {+ t.Fatalf("versions = %d, want the one that actually published", versions)+ }+}++func replaceOnce(t *testing.T, source, old, replacement string) string {+ t.Helper()+ if !strings.Contains(source, old) {+ t.Fatalf("fixture does not contain %q", old)+ }+ return strings.Replace(source, old, replacement, 1)+}diff --git a/server/internal/handler/plugin_package_test.go b/server/internal/handler/plugin_package_test.gonew file mode 100644index 0000000000..2d0d189bb1--- /dev/null+++ b/server/internal/handler/plugin_package_test.go@@ -0,0 +1,316 @@+package handler++import (+ "archive/zip"+ "bytes"+ "context"+ "encoding/json"+ "mime/multipart"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// Publishing, and the guarantee it exists for.+//+// The old model froze the manifest at install and loaded the surface script from+// the author's server on every panel open, so "the administrator approved this"+// and "this is what runs" were two different statements. These tests pin the+// replacement: an installation names one immutable version, and publishing+// another one changes nothing until an administrator upgrades.++const packageTestManifest = `{+ "manifest_version": 1,+ "key": "com.example.published",+ "name": "Published Panel",+ "version": "%VERSION%",+ "author": { "name": "example" },+ "scopes": ["issues:read"],+ "contributes": {+ "surfaces": [{ "key": "hello", "type": "issue_panel", "name": "Hello", "entry": "ui/main.js" }]+ }+}`++func packageManifest(version string) string {+ return strings.Replace(packageTestManifest, "%VERSION%", version, 1)+}++func pluginBundleZip(t *testing.T, manifest, script string) []byte {+ t.Helper()+ var buffer bytes.Buffer+ writer := zip.NewWriter(&buffer)+ for name, content := range map[string]string{+ plugincontract.ManifestFilename: manifest,+ "ui/main.js": script,+ } {+ entry, err := writer.Create(name)+ if err != nil {+ t.Fatalf("create zip entry %s: %v", name, err)+ }+ if _, err := entry.Write([]byte(content)); err != nil {+ t.Fatalf("write zip entry %s: %v", name, err)+ }+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close zip: %v", err)+ }+ return buffer.Bytes()+}++func uploadPluginBundle(t *testing.T, archive []byte) *httptest.ResponseRecorder {+ t.Helper()+ var body bytes.Buffer+ form := multipart.NewWriter(&body)+ part, err := form.CreateFormFile("bundle", "plugin.zip")+ if err != nil {+ t.Fatalf("create form file: %v", err)+ }+ if _, err := part.Write(archive); err != nil {+ t.Fatalf("write form file: %v", err)+ }+ if err := form.Close(); err != nil {+ t.Fatalf("close form: %v", err)+ }++ request := httptest.NewRequest(http.MethodPost, "/plugins/packages", &body)+ request.Header.Set("X-User-ID", testUserID)+ request.Header.Set("Content-Type", form.FormDataContentType())+ routeContext := chi.NewRouteContext()+ routeContext.URLParams.Add("id", testWorkspaceID)+ request = request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))++ recorder := httptest.NewRecorder()+ testHandler.PublishPluginPackage(recorder, request)+ return recorder+}++func publishUploadedBundle(t *testing.T, manifest, script string) service.PluginPackageSummary {+ t.Helper()+ recorder := uploadPluginBundle(t, pluginBundleZip(t, manifest, script))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("publish: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var published service.PluginPackageSummary+ if err := json.Unmarshal(recorder.Body.Bytes(), &published); err != nil {+ t.Fatalf("decode published package: %v", err)+ }+ return published+}++func installPublishedVersion(t *testing.T, versionID string) string {+ t.Helper()+ body, _ := json.Marshal(map[string]any{"version_id": versionID, "granted_scopes": []string{"issues:read"}})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatalf("decode installation: %v", err)+ }+ return installed.ID+}++func surfaceScript(t *testing.T, installationID, surfaceKey string) (*httptest.ResponseRecorder, service.PluginSurfaceScript) {+ t.Helper()+ recorder := httptest.NewRecorder()+ testHandler.GetPluginSurfaceScript(recorder, pluginHandlerRequest(http.MethodGet, "/script", nil, map[string]string{+ "id": testWorkspaceID,+ "installationId": installationID,+ "surfaceKey": surfaceKey,+ }))+ var script service.PluginSurfaceScript+ if recorder.Code == http.StatusOK {+ if err := json.Unmarshal(recorder.Body.Bytes(), &script); err != nil {+ t.Fatalf("decode surface script: %v", err)+ }+ }+ return recorder, script+}++// An author with no server of their own publishes a panel plugin by upload, an+// administrator installs it, and the panel's code comes back from us. That is+// the acceptance criterion for the whole change.+func TestUploadedBundleInstallsAndServesItsOwnCode(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withHostCapabilities(t)++ published := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ if len(published.Versions) != 1 || published.Versions[0].Version != "1.0.0" {+ t.Fatalf("unexpected published versions: %+v", published.Versions)+ }+ if published.Versions[0].Digest == "" || published.Versions[0].SizeBytes == 0 {+ t.Fatalf("a published version must report what was stored: %+v", published.Versions[0])+ }++ installationID := installPublishedVersion(t, published.Versions[0].ID)+ recorder, script := surfaceScript(t, installationID, "hello")+ if recorder.Code != http.StatusOK {+ t.Fatalf("surface script: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(script.Code, "console.log('v1')") {+ t.Fatalf("the served code is not what was uploaded: %q", script.Code)+ }+ if script.Version != "1.0.0" {+ t.Fatalf("script version = %q, want the installed version", script.Version)+ }+}++// The invariant the RFC called non-negotiable: publishing again must not change+// what an installed workspace runs.+func TestPublishingANewVersionDoesNotChangeAnInstalledWorkspace(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withHostCapabilities(t)++ first := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ installationID := installPublishedVersion(t, first.Versions[0].ID)++ second := publishUploadedBundle(t, packageManifest("2.0.0"), "console.log('v2');\n")+ if len(second.Versions) != 2 {+ t.Fatalf("the second publish should add a version, not replace one: %+v", second.Versions)+ }++ _, script := surfaceScript(t, installationID, "hello")+ if strings.Contains(script.Code, "v2") {+ t.Fatalf("a publish changed the code an installed workspace runs: %q", script.Code)+ }+ if script.Version != "1.0.0" {+ t.Fatalf("installed version = %q, want 1.0.0 until an administrator upgrades", script.Version)+ }++ // The settings page has to be able to say which one is running, or "upgrade+ // available" is not something an administrator can act on.+ installedFlags := map[string]bool{}+ for _, version := range second.Versions {+ installedFlags[version.Version] = version.Installed+ }+ if !installedFlags["1.0.0"] || installedFlags["2.0.0"] {+ t.Fatalf("installed markers are wrong: %+v", second.Versions)+ }++ // And upgrading is what moves it.+ upgradeVersionID := ""+ for _, version := range second.Versions {+ if version.Version == "2.0.0" {+ upgradeVersionID = version.ID+ }+ }+ if got := installPublishedVersion(t, upgradeVersionID); got != installationID {+ t.Fatalf("upgrade created a second installation: %s != %s", got, installationID)+ }+ if _, upgraded := surfaceScript(t, installationID, "hello"); !strings.Contains(upgraded.Code, "v2") {+ t.Fatalf("after upgrading, the code is still %q", upgraded.Code)+ }+}++// Republishing a version is refused rather than accepted as an overwrite. The+// unique index is what makes immutability a rule instead of a convention.+func TestPublishRefusesToOverwriteAnExistingVersion(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withHostCapabilities(t)++ publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ recorder := uploadPluginBundle(t, pluginBundleZip(t, packageManifest("1.0.0"), "console.log('tampered');\n"))+ if recorder.Code != http.StatusConflict {+ t.Fatalf("republish status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(recorder.Body.String(), "immutable") {+ t.Fatalf("the conflict does not explain itself: %s", recorder.Body.String())+ }+}++func TestDeletePublishedPackageRefusesWhileInstalled(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withHostCapabilities(t)++ published := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ installationID := installPublishedVersion(t, published.Versions[0].ID)++ params := map[string]string{"id": testWorkspaceID, "packageId": published.ID}+ recorder := httptest.NewRecorder()+ testHandler.DeletePluginPackage(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/packages", nil, params))+ if recorder.Code != http.StatusConflict {+ t.Fatalf("delete while installed status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ uninstall := httptest.NewRecorder()+ testHandler.UninstallPlugin(uninstall, pluginHandlerRequest(http.MethodDelete, "/plugins", nil, map[string]string{+ "id": testWorkspaceID, "installationId": installationID,+ }))+ if uninstall.Code != http.StatusNoContent {+ t.Fatalf("uninstall status=%d body=%s", uninstall.Code, uninstall.Body.String())+ }++ recorder = httptest.NewRecorder()+ testHandler.DeletePluginPackage(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/packages", nil, params))+ if recorder.Code != http.StatusNoContent {+ t.Fatalf("delete after uninstall status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ // The stored bundle goes with it; a package row with orphaned files behind+ // it is storage nothing can reach.+ var remaining int+ if err := testPool.QueryRow(context.Background(),+ `SELECT COUNT(*) FROM plugin_package_file WHERE version_id IN (+ SELECT id FROM plugin_package_version WHERE workspace_id = $1)`, testWorkspaceID).Scan(&remaining); err != nil {+ t.Fatalf("count package files: %v", err)+ }+ if remaining != 0 {+ t.Fatalf("deleting the package left %d files behind", remaining)+ }+}++func TestSurfaceScriptRefusesWhatWasNeverInstalled(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withHostCapabilities(t)++ published := publishUploadedBundle(t, packageManifest("1.0.0"), "console.log('v1');\n")+ installationID := installPublishedVersion(t, published.Versions[0].ID)++ // A surface key the installed manifest does not declare. The manifest+ // consulted is the installation's own snapshot, so this cannot be widened by+ // publishing a version that declares more.+ if recorder, _ := surfaceScript(t, installationID, "nope"); recorder.Code != http.StatusNotFound {+ t.Fatalf("unknown surface key status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ disable := httptest.NewRecorder()+ testHandler.DisablePlugin(disable, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil, map[string]string{+ "id": testWorkspaceID, "installationId": installationID,+ }))+ if disable.Code != http.StatusOK {+ t.Fatalf("disable status=%d body=%s", disable.Code, disable.Body.String())+ }+ // Disabling has to stop the code from being served, or "disabled" is a UI+ // state rather than a decision.+ if recorder, _ := surfaceScript(t, installationID, "hello"); recorder.Code != http.StatusForbidden {+ t.Fatalf("disabled installation served its code: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++// withHostCapabilities enables every contribution kind for the duration of a+// test, so these exercise publishing rather than the staged-rollout gate.+func withHostCapabilities(t *testing.T) {+ t.Helper()+ previous := testHandler.PluginService.Host+ testHandler.PluginService.Host = plugincontract.Capabilities{+ SurfaceTypes: map[string]bool{plugincontract.SurfaceIssuePanel: true, plugincontract.SurfaceSidebarPanel: true, plugincontract.SurfaceModal: true},+ HookTriggers: map[string]bool{plugincontract.TriggerUI: true, plugincontract.TriggerManual: true, plugincontract.TriggerAgent: true, plugincontract.TriggerEvent: true},+ HookTransport: map[string]bool{plugincontract.TransportHTTP: true, plugincontract.TransportMCP: true},+ ResourceTypes: map[string]bool{plugincontract.ResourceSkill: true},+ }+ t.Cleanup(func() { testHandler.PluginService.Host = previous })+}diff --git a/server/internal/handler/plugin_skill_test.go b/server/internal/handler/plugin_skill_test.goindex 22f857e7f7..c4a2aa1970 100644--- a/server/internal/handler/plugin_skill_test.go+++ b/server/internal/handler/plugin_skill_test.go@@ -52,9 +52,9 @@ func writePluginSkillFile(t *testing.T, root, key, content string) {func installSkillPlugin(t *testing.T, root, manifest string) string {t.Helper()- source := withLocalPluginSourceIn(t, root, manifest)+ versionID := withLocalPluginSourceIn(t, root, manifest)body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read"},})recorder := httptest.NewRecorder()@@ -182,9 +182,9 @@ func TestPluginSkillWillNotOverwriteAHumanAuthoredSkill(t *testing.T) {root := t.TempDir()writePluginSkillFile(t, root, "pr-review", prReviewSkill)- source := withLocalPluginSourceIn(t, root, skillPluginManifest)+ versionID := withLocalPluginSourceIn(t, root, skillPluginManifest)body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read"},})recorder := httptest.NewRecorder()diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.goindex d69ae66408..7b206becb4 100644--- a/server/internal/handler/plugin_test.go+++ b/server/internal/handler/plugin_test.go@@ -70,26 +70,63 @@ func pluginHandlerRequest(method, path string, body []byte, params map[string]streturn request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))}+// writeLocalPluginManifest writes the manifest plus a stub for every file it+// declares.+//+// Publishing validates that the whole bundle is present, which is the point of+// the artifact model: a surface whose entry does not exist is refused at publish+// instead of failing in a reader's browser. A file a test already wrote is left+// alone, so a suite that supplies its own SKILL.md keeps it.func writeLocalPluginManifest(t *testing.T, root, manifest string) {t.Helper()- if err := os.MkdirAll(filepath.Join(root, "hello"), 0o755); err != nil {+ dir := filepath.Join(root, "hello")+ if err := os.MkdirAll(dir, 0o755); err != nil {t.Fatalf("create local plugin dir: %v", err)}- if err := os.WriteFile(filepath.Join(root, "hello", plugincontract.ManifestFilename), []byte(manifest), 0o644); err != nil {+ if err := os.WriteFile(filepath.Join(dir, plugincontract.ManifestFilename), []byte(manifest), 0o644); err != nil {t.Fatalf("write local manifest: %v", err)}+ // A manifest that does not parse is itself a fixture — publishing has to be+ // what rejects it, so there is nothing to stub out.+ parsed, _, err := plugincontract.ParseManifest([]byte(manifest))+ if err != nil {+ return+ }+ for _, surface := range parsed.Contributes.Surfaces {+ writeLocalPluginFile(t, dir, surface.Entry, "// stub surface\n")+ }+ for _, resource := range parsed.Contributes.Resources {+ writeLocalPluginFile(t, dir, resource.Entry, "---\nname: "+resource.Key+"\ndescription: Stub resource.\n---\n\nStub.\n")+ }+ if parsed.Icon != "" {+ writeLocalPluginFile(t, dir, parsed.Icon, "icon")+ }+}++func writeLocalPluginFile(t *testing.T, dir, entry, content string) {+ t.Helper()+ path := filepath.Join(dir, filepath.FromSlash(entry))+ if _, err := os.Stat(path); err == nil {+ return+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("create plugin file dir: %v", err)+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatalf("write plugin file %s: %v", entry, err)+ }}-// withLocalPluginSource points the service at a temp MULTICA_PLUGIN_DIR and-// enables every capability, so these tests exercise the HTTP surface rather-// than the staged-rollout gate.+// withLocalPluginSource points the service at a temp MULTICA_PLUGIN_DIR,+// enables every capability, publishes the plugin, and returns the published+// version id — which is what an install names now.func withLocalPluginSource(t *testing.T, manifest string) string {t.Helper()return withLocalPluginSourceIn(t, t.TempDir(), manifest)}// withLocalPluginSourceIn takes the root explicitly so an upgrade test can-// rewrite the manifest in place and install again from the same source URL.+// rewrite the manifest in place and publish a second version from it.func withLocalPluginSourceIn(t *testing.T, root string, manifest string) string {t.Helper()writeLocalPluginManifest(t, root, manifest)@@ -114,7 +151,31 @@ func withLocalPluginSourceIn(t *testing.T, root string, manifest string) stringtestHandler.PluginService.Host = previousHosttestHandler.PluginService.Secrets = previousSecrets})- return service.LocalSourcePrefix + "hello"+ return publishLocalPlugin(t, "hello")+}++// publishLocalPlugin publishes a directory under MULTICA_PLUGIN_DIR and returns+// the id of the version it created. Re-publishing an unchanged version string is+// what a development loop does, so the service gives those a `+dev.N` suffix+// rather than a conflict — which is why this always returns a NEW version.+func publishLocalPlugin(t *testing.T, name string) string {+ t.Helper()+ body, _ := json.Marshal(map[string]string{"name": name})+ recorder := httptest.NewRecorder()+ testHandler.PublishLocalPluginPackage(recorder,+ pluginHandlerRequest(http.MethodPost, "/plugins/packages/local", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("publish %s: status=%d body=%s", name, recorder.Code, recorder.Body.String())+ }+ var published service.PluginPackageSummary+ if err := json.Unmarshal(recorder.Body.Bytes(), &published); err != nil {+ t.Fatalf("decode published package: %v", err)+ }+ if len(published.Versions) == 0 {+ t.Fatalf("publish %s returned no versions", name)+ }+ // Newest first.+ return published.Versions[0].ID}func cleanupPluginInstallations(t *testing.T) {@@ -124,6 +185,9 @@ func cleanupPluginInstallations(t *testing.T) {testPool.Exec(ctx, `DELETE FROM plugin_storage WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)testPool.Exec(ctx, `DELETE FROM plugin_secret WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)testPool.Exec(ctx, `DELETE FROM plugin_installation WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_package_file WHERE version_id IN (SELECT id FROM plugin_package_version WHERE workspace_id = $1)`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_package_version WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_package WHERE workspace_id = $1`, testWorkspaceID)}remove()t.Cleanup(remove)@@ -153,10 +217,10 @@ func TestPluginManagementRequiresPluginsV1(t *testing.T) {func TestPluginPreviewShowsScopesWithoutInstalling(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, handlerTestManifest)+ versionID := withLocalPluginSource(t, handlerTestManifest)recorder := httptest.NewRecorder()- body, _ := json.Marshal(map[string]string{"source_url": source})+ body, _ := json.Marshal(map[string]string{"version_id": versionID})testHandler.PreviewPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/preview", body, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusOK {t.Fatalf("preview status=%d body=%s", recorder.Code, recorder.Body.String())@@ -194,9 +258,9 @@ func TestPluginPreviewShowsScopesWithoutInstalling(t *testing.T) {func TestPluginInstallRequiresExactConsent(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, handlerTestManifest)+ versionID := withLocalPluginSource(t, handlerTestManifest)- partial, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{"issues:read"}})+ partial, _ := json.Marshal(map[string]any{"version_id": versionID, "granted_scopes": []string{"issues:read"}})recorder := httptest.NewRecorder()testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", partial, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusConflict {@@ -204,7 +268,7 @@ func TestPluginInstallRequiresExactConsent(t *testing.T) {}extra, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "storage:user", "issues:write"},})recorder = httptest.NewRecorder()@@ -217,10 +281,10 @@ func TestPluginInstallRequiresExactConsent(t *testing.T) {func TestPluginInstallConfigureAndUninstall(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, handlerTestManifest)+ versionID := withLocalPluginSource(t, handlerTestManifest)install, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "storage:user"},})recorder := httptest.NewRecorder()@@ -310,14 +374,23 @@ func TestPluginInstallConfigureAndUninstall(t *testing.T) {}}-func TestPluginInstallRejectsMalformedManifest(t *testing.T) {+// A malformed manifest is now refused by PUBLISHING, not by installing. That is+// the move this whole change is: the artifact is parsed once, when the author+// hands it over, so an administrator can never be shown a consent screen for+// something that was never going to load.+func TestPluginPublishRejectsMalformedManifest(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, `{"manifest_version":1,"key":"com.example.hello","surprise":true}`)+ root := t.TempDir()+ writeLocalPluginManifest(t, root, `{"manifest_version":1,"key":"com.example.hello","surprise":true}`)+ previousDir := testHandler.PluginService.LocalDir+ testHandler.PluginService.LocalDir = root+ t.Cleanup(func() { testHandler.PluginService.LocalDir = previousDir })- body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{}})+ body, _ := json.Marshal(map[string]string{"name": "hello"})recorder := httptest.NewRecorder()- testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ testHandler.PublishLocalPluginPackage(recorder,+ pluginHandlerRequest(http.MethodPost, "/plugins/packages/local", body, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusBadRequest {t.Fatalf("malformed manifest status=%d body=%s", recorder.Code, recorder.Body.String())}@@ -326,6 +399,37 @@ func TestPluginInstallRejectsMalformedManifest(t *testing.T) {}}+// The other half of publish-time validation: a manifest that parses but names a+// file the bundle does not carry. Under URL hosting this failed months later in+// a reader's browser, with nothing in the product that could have caught it.+func TestPluginPublishRejectsMissingSurfaceEntry(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ root := t.TempDir()+ // Written directly rather than through writeLocalPluginManifest, which+ // stubs out every declared file — the missing entry IS the fixture.+ if err := os.MkdirAll(filepath.Join(root, "hello"), 0o755); err != nil {+ t.Fatalf("create local plugin dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(root, "hello", plugincontract.ManifestFilename), []byte(handlerTestManifest), 0o644); err != nil {+ t.Fatalf("write local manifest: %v", err)+ }+ previousDir := testHandler.PluginService.LocalDir+ testHandler.PluginService.LocalDir = root+ t.Cleanup(func() { testHandler.PluginService.LocalDir = previousDir })++ body, _ := json.Marshal(map[string]string{"name": "hello"})+ recorder := httptest.NewRecorder()+ testHandler.PublishLocalPluginPackage(recorder,+ pluginHandlerRequest(http.MethodPost, "/plugins/packages/local", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("missing surface entry status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(recorder.Body.String(), "ui/main.js") {+ t.Fatalf("error does not name the missing file: %s", recorder.Body.String())+ }+}+func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)@@ -338,7 +442,7 @@ func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {// of about the gate. It also had a shelf life: once every kind ships there// is nothing left to write such a fixture against. Narrowing the host here// keeps the assertion true for good.- source := withLocalPluginSource(t, hookOnlyTestManifest)+ versionID := withLocalPluginSource(t, hookOnlyTestManifest)testHandler.PluginService.Host = plugincontract.Capabilities{SurfaceTypes: map[string]bool{plugincontract.SurfaceIssuePanel: true},HookTriggers: map[string]bool{},@@ -347,7 +451,7 @@ func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {}body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "net:example.com"},})recorder := httptest.NewRecorder()@@ -369,11 +473,11 @@ func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {func TestPluginInstallAcceptsEveryCapabilityThisHostShips(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, hookOnlyTestManifest)+ versionID := withLocalPluginSource(t, hookOnlyTestManifest)testHandler.PluginService.Host = plugincontract.HostCapabilities()body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "net:example.com"},})recorder := httptest.NewRecorder()@@ -391,11 +495,11 @@ func TestPluginInstallAcceptsAShippedSurface(t *testing.T) {// The other half of the gate: a contribution the host DOES ship must install// against the real HostCapabilities set, not only against a test set that// enables everything.- source := withLocalPluginSource(t, handlerTestManifest)+ versionID := withLocalPluginSource(t, handlerTestManifest)testHandler.PluginService.Host = plugincontract.HostCapabilities()body, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "storage:user"},})recorder := httptest.NewRecorder()@@ -421,10 +525,10 @@ func TestPluginUpgradePrunesSecretsTheNewManifestDropped(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)root := t.TempDir()- source := withLocalPluginSourceIn(t, root, handlerTestManifest)+ versionID := withLocalPluginSourceIn(t, root, handlerTestManifest)install, _ := json.Marshal(map[string]any{- "source_url": source,+ "version_id": versionID,"granted_scopes": []string{"issues:read", "comments:write", "storage:user"},})recorder := httptest.NewRecorder()@@ -452,9 +556,16 @@ func TestPluginUpgradePrunesSecretsTheNewManifestDropped(t *testing.T) {upgraded = strings.Replace(upgraded, `,"token": { "type": "secret", "label": "Token" }`, "", 1)writeLocalPluginManifest(t, root, upgraded)+ // Upgrading is installing a DIFFERENT version. Re-posting the same version+ // id would be a no-op by design, which is the guarantee under test elsewhere.+ upgradedVersionID := publishLocalPlugin(t, "hello")+ upgrade, _ := json.Marshal(map[string]any{+ "version_id": upgradedVersionID,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ })recorder = httptest.NewRecorder()- testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", install, map[string]string{"id": testWorkspaceID}))+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", upgrade, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusCreated {t.Fatalf("upgrade status=%d body=%s", recorder.Code, recorder.Body.String())}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 522a85cf89..683c8c451a 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -94,6 +94,9 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"plugin_invocation": workspaceDelete,"plugin_storage": workspaceDelete,"plugin_secret": workspaceDelete,+ "plugin_package": workspaceDelete,+ "plugin_package_version": workspaceDelete,+ "plugin_package_file": workspaceDelete,"project": workspaceDelete,"project_resource": workspaceDelete,"quick_action": workspaceDelete,diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.goindex f6ebc5a086..c7280907f3 100644--- a/server/internal/service/plugin.go+++ b/server/internal/service/plugin.go@@ -7,12 +7,10 @@ import ("encoding/json""errors""fmt"- "io""log/slog""net/http""net/url""os"- "path/filepath""strings""time"@@ -24,28 +22,24 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/featureflag""github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/remotemcp")-// LocalSourcePrefix installs from MULTICA_PLUGIN_DIR instead of the network.-// Self-hosted operators and plugin authors need a loop that does not require-// publishing to a public HTTPS host first.-const LocalSourcePrefix = "local:"--// PluginService owns plugin installation, configuration, and plugin-owned-// state.+// PluginService owns plugin publishing, installation, configuration, and+// plugin-owned state.type PluginService struct {Queries *db.QueriesTxStarter TxStarter// Secrets encrypts `secret` config values. Nil disables secret writes so a// misconfigured deployment fails closed instead of storing plaintext.Secrets *secretbox.Box- // LocalDir is MULTICA_PLUGIN_DIR. Empty disables local sources.+ // LocalDir is MULTICA_PLUGIN_DIR: a directory of plugin sources an author+ // can publish from without zipping and uploading after every edit. Empty+ // disables the development publish channel.LocalDir string- // DevOrigins is MULTICA_PLUGIN_DEV_ORIGINS: origins a plugin author may- // serve a manifest from while building one, typically a localhost static- // server. Empty in every deployment that has not opted in, which is the- // only reason it is safe to skip the public-HTTPS guard for them.+ // DevOrigins is MULTICA_PLUGIN_DEV_ORIGINS: hook endpoint origins an author+ // may point a plugin at while building one, typically a localhost server.+ // Empty in every deployment that has not opted in, which is the only reason+ // it is safe to skip the public-HTTPS guard for them.DevOrigins []string// Host gates which declared contributions this build can actually run.Host plugincontract.Capabilities@@ -161,10 +155,17 @@ func pluginErrf(kind PluginErrorKind, format string, args ...any) *PluginError {// manifest text plus the scope list: there is no signature, no trust tier, and// no publisher verification in this model, so the administrator reading the// scopes IS the trust decision.+//+// What it describes is one published version, and installing binds to that same+// version — so unlike the URL model this replaced, the code approved here is the+// code that runs.type PluginPreview struct {Manifest plugincontract.Manifest `json:"manifest"`Scopes []string `json:"scopes"`ConfigSchema []PluginConfigField `json:"config_schema"`+ VersionID string `json:"version_id"`+ Version string `json:"version"`+ Digest string `json:"digest"`// Upgrade describes what changes if this replaces an existing install.Installed bool `json:"installed"`InstalledVersion string `json:"installed_version,omitempty"`@@ -202,44 +203,19 @@ func ConfigFieldsForManifest(manifest plugincontract.Manifest) []PluginConfigFiereturn fields}-// FetchManifest resolves a source URL to a parsed manifest.+// ManifestForVersion decodes the manifest a published version froze at publish+// time.//-// Network sources reuse the Remote MCP endpoint guard: public HTTPS only, no-// userinfo/query/fragment, private and metadata address ranges refused, and the-// dialer re-checks the resolved address so a DNS rebind between validation and-// connection cannot reach an internal host.-func (s *PluginService) FetchManifest(ctx context.Context, sourceURL string) (plugincontract.Manifest, []byte, error) {- sourceURL = strings.TrimSpace(sourceURL)- if sourceURL == "" {- return plugincontract.Manifest{}, nil, pluginErrf(PluginErrorInvalid, "source_url is required")- }- if len(sourceURL) > 2048 {- return plugincontract.Manifest{}, nil, pluginErrf(PluginErrorInvalid, "source_url is too long")- }-- var raw []byte- var err error- switch {- case strings.HasPrefix(sourceURL, LocalSourcePrefix):- raw, err = s.readLocalManifest(strings.TrimPrefix(sourceURL, LocalSourcePrefix))- case s.isDevOrigin(sourceURL):- // Explicitly opted in by the operator, so the public-HTTPS guard is- // skipped rather than worked around. This is what makes iterating on a- // surface possible: the author serves it from localhost and installs by- // URL, exactly as a published plugin would be.- raw, err = fetchDevManifest(ctx, sourceURL)- default:- raw, err = fetchRemoteManifest(ctx, sourceURL)- }- if err != nil {- return plugincontract.Manifest{}, nil, err- }-- manifest, canonical, parseErr := plugincontract.ParseManifest(raw)- if parseErr != nil {- return plugincontract.Manifest{}, nil, &PluginError{Kind: PluginErrorInvalid, Message: "plugin manifest is invalid", Err: parseErr}+// Nothing is fetched. The manifest, the surface scripts and the skill text were+// all validated together when the author published, and they are read back+// together — an installation cannot end up consenting to one version's manifest+// while running another version's code.+func ManifestForVersion(version db.PluginPackageVersion) (plugincontract.Manifest, []byte, error) {+ var manifest plugincontract.Manifest+ if err := json.Unmarshal(version.Manifest, &manifest); err != nil {+ return plugincontract.Manifest{}, nil, &PluginError{Kind: PluginErrorInvalid, Message: "published plugin manifest is unreadable", Err: err}}- return manifest, canonical, nil+ return manifest, version.Manifest, nil}// parseDevOrigins reads the opt-in list. Anything that is not a bare origin is@@ -281,85 +257,15 @@ func (s *PluginService) isDevOrigin(sourceURL string) bool {return false}-// fetchDevManifest is the opted-in path: an ordinary bounded GET with no SSRF-// guard, because the operator named this exact origin.-func fetchDevManifest(ctx context.Context, sourceURL string) ([]byte, error) {- request, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil)- if err != nil {- return nil, &PluginError{Kind: PluginErrorInvalid, Message: "build manifest request", Err: err}- }- response, err := (&http.Client{Timeout: 10 * time.Second}).Do(request)- if err != nil {- return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "fetch plugin manifest", Err: err}- }- defer response.Body.Close()- if response.StatusCode != http.StatusOK {- return nil, pluginErrf(PluginErrorUnavailable, "plugin manifest request returned HTTP %d", response.StatusCode)- }- raw, err := io.ReadAll(io.LimitReader(response.Body, plugincontract.MaxManifestSize+1))- if err != nil {- return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin manifest", Err: err}- }- if len(raw) > plugincontract.MaxManifestSize {- return nil, pluginErrf(PluginErrorInvalid, "plugin manifest exceeds %d bytes", plugincontract.MaxManifestSize)- }- return raw, nil-}--func (s *PluginService) readLocalManifest(name string) ([]byte, error) {- if s.LocalDir == "" {- return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")- }- // The name indexes a directory the operator already controls, but it still- // arrives over the API, so it must not be able to escape the configured- // root or name a dotfile path.- if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {- return nil, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")- }- path := filepath.Join(s.LocalDir, name, plugincontract.ManifestFilename)- raw, err := os.ReadFile(path)- if errors.Is(err, os.ErrNotExist) {- return nil, pluginErrf(PluginErrorNotFound, "no %s found for local plugin %q", plugincontract.ManifestFilename, name)- }- if err != nil {- return nil, &PluginError{Kind: PluginErrorInvalid, Message: "read local plugin manifest", Err: err}- }- return raw, nil-}--func fetchRemoteManifest(ctx context.Context, sourceURL string) ([]byte, error) {- endpoint, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, sourceURL, nil, nil)- if err != nil {- return nil, &PluginError{Kind: PluginErrorInvalid, Message: "source_url must be a plain public HTTPS URL", Err: err}- }- request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)+// PreviewPlugin reads a published version's manifest without writing anything.+// It is the first half of the two-step install: the administrator must see the+// scopes before an installation row exists.+func (s *PluginService) PreviewPlugin(ctx context.Context, workspaceID pgtype.UUID, versionID string) (*PluginPreview, error) {+ version, err := s.VersionForWorkspace(ctx, workspaceID, versionID)if err != nil {- return nil, &PluginError{Kind: PluginErrorInvalid, Message: "build manifest request", Err: err}- }- request.Header.Set("Accept", "application/json")- response, err := remotemcp.NewSecureHTTPClient(endpoint).Do(request)- if err != nil {- return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "fetch plugin manifest", Err: err}- }- defer response.Body.Close()- if response.StatusCode != http.StatusOK {- return nil, pluginErrf(PluginErrorUnavailable, "plugin manifest request returned HTTP %d", response.StatusCode)- }- raw, err := io.ReadAll(io.LimitReader(response.Body, plugincontract.MaxManifestSize+1))- if err != nil {- return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin manifest", Err: err}- }- if len(raw) > plugincontract.MaxManifestSize {- return nil, pluginErrf(PluginErrorInvalid, "plugin manifest exceeds %d bytes", plugincontract.MaxManifestSize)+ return nil, err}- return raw, nil-}--// PreviewPlugin fetches and parses a manifest without writing anything. It is-// the first half of the two-step install: the administrator must see the scopes-// before an installation row exists.-func (s *PluginService) PreviewPlugin(ctx context.Context, workspaceID pgtype.UUID, sourceURL string) (*PluginPreview, error) {- manifest, _, err := s.FetchManifest(ctx, sourceURL)+ manifest, _, err := ManifestForVersion(version)if err != nil {return nil, err}@@ -371,6 +277,9 @@ func (s *PluginService) PreviewPlugin(ctx context.Context, workspaceID pgtype.UUManifest: manifest,Scopes: manifest.Scopes,ConfigSchema: ConfigFieldsForManifest(manifest),+ VersionID: uuidString(version.ID),+ Version: version.Version,+ Digest: version.Digest,}existing, err := s.Queries.GetWorkspacePluginInstallationByKey(ctx, db.GetWorkspacePluginInstallationByKeyParams{WorkspaceID: workspaceID,@@ -423,8 +332,17 @@ func decodeScopes(raw []byte) []string {// manifest exactly: partial consent would leave the plugin silently broken, and// consenting to a scope the manifest does not request would grant access the// administrator was never shown a reason for.-func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pgtype.UUID, sourceURL string, grantedScopes []string) (db.PluginInstallation, error) {- manifest, canonical, err := s.FetchManifest(ctx, sourceURL)+//+// The installation is bound to one published version. A later publish creates+// another version and does not touch this row — upgrading is a second, explicit+// consent, which is what makes "approved the manifest, ran the code" a true+// statement rather than an aspiration.+func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pgtype.UUID, versionID string, grantedScopes []string) (db.PluginInstallation, error) {+ version, err := s.VersionForWorkspace(ctx, workspaceID, versionID)+ if err != nil {+ return db.PluginInstallation{}, err+ }+ manifest, canonical, err := ManifestForVersion(version)if err != nil {return db.PluginInstallation{}, err}@@ -454,11 +372,21 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pdefer func() { _ = tx.Rollback(ctx) }()queries := s.Queries.WithTx(tx)+ if lockErr := lockPluginPackageKey(ctx, queries, workspaceID, manifest.Key); lockErr != nil {+ return db.PluginInstallation{}, lockErr+ }+ if recheckErr := requireVersionStillPublished(ctx, queries, workspaceID, version.ID); recheckErr != nil {+ return db.PluginInstallation{}, recheckErr+ }+installation, createErr := queries.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{- WorkspaceID: workspaceID,- PluginKey: manifest.Key,- SourceUrl: sourceURL,- Version: manifest.Version,+ WorkspaceID: workspaceID,+ PluginKey: manifest.Key,+ PackageVersionID: version.ID,+ // The published version string, not the manifest's: a development+ // publish lands under a `+dev.N` suffix, and the settings page has to+ // name the version that actually exists.+ Version: version.Version,Manifest: canonical,GrantedScopes: scopesJSON,InstalledBy: userID,@@ -471,7 +399,7 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID p}return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "install plugin", Err: createErr}}- if skillErr := s.InstallSkillResources(ctx, queries, installation, manifest, sourceURL, userID); skillErr != nil {+ if skillErr := s.InstallSkillResources(ctx, queries, installation, manifest, userID); skillErr != nil {return db.PluginInstallation{}, skillErr}if commitErr := tx.Commit(ctx); commitErr != nil {@@ -501,18 +429,25 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pdefer func() { _ = tx.Rollback(ctx) }()queries := s.Queries.WithTx(tx)+ if err := lockPluginPackageKey(ctx, queries, workspaceID, manifest.Key); err != nil {+ return db.PluginInstallation{}, err+ }+ if err := requireVersionStillPublished(ctx, queries, workspaceID, version.ID); err != nil {+ return db.PluginInstallation{}, err+ }+for _, key := range orphanedSecrets {if _, err := queries.DeletePluginSecret(ctx, db.DeletePluginSecretParams{InstallationID: existing.ID, Key: key}); err != nil {return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "prune plugin secret", Err: err}}}updated, err := queries.UpdatePluginInstallationManifest(ctx, db.UpdatePluginInstallationManifestParams{- ID: existing.ID,- SourceUrl: sourceURL,- Version: manifest.Version,- Manifest: canonical,- GrantedScopes: scopesJSON,- Config: config,+ ID: existing.ID,+ PackageVersionID: version.ID,+ Version: version.Version,+ Manifest: canonical,+ GrantedScopes: scopesJSON,+ Config: config,})if err != nil {return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "upgrade plugin", Err: err}@@ -520,7 +455,7 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID p// Re-run on upgrade so a changed SKILL.md takes effect and a dropped one is// pruned. Same transaction as the manifest snapshot: the two must never// disagree about what this version contributes.- if err := s.InstallSkillResources(ctx, queries, updated, manifest, sourceURL, userID); err != nil {+ if err := s.InstallSkillResources(ctx, queries, updated, manifest, userID); err != nil {return db.PluginInstallation{}, err}if err := tx.Commit(ctx); err != nil {@@ -824,31 +759,3 @@ func (s *PluginService) InstallationForWorkspace(ctx context.Context, workspaceI}return installation, nil}--// readLocalFile reads a file from inside a local plugin directory.-//-// Same containment as readLocalManifest, plus one more: the joined path is-// re-checked against the plugin's own directory after cleaning. `entry` is-// validated at manifest-parse time to be relative and traversal-free, but this-// is the layer that touches the filesystem and it does not get to assume that.-func (s *PluginService) readLocalFile(name, entry string) ([]byte, error) {- if s.LocalDir == "" {- return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")- }- if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {- return nil, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")- }- root := filepath.Join(s.LocalDir, name)- path := filepath.Clean(filepath.Join(root, entry))- if path != root && !strings.HasPrefix(path, root+string(os.PathSeparator)) {- return nil, pluginErrf(PluginErrorInvalid, "plugin resource %q escapes its directory", entry)- }- raw, err := os.ReadFile(path)- if errors.Is(err, os.ErrNotExist) {- return nil, pluginErrf(PluginErrorNotFound, "plugin resource %q was not found", entry)- }- if err != nil {- return nil, &PluginError{Kind: PluginErrorInvalid, Message: "read plugin resource", Err: err}- }- return raw, nil-}diff --git a/server/internal/service/plugin_package.go b/server/internal/service/plugin_package.gonew file mode 100644index 0000000000..0d2648d45d--- /dev/null+++ b/server/internal/service/plugin_package.go@@ -0,0 +1,524 @@+package service++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// Publishing.+//+// An author uploads an artifact bundle; Multica stores it and serves it. There+// is no source URL, and there is no second way in: what an administrator+// approves and what a reader's browser runs are the same rows in this database.+//+// A published version is immutable. Publishing again creates another version and+// changes nothing for a workspace that already installed one — upgrading is an+// administrator's action, which is the whole reason the two are separate.+//+// Only the frontend artifact moved here. Hook endpoints and MCP servers still+// live on the author's own infrastructure; we do not run third-party backends.++// PluginPackageVersionSummary is one published version as the settings page+// lists it.+type PluginPackageVersionSummary struct {+ ID string `json:"id"`+ Version string `json:"version"`+ Digest string `json:"digest"`+ SizeBytes int64 `json:"size_bytes"`+ PublishedAt string `json:"published_at"`+ // Installed marks the version this workspace currently runs, so "which one+ // am I on" is answerable without cross-referencing two lists.+ Installed bool `json:"installed"`+}++// PluginPackageSummary is one publishable plugin identity with its versions,+// newest first.+type PluginPackageSummary struct {+ ID string `json:"id"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ Versions []PluginPackageVersionSummary `json:"versions"`+ CreatedAt string `json:"created_at"`+}++const pluginTimeFormat = "2006-01-02T15:04:05Z07:00"++// PublishBundle stores an uploaded artifact bundle as a new immutable version.+func (s *PluginService) PublishBundle(ctx context.Context, workspaceID, userID pgtype.UUID, archive []byte) (PluginPackageSummary, error) {+ bundle, err := plugincontract.ParseBundle(archive)+ if err != nil {+ // The wrapped text names the file or field at fault, and it is written+ // for the author. A publish failure they cannot act on would send them+ // back to guessing, which is the failure mode this whole path replaces.+ return PluginPackageSummary{}, pluginErrf(PluginErrorInvalid, "plugin package is invalid: %v", err)+ }+ return s.publish(ctx, workspaceID, userID, bundle, false)+}++// PublishLocalBundle publishes from MULTICA_PLUGIN_DIR — the development+// channel, so an author iterating on a surface does not have to zip and upload+// after every edit.+//+// It produces an ordinary immutable version rather than a live directory the+// panel reads at render time. A second render path would mean "is the code+// frozen?" depended on how the plugin was installed, which is exactly the+// ambiguity this change removes. Re-publishing an unchanged version string is+// what a dev loop does constantly, so those get a `+dev.N` build suffix instead+// of a conflict.+func (s *PluginService) PublishLocalBundle(ctx context.Context, workspaceID, userID pgtype.UUID, name string) (PluginPackageSummary, error) {+ if s.LocalDir == "" {+ return PluginPackageSummary{}, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")+ }+ if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {+ return PluginPackageSummary{}, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")+ }+ bundle, err := plugincontract.ParseBundleFromDir(func(entry string) ([]byte, bool, error) {+ content, readErr := s.readLocalFile(name, entry)+ var pluginErr *PluginError+ if errors.As(readErr, &pluginErr) && pluginErr.Kind == PluginErrorNotFound {+ return nil, false, nil+ }+ if readErr != nil {+ return nil, false, readErr+ }+ return content, true, nil+ })+ if err != nil {+ return PluginPackageSummary{}, pluginErrf(PluginErrorInvalid, "local plugin package is invalid: %v", err)+ }+ return s.publish(ctx, workspaceID, userID, bundle, true)+}++// publish writes the package row, the version and its files in ONE transaction,+// under the (workspace, plugin key) lock.+//+// All three parts are in the same transaction for the same reason: any partial+// result is a lie the version list cannot show. A version whose files half+// landed is a panel that loads nothing; a package row whose display name was+// updated by a publish that then conflicted claims to describe a version that+// was never stored; and a first publish that failed after creating the package+// leaves a plugin with zero versions in the list.+func (s *PluginService) publish(ctx context.Context, workspaceID, userID pgtype.UUID, bundle plugincontract.Bundle, devLoop bool) (PluginPackageSummary, error) {+ if err := bundle.Manifest.CheckCapabilities(s.Host); err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorIncompatible, Message: capabilityMessage(err), Err: err}+ }++ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "begin publish", Err: err}+ }+ defer func() { _ = tx.Rollback(ctx) }()+ queries := s.Queries.WithTx(tx)++ if err := lockPluginPackageKey(ctx, queries, workspaceID, bundle.Manifest.Key); err != nil {+ return PluginPackageSummary{}, err+ }+ pkg, err := upsertPackage(ctx, queries, workspaceID, userID, bundle.Manifest)+ if err != nil {+ return PluginPackageSummary{}, err+ }+ existing, err := queries.ListPluginPackageVersions(ctx, pkg.ID)+ if err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "list published versions", Err: err}+ }+ version, err := resolvePublishVersion(bundle.Manifest.Version, existing, devLoop)+ if err != nil {+ return PluginPackageSummary{}, err+ }++ row, err := queries.CreatePluginPackageVersion(ctx, db.CreatePluginPackageVersionParams{+ PackageID: pkg.ID,+ WorkspaceID: workspaceID,+ Version: version,+ Manifest: bundle.Canonical,+ Digest: BundleDigest(bundle),+ SizeBytes: int64(bundle.TotalSize()),+ PublishedBy: userID,+ })+ if err != nil {+ if isUniqueViolation(err) {+ return PluginPackageSummary{}, pluginErrf(PluginErrorConflict, "version %s of this plugin is already published; published versions are immutable, so publish a new version instead", version)+ }+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "publish plugin version", Err: err}+ }+ for _, file := range bundle.Files {+ sum := sha256.Sum256(file.Content)+ if err := queries.CreatePluginPackageFile(ctx, db.CreatePluginPackageFileParams{+ VersionID: row.ID,+ Path: file.Path,+ Content: file.Content,+ SizeBytes: int64(len(file.Content)),+ Sha256: hex.EncodeToString(sum[:]),+ }); err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "store plugin package file", Err: err}+ }+ }+ if err := tx.Commit(ctx); err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "commit publish", Err: err}+ }+ return s.packageSummary(ctx, workspaceID, pkg)+}++// BundleDigest hashes the bundle's contents: the canonical manifest, then each+// file's path and bytes in sorted order.+//+// Deliberately not a hash of the uploaded archive. Two zips of identical files+// differ in timestamps and compression, and the question the digest answers is+// "are we looking at the same plugin", not "was this the same upload".+func BundleDigest(bundle plugincontract.Bundle) string {+ hash := sha256.New()+ hash.Write(bundle.Canonical)+ for _, file := range bundle.Files {+ fmt.Fprintf(hash, "\n%s\n%d\n", file.Path, len(file.Content))+ hash.Write(file.Content)+ }+ return hex.EncodeToString(hash.Sum(nil))+}++// resolvePublishVersion decides what version string this publish lands under.+//+// An upload keeps the manifest's version and collides loudly if it is taken —+// that collision IS the immutability guarantee, and an author who meant to+// change something needs to say so in the manifest. A local development publish+// takes `+dev.N` instead, because re-publishing an unchanged version is what+// editing a file and reloading looks like.+func resolvePublishVersion(version string, existing []db.PluginPackageVersion, devLoop bool) (string, error) {+ if !devLoop {+ return version, nil+ }+ taken := map[string]bool{}+ highest := 0+ for _, row := range existing {+ taken[row.Version] = true+ if suffix, ok := strings.CutPrefix(row.Version, version+"+dev."); ok {+ if number, err := strconv.Atoi(suffix); err == nil && number > highest {+ highest = number+ }+ }+ }+ if !taken[version] {+ return version, nil+ }+ candidate := version + "+dev." + strconv.Itoa(highest+1)+ if len(candidate) > plugincontract.MaxVersionLength {+ return "", pluginErrf(PluginErrorInvalid, "version %q leaves no room for a development suffix; shorten it below %d bytes", version, plugincontract.MaxVersionLength)+ }+ return candidate, nil+}++// lockPluginPackageKey takes the transaction-scoped lock that serializes+// publish, install and delete for one plugin. Every caller must already be in a+// transaction — the lock is released by its commit or rollback.+func lockPluginPackageKey(ctx context.Context, queries *db.Queries, workspaceID pgtype.UUID, pluginKey string) error {+ if err := queries.LockPluginPackageKey(ctx, uuidString(workspaceID)+":"+pluginKey); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "lock plugin package", Err: err}+ }+ return nil+}++// upsertPackage takes `queries` rather than reading s.Queries so it runs inside+// its caller's transaction: the display name must move only if the version that+// carries it is actually stored.+func upsertPackage(ctx context.Context, queries *db.Queries, workspaceID, userID pgtype.UUID, manifest plugincontract.Manifest) (db.PluginPackage, error) {+ existing, err := queries.GetWorkspacePluginPackageByKey(ctx, db.GetWorkspacePluginPackageByKeyParams{+ WorkspaceID: workspaceID,+ PluginKey: manifest.Key,+ })+ if err == nil {+ if existing.Name == manifest.Name {+ return existing, nil+ }+ // The display name follows the newest publish; the key does not move.+ updated, updateErr := queries.UpdatePluginPackageName(ctx, db.UpdatePluginPackageNameParams{+ ID: existing.ID,+ Name: manifest.Name,+ })+ if updateErr != nil {+ return db.PluginPackage{}, &PluginError{Kind: PluginErrorUnavailable, Message: "update plugin package", Err: updateErr}+ }+ return updated, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return db.PluginPackage{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin package", Err: err}+ }+ created, err := queries.CreatePluginPackage(ctx, db.CreatePluginPackageParams{+ WorkspaceID: workspaceID,+ PluginKey: manifest.Key,+ Name: manifest.Name,+ CreatedBy: userID,+ })+ if err != nil {+ if isUniqueViolation(err) {+ // Belt and braces behind the lock: a publish racing one in another+ // process that has not yet taken it still loses the index cleanly.+ return db.PluginPackage{}, pluginErrf(PluginErrorConflict, "this plugin was just published by someone else; try again")+ }+ return db.PluginPackage{}, &PluginError{Kind: PluginErrorUnavailable, Message: "create plugin package", Err: err}+ }+ return created, nil+}++// ListPackages returns everything published in this workspace with its versions.+func (s *PluginService) ListPackages(ctx context.Context, workspaceID pgtype.UUID) ([]PluginPackageSummary, error) {+ packages, err := s.Queries.ListWorkspacePluginPackages(ctx, workspaceID)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin packages", Err: err}+ }+ summaries := make([]PluginPackageSummary, 0, len(packages))+ for _, pkg := range packages {+ summary, err := s.packageSummary(ctx, workspaceID, pkg)+ if err != nil {+ return nil, err+ }+ summaries = append(summaries, summary)+ }+ return summaries, nil+}++func (s *PluginService) packageSummary(ctx context.Context, workspaceID pgtype.UUID, pkg db.PluginPackage) (PluginPackageSummary, error) {+ versions, err := s.Queries.ListPluginPackageVersions(ctx, pkg.ID)+ if err != nil {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "list published versions", Err: err}+ }+ // Which version this workspace runs, if any. Read from the installation+ // rather than "the newest one": the two disagreeing is the normal state+ // after a publish, and hiding that would defeat the point.+ installedVersionID := ""+ installation, err := s.Queries.GetWorkspacePluginInstallationByKey(ctx, db.GetWorkspacePluginInstallationByKeyParams{+ WorkspaceID: workspaceID,+ PluginKey: pkg.PluginKey,+ })+ if err == nil {+ installedVersionID = uuidString(installation.PackageVersionID)+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return PluginPackageSummary{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin installation", Err: err}+ }++ rendered := make([]PluginPackageVersionSummary, 0, len(versions))+ for _, version := range versions {+ id := uuidString(version.ID)+ rendered = append(rendered, PluginPackageVersionSummary{+ ID: id,+ Version: version.Version,+ Digest: version.Digest,+ SizeBytes: version.SizeBytes,+ PublishedAt: version.CreatedAt.Time.UTC().Format(pluginTimeFormat),+ Installed: id != "" && id == installedVersionID,+ })+ }+ return PluginPackageSummary{+ ID: uuidString(pkg.ID),+ PluginKey: pkg.PluginKey,+ Name: pkg.Name,+ Versions: rendered,+ CreatedAt: pkg.CreatedAt.Time.UTC().Format(pluginTimeFormat),+ }, nil+}++// DeletePackage removes a package with every version and file it published.+//+// Refused while any installation still runs one of those versions: deleting them+// would leave an installed panel with no code to load, and an installation is+// the administrator's decision to unwind, not the publisher's.+func (s *PluginService) DeletePackage(ctx context.Context, workspaceID pgtype.UUID, packageID string) error {+ parsed, err := util.ParseUUID(packageID)+ if err != nil {+ return pluginErrf(PluginErrorNotFound, "plugin package not found")+ }+ // Read once outside the transaction only to learn the plugin key the lock is+ // taken on. Everything the decision rests on is re-read inside it.+ pkg, err := s.Queries.GetWorkspacePluginPackage(ctx, db.GetWorkspacePluginPackageParams{+ WorkspaceID: workspaceID,+ ID: parsed,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return pluginErrf(PluginErrorNotFound, "plugin package not found")+ }+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin package", Err: err}+ }++ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "begin delete", Err: err}+ }+ defer func() { _ = tx.Rollback(ctx) }()+ queries := s.Queries.WithTx(tx)++ if err := lockPluginPackageKey(ctx, queries, workspaceID, pkg.PluginKey); err != nil {+ return err+ }+ // Counted INSIDE the lock, not before it. Counting outside would let an+ // install that started after the count commit after the delete, leaving an+ // installation whose version is gone.+ installed, err := queries.CountInstallationsOfPackageVersions(ctx, pkg.ID)+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "count installations", Err: err}+ }+ if installed > 0 {+ return pluginErrf(PluginErrorConflict, "this plugin is still installed; uninstall it before deleting the published package")+ }++ // Files first: they name a version that is about to stop existing, and there+ // are no cascades by repository policy.+ if err := queries.DeletePluginPackageFilesByPackage(ctx, pkg.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin package files", Err: err}+ }+ if err := queries.DeletePluginPackageVersionsByPackage(ctx, pkg.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin package versions", Err: err}+ }+ if err := queries.DeletePluginPackage(ctx, pkg.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin package", Err: err}+ }+ if err := tx.Commit(ctx); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "commit delete", Err: err}+ }+ return nil+}++// requireVersionStillPublished re-reads a version inside the caller's locked+// transaction.+//+// Install validates the version, its manifest and its scopes before opening a+// transaction — none of that can be done under a lock without holding it across+// work that does not need it. So the version is confirmed once more after the+// lock is held, which is the point at which a concurrent delete can no longer+// slip in between.+func requireVersionStillPublished(ctx context.Context, queries *db.Queries, workspaceID, versionID pgtype.UUID) error {+ _, err := queries.GetWorkspacePluginPackageVersion(ctx, db.GetWorkspacePluginPackageVersionParams{+ WorkspaceID: workspaceID,+ ID: versionID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return pluginErrf(PluginErrorConflict, "this version was deleted while the install was being confirmed; publish or pick another version")+ }+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "re-read published plugin version", Err: err}+ }+ return nil+}++// VersionForWorkspace loads a published version and confirms it belongs to the+// workspace in the URL. Publishing is workspace-private, so a version id from+// another workspace must not be installable here.+func (s *PluginService) VersionForWorkspace(ctx context.Context, workspaceID pgtype.UUID, versionID string) (db.PluginPackageVersion, error) {+ parsed, err := util.ParseUUID(strings.TrimSpace(versionID))+ if err != nil {+ return db.PluginPackageVersion{}, pluginErrf(PluginErrorNotFound, "published plugin version not found")+ }+ version, err := s.Queries.GetWorkspacePluginPackageVersion(ctx, db.GetWorkspacePluginPackageVersionParams{+ WorkspaceID: workspaceID,+ ID: parsed,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return db.PluginPackageVersion{}, pluginErrf(PluginErrorNotFound, "published plugin version not found")+ }+ if err != nil {+ return db.PluginPackageVersion{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load published plugin version", Err: err}+ }+ return version, nil+}++// PluginSurfaceScript is the code one surface runs, plus the digest of the+// version it came from.+type PluginSurfaceScript struct {+ Code string `json:"code"`+ Version string `json:"version"`+ Digest string `json:"digest"`+}++// SurfaceScript returns the script for one surface of an installation.+//+// Read from the installed version's stored files, never fetched: this is the+// method that makes "the administrator consented to this code" true rather than+// aspirational. The manifest consulted is the installation's own snapshot, so a+// surface the admin never approved cannot be named here even if a later version+// declares one.+func (s *PluginService) SurfaceScript(ctx context.Context, installation db.PluginInstallation, surfaceKey string) (PluginSurfaceScript, error) {+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ return PluginSurfaceScript{}, &PluginError{Kind: PluginErrorInvalid, Message: "stored plugin manifest is unreadable", Err: err}+ }+ entry := ""+ for _, surface := range manifest.Contributes.Surfaces {+ if surface.Key == surfaceKey {+ entry = surface.Entry+ break+ }+ }+ if entry == "" {+ return PluginSurfaceScript{}, pluginErrf(PluginErrorNotFound, "this Plugin does not contribute a surface named %q", surfaceKey)+ }+ file, err := s.Queries.GetPluginPackageFile(ctx, db.GetPluginPackageFileParams{+ VersionID: installation.PackageVersionID,+ Path: entry,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return PluginSurfaceScript{}, pluginErrf(PluginErrorNotFound, "the installed version does not contain %q", entry)+ }+ if err != nil {+ return PluginSurfaceScript{}, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin surface", Err: err}+ }+ return PluginSurfaceScript{+ Code: string(file.Content),+ Version: installation.Version,+ Digest: file.Sha256,+ }, nil+}++// packageFile reads one file of a published version, for install-time work such+// as skill resources.+func (s *PluginService) packageFile(ctx context.Context, queries *db.Queries, versionID pgtype.UUID, entry string) ([]byte, error) {+ file, err := queries.GetPluginPackageFile(ctx, db.GetPluginPackageFileParams{+ VersionID: versionID,+ Path: entry,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, pluginErrf(PluginErrorInvalid, "the published version does not contain %q", entry)+ }+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin package file", Err: err}+ }+ return file.Content, nil+}++// readLocalFile reads a file from inside a local plugin directory.+//+// `entry` is validated by the contract package to be relative and+// traversal-free, but this is the layer that touches the filesystem and it does+// not get to assume that: the joined path is re-checked against the plugin's own+// directory after cleaning.+func (s *PluginService) readLocalFile(name, entry string) ([]byte, error) {+ if s.LocalDir == "" {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")+ }+ if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")+ }+ root := filepath.Join(s.LocalDir, name)+ path := filepath.Clean(filepath.Join(root, entry))+ if path != root && !strings.HasPrefix(path, root+string(os.PathSeparator)) {+ return nil, pluginErrf(PluginErrorInvalid, "plugin resource %q escapes its directory", entry)+ }+ raw, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return nil, pluginErrf(PluginErrorNotFound, "plugin resource %q was not found", entry)+ }+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "read plugin resource", Err: err}+ }+ return raw, nil+}diff --git a/server/internal/service/plugin_skill.go b/server/internal/service/plugin_skill.goindex be5ab91e4e..949b04c03e 100644--- a/server/internal/service/plugin_skill.go+++ b/server/internal/service/plugin_skill.go@@ -2,7 +2,6 @@ package serviceimport ("context"- "net/url""strings""github.com/jackc/pgx/v5/pgtype"@@ -22,21 +21,16 @@ import (// which skill, so uninstall removes exactly those and nothing a person wrote.// That is one nullable column.//-// A resource is not a hook — nothing calls anything. The file is fetched once,-// at install, from the same origin as the manifest, and after that it is just a-// skill.--// maxSkillBytes bounds one fetched SKILL.md. Generous for prose, small enough-// that a source URL cannot use the install path to push a large body into the-// database.-const maxSkillBytes = 256 * 1024+// A resource is not a hook — nothing calls anything. The file was validated and+// stored when the author published the version, so installing it is a read from+// our own database rather than a fetch of whatever the author is serving today.// InstallSkillResources writes the manifest's skill resources and prunes the// ones this installation no longer declares.//// Called inside the install transaction: a plugin that half-installs its skills// is worse than one that fails, because the missing half is invisible.-func (s *PluginService) InstallSkillResources(ctx context.Context, queries *db.Queries, installation db.PluginInstallation, manifest plugincontract.Manifest, sourceURL string, userID pgtype.UUID) error {+func (s *PluginService) InstallSkillResources(ctx context.Context, queries *db.Queries, installation db.PluginInstallation, manifest plugincontract.Manifest, userID pgtype.UUID) error {resources := skillResources(manifest)// Prune first, so a rename frees its old name before the new one is@@ -57,15 +51,16 @@ func (s *PluginService) InstallSkillResources(ctx context.Context, queries *db.Q}for _, resource := range resources {- content, err := s.fetchSkillResource(ctx, sourceURL, resource.Entry)+ raw, err := s.packageFile(ctx, queries, installation.PackageVersionID, resource.Entry)if err != nil {return err}- name, description := skill.ParseSkillFrontmatter(content)+ content := string(raw)+ _, description := skill.ParseSkillFrontmatter(content)// The manifest key is authoritative for the name, not the frontmatter.// The consent screen listed the key, the tool namespace uses it, and a// file that disagrees must not silently install under another name.- name = resource.Key+ name := resource.Keyif strings.TrimSpace(description) == "" {description = "Provided by the " + manifest.Name + " Plugin."}@@ -97,43 +92,3 @@ func skillResources(manifest plugincontract.Manifest) []plugincontract.Resource}return resources}--// fetchSkillResource reads one SKILL.md from beside the manifest.-//-// Resolved relative to the source URL rather than taken as a URL of its own:-// the manifest already passed the origin checks, and letting a resource name an-// arbitrary address would hand the install path a second, unreviewed fetch-// target. `entry` is validated at parse time to be a relative path with no-// traversal, which is what makes this safe to join.-func (s *PluginService) fetchSkillResource(ctx context.Context, sourceURL, entry string) (string, error) {- if strings.HasPrefix(sourceURL, LocalSourcePrefix) {- raw, err := s.readLocalFile(strings.TrimPrefix(sourceURL, LocalSourcePrefix), entry)- if err != nil {- return "", err- }- return string(raw), nil- }-- base, err := url.Parse(sourceURL)- if err != nil {- return "", pluginErrf(PluginErrorInvalid, "source_url is not a valid URL")- }- resolved := base.JoinPath("..", entry).String()-- var raw []byte- if s.isDevOrigin(resolved) {- raw, err = fetchDevManifest(ctx, resolved)- } else {- raw, err = fetchRemoteManifest(ctx, resolved)- }- if err != nil {- return "", &PluginError{Kind: PluginErrorInvalid, Message: "fetch plugin skill " + entry, Err: err}- }- if len(raw) > maxSkillBytes {- return "", pluginErrf(PluginErrorInvalid, "plugin skill %s exceeds %d bytes", entry, maxSkillBytes)- }- if strings.TrimSpace(string(raw)) == "" {- return "", pluginErrf(PluginErrorInvalid, "plugin skill %s is empty", entry)- }- return string(raw), nil-}diff --git a/server/internal/service/plugin_sql_integration_test.go b/server/internal/service/plugin_sql_integration_test.goindex 8989090e83..fc36218a2c 100644--- a/server/internal/service/plugin_sql_integration_test.go+++ b/server/internal/service/plugin_sql_integration_test.go@@ -6,6 +6,7 @@ import ("errors""fmt""os"+ "strings""testing""time"@@ -66,13 +67,42 @@ func TestDeleteWorkspacePluginDataClearsEveryPluginTable(t *testing.T) {parsedWorkspaceID := mustParseUUID(t, workspaceID)manifest, _ := json.Marshal(map[string]any{"manifest_version": 1})+ pkg, err := queries.CreatePluginPackage(ctx, db.CreatePluginPackageParams{+ WorkspaceID: parsedWorkspaceID,+ PluginKey: fmt.Sprintf("com.example.teardown%d", suffix),+ Name: "Teardown",+ })+ if err != nil {+ t.Fatalf("create package: %v", err)+ }+ version, err := queries.CreatePluginPackageVersion(ctx, db.CreatePluginPackageVersionParams{+ PackageID: pkg.ID,+ WorkspaceID: parsedWorkspaceID,+ Version: "1.0.0",+ Manifest: manifest,+ Digest: strings.Repeat("a", 64),+ SizeBytes: 1,+ })+ if err != nil {+ t.Fatalf("create package version: %v", err)+ }+ if err := queries.CreatePluginPackageFile(ctx, db.CreatePluginPackageFileParams{+ VersionID: version.ID,+ Path: "ui/main.js",+ Content: []byte("// stub"),+ SizeBytes: 7,+ Sha256: strings.Repeat("b", 64),+ }); err != nil {+ t.Fatalf("create package file: %v", err)+ }+installation, err := queries.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{- WorkspaceID: parsedWorkspaceID,- PluginKey: fmt.Sprintf("com.example.teardown%d", suffix),- SourceUrl: "local:fixture",- Version: "1.0.0",- Manifest: manifest,- GrantedScopes: []byte(`["issues:read"]`),+ WorkspaceID: parsedWorkspaceID,+ PluginKey: fmt.Sprintf("com.example.teardown%d", suffix),+ PackageVersionID: version.ID,+ Version: "1.0.0",+ Manifest: manifest,+ GrantedScopes: []byte(`["issues:read"]`),})if err != nil {t.Fatalf("create installation: %v", err)@@ -116,4 +146,28 @@ func TestDeleteWorkspacePluginDataClearsEveryPluginTable(t *testing.T) {t.Fatalf("%s kept %d rows after workspace deletion", table, remaining)}}+ // Published artifacts are the largest thing a deleted workspace can strand:+ // they exist whether or not anything installed them, so the sweep has to+ // clear them by workspace rather than through the installation ids.+ for _, table := range []string{"plugin_package", "plugin_package_version"} {+ var remaining int+ if err := tx.QueryRow(ctx,+ fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE workspace_id = $1`, table),+ parsedWorkspaceID,+ ).Scan(&remaining); err != nil {+ t.Fatalf("count %s: %v", table, err)+ }+ if remaining != 0 {+ t.Fatalf("%s kept %d rows after workspace deletion", table, remaining)+ }+ }+ var remainingFiles int+ if err := tx.QueryRow(ctx,+ `SELECT COUNT(*) FROM plugin_package_file WHERE version_id = $1`, version.ID,+ ).Scan(&remainingFiles); err != nil {+ t.Fatalf("count plugin_package_file: %v", err)+ }+ if remainingFiles != 0 {+ t.Fatalf("plugin_package_file kept %d rows after workspace deletion", remainingFiles)+ }}diff --git a/server/internal/service/plugin_storage_db_test.go b/server/internal/service/plugin_storage_db_test.goindex 38e89f8ce2..55b8350c49 100644--- a/server/internal/service/plugin_storage_db_test.go+++ b/server/internal/service/plugin_storage_db_test.go@@ -61,10 +61,14 @@ func seedPluginInstallation(t *testing.T, pool *pgxpool.Pool) pgtype.UUID {t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID) })manifest, _ := json.Marshal(map[string]any{"manifest_version": 1})+ // An installation names the published version it runs. This suite is about+ // the KV quotas, so the version id is a bare identifier with no package row+ // behind it — relationships are application-owned by repository policy, and+ // nothing on this path resolves it.var installationID stringif err := pool.QueryRow(ctx,- `INSERT INTO plugin_installation (workspace_id, plugin_key, source_url, version, manifest)- VALUES ($1, $2, 'local:fixture', '1.0.0', $3) RETURNING id`,+ `INSERT INTO plugin_installation (workspace_id, plugin_key, package_version_id, version, manifest)+ VALUES ($1, $2, gen_random_uuid(), '1.0.0', $3) RETURNING id`,workspaceID, fmt.Sprintf("com.example.storage%d", suffix), manifest,).Scan(&installationID); err != nil {t.Fatalf("seed plugin installation: %v", err)diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.goindex ad518b561a..0691b8d123 100644--- a/server/internal/service/plugin_test.go+++ b/server/internal/service/plugin_test.go@@ -1,7 +1,6 @@package serviceimport (- "context""encoding/json""errors""os"@@ -175,7 +174,10 @@ func TestConfigFieldsForManifestKeepsDeclarationOrder(t *testing.T) {}}-func TestFetchManifestFromLocalDir(t *testing.T) {+// readLocalFile is the only path left that touches the filesystem on behalf of+// an API caller. The directory name arrives over HTTP, so it must not be able to+// escape MULTICA_PLUGIN_DIR or name a dotfile path.+func TestReadLocalFileStaysInsideThePluginDirectory(t *testing.T) {root := t.TempDir()if err := os.MkdirAll(filepath.Join(root, "hello"), 0o755); err != nil {t.Fatalf("create local plugin dir: %v", err)@@ -183,50 +185,82 @@ func TestFetchManifestFromLocalDir(t *testing.T) {if err := os.WriteFile(filepath.Join(root, "hello", plugincontract.ManifestFilename), []byte(testManifestJSON), 0o644); err != nil {t.Fatalf("write local manifest: %v", err)}+ // A file the caller must not be able to reach by naming a traversing entry.+ if err := os.WriteFile(filepath.Join(root, "secret.txt"), []byte("nope"), 0o644); err != nil {+ t.Fatalf("write sibling file: %v", err)+ }service := &PluginService{LocalDir: root}- manifest, canonical, err := service.FetchManifest(context.Background(), LocalSourcePrefix+"hello")+ raw, err := service.readLocalFile("hello", plugincontract.ManifestFilename)if err != nil {- t.Fatalf("FetchManifest: %v", err)+ t.Fatalf("readLocalFile: %v", err)}- if manifest.Key != "com.example.hello" || len(canonical) == 0 {- t.Fatalf("unexpected manifest: %+v", manifest)+ if len(raw) == 0 {+ t.Fatal("readLocalFile returned nothing")}- if _, _, err := service.FetchManifest(context.Background(), LocalSourcePrefix+"missing"); err == nil {- t.Fatal("FetchManifest accepted a missing local plugin")+ if _, err := service.readLocalFile("hello", "missing.js"); err == nil {+ t.Fatal("readLocalFile accepted a missing entry")} else if kind := pluginErrKind(t, err); kind != PluginErrorNotFound {- t.Fatalf("missing local plugin kind = %q, want %q", kind, PluginErrorNotFound)+ t.Fatalf("missing entry kind = %q, want %q", kind, PluginErrorNotFound)}- // A traversing name would let an API caller read any manifest-shaped file- // on the host, so it is rejected before it reaches the filesystem.for _, name := range []string{"../secrets", "nested/plugin", ".hidden", ""} {- if _, _, err := service.FetchManifest(context.Background(), LocalSourcePrefix+name); err == nil {- t.Fatalf("FetchManifest accepted local source %q", name)+ if _, err := service.readLocalFile(name, plugincontract.ManifestFilename); err == nil {+ t.Fatalf("readLocalFile accepted local source %q", name)}}+ if _, err := service.readLocalFile("hello", "../secret.txt"); err == nil {+ t.Fatal("readLocalFile followed a traversing entry out of the plugin directory")+ }disabled := &PluginService{}- if _, _, err := disabled.FetchManifest(context.Background(), LocalSourcePrefix+"hello"); err == nil {+ if _, err := disabled.readLocalFile("hello", plugincontract.ManifestFilename); err == nil {t.Fatal("local sources must require MULTICA_PLUGIN_DIR")}}-func TestFetchManifestRejectsNonPublicSources(t *testing.T) {- service := &PluginService{}- for _, source := range []string{- "",- "http://example.com/multica.plugin.json",- "https://localhost/multica.plugin.json",- "https://127.0.0.1/multica.plugin.json",- "https://169.254.169.254/latest/meta-data",- "file:///etc/passwd",- "https://user:[email protected]/multica.plugin.json",- } {- if _, _, err := service.FetchManifest(context.Background(), source); err == nil {- t.Fatalf("FetchManifest accepted source %q", source)- }+// A published version's manifest is read back from the row, never re-parsed+// from anything the author still controls.+func TestManifestForVersionReadsTheStoredSnapshot(t *testing.T) {+ _, canonical, err := plugincontract.ParseManifest([]byte(testManifestJSON))+ if err != nil {+ t.Fatalf("parse manifest: %v", err)+ }+ manifest, raw, err := ManifestForVersion(db.PluginPackageVersion{Manifest: canonical})+ if err != nil {+ t.Fatalf("ManifestForVersion: %v", err)+ }+ if manifest.Key != "com.example.hello" || len(raw) == 0 {+ t.Fatalf("unexpected manifest: %+v", manifest)+ }+ if _, _, err := ManifestForVersion(db.PluginPackageVersion{Manifest: []byte("not json")}); err == nil {+ t.Fatal("ManifestForVersion accepted a corrupt snapshot")+ }+}++// Publishing the same version twice is a conflict for an upload — that+// collision IS immutability — but a development publish takes a build suffix,+// because re-publishing an unchanged version is what editing a file looks like.+func TestResolvePublishVersion(t *testing.T) {+ existing := []db.PluginPackageVersion{+ {Version: "1.0.0"},+ {Version: "1.0.0+dev.1"},+ {Version: "1.0.0+dev.2"},+ }++ if got, err := resolvePublishVersion("1.0.0", existing, false); err != nil || got != "1.0.0" {+ t.Fatalf("upload version = %q, %v; want the manifest's own version so the unique index refuses it", got, err)+ }+ if got, err := resolvePublishVersion("1.0.0", existing, true); err != nil || got != "1.0.0+dev.3" {+ t.Fatalf("dev version = %q, %v; want 1.0.0+dev.3", got, err)+ }+ if got, err := resolvePublishVersion("2.0.0", existing, true); err != nil || got != "2.0.0" {+ t.Fatalf("unused dev version = %q, %v; want 2.0.0 with no suffix", got, err)+ }+ long := "1.0.0+" + strings.Repeat("a", plugincontract.MaxVersionLength-6)+ if _, err := resolvePublishVersion(long, []db.PluginPackageVersion{{Version: long}}, true); err == nil {+ t.Fatal("a version with no room for a dev suffix must be refused, not silently truncated")}}diff --git a/server/migrations/392_plugin_package_publishing.down.sql b/server/migrations/392_plugin_package_publishing.down.sqlnew file mode 100644index 0000000000..76fb79c727--- /dev/null+++ b/server/migrations/392_plugin_package_publishing.down.sql@@ -0,0 +1,17 @@+-- Rolling back returns installations to naming a source URL. Published versions+-- are dropped with the tables that hold them; there is nowhere else to put the+-- bytes, and an installation pointing at a version that no longer exists would+-- render a panel that cannot load.+DELETE FROM skill WHERE plugin_installation_id IS NOT NULL;+DELETE FROM plugin_invocation;+DELETE FROM plugin_secret;+DELETE FROM plugin_storage;+DELETE FROM plugin_installation;++ALTER TABLE plugin_installation DROP COLUMN IF EXISTS package_version_id;+ALTER TABLE plugin_installation+ ADD COLUMN source_url TEXT NOT NULL DEFAULT '' CHECK (char_length(source_url) BETWEEN 0 AND 2048);++DROP TABLE IF EXISTS plugin_package_file;+DROP TABLE IF EXISTS plugin_package_version;+DROP TABLE IF EXISTS plugin_package;diff --git a/server/migrations/392_plugin_package_publishing.up.sql b/server/migrations/392_plugin_package_publishing.up.sqlnew file mode 100644index 0000000000..009bf30282--- /dev/null+++ b/server/migrations/392_plugin_package_publishing.up.sql@@ -0,0 +1,83 @@+-- Platform-hosted plugin artifacts.+--+-- Until now a plugin was a URL: the manifest was fetched once and frozen as the+-- consented snapshot, but the surface script was loaded from the author's server+-- every time a panel opened. So the administrator consented to a manifest while+-- the browser ran whatever code that host served that day, the author's uptime+-- became our uptime, and every panel open told the author who was reading which+-- issue.+--+-- What replaces it: the author uploads an artifact bundle, Multica stores it,+-- and an installation is bound to one immutable version. Nothing about a+-- published version is ever updated in place — a new publish is a new row, and+-- an installed workspace keeps running the version it consented to until an+-- administrator upgrades it.+--+-- Hook endpoints and MCP servers stay on the author's own infrastructure. Only+-- the frontend artifact moved.++-- One publishable plugin identity per workspace. Publishing is workspace-private+-- for now; a public directory needs review, reporting and takedown, which is a+-- separate decision from where the bytes live.+CREATE TABLE plugin_package (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ plugin_key TEXT NOT NULL CHECK (char_length(plugin_key) BETWEEN 3 AND 255),+ name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 160),+ created_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- One published version. Immutable by construction: no statement in the+-- application updates this row, and republishing an existing version is a+-- conflict rather than an overwrite. That is the whole point — "what the admin+-- approved" and "what the browser runs" have to name the same bytes.+--+-- workspace_id is denormalized so every read can be scoped without joining+-- through plugin_package; relationships stay application-owned by repository+-- policy, so there is no foreign key to join through cheaply anyway.+CREATE TABLE plugin_package_version (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ package_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ version TEXT NOT NULL CHECK (char_length(version) BETWEEN 1 AND 64),+ manifest JSONB NOT NULL CHECK (jsonb_typeof(manifest) = 'object'),+ -- sha256 of the uploaded bundle, hex. Shown to the publisher so two people+ -- can confirm they are looking at the same artifact.+ digest TEXT NOT NULL CHECK (char_length(digest) = 64),+ size_bytes BIGINT NOT NULL CHECK (size_bytes >= 0),+ published_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- The files a version ships: the surface scripts, the skill text, the icon.+--+-- Stored in Postgres rather than object storage. A bundle is capped at a few+-- hundred kilobytes by the service, and this way an installed plugin cannot be+-- half-available: the manifest snapshot and the code it names commit together+-- and are restored together. Object storage would reintroduce, against our own+-- bucket, exactly the availability split this change exists to remove.+CREATE TABLE plugin_package_file (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ version_id UUID NOT NULL,+ path TEXT NOT NULL CHECK (char_length(path) BETWEEN 1 AND 1024),+ content BYTEA NOT NULL,+ size_bytes BIGINT NOT NULL CHECK (size_bytes >= 0),+ sha256 TEXT NOT NULL CHECK (char_length(sha256) = 64),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Every existing installation names a source URL, which is no longer a concept.+-- There is nothing to migrate them to: the code they would run was never+-- published here, so binding them to a version would be an invention. plugins_v1+-- has never left its feature flag and holds no production data, so they are+-- removed — the same call migration 344 made for the same reason.+DELETE FROM skill WHERE plugin_installation_id IS NOT NULL;+DELETE FROM plugin_invocation;+DELETE FROM plugin_secret;+DELETE FROM plugin_storage;+DELETE FROM plugin_installation;++ALTER TABLE plugin_installation DROP COLUMN IF EXISTS source_url;+ALTER TABLE plugin_installation ADD COLUMN package_version_id UUID NOT NULL;diff --git a/server/migrations/393_plugin_package_workspace_key_index.down.sql b/server/migrations/393_plugin_package_workspace_key_index.down.sqlnew file mode 100644index 0000000000..b428adadcd--- /dev/null+++ b/server/migrations/393_plugin_package_workspace_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_package_workspace_key;diff --git a/server/migrations/393_plugin_package_workspace_key_index.up.sql b/server/migrations/393_plugin_package_workspace_key_index.up.sqlnew file mode 100644index 0000000000..10cd7f7459--- /dev/null+++ b/server/migrations/393_plugin_package_workspace_key_index.up.sql@@ -0,0 +1,4 @@+-- One package per plugin key per workspace: publishing a new version of an+-- existing key must find the same package, not create a second one.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_package_workspace_key+ ON plugin_package (workspace_id, plugin_key);diff --git a/server/migrations/394_plugin_package_version_unique_index.down.sql b/server/migrations/394_plugin_package_version_unique_index.down.sqlnew file mode 100644index 0000000000..59e932d181--- /dev/null+++ b/server/migrations/394_plugin_package_version_unique_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_package_version_unique;diff --git a/server/migrations/394_plugin_package_version_unique_index.up.sql b/server/migrations/394_plugin_package_version_unique_index.up.sqlnew file mode 100644index 0000000000..70c80e7d3c--- /dev/null+++ b/server/migrations/394_plugin_package_version_unique_index.up.sql@@ -0,0 +1,4 @@+-- A version is published once. This index is what makes immutability a database+-- rule rather than a convention the service is trusted to keep.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_package_version_unique+ ON plugin_package_version (package_id, version);diff --git a/server/migrations/395_plugin_package_version_package_index.down.sql b/server/migrations/395_plugin_package_version_package_index.down.sqlnew file mode 100644index 0000000000..5c6e6ebab0--- /dev/null+++ b/server/migrations/395_plugin_package_version_package_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_package_version_package;diff --git a/server/migrations/395_plugin_package_version_package_index.up.sql b/server/migrations/395_plugin_package_version_package_index.up.sqlnew file mode 100644index 0000000000..1f6eff2605--- /dev/null+++ b/server/migrations/395_plugin_package_version_package_index.up.sql@@ -0,0 +1,3 @@+-- The version list a publisher reads: newest first, per package.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_package_version_package+ ON plugin_package_version (package_id, created_at DESC);diff --git a/server/migrations/396_plugin_package_file_path_index.down.sql b/server/migrations/396_plugin_package_file_path_index.down.sqlnew file mode 100644index 0000000000..6cfa6a3fab--- /dev/null+++ b/server/migrations/396_plugin_package_file_path_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_package_file_path;diff --git a/server/migrations/396_plugin_package_file_path_index.up.sql b/server/migrations/396_plugin_package_file_path_index.up.sqlnew file mode 100644index 0000000000..4496af149f--- /dev/null+++ b/server/migrations/396_plugin_package_file_path_index.up.sql@@ -0,0 +1,4 @@+-- Serving one file of a version is a point lookup by path, and a bundle must not+-- be able to ship the same path twice.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_package_file_path+ ON plugin_package_file (version_id, path);diff --git a/server/migrations/397_plugin_installation_package_version_index.down.sql b/server/migrations/397_plugin_installation_package_version_index.down.sqlnew file mode 100644index 0000000000..b18e4ce41b--- /dev/null+++ b/server/migrations/397_plugin_installation_package_version_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_installation_package_version;diff --git a/server/migrations/397_plugin_installation_package_version_index.up.sql b/server/migrations/397_plugin_installation_package_version_index.up.sqlnew file mode 100644index 0000000000..b44d63a66d--- /dev/null+++ b/server/migrations/397_plugin_installation_package_version_index.up.sql@@ -0,0 +1,4 @@+-- Deleting a published version has to know whether any workspace still runs it.+-- Without this index that check is a sequential scan on every publish page load.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_installation_package_version+ ON plugin_installation (package_version_id);diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex dd5c700622..6fa1d209ac 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -964,21 +964,21 @@ type PinnedItem struct {}type PluginInstallation struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- PluginKey string `json:"plugin_key"`- SourceUrl string `json:"source_url"`- Version string `json:"version"`- Manifest []byte `json:"manifest"`- GrantedScopes []byte `json:"granted_scopes"`- Config []byte `json:"config"`- Enabled bool `json:"enabled"`- InstalledBy pgtype.UUID `json:"installed_by"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- TokenHash pgtype.Text `json:"token_hash"`- TokenRotatedAt pgtype.Timestamptz `json:"token_rotated_at"`- McpApprovals []byte `json:"mcp_approvals"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ Config []byte `json:"config"`+ Enabled bool `json:"enabled"`+ InstalledBy pgtype.UUID `json:"installed_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ TokenHash pgtype.Text `json:"token_hash"`+ TokenRotatedAt pgtype.Timestamptz `json:"token_rotated_at"`+ McpApprovals []byte `json:"mcp_approvals"`+ PackageVersionID pgtype.UUID `json:"package_version_id"`}type PluginInvocation struct {@@ -995,6 +995,38 @@ type PluginInvocation struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type PluginPackage struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type PluginPackageFile struct {+ ID pgtype.UUID `json:"id"`+ VersionID pgtype.UUID `json:"version_id"`+ Path string `json:"path"`+ Content []byte `json:"content"`+ SizeBytes int64 `json:"size_bytes"`+ Sha256 string `json:"sha256"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type PluginPackageVersion struct {+ ID pgtype.UUID `json:"id"`+ PackageID pgtype.UUID `json:"package_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ Digest string `json:"digest"`+ SizeBytes int64 `json:"size_bytes"`+ PublishedBy pgtype.UUID `json:"published_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type PluginSecret struct {ID pgtype.UUID `json:"id"`InstallationID pgtype.UUID `json:"installation_id"`diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.goindex 87c74a9f58..e4ed4ad36d 100644--- a/server/pkg/db/generated/plugin.sql.go+++ b/server/pkg/db/generated/plugin.sql.go@@ -11,6 +11,22 @@ import ("github.com/jackc/pgx/v5/pgtype")+const countInstallationsOfPackageVersions = `-- name: CountInstallationsOfPackageVersions :one+SELECT count(*) FROM plugin_installation+WHERE package_version_id IN (+ SELECT id FROM plugin_package_version WHERE package_id = $1+)+`++// Whether any workspace still runs a version of this package. Publishing is+// workspace-private, so this is scoped to the same workspace by construction.+func (q *Queries) CountInstallationsOfPackageVersions(ctx context.Context, packageID pgtype.UUID) (int64, error) {+ row := q.db.QueryRow(ctx, countInstallationsOfPackageVersions, packageID)+ var count int64+ err := row.Scan(&count)+ return count, err+}+const countRecentPluginFailures = `-- name: CountRecentPluginFailures :oneSELECT count(*) FROM plugin_invocationWHERE installation_id = $1 AND hook_key = $2 AND created_at > $3 AND status <> 'ok'@@ -53,26 +69,26 @@ func (q *Queries) CountRecentPluginInvocations(ctx context.Context, arg CountRecconst createPluginInstallation = `-- name: CreatePluginInstallation :oneINSERT INTO plugin_installation (- workspace_id, plugin_key, source_url, version, manifest, granted_scopes, installed_by+ workspace_id, plugin_key, package_version_id, version, manifest, granted_scopes, installed_by) VALUES ($1, $2, $3, $4, $5, $6, $7)-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+RETURNING id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id`type CreatePluginInstallationParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- PluginKey string `json:"plugin_key"`- SourceUrl string `json:"source_url"`- Version string `json:"version"`- Manifest []byte `json:"manifest"`- GrantedScopes []byte `json:"granted_scopes"`- InstalledBy pgtype.UUID `json:"installed_by"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ PackageVersionID pgtype.UUID `json:"package_version_id"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ InstalledBy pgtype.UUID `json:"installed_by"`}func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePluginInstallationParams) (PluginInstallation, error) {row := q.db.QueryRow(ctx, createPluginInstallation,arg.WorkspaceID,arg.PluginKey,- arg.SourceUrl,+ arg.PackageVersionID,arg.Version,arg.Manifest,arg.GrantedScopes,@@ -83,7 +99,6 @@ func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePlugin&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -95,6 +110,7 @@ func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePlugin&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}@@ -147,6 +163,108 @@ func (q *Queries) CreatePluginInvocation(ctx context.Context, arg CreatePluginInreturn i, err}+const createPluginPackage = `-- name: CreatePluginPackage :one+INSERT INTO plugin_package (workspace_id, plugin_key, name, created_by)+VALUES ($1, $2, $3, $4)+RETURNING id, workspace_id, plugin_key, name, created_by, created_at, updated_at+`++type CreatePluginPackageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ CreatedBy pgtype.UUID `json:"created_by"`+}++func (q *Queries) CreatePluginPackage(ctx context.Context, arg CreatePluginPackageParams) (PluginPackage, error) {+ row := q.db.QueryRow(ctx, createPluginPackage,+ arg.WorkspaceID,+ arg.PluginKey,+ arg.Name,+ arg.CreatedBy,+ )+ var i PluginPackage+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.Name,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const createPluginPackageFile = `-- name: CreatePluginPackageFile :exec+INSERT INTO plugin_package_file (version_id, path, content, size_bytes, sha256)+VALUES ($1, $2, $3, $4, $5)+`++type CreatePluginPackageFileParams struct {+ VersionID pgtype.UUID `json:"version_id"`+ Path string `json:"path"`+ Content []byte `json:"content"`+ SizeBytes int64 `json:"size_bytes"`+ Sha256 string `json:"sha256"`+}++func (q *Queries) CreatePluginPackageFile(ctx context.Context, arg CreatePluginPackageFileParams) error {+ _, err := q.db.Exec(ctx, createPluginPackageFile,+ arg.VersionID,+ arg.Path,+ arg.Content,+ arg.SizeBytes,+ arg.Sha256,+ )+ return err+}++const createPluginPackageVersion = `-- name: CreatePluginPackageVersion :one+INSERT INTO plugin_package_version (+ package_id, workspace_id, version, manifest, digest, size_bytes, published_by+) VALUES ($1, $2, $3, $4, $5, $6, $7)+RETURNING id, package_id, workspace_id, version, manifest, digest, size_bytes, published_by, created_at+`++type CreatePluginPackageVersionParams struct {+ PackageID pgtype.UUID `json:"package_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ Digest string `json:"digest"`+ SizeBytes int64 `json:"size_bytes"`+ PublishedBy pgtype.UUID `json:"published_by"`+}++// Published versions are only ever inserted. Nothing updates one, and the+// (package_id, version) unique index is what makes a second publish of the same+// version a conflict instead of a silent overwrite.+func (q *Queries) CreatePluginPackageVersion(ctx context.Context, arg CreatePluginPackageVersionParams) (PluginPackageVersion, error) {+ row := q.db.QueryRow(ctx, createPluginPackageVersion,+ arg.PackageID,+ arg.WorkspaceID,+ arg.Version,+ arg.Manifest,+ arg.Digest,+ arg.SizeBytes,+ arg.PublishedBy,+ )+ var i PluginPackageVersion+ err := row.Scan(+ &i.ID,+ &i.PackageID,+ &i.WorkspaceID,+ &i.Version,+ &i.Manifest,+ &i.Digest,+ &i.SizeBytes,+ &i.PublishedBy,+ &i.CreatedAt,+ )+ return i, err+}+const deleteExpiredPluginInvocations = `-- name: DeleteExpiredPluginInvocations :execrowsDELETE FROM plugin_invocation WHERE created_at < $1`@@ -178,6 +296,34 @@ func (q *Queries) DeletePluginInvocationsByInstallation(ctx context.Context, insreturn err}+const deletePluginPackage = `-- name: DeletePluginPackage :exec+DELETE FROM plugin_package WHERE id = $1+`++func (q *Queries) DeletePluginPackage(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginPackage, id)+ return err+}++const deletePluginPackageFilesByPackage = `-- name: DeletePluginPackageFilesByPackage :exec+DELETE FROM plugin_package_file+WHERE version_id IN (SELECT id FROM plugin_package_version WHERE package_id = $1)+`++func (q *Queries) DeletePluginPackageFilesByPackage(ctx context.Context, packageID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginPackageFilesByPackage, packageID)+ return err+}++const deletePluginPackageVersionsByPackage = `-- name: DeletePluginPackageVersionsByPackage :exec+DELETE FROM plugin_package_version WHERE package_id = $1+`++func (q *Queries) DeletePluginPackageVersionsByPackage(ctx context.Context, packageID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginPackageVersionsByPackage, packageID)+ return err+}+const deletePluginSecret = `-- name: DeletePluginSecret :execrowsDELETE FROM plugin_secret WHERE installation_id = $1 AND key = $2`@@ -265,7 +411,7 @@ func (q *Queries) DeletePluginStorageValue(ctx context.Context, arg DeletePlugin}const getPluginInstallation = `-- name: GetPluginInstallation :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation WHERE id = $1+SELECT id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id FROM plugin_installation WHERE id = $1`func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (PluginInstallation, error) {@@ -275,7 +421,6 @@ func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (Pl&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -287,12 +432,13 @@ func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (Pl&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}const getPluginInstallationByTokenHash = `-- name: GetPluginInstallationByTokenHash :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation WHERE token_hash = $1+SELECT id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id FROM plugin_installation WHERE token_hash = $1`// Looked up by hash, so the plaintext token exists only in the caller's request.@@ -303,7 +449,6 @@ func (q *Queries) GetPluginInstallationByTokenHash(ctx context.Context, tokenHas&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -315,6 +460,32 @@ func (q *Queries) GetPluginInstallationByTokenHash(ctx context.Context, tokenHas&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,+ )+ return i, err+}++const getPluginPackageFile = `-- name: GetPluginPackageFile :one+SELECT id, version_id, path, content, size_bytes, sha256, created_at FROM plugin_package_file+WHERE version_id = $1 AND path = $2+`++type GetPluginPackageFileParams struct {+ VersionID pgtype.UUID `json:"version_id"`+ Path string `json:"path"`+}++func (q *Queries) GetPluginPackageFile(ctx context.Context, arg GetPluginPackageFileParams) (PluginPackageFile, error) {+ row := q.db.QueryRow(ctx, getPluginPackageFile, arg.VersionID, arg.Path)+ var i PluginPackageFile+ err := row.Scan(+ &i.ID,+ &i.VersionID,+ &i.Path,+ &i.Content,+ &i.SizeBytes,+ &i.Sha256,+ &i.CreatedAt,)return i, err}@@ -412,7 +583,7 @@ func (q *Queries) GetPluginStorageValue(ctx context.Context, arg GetPluginStorag}const getWorkspacePluginInstallation = `-- name: GetWorkspacePluginInstallation :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation+SELECT id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id FROM plugin_installationWHERE workspace_id = $1 AND id = $2`@@ -428,7 +599,6 @@ func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWor&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -440,12 +610,13 @@ func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWor&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}const getWorkspacePluginInstallationByKey = `-- name: GetWorkspacePluginInstallationByKey :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation+SELECT id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id FROM plugin_installationWHERE workspace_id = $1 AND plugin_key = $2`@@ -461,7 +632,6 @@ func (q *Queries) GetWorkspacePluginInstallationByKey(ctx context.Context, arg G&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -473,6 +643,84 @@ func (q *Queries) GetWorkspacePluginInstallationByKey(ctx context.Context, arg G&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,+ )+ return i, err+}++const getWorkspacePluginPackage = `-- name: GetWorkspacePluginPackage :one+SELECT id, workspace_id, plugin_key, name, created_by, created_at, updated_at FROM plugin_package+WHERE workspace_id = $1 AND id = $2+`++type GetWorkspacePluginPackageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) GetWorkspacePluginPackage(ctx context.Context, arg GetWorkspacePluginPackageParams) (PluginPackage, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginPackage, arg.WorkspaceID, arg.ID)+ var i PluginPackage+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.Name,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getWorkspacePluginPackageByKey = `-- name: GetWorkspacePluginPackageByKey :one+SELECT id, workspace_id, plugin_key, name, created_by, created_at, updated_at FROM plugin_package+WHERE workspace_id = $1 AND plugin_key = $2+`++type GetWorkspacePluginPackageByKeyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+}++func (q *Queries) GetWorkspacePluginPackageByKey(ctx context.Context, arg GetWorkspacePluginPackageByKeyParams) (PluginPackage, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginPackageByKey, arg.WorkspaceID, arg.PluginKey)+ var i PluginPackage+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.Name,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getWorkspacePluginPackageVersion = `-- name: GetWorkspacePluginPackageVersion :one+SELECT id, package_id, workspace_id, version, manifest, digest, size_bytes, published_by, created_at FROM plugin_package_version+WHERE workspace_id = $1 AND id = $2+`++type GetWorkspacePluginPackageVersionParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) GetWorkspacePluginPackageVersion(ctx context.Context, arg GetWorkspacePluginPackageVersionParams) (PluginPackageVersion, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginPackageVersion, arg.WorkspaceID, arg.ID)+ var i PluginPackageVersion+ err := row.Scan(+ &i.ID,+ &i.PackageID,+ &i.WorkspaceID,+ &i.Version,+ &i.Manifest,+ &i.Digest,+ &i.SizeBytes,+ &i.PublishedBy,+ &i.CreatedAt,)return i, err}@@ -521,6 +769,75 @@ func (q *Queries) ListPluginInvocations(ctx context.Context, arg ListPluginInvocreturn items, nil}+const listPluginPackageFilePaths = `-- name: ListPluginPackageFilePaths :many+SELECT path, size_bytes, sha256 FROM plugin_package_file+WHERE version_id = $1+ORDER BY path ASC+`++type ListPluginPackageFilePathsRow struct {+ Path string `json:"path"`+ SizeBytes int64 `json:"size_bytes"`+ Sha256 string `json:"sha256"`+}++// Paths and sizes only: the publisher's file list never needs the bytes.+func (q *Queries) ListPluginPackageFilePaths(ctx context.Context, versionID pgtype.UUID) ([]ListPluginPackageFilePathsRow, error) {+ rows, err := q.db.Query(ctx, listPluginPackageFilePaths, versionID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListPluginPackageFilePathsRow{}+ for rows.Next() {+ var i ListPluginPackageFilePathsRow+ if err := rows.Scan(&i.Path, &i.SizeBytes, &i.Sha256); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPluginPackageVersions = `-- name: ListPluginPackageVersions :many+SELECT id, package_id, workspace_id, version, manifest, digest, size_bytes, published_by, created_at FROM plugin_package_version+WHERE package_id = $1+ORDER BY created_at DESC+`++func (q *Queries) ListPluginPackageVersions(ctx context.Context, packageID pgtype.UUID) ([]PluginPackageVersion, error) {+ rows, err := q.db.Query(ctx, listPluginPackageVersions, packageID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []PluginPackageVersion{}+ for rows.Next() {+ var i PluginPackageVersion+ if err := rows.Scan(+ &i.ID,+ &i.PackageID,+ &i.WorkspaceID,+ &i.Version,+ &i.Manifest,+ &i.Digest,+ &i.SizeBytes,+ &i.PublishedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listPluginSecretKeys = `-- name: ListPluginSecretKeys :manySELECT key, updated_at FROM plugin_secretWHERE installation_id = $1@@ -629,7 +946,7 @@ func (q *Queries) ListPluginStorageKeys(ctx context.Context, arg ListPluginStora}const listWorkspacePluginInstallations = `-- name: ListWorkspacePluginInstallations :many-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation+SELECT id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id FROM plugin_installationWHERE workspace_id = $1ORDER BY created_at ASC`@@ -647,7 +964,6 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspac&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -659,6 +975,7 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspac&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,); err != nil {return nil, err}@@ -670,12 +987,66 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspacreturn items, nil}+const listWorkspacePluginPackages = `-- name: ListWorkspacePluginPackages :many+SELECT id, workspace_id, plugin_key, name, created_by, created_at, updated_at FROM plugin_package+WHERE workspace_id = $1+ORDER BY name ASC+`++func (q *Queries) ListWorkspacePluginPackages(ctx context.Context, workspaceID pgtype.UUID) ([]PluginPackage, error) {+ rows, err := q.db.Query(ctx, listWorkspacePluginPackages, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []PluginPackage{}+ for rows.Next() {+ var i PluginPackage+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.Name,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockPluginPackageKey = `-- name: LockPluginPackageKey :exec+SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))+`++// Serializes publish, install and delete for one (workspace, plugin key).+//+// Relationships are application-owned by repository policy, so there are no+// foreign keys to make "this version still exists" true across statements.+// Without this lock the interleaving `delete counts 0 installs` → `install+// reads the version` → `delete commits` → `install commits` leaves an+// installation pointing at a version that no longer exists, and its panel 404s+// forever with nothing in the product able to explain why.+//+// Keyed on the plugin key rather than the package id because publish has no+// package id yet — the row it would lock is the one it may be about to create.+func (q *Queries) LockPluginPackageKey(ctx context.Context, dollar_1 string) error {+ _, err := q.db.Exec(ctx, lockPluginPackageKey, dollar_1)+ return err+}+const setPluginInstallationEnabled = `-- name: SetPluginInstallationEnabled :oneUPDATE plugin_installationSET enabled = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+RETURNING id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id`type SetPluginInstallationEnabledParams struct {@@ -690,7 +1061,6 @@ func (q *Queries) SetPluginInstallationEnabled(ctx context.Context, arg SetPlugi&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -702,6 +1072,7 @@ func (q *Queries) SetPluginInstallationEnabled(ctx context.Context, arg SetPlugi&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}@@ -726,7 +1097,7 @@ const setPluginMCPApprovals = `-- name: SetPluginMCPApprovals :oneUPDATE plugin_installationSET mcp_approvals = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+RETURNING id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id`type SetPluginMCPApprovalsParams struct {@@ -741,7 +1112,6 @@ func (q *Queries) SetPluginMCPApprovals(ctx context.Context, arg SetPluginMCPApp&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -753,6 +1123,7 @@ func (q *Queries) SetPluginMCPApprovals(ctx context.Context, arg SetPluginMCPApp&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}@@ -762,7 +1133,7 @@ UPDATE plugin_installationSET config = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+RETURNING id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id`type UpdatePluginInstallationConfigParams struct {@@ -777,7 +1148,6 @@ func (q *Queries) UpdatePluginInstallationConfig(ctx context.Context, arg Update&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -789,38 +1159,40 @@ func (q *Queries) UpdatePluginInstallationConfig(ctx context.Context, arg Update&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,)return i, err}const updatePluginInstallationManifest = `-- name: UpdatePluginInstallationManifest :oneUPDATE plugin_installation-SET source_url = $2,+SET package_version_id = $2,version = $3,manifest = $4,granted_scopes = $5,config = $6,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+RETURNING id, workspace_id, plugin_key, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals, package_version_id`type UpdatePluginInstallationManifestParams struct {- ID pgtype.UUID `json:"id"`- SourceUrl string `json:"source_url"`- Version string `json:"version"`- Manifest []byte `json:"manifest"`- GrantedScopes []byte `json:"granted_scopes"`- Config []byte `json:"config"`+ ID pgtype.UUID `json:"id"`+ PackageVersionID pgtype.UUID `json:"package_version_id"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ Config []byte `json:"config"`}-// Upgrade path: the re-consented manifest snapshot replaces the old one in-// place. Config values survive on purpose; fields the new manifest dropped are-// pruned by the service before this runs.+// Upgrade path: the installation is re-pointed at another published version and+// takes that version's consented manifest snapshot. Config values survive on+// purpose; fields the new manifest dropped are pruned by the service before this+// runs.func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg UpdatePluginInstallationManifestParams) (PluginInstallation, error) {row := q.db.QueryRow(ctx, updatePluginInstallationManifest,arg.ID,- arg.SourceUrl,+ arg.PackageVersionID,arg.Version,arg.Manifest,arg.GrantedScopes,@@ -831,7 +1203,6 @@ func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg Upda&i.ID,&i.WorkspaceID,&i.PluginKey,- &i.SourceUrl,&i.Version,&i.Manifest,&i.GrantedScopes,@@ -843,6 +1214,37 @@ func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg Upda&i.TokenHash,&i.TokenRotatedAt,&i.McpApprovals,+ &i.PackageVersionID,+ )+ return i, err+}++const updatePluginPackageName = `-- name: UpdatePluginPackageName :one+UPDATE plugin_package+SET name = $2,+ updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, plugin_key, name, created_by, created_at, updated_at+`++type UpdatePluginPackageNameParams struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+}++// The display name follows the newest published version. The key never moves:+// it is the identity an installation was consented under.+func (q *Queries) UpdatePluginPackageName(ctx context.Context, arg UpdatePluginPackageNameParams) (PluginPackage, error) {+ row := q.db.QueryRow(ctx, updatePluginPackageName, arg.ID, arg.Name)+ var i PluginPackage+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.Name,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,)return i, err}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex f7a8fabda9..3d06b1bfd7 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -502,6 +502,23 @@ deleted_secrets AS (deleted_invocations AS (DELETE FROM plugin_invocationWHERE workspace_id = $1+),+versions AS MATERIALIZED (+ SELECT plugin_package_version.id+ FROM plugin_package_version+ WHERE plugin_package_version.workspace_id = $1+),+deleted_package_files AS (+ DELETE FROM plugin_package_file+ WHERE version_id IN (SELECT id FROM versions)+),+deleted_package_versions AS (+ DELETE FROM plugin_package_version+ WHERE workspace_id = $1+),+deleted_packages AS (+ DELETE FROM plugin_package+ WHERE workspace_id = $1)DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)`@@ -512,6 +529,9 @@ DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)// Hook call records are workspace-scoped in their own right, so this deletes by// workspace rather than through the installation ids: a row whose installation// was already uninstalled would otherwise survive the workspace it described.+// Published artifacts are workspace-scoped too, and independent of whether+// anything installed them. Deleting the workspace without these would leave the+// stored bundles as the largest orphan the plugin surface can produce.func (q *Queries) DeleteWorkspacePluginData(ctx context.Context, workspaceID pgtype.UUID) error {_, err := q.db.Exec(ctx, deleteWorkspacePluginData, workspaceID)return errdiff --git a/server/pkg/db/queries/plugin.sql b/server/pkg/db/queries/plugin.sqlindex ff3da4e001..e4653f6bc6 100644--- a/server/pkg/db/queries/plugin.sql+++ b/server/pkg/db/queries/plugin.sql@@ -1,15 +1,107 @@+-- name: LockPluginPackageKey :exec+-- Serializes publish, install and delete for one (workspace, plugin key).+--+-- Relationships are application-owned by repository policy, so there are no+-- foreign keys to make "this version still exists" true across statements.+-- Without this lock the interleaving `delete counts 0 installs` → `install+-- reads the version` → `delete commits` → `install commits` leaves an+-- installation pointing at a version that no longer exists, and its panel 404s+-- forever with nothing in the product able to explain why.+--+-- Keyed on the plugin key rather than the package id because publish has no+-- package id yet — the row it would lock is the one it may be about to create.+SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0));++-- name: CreatePluginPackage :one+INSERT INTO plugin_package (workspace_id, plugin_key, name, created_by)+VALUES ($1, $2, $3, $4)+RETURNING *;++-- name: UpdatePluginPackageName :one+-- The display name follows the newest published version. The key never moves:+-- it is the identity an installation was consented under.+UPDATE plugin_package+SET name = $2,+ updated_at = now()+WHERE id = $1+RETURNING *;++-- name: GetWorkspacePluginPackageByKey :one+SELECT * FROM plugin_package+WHERE workspace_id = $1 AND plugin_key = $2;++-- name: GetWorkspacePluginPackage :one+SELECT * FROM plugin_package+WHERE workspace_id = $1 AND id = $2;++-- name: ListWorkspacePluginPackages :many+SELECT * FROM plugin_package+WHERE workspace_id = $1+ORDER BY name ASC;++-- name: DeletePluginPackage :exec+DELETE FROM plugin_package WHERE id = $1;++-- name: CreatePluginPackageVersion :one+-- Published versions are only ever inserted. Nothing updates one, and the+-- (package_id, version) unique index is what makes a second publish of the same+-- version a conflict instead of a silent overwrite.+INSERT INTO plugin_package_version (+ package_id, workspace_id, version, manifest, digest, size_bytes, published_by+) VALUES ($1, $2, $3, $4, $5, $6, $7)+RETURNING *;++-- name: ListPluginPackageVersions :many+SELECT * FROM plugin_package_version+WHERE package_id = $1+ORDER BY created_at DESC;++-- name: GetWorkspacePluginPackageVersion :one+SELECT * FROM plugin_package_version+WHERE workspace_id = $1 AND id = $2;++-- name: DeletePluginPackageVersionsByPackage :exec+DELETE FROM plugin_package_version WHERE package_id = $1;++-- name: CountInstallationsOfPackageVersions :one+-- Whether any workspace still runs a version of this package. Publishing is+-- workspace-private, so this is scoped to the same workspace by construction.+SELECT count(*) FROM plugin_installation+WHERE package_version_id IN (+ SELECT id FROM plugin_package_version WHERE package_id = $1+);++-- name: CreatePluginPackageFile :exec+INSERT INTO plugin_package_file (version_id, path, content, size_bytes, sha256)+VALUES ($1, $2, $3, $4, $5);++-- name: GetPluginPackageFile :one+SELECT * FROM plugin_package_file+WHERE version_id = $1 AND path = $2;++-- name: ListPluginPackageFilePaths :many+-- Paths and sizes only: the publisher's file list never needs the bytes.+SELECT path, size_bytes, sha256 FROM plugin_package_file+WHERE version_id = $1+ORDER BY path ASC;++-- name: DeletePluginPackageFilesByPackage :exec+DELETE FROM plugin_package_file+WHERE version_id IN (SELECT id FROM plugin_package_version WHERE package_id = $1);+-- name: CreatePluginInstallation :oneINSERT INTO plugin_installation (- workspace_id, plugin_key, source_url, version, manifest, granted_scopes, installed_by+ workspace_id, plugin_key, package_version_id, version, manifest, granted_scopes, installed_by) VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING *;-- name: UpdatePluginInstallationManifest :one--- Upgrade path: the re-consented manifest snapshot replaces the old one in--- place. Config values survive on purpose; fields the new manifest dropped are--- pruned by the service before this runs.+-- Upgrade path: the installation is re-pointed at another published version and+-- takes that version's consented manifest snapshot. Config values survive on+-- purpose; fields the new manifest dropped are pruned by the service before this+-- runs.UPDATE plugin_installation-SET source_url = $2,+SET package_version_id = $2,version = $3,manifest = $4,granted_scopes = $5,diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 5bf5a592f0..be3aa931a5 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -604,6 +604,26 @@ deleted_secrets AS (deleted_invocations AS (DELETE FROM plugin_invocationWHERE workspace_id = $1+),+-- Published artifacts are workspace-scoped too, and independent of whether+-- anything installed them. Deleting the workspace without these would leave the+-- stored bundles as the largest orphan the plugin surface can produce.+versions AS MATERIALIZED (+ SELECT plugin_package_version.id+ FROM plugin_package_version+ WHERE plugin_package_version.workspace_id = $1+),+deleted_package_files AS (+ DELETE FROM plugin_package_file+ WHERE version_id IN (SELECT id FROM versions)+),+deleted_package_versions AS (+ DELETE FROM plugin_package_version+ WHERE workspace_id = $1+),+deleted_packages AS (+ DELETE FROM plugin_package+ WHERE workspace_id = $1)DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations);diff --git a/server/pkg/plugincontract/bundle.go b/server/pkg/plugincontract/bundle.gonew file mode 100644index 0000000000..d6fd4bbb53--- /dev/null+++ b/server/pkg/plugincontract/bundle.go@@ -0,0 +1,409 @@+package plugincontract++import (+ "archive/zip"+ "bytes"+ "fmt"+ "io"+ "io/fs"+ "path"+ "sort"+ "strings"+ "unicode/utf8"++ "github.com/tdewolff/parse/v2"+ "github.com/tdewolff/parse/v2/js"+)++// A bundle is what an author publishes: the manifest plus every file the+// manifest names. It is the unit the administrator consents to, so it is parsed+// and validated once, at publish time, and never re-derived from anything the+// author still controls.+//+// Publish-time validation is the point. Under URL hosting, a surface whose entry+// did not exist failed silently in the reader's browser months later; here the+// publish is refused with the missing path named.++const (+ // MaxBundleSize bounds the uploaded archive itself.+ MaxBundleSize = 2 << 20++ // MaxBundleFileSize bounds one file inside it. A surface entry is a single+ // script with its assets inlined, which is what this has to fit.+ MaxBundleFileSize = 1 << 20++ // MaxBundleTotalSize bounds the sum of the files a version keeps. Checked+ // against decompressed sizes as they are read, so an archive that expands+ // far beyond its compressed size is refused rather than buffered.+ MaxBundleTotalSize = 4 << 20++ // MaxBundleEntries bounds how many entries the archive may contain at all,+ // including ones the manifest never names.+ MaxBundleEntries = 512++ // MaxSkillBytes bounds one SKILL.md. Generous for prose, small enough that+ // publishing cannot be used to push a large body into the database.+ MaxSkillBytes = 256 * 1024+)++// BundleFile is one stored file of a published version. Paths are the manifest's+// own relative entries, so nothing has to be re-resolved at serve time.+type BundleFile struct {+ Path string+ Content []byte+}++// Bundle is a parsed, validated artifact package.+type Bundle struct {+ Manifest Manifest+ // Canonical is the re-encoded manifest an installation stores as its+ // consented snapshot, identical to what ParseManifest returns.+ Canonical []byte+ // Files holds only the entries the manifest references, sorted by path.+ // Anything else in the archive is dropped: nothing can ever serve it, so+ // keeping it would be storage with no read path.+ Files []BundleFile+}++// File returns one file of the bundle by its manifest-relative path.+func (b Bundle) File(entry string) ([]byte, bool) {+ for _, file := range b.Files {+ if file.Path == entry {+ return file.Content, true+ }+ }+ return nil, false+}++// TotalSize is the stored footprint of the bundle's files.+func (b Bundle) TotalSize() int {+ total := 0+ for _, file := range b.Files {+ total += len(file.Content)+ }+ return total+}++// ParseBundle reads a zip archive into a validated bundle.+func ParseBundle(archive []byte) (Bundle, error) {+ if len(archive) == 0 {+ return Bundle{}, fmt.Errorf("plugin package is empty")+ }+ if len(archive) > MaxBundleSize {+ return Bundle{}, fmt.Errorf("plugin package exceeds %d bytes", MaxBundleSize)+ }+ reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))+ if err != nil {+ return Bundle{}, fmt.Errorf("plugin package must be a zip archive: %w", err)+ }+ if len(reader.File) > MaxBundleEntries {+ return Bundle{}, fmt.Errorf("plugin package contains more than %d entries", MaxBundleEntries)+ }++ entries, err := zipEntryPaths(reader)+ if err != nil {+ return Bundle{}, err+ }+ prefix, err := manifestPrefix(entries)+ if err != nil {+ return Bundle{}, err+ }++ // Files are read lazily, so an archive full of large unreferenced entries+ // costs nothing: only what the manifest names is decompressed, and the+ // running total is checked as each one lands.+ total := 0+ open := func(entry string) ([]byte, bool, error) {+ file, ok := findZipFile(reader, prefix+entry)+ if !ok {+ return nil, false, nil+ }+ content, readErr := readZipFile(file)+ if readErr != nil {+ return nil, false, readErr+ }+ total += len(content)+ if total > MaxBundleTotalSize {+ return nil, false, fmt.Errorf("plugin package files exceed %d bytes", MaxBundleTotalSize)+ }+ return content, true, nil+ }+ return buildBundle(open, prefix)+}++// ParseBundleFromDir builds the same validated bundle from a filesystem+// directory, for the local development channel. `read` is the caller's+// containment-checked reader — this package never touches the filesystem.+func ParseBundleFromDir(read func(entry string) ([]byte, bool, error)) (Bundle, error) {+ total := 0+ open := func(entry string) ([]byte, bool, error) {+ content, ok, err := read(entry)+ if err != nil || !ok {+ return nil, ok, err+ }+ if len(content) > MaxBundleFileSize {+ return nil, false, fmt.Errorf("plugin file %q exceeds %d bytes", entry, MaxBundleFileSize)+ }+ total += len(content)+ if total > MaxBundleTotalSize {+ return nil, false, fmt.Errorf("plugin package files exceed %d bytes", MaxBundleTotalSize)+ }+ return content, true, nil+ }+ return buildBundle(open, "")+}++// buildBundle is the shared half: parse the manifest, then collect exactly the+// files it references. Both publish paths run this, so an uploaded package and a+// local directory can never be validated to different standards.+func buildBundle(open func(entry string) ([]byte, bool, error), prefix string) (Bundle, error) {+ rawManifest, ok, err := open(ManifestFilename)+ if err != nil {+ return Bundle{}, err+ }+ if !ok {+ if prefix != "" {+ return Bundle{}, fmt.Errorf("plugin package must contain %s", prefix+ManifestFilename)+ }+ return Bundle{}, fmt.Errorf("plugin package must contain %s", ManifestFilename)+ }+ manifest, canonical, err := ParseManifest(rawManifest)+ if err != nil {+ return Bundle{}, err+ }++ files := make([]BundleFile, 0, len(manifest.Contributes.Surfaces)+len(manifest.Contributes.Resources)+1)+ seen := map[string]bool{}+ collect := func(entry string) ([]byte, error) {+ if seen[entry] {+ // Two contributions may legitimately name the same file; storing it+ // twice would trip the (version_id, path) unique index.+ content, _ := findFile(files, entry)+ return content, nil+ }+ content, ok, err := open(entry)+ if err != nil {+ return nil, err+ }+ if !ok {+ return nil, fmt.Errorf("plugin package is missing %q, which the manifest declares", entry)+ }+ if len(content) > MaxBundleFileSize {+ return nil, fmt.Errorf("plugin file %q exceeds %d bytes", entry, MaxBundleFileSize)+ }+ seen[entry] = true+ files = append(files, BundleFile{Path: entry, Content: content})+ return content, nil+ }++ for _, surface := range manifest.Contributes.Surfaces {+ content, err := collect(surface.Entry)+ if err != nil {+ return Bundle{}, err+ }+ if err := validateSurfaceScript(surface.Entry, content); err != nil {+ return Bundle{}, err+ }+ }+ for _, resource := range manifest.Contributes.Resources {+ content, err := collect(resource.Entry)+ if err != nil {+ return Bundle{}, err+ }+ if err := validateSkillFile(resource.Entry, content); err != nil {+ return Bundle{}, err+ }+ }+ if manifest.Icon != "" {+ content, err := collect(manifest.Icon)+ if err != nil {+ return Bundle{}, err+ }+ if len(content) == 0 {+ return Bundle{}, fmt.Errorf("plugin icon %q is empty", manifest.Icon)+ }+ }++ sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })+ return Bundle{Manifest: manifest, Canonical: canonical, Files: files}, nil+}++func findFile(files []BundleFile, entry string) ([]byte, bool) {+ for _, file := range files {+ if file.Path == entry {+ return file.Content, true+ }+ }+ return nil, false+}++// validateSurfaceScript refuses what would only fail later in a reader's+// browser. The host inlines this text into the surface document, so it has to be+// text, and a static `import` cannot resolve there — a surface is one file with+// no module graph, which is the contract the SDK is shipped for.+func validateSurfaceScript(entry string, content []byte) error {+ if len(bytes.TrimSpace(content)) == 0 {+ return fmt.Errorf("surface entry %q is empty", entry)+ }+ if !utf8.Valid(content) {+ return fmt.Errorf("surface entry %q must be UTF-8 text", entry)+ }+ moduleSyntax, err := parseSurfaceScript(content)+ if err != nil {+ return fmt.Errorf("surface entry %q is not valid JavaScript: %w", entry, err)+ }+ if moduleSyntax {+ return fmt.Errorf("surface entry %q has top-level import/export/await or import.meta; a surface is a single classic script with no module graph, so bundle its dependencies in", entry)+ }+ return nil+}++// parseSurfaceScript uses a JavaScript parser rather than recognizing source+// text by hand. Publishing is the boundary: a false positive blocks an author+// with no workaround, while missed module-only syntax becomes a broken+// classic-script frame. Lexical details such as regex literals, template+// expressions, comments between `import` and `(`, and two statements on one+// line therefore have to follow JavaScript grammar, not a local approximation+// of it.+func parseSurfaceScript(source []byte) (bool, error) {+ ast, err := js.Parse(parse.NewInputBytes(source), js.Options{})+ if err != nil {+ return false, err+ }+ visitor := &surfaceModuleSyntaxVisitor{}+ js.Walk(visitor, ast)+ return visitor.moduleOnly, nil+}++// tdewolff parses a module grammar at the root, where top-level await and+// import.meta are valid. Surface entries execute as classic scripts, so walk+// the parsed tree and reject those constructs explicitly. Await remains valid+// inside a nested async function; import.meta is module-only at every depth.+type surfaceModuleSyntaxVisitor struct {+ functionDepth int+ moduleOnly bool+}++func (v *surfaceModuleSyntaxVisitor) Enter(node js.INode) js.IVisitor {+ switch node := node.(type) {+ case *js.ImportStmt, *js.ExportStmt, *js.ImportMetaExpr:+ v.moduleOnly = true+ case *js.UnaryExpr:+ if node.Op == js.AwaitToken && v.functionDepth == 0 {+ v.moduleOnly = true+ }+ case *js.FuncDecl, *js.ArrowFunc:+ v.functionDepth+++ }+ return v+}++func (v *surfaceModuleSyntaxVisitor) Exit(node js.INode) {+ switch node.(type) {+ case *js.FuncDecl, *js.ArrowFunc:+ v.functionDepth--+ }+}++func validateSkillFile(entry string, content []byte) error {+ if len(bytes.TrimSpace(content)) == 0 {+ return fmt.Errorf("skill resource %q is empty", entry)+ }+ if !utf8.Valid(content) {+ return fmt.Errorf("skill resource %q must be UTF-8 text", entry)+ }+ if len(content) > MaxSkillBytes {+ return fmt.Errorf("skill resource %q exceeds %d bytes", entry, MaxSkillBytes)+ }+ return nil+}++// zipEntryPaths returns the archive's file paths, refusing anything that could+// escape a directory once written or read by path. The bundle is never unpacked+// to disk, but the paths are matched against manifest entries, and a path that+// normalizes differently than it reads is a way to ship one file and have+// another consented to.+func zipEntryPaths(reader *zip.Reader) ([]string, error) {+ paths := make([]string, 0, len(reader.File))+ for _, file := range reader.File {+ name := file.Name+ if strings.HasSuffix(name, "/") {+ continue // directory entry+ }+ if file.Mode()&fs.ModeSymlink != 0 {+ // Symlinks in a zip carry their target as content. Nothing here+ // follows one, but storing it would publish a file whose meaning+ // depends on a filesystem that does not exist on our side.+ return nil, fmt.Errorf("plugin package must not contain symlinks (%q)", name)+ }+ if strings.ContainsRune(name, '\\') {+ return nil, fmt.Errorf("plugin package entry %q must use forward slashes", name)+ }+ if path.IsAbs(name) || name != path.Clean(name) || strings.HasPrefix(name, "../") {+ return nil, fmt.Errorf("plugin package entry %q must be a plain relative path", name)+ }+ paths = append(paths, name)+ }+ return paths, nil+}++// manifestPrefix finds the directory the manifest sits in.+//+// Zipping a folder is what a person does, and it produces+// `my-plugin/multica.plugin.json`. Accepting exactly one leading directory turns+// the most common publish failure into a non-event; two different roots stay an+// error, because then there is no single answer to what the package is.+func manifestPrefix(paths []string) (string, error) {+ candidates := map[string]bool{}+ for _, name := range paths {+ if name == ManifestFilename {+ return "", nil+ }+ if dir, file := path.Split(name); file == ManifestFilename {+ candidates[dir] = true+ }+ }+ switch len(candidates) {+ case 0:+ return "", fmt.Errorf("plugin package must contain %s", ManifestFilename)+ case 1:+ for dir := range candidates {+ if strings.Count(strings.TrimSuffix(dir, "/"), "/") > 0 {+ return "", fmt.Errorf("%s must be at the root of the package, or one directory below it", ManifestFilename)+ }+ return dir, nil+ }+ }+ return "", fmt.Errorf("plugin package contains more than one %s", ManifestFilename)+}++func findZipFile(reader *zip.Reader, name string) (*zip.File, bool) {+ for _, file := range reader.File {+ if file.Name == name {+ return file, true+ }+ }+ return nil, false+}++func readZipFile(file *zip.File) ([]byte, error) {+ // The archive declares an uncompressed size; it is a claim by whoever built+ // it, so it is used only to refuse early. The read below is bounded on its+ // own and does not trust it.+ if file.UncompressedSize64 > MaxBundleFileSize {+ return nil, fmt.Errorf("plugin file %q exceeds %d bytes", file.Name, MaxBundleFileSize)+ }+ handle, err := file.Open()+ if err != nil {+ return nil, fmt.Errorf("read plugin file %q: %w", file.Name, err)+ }+ defer handle.Close()+ content, err := io.ReadAll(io.LimitReader(handle, MaxBundleFileSize+1))+ if err != nil {+ return nil, fmt.Errorf("read plugin file %q: %w", file.Name, err)+ }+ if len(content) > MaxBundleFileSize {+ return nil, fmt.Errorf("plugin file %q exceeds %d bytes", file.Name, MaxBundleFileSize)+ }+ return content, nil+}diff --git a/server/pkg/plugincontract/bundle_test.go b/server/pkg/plugincontract/bundle_test.gonew file mode 100644index 0000000000..bd44b69af1--- /dev/null+++ b/server/pkg/plugincontract/bundle_test.go@@ -0,0 +1,295 @@+package plugincontract_test++import (+ "archive/zip"+ "bytes"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++const bundleManifest = `{+ "manifest_version": 1,+ "key": "com.example.hello",+ "name": "Hello Panel",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read"],+ "contributes": {+ "surfaces": [{ "key": "hello", "type": "issue_panel", "name": "Hello", "entry": "ui/main.js" }],+ "resources": [{ "type": "skill", "key": "pr-review", "entry": "skills/pr-review/SKILL.md" }]+ }+}`++func zipBundle(t *testing.T, files map[string]string) []byte {+ t.Helper()+ var buffer bytes.Buffer+ writer := zip.NewWriter(&buffer)+ for name, content := range files {+ entry, err := writer.Create(name)+ if err != nil {+ t.Fatalf("create zip entry %s: %v", name, err)+ }+ if _, err := entry.Write([]byte(content)); err != nil {+ t.Fatalf("write zip entry %s: %v", name, err)+ }+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close zip: %v", err)+ }+ return buffer.Bytes()+}++func TestParseBundleKeepsOnlyDeclaredFiles(t *testing.T) {+ archive := zipBundle(t, map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": "console.log('hi');\n",+ "skills/pr-review/SKILL.md": "---\nname: pr-review\n---\n\nRead the diff.\n",+ // Never referenced by the manifest, so nothing could ever serve it.+ "README.md": "# hello\n",+ })++ bundle, err := plugincontract.ParseBundle(archive)+ if err != nil {+ t.Fatalf("ParseBundle: %v", err)+ }+ if bundle.Manifest.Key != "com.example.hello" || len(bundle.Canonical) == 0 {+ t.Fatalf("unexpected manifest: %+v", bundle.Manifest)+ }+ if len(bundle.Files) != 2 {+ t.Fatalf("files = %d, want the two the manifest declares: %+v", len(bundle.Files), bundle.Files)+ }+ if _, ok := bundle.File("README.md"); ok {+ t.Fatal("an undeclared file was stored; nothing can ever serve it")+ }+ if content, ok := bundle.File("ui/main.js"); !ok || !strings.Contains(string(content), "console.log") {+ t.Fatalf("surface entry was not stored: %q", content)+ }+}++// Zipping a folder is what a person does, and it produces+// `my-plugin/multica.plugin.json`. One leading directory is accepted; the+// manifest's own entries stay relative to it.+func TestParseBundleAcceptsOneWrappingDirectory(t *testing.T) {+ archive := zipBundle(t, map[string]string{+ "hello-panel/" + plugincontract.ManifestFilename: bundleManifest,+ "hello-panel/ui/main.js": "console.log('hi');\n",+ "hello-panel/skills/pr-review/SKILL.md": "Read the diff.\n",+ })++ bundle, err := plugincontract.ParseBundle(archive)+ if err != nil {+ t.Fatalf("ParseBundle: %v", err)+ }+ if _, ok := bundle.File("ui/main.js"); !ok {+ t.Fatalf("entries must stay relative to the manifest: %+v", bundle.Files)+ }+}++func TestParseBundleRejections(t *testing.T) {+ cases := []struct {+ name string+ files map[string]string+ want string+ }{+ {+ name: "no manifest",+ files: map[string]string{"ui/main.js": "console.log('hi');"},+ want: plugincontract.ManifestFilename,+ },+ {+ name: "declared surface entry is missing",+ files: map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ },+ want: "ui/main.js",+ },+ {+ name: "declared skill is missing",+ files: map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": "console.log('hi');",+ },+ want: "skills/pr-review/SKILL.md",+ },+ {+ name: "surface entry is empty",+ files: map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": " \n",+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ },+ want: "empty",+ },+ {+ // The failure the repository's own deploy-sentinel example shipped+ // with: an entry that cannot load, caught at publish instead of in a+ // reader's browser.+ name: "surface entry has a top-level import",+ files: map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": "import { multica } from \"https://esm.sh/@multica/plugin-sdk@1\";\n",+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ },+ want: "top-level import",+ },+ {+ name: "surface entry is not valid JavaScript",+ files: map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": "const = 1;\n",+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ },+ want: "not valid JavaScript",+ },+ {+ name: "two manifests",+ files: map[string]string{+ "a/" + plugincontract.ManifestFilename: bundleManifest,+ "b/" + plugincontract.ManifestFilename: bundleManifest,+ },+ want: "more than one",+ },+ {+ name: "manifest is buried too deep",+ files: map[string]string{+ "a/b/" + plugincontract.ManifestFilename: bundleManifest,+ },+ want: "root of the package",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ _, err := plugincontract.ParseBundle(zipBundle(t, tc.files))+ if err == nil {+ t.Fatal("ParseBundle accepted an invalid package")+ }+ if !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("error %q does not name %q; a publish failure the author cannot act on is a bug", err, tc.want)+ }+ })+ }+}++func TestParseBundleRejectsTraversingEntries(t *testing.T) {+ for _, name := range []string{"../escape.js", "/absolute.js", "ui/../../escape.js"} {+ archive := zipBundle(t, map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ name: "console.log('hi');",+ })+ if _, err := plugincontract.ParseBundle(archive); err == nil {+ t.Fatalf("ParseBundle accepted entry %q", name)+ }+ }+}++func TestParseBundleRejectsOversizedInput(t *testing.T) {+ if _, err := plugincontract.ParseBundle(nil); err == nil {+ t.Fatal("ParseBundle accepted an empty package")+ }+ if _, err := plugincontract.ParseBundle(bytes.Repeat([]byte{0}, plugincontract.MaxBundleSize+1)); err == nil {+ t.Fatal("ParseBundle accepted a package over the size limit")+ }+ // Compresses to almost nothing, so the archive is small while the file it+ // carries is not. The limit has to be enforced on what is read out.+ archive := zipBundle(t, map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": strings.Repeat("a", plugincontract.MaxBundleFileSize+1),+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ })+ if _, err := plugincontract.ParseBundle(archive); err == nil {+ t.Fatal("ParseBundle accepted a file that expands past the per-file limit")+ }+}++// The local development channel and an upload must be validated to the same+// standard, or "is this code frozen?" would depend on how it was published.+func TestParseBundleFromDirMatchesTheUploadPath(t *testing.T) {+ files := map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": "console.log('hi');\n",+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ }+ read := func(entry string) ([]byte, bool, error) {+ content, ok := files[entry]+ return []byte(content), ok, nil+ }+ bundle, err := plugincontract.ParseBundleFromDir(read)+ if err != nil {+ t.Fatalf("ParseBundleFromDir: %v", err)+ }+ if len(bundle.Files) != 2 {+ t.Fatalf("files = %+v", bundle.Files)+ }++ delete(files, "ui/main.js")+ if _, err := plugincontract.ParseBundleFromDir(read); err == nil {+ t.Fatal("a missing surface entry must fail the local publish too")+ }+}++// The publish-time module check refuses a publish, so it is asymmetric: missing+// an import costs the author a readable runtime error, while a false positive+// blocks a legitimate publish outright. This pins both directions.+func TestSurfaceEntryModuleDetection(t *testing.T) {+ refused := map[string]string{+ "bare import": "import { multica } from \"./sdk.js\";\n",+ "indented import": " import { multica } from \"./sdk.js\";\n",+ "import after a line comment": "// set up\nimport { multica } from \"./sdk.js\";\n",+ "import after a block comment": "/* set up */ import { multica } from \"./sdk.js\";\n",+ "namespace import": "import * as sdk from \"./sdk.js\";\n",+ "named export": "export { render };\n",+ "import after another statement": "const x = 1; import y from \"./y.js\";\n",+ "export after another statement": "const x = 1; export { x };\n",+ "import inside a function": "function boot() {\n import { x } from \"./x.js\";\n}\n",+ "top-level await": "await 1;\n",+ "import meta": "console.log(import.meta.url);\n",+ }+ for name, source := range refused {+ t.Run(name, func(t *testing.T) {+ if _, err := parseDirBundle(t, source); err == nil {+ t.Fatal("a module-only entry was published; it cannot load as a classic script")+ }+ })+ }++ accepted := map[string]string{+ // The case the line-prefix version got wrong: a surface that renders a+ // code sample is ordinary, and refusing it leaves the author stuck.+ "import inside a template literal": "const help = `\nimport { multica } from \"@multica/plugin-sdk\";\n`;\nconsole.log(help);\n",+ "import inside a string": "const help = \"import x from 'y'\";\nconsole.log(help);\n",+ "import inside a comment": "// import { x } from \"./x.js\";\nconsole.log(1);\n",+ // Dynamic import is legal in a classic script.+ "dynamic import": "const load = () => import(\"./late.js\");\nload();\n",+ "spaced dynamic import": "const load = () => import (\"./late.js\");\nload();\n",+ "commented dynamic import": "const load = () => import /* webpackIgnore */ (\"https://example.com/late.js\");\nload();\n",+ "regexp containing import": "const matcher = /import y from ['\"]x['\"]/;\nconsole.log(matcher);\n",+ "a property named import": "const registry = {};\nregistry.import = 1;\n",+ "a word starting with export": "const exports = {};\nexports.value = 1;\n",+ "nested template expression": "const x = `a${ `b` }c`;\nconsole.log(x);\n",+ "await in an async function": "async function boot() { await Promise.resolve(); }\nboot();\n",+ "await in an async arrow": "const boot = async () => { await Promise.resolve(); };\nboot();\n",+ }+ for name, source := range accepted {+ t.Run(name, func(t *testing.T) {+ if _, err := parseDirBundle(t, source); err != nil {+ t.Fatalf("a valid surface entry was refused: %v", err)+ }+ })+ }+}++func parseDirBundle(t *testing.T, entry string) (plugincontract.Bundle, error) {+ t.Helper()+ files := map[string]string{+ plugincontract.ManifestFilename: bundleManifest,+ "ui/main.js": entry,+ "skills/pr-review/SKILL.md": "Read the diff.\n",+ }+ return plugincontract.ParseBundleFromDir(func(name string) ([]byte, bool, error) {+ content, ok := files[name]+ return []byte(content), ok, nil+ })+}