Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6350: rebuild the plugin system (3/4) — hook engine (#7182)

Jiayuan Zhang659bb41abd60
diff --git a/examples/plugins/triage-notify/README.md b/examples/plugins/triage-notify/README.md
new file mode 100644
index 0000000000..d36349f3b5
--- /dev/null
+++ b/examples/plugins/triage-notify/README.md
@@ -0,0 +1,82 @@
+# Triage Notify
+
+Demonstrates the hook engine: Multica calling **out** to a plugin's own server,
+and that server calling back in.
+
+The three previous examples only ever ran inbound — a sandboxed panel asking the
+host for things. This one has a backend, which is what makes every check in the
+hook engine necessary.
+
+## The three triggers
+
+The same hook, reached three ways. What differs is who caused it, and therefore
+whose name the resulting comment carries.
+
+| Trigger | Where it comes from | Blocks? | Comment author |
+| --- | --- | --- | --- |
+| `ui` | The **Triage this issue** button in the panel | The panel only | The person who clicked |
+| `manual` | The **Triage this issue** entry in the issue actions menu | That menu only | The person who picked it |
+| `event` | Automatically, when an issue is created | **Never** | The plugin itself |
+
+`event` never blocking is not a performance tuning choice. The event bus runs its
+listeners inline on the goroutine of the request that published, so a hook
+dialled from there would put `triage.example.com` on the critical path of
+creating an issue — and an issue would fail to be created because somebody
+else's server was slow.
+
+## Running the handler
+
+```bash
+# The signing secret is shown once, next to the install token, when an admin
+# rotates the plugin's token in workspace settings.
+MULTICA_SIGNING_SECRET=whsec_… node server/handler.mjs
+```
+
+`server/handler.mjs` is the interesting file if you are writing a plugin. It
+shows the four things a handler must do and one the host cannot do for you:
+
+1. **Verify against the raw bytes.** Parse *after* verifying. Re-serializing the
+ JSON and signing that instead is the classic way to make valid signatures
+ fail and invalid ones pass — key order and whitespace are not preserved.
+2. **Check the timestamp.** It is inside the signature, so a captured request
+ expires. Five minutes is the host's tolerance.
+3. **Compare in constant time.** A byte-at-a-time comparison leaks how much of a
+ guessed signature was right, which is enough to recover the rest.
+4. **Remember signatures inside the window.** *This is the part the host cannot
+ do for you.* The timestamp bounds a replay to a few minutes; only the
+ receiver can close the gap entirely by refusing bytes it has already seen.
+
+## Calling back
+
+Each request carries a `callback_token` and a `callback_url`. The token is
+scoped to that one invocation and expires in minutes — spend it on the work at
+hand rather than storing it.
+
+You do not choose what identity the callback writes as. That was decided when
+the hook was dispatched: a `ui`/`manual` call writes as the person who triggered
+it (recorded with `via_plugin_id`), an `event` call writes as the plugin. A
+handler cannot elect to write as somebody else, which is the reason the callback
+token exists instead of just handing out the install token.
+
+## Where a plugin can send data
+
+`net:triage.example.com` in the manifest is the whole answer, and the admin sees
+that exact line on the consent screen. It is an exact host match, never a
+suffix: a plugin that needs `api.triage.example.com` declares that too. The same
+list becomes the panel's CSP `connect-src`, so one string means one thing in
+both places.
+
+Nothing a deployment can configure widens it. `MULTICA_PLUGIN_DEV_ORIGINS` lets
+an author point a hook at a local server during development, but the `net:`
+check still runs — the operator can relax where the network guard applies, not
+what the admin approved.
+
+## Local development
+
+```bash
+export MULTICA_PLUGIN_DEV_ORIGINS=https://localhost:8787
+```
+
+Then point `transport.url` at your local handler and declare the matching
+`net:localhost` scope. Without the opt-in the host refuses to dial a private
+address, which is the SSRF guard doing its job.
diff --git a/examples/plugins/triage-notify/multica.plugin.json b/examples/plugins/triage-notify/multica.plugin.json
new file mode 100644
index 0000000000..582f57241f
--- /dev/null
+++ b/examples/plugins/triage-notify/multica.plugin.json
@@ -0,0 +1,68 @@
+{
+ "manifest_version": 1,
+ "key": "ai.multica.triage-notify",
+ "name": "Triage Notify",
+ "description": "Sends an issue to an external triage service and writes its answer back as a comment. Demonstrates all three host-driven hook triggers: a button in the panel, an entry in the issue menu, and automatic dispatch when an issue is created.",
+ "version": "1.0.0",
+ "author": {
+ "name": "multica",
+ "url": "https://multica.ai"
+ },
+ "scopes": [
+ "issues:read",
+ "comments:read",
+ "comments:write",
+ "net:triage.example.com"
+ ],
+ "config": {
+ "team": {
+ "type": "string",
+ "label": "Team",
+ "description": "Passed to the triage service so it can route the issue.",
+ "required": true,
+ "placeholder": "platform"
+ }
+ },
+ "contributes": {
+ "surfaces": [
+ {
+ "key": "triage",
+ "type": "issue_panel",
+ "name": "Triage",
+ "entry": "ui/main.js",
+ "platforms": [
+ "web",
+ "desktop"
+ ]
+ }
+ ],
+ "hooks": [
+ {
+ "key": "triage_issue",
+ "name": "Triage this issue",
+ "description": "Sends the issue title and description to the triage service and posts its suggested owner and priority back as a comment.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "reason": {
+ "type": "string"
+ }
+ }
+ },
+ "triggers": [
+ "ui",
+ "manual",
+ "event"
+ ],
+ "events": [
+ "issue.created"
+ ],
+ "transport": {
+ "type": "http",
+ "url": "https://triage.example.com/hooks/triage"
+ },
+ "timeout_ms": 8000
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/examples/plugins/triage-notify/server/handler.mjs b/examples/plugins/triage-notify/server/handler.mjs
new file mode 100644
index 0000000000..985a2374cf
--- /dev/null
+++ b/examples/plugins/triage-notify/server/handler.mjs
@@ -0,0 +1,177 @@
+#!/usr/bin/env node
+/**
+ * A reference hook handler — the plugin author's side of the contract.
+ *
+ * This is the half that does NOT run in Multica. It is an ordinary HTTP server
+ * the author operates; Multica only ever sends it a signed POST. Everything
+ * security-relevant here is on this side of the wire, which is the point: the
+ * host cannot make a handler safe, it can only give it what it needs to be.
+ *
+ * Run:
+ * MULTICA_SIGNING_SECRET=whsec_... node handler.mjs
+ *
+ * The signing secret is shown once, next to the install token, when an admin
+ * rotates the plugin's token in workspace settings.
+ */
+
+import { createServer as createHTTPServer } from "node:http";
+import { createServer as createHTTPSServer } from "node:https";
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { readFileSync } from "node:fs";
+
+const PORT = Number(process.env.PORT ?? 8787);
+const SIGNING_SECRET = process.env.MULTICA_SIGNING_SECRET ?? "";
+const TOLERANCE_SECONDS = 5 * 60;
+
+if (!SIGNING_SECRET) {
+ console.error("MULTICA_SIGNING_SECRET is required. Rotate the plugin token in Multica to obtain it.");
+ process.exit(1);
+}
+
+/**
+ * Replay protection, the half the host cannot do for you.
+ *
+ * The timestamp in the signature bounds a captured request to a few minutes.
+ * Remembering the signatures seen inside that window closes the rest: the same
+ * bytes cannot be delivered twice, even immediately. Without this, an attacker
+ * who observes one valid request can repeat it until the window expires.
+ */
+const seenSignatures = new Map();
+
+function rememberSignature(signature, now) {
+ for (const [seen, at] of seenSignatures) {
+ if (now - at > TOLERANCE_SECONDS * 1000) seenSignatures.delete(seen);
+ }
+ if (seenSignatures.has(signature)) return false;
+ seenSignatures.set(signature, now);
+ return true;
+}
+
+function verify(rawBody, headers) {
+ const timestamp = headers["x-multica-timestamp"];
+ const presented = String(headers["x-multica-signature"] ?? "").replace(/^v1=/, "");
+ if (!timestamp || !presented) return "missing signature headers";
+
+ const drift = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
+ if (!Number.isFinite(drift) || drift > TOLERANCE_SECONDS) return "timestamp outside the accepted window";
+
+ const secret = Buffer.from(SIGNING_SECRET.replace(/^whsec_/, ""), "hex");
+ const expected = createHmac("sha256", secret)
+ .update(timestamp)
+ .update(".")
+ .update(rawBody)
+ .digest("hex");
+
+ // Constant time. A byte-at-a-time comparison leaks how much of a guessed
+ // signature was correct, which is enough to recover the rest.
+ const expectedBytes = Buffer.from(expected, "utf8");
+ const presentedBytes = Buffer.from(presented, "utf8");
+ if (expectedBytes.length !== presentedBytes.length) return "signature does not match";
+ if (!timingSafeEqual(expectedBytes, presentedBytes)) return "signature does not match";
+
+ if (!rememberSignature(presented, Date.now())) return "this request was already delivered";
+ return null;
+}
+
+/**
+ * Calls Multica back using the one-shot token that arrived with the request.
+ *
+ * The token is scoped to this invocation and expires in minutes, so it is worth
+ * spending on the work at hand rather than storing. It is good for as many calls
+ * as the job needs — reading the issue and then commenting on it is two, which
+ * is the floor for a handler that does anything with what it read. Which identity the writes
+ * land under was decided when the hook was dispatched: a ui/manual call writes
+ * as the person who triggered it, an event call writes as the plugin.
+ */
+async function callback(body, method, path, payload) {
+ const response = await fetch(`${body.callback_url}${path}`, {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${body.callback_token}`,
+ },
+ body: payload === undefined ? undefined : JSON.stringify(payload),
+ });
+ if (!response.ok) {
+ throw new Error(`Multica answered ${response.status}: ${await response.text()}`);
+ }
+ return response.json();
+}
+
+/** Stand-in for whatever the author's real triage service does. */
+function triage(issue) {
+ const text = `${issue.title ?? ""} ${issue.description ?? ""}`.toLowerCase();
+ if (text.includes("crash") || text.includes("data loss")) {
+ return { priority: "urgent", owner: "on-call" };
+ }
+ if (text.includes("slow") || text.includes("timeout")) {
+ return { priority: "high", owner: "performance" };
+ }
+ return { priority: "medium", owner: "triage" };
+}
+
+// TLS when a cert is supplied. A hook transport URL must be HTTPS — the
+// manifest validator requires it — so a handler that only speaks HTTP cannot be
+// pointed at even in development.
+const tlsCert = process.env.MULTICA_HOOK_TLS_CERT;
+const tlsKey = process.env.MULTICA_HOOK_TLS_KEY;
+const createServer = tlsCert && tlsKey
+ ? (handler) => createHTTPSServer({ cert: readFileSync(tlsCert), key: readFileSync(tlsKey) }, handler)
+ : createHTTPServer;
+
+const server = createServer((request, response) => {
+ if (request.method !== "POST" || !request.url?.startsWith("/hooks/triage")) {
+ response.writeHead(404).end();
+ return;
+ }
+
+ const chunks = [];
+ request.on("data", (chunk) => chunks.push(chunk));
+ request.on("end", async () => {
+ // Verify against the RAW bytes, before any parsing. Re-serializing JSON
+ // and signing that instead is the classic way to make a valid signature
+ // fail and an invalid one pass — key order and spacing are not preserved.
+ const rawBody = Buffer.concat(chunks);
+ const failure = verify(rawBody, request.headers);
+ if (failure) {
+ console.warn(`rejected: ${failure}`);
+ response.writeHead(401, { "Content-Type": "application/json" });
+ response.end(JSON.stringify({ error: failure }));
+ return;
+ }
+
+ const body = JSON.parse(rawBody.toString("utf8"));
+ console.log(`hook ${body.hook_key} via ${body.trigger}${body.event_type ? ` (${body.event_type})` : ""} as ${body.actor?.type}`);
+
+ try {
+ // The host tells us which issue this is about, having already resolved and
+ // permission-checked it. Preferred over anything in `input`: for an event
+ // trigger there was no client to supply it, and for ui/manual a
+ // client-supplied id is not something a handler should trust.
+ const issueId = body.issue_id ?? body.input?.issue_id ?? body.input?.issue?.id;
+ if (!issueId) {
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end(JSON.stringify({ skipped: "no issue in scope" }));
+ return;
+ }
+
+ const issue = await callback(body, "GET", `/issues/${encodeURIComponent(issueId)}`);
+ const verdict = triage(issue);
+ await callback(body, "POST", `/issues/${encodeURIComponent(issueId)}/comments`, {
+ content: `Triage: **${verdict.priority}**, suggested owner **${verdict.owner}**.`,
+ });
+
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end(JSON.stringify(verdict));
+ } catch (error) {
+ console.error(error);
+ // Answer with a status, not with the internal error text: whatever we
+ // return is the host's problem to classify, and echoing internals here
+ // is how a handler leaks its own configuration into someone's log.
+ response.writeHead(502, { "Content-Type": "application/json" });
+ response.end(JSON.stringify({ error: "triage failed" }));
+ }
+ });
+});
+
+server.listen(PORT, () => console.log(`triage handler listening on ${tlsCert ? "https" : "http"}://127.0.0.1:${PORT}`));
diff --git a/examples/plugins/triage-notify/ui/main.js b/examples/plugins/triage-notify/ui/main.js
new file mode 100644
index 0000000000..0a9e68d390
--- /dev/null
+++ b/examples/plugins/triage-notify/ui/main.js
@@ -0,0 +1,150 @@
+// Triage Notify — the surface half.
+//
+// This panel exists to demonstrate the `ui` trigger: a button the plugin drew
+// itself, inside its own frame, that asks the HOST to call the plugin's backend.
+//
+// Note what it does NOT do. It does not fetch triage.example.com directly, even
+// though that is the plugin's own server. Going through the host is what makes
+// the call signed, rate limited, bounded to the granted net: domains, recorded
+// for the admin, and issued a short-lived callback token. A surface that called
+// its own backend would have none of that — and the user would have no record
+// that it happened at all.
+
+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(Object.assign(new Error(payload.error), { status: payload.status }));
+ };
+ port.start();
+ applyTheme(data.theme);
+ boot();
+});
+
+(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 });
+ });
+}
+
+function resize() {
+ port.postMessage({ id: `z${Date.now()}`, kind: "ui.resize", height: document.body.scrollHeight + 8 });
+}
+
+// --- business logic -------------------------------------------------------
+
+let context = null;
+
+async function boot() {
+ context = await call("GET", "/context");
+ render({ state: "idle" });
+}
+
+/**
+ * The `ui` trigger.
+ *
+ * The host checks that this plugin's manifest actually declared `ui` on this
+ * hook, then makes the call on our behalf. The result comes back here, so the
+ * person who pressed the button sees what happened — which is the whole reason
+ * ui and manual block and `event` does not.
+ */
+async function triage() {
+ render({ state: "running" });
+ try {
+ const result = await call("POST", "/hooks/triage_issue", {
+ trigger: "ui",
+ issue_id: context.issue?.id,
+ input: { issue_id: context.issue?.id, reason: "requested from the panel" },
+ });
+ if (result.status === "ok") {
+ render({ state: "done", output: result.output });
+ } else {
+ // "refused" means the host never made the call — a scope nobody granted,
+ // a rate limit, a disabled install. Saying "the service failed" would
+ // send the reader to debug the wrong system.
+ render({
+ state: "error",
+ message: result.status === "refused"
+ ? `Not run: ${result.error}`
+ : `Triage service failed: ${result.error}`,
+ });
+ }
+ } catch (error) {
+ render({ state: "error", message: error.message });
+ }
+}
+
+function render(view) {
+ const disabled = view.state === "running";
+ document.body.innerHTML = `
+ <div class="wrap">
+ <p class="lede">${
+ context?.issue
+ ? "Ask the triage service to suggest an owner and priority for this issue."
+ : "Open this panel on an issue to triage it."
+ }</p>
+ ${context?.issue ? `<button id="run" ${disabled ? "disabled" : ""}>${
+ disabled ? "Triaging…" : "Triage this issue"
+ }</button>` : ""}
+ ${view.state === "done" ? `<p class="ok">Suggested: <strong>${escapeHtml(
+ String(view.output?.priority ?? "unknown"),
+ )}</strong> → <strong>${escapeHtml(String(view.output?.owner ?? "unknown"))}</strong>. A comment was posted.</p>` : ""}
+ ${view.state === "error" ? `<p class="bad">${escapeHtml(view.message)}</p>` : ""}
+ </div>
+ `;
+ document.getElementById("run")?.addEventListener("click", () => void triage());
+ resize();
+}
+
+function escapeHtml(value) {
+ return String(value).replace(/[&<>"']/g, (character) => ({
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
+ })[character]);
+}
+
+const style = document.createElement("style");
+style.textContent = `
+ body { margin: 0; font: 13px/1.5 system-ui, sans-serif; color: var(--foreground, #111); }
+ .wrap { padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
+ .lede { margin: 0; color: var(--muted-foreground, #666); }
+ button {
+ align-self: flex-start; padding: 6px 12px; border-radius: 6px; cursor: pointer;
+ border: 1px solid var(--border, #d4d4d8); background: var(--background, #fff);
+ color: inherit; font: inherit;
+ }
+ button:disabled { opacity: .6; cursor: default; }
+ .ok, .bad { margin: 0; }
+ .bad { color: var(--destructive, #b91c1c); }
+`;
+document.head.appendChild(style);
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 872b7b7ab2..73ee37602b 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -148,9 +148,12 @@ import type {
WebhookDelivery,
NotificationPreferenceResponse,
NotificationPreferences,
+ PluginHookResult,
PluginInstallation,
PluginInstallationListResponse,
+ PluginInvocation,
PluginPreview,
+ PluginTokenIssue,
PluginPreviewRequest,
PluginInstallRequest,
PluginConfigRequest,
@@ -389,7 +392,10 @@ import {
EMPTY_WORKSPACE_MCP_SERVER,
EMPTY_PLUGIN_INSTALLATION_LIST,
EMPTY_PLUGIN_PREVIEW,
+ PluginHookResultSchema,
PluginInstallationListResponseSchema,
+ PluginInvocationListSchema,
+ PluginTokenIssueSchema,
PluginInstallationSchema,
PluginPreviewSchema,
WorkspaceMcpServerListSchema,
@@ -2497,6 +2503,54 @@ export class ApiClient {
});
}
+ /**
+ * Invokes one hook on behalf of a person.
+ *
+ * `ui` comes from a button inside a surface, `manual` from the issue actions
+ * menu or the command palette. Both block this request and only this request:
+ * somebody is waiting for the answer. The `event` trigger never comes through
+ * here — the host dispatches it, so no client can ask for one and inherit an
+ * identity that is supposed to be the plugin's.
+ */
+ async invokePluginHook(
+ installationId: string,
+ hookKey: string,
+ request: { trigger: "ui" | "manual"; issueId?: string; input?: unknown },
+ ): Promise<PluginHookResult> {
+ const raw = await this.fetch<unknown>(`/api/v1/plugin/hooks/${encodeURIComponent(hookKey)}`, {
+ method: "POST",
+ headers: { "X-Multica-Plugin-Installation": installationId },
+ body: JSON.stringify({ trigger: request.trigger, issue_id: request.issueId, input: request.input }),
+ });
+ return parseWithFallback(raw, PluginHookResultSchema, {
+ status: "ok",
+ hook_key: hookKey,
+ trigger: request.trigger,
+ latency_ms: 0,
+ attempts: 1,
+ }, { endpoint: "POST /api/v1/plugin/hooks/{key}" });
+ }
+
+ async listPluginInvocations(workspaceId: string, installationId: string): Promise<PluginInvocation[]> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/invocations`);
+ return parseWithFallback(raw, PluginInvocationListSchema, { invocations: [] }, {
+ endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/invocations",
+ }).invocations;
+ }
+
+ async rotatePluginToken(workspaceId: string, installationId: string): Promise<PluginTokenIssue> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/token`, {
+ method: "POST",
+ });
+ return parseWithFallback(raw, PluginTokenIssueSchema, { token: "", signing_secret: "" }, {
+ endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/token",
+ });
+ }
+
+ async revokePluginToken(workspaceId: string, installationId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/token`, { method: "DELETE" });
+ }
+
async uninstallPlugin(workspaceId: string, installationId: string): Promise<void> {
await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}`, {
method: "DELETE",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 8ad4aeb220..876e07c091 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -159,6 +159,46 @@ export const EMPTY_PLUGIN_INSTALLATION_LIST: PluginInstallationListResponse = {
plugins: [],
};
+/**
+ * One completed hook call. `status` is the host's classification, not the
+ * endpoint's: "refused" means we declined to make the call at all, which is a
+ * different problem for the reader than an endpoint that answered badly.
+ */
+export const PluginHookResultSchema = z.object({
+ status: z.string().default("ok"),
+ output: z.unknown().optional(),
+ error: z.string().optional(),
+ latency_ms: z.number().default(0),
+ hook_key: z.string().default(""),
+ trigger: z.string().default(""),
+ attempts: z.number().default(1),
+}).loose();
+
+export const PluginInvocationSchema = z.object({
+ id: z.string().default(""),
+ hook_key: z.string().default(""),
+ trigger: z.string().default(""),
+ status: z.string().default(""),
+ event_type: z.string().optional(),
+ attempt: z.number().default(1),
+ latency_ms: z.number().default(0),
+ error: z.string().optional(),
+ created_at: z.string().default(""),
+}).loose();
+
+export const PluginInvocationListSchema = z.object({
+ invocations: z.array(PluginInvocationSchema).default([]),
+}).loose();
+
+/**
+ * Returned once, by the request that minted it. There is no read endpoint for
+ * either value, so a client that discards this cannot recover it.
+ */
+export const PluginTokenIssueSchema = z.object({
+ token: z.string().default(""),
+ signing_secret: z.string().default(""),
+}).loose();
+
export const PluginManifestSummarySchema = z.object({
key: z.string().default(""),
name: z.string().default(""),
diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.ts
index 47f7e4ad2f..1d3d9bbeca 100644
--- a/packages/core/plugins/mutations.ts
+++ b/packages/core/plugins/mutations.ts
@@ -52,3 +52,43 @@ export function useUninstallPlugin(wsId: string) {
onSettled: invalidate,
});
}
+
+/**
+ * Invokes a hook the user asked for.
+ *
+ * A mutation rather than a query for the same reason preview is: it performs an
+ * outbound call to a third-party server, and a cache refetch must never replay
+ * it. Whatever the hook did on the far side is not something to repeat because
+ * a component remounted.
+ *
+ * Deliberately does NOT invalidate on settle. A hook may have changed nothing,
+ * or may have written through the Action API under its own attribution — the
+ * caller knows which and invalidates what it actually expects to have moved.
+ */
+export function useInvokePluginHook() {
+ return useMutation({
+ mutationFn: ({ installationId, hookKey, ...request }: {
+ installationId: string;
+ hookKey: string;
+ trigger: "ui" | "manual";
+ issueId?: string;
+ input?: unknown;
+ }) => api.invokePluginHook(installationId, hookKey, request),
+ });
+}
+
+export function useRotatePluginToken(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: (installationId: string) => api.rotatePluginToken(wsId, installationId),
+ onSettled: invalidate,
+ });
+}
+
+export function useRevokePluginToken(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: (installationId: string) => api.revokePluginToken(wsId, installationId),
+ onSettled: invalidate,
+ });
+}
diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.ts
index d235ec30e4..da4d3001aa 100644
--- a/packages/core/plugins/queries.ts
+++ b/packages/core/plugins/queries.ts
@@ -13,3 +13,18 @@ export function pluginInstallationsOptions(wsId: string) {
enabled: wsId.length > 0,
});
}
+
+/**
+ * A hook's recent calls, for the author staring at a failing endpoint.
+ *
+ * Short-lived in cache: the point of opening it is to see what happened just
+ * now, and a stale list is worse than a slow one here.
+ */
+export function pluginInvocationsOptions(wsId: string, installationId: string) {
+ return queryOptions({
+ queryKey: [...pluginKeys.all(wsId), installationId, "invocations"] as const,
+ queryFn: () => api.listPluginInvocations(wsId, installationId),
+ enabled: wsId.length > 0 && installationId.length > 0,
+ staleTime: 5_000,
+ });
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 3a1059beb3..3cacd641ce 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -99,6 +99,9 @@ export type {
PluginPreviewRequest,
PluginInstallRequest,
PluginConfigRequest,
+ PluginHookResult,
+ PluginInvocation,
+ PluginTokenIssue,
} from "./plugin";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.ts
index 562fee010c..d6559a120d 100644
--- a/packages/core/types/plugin.ts
+++ b/packages/core/types/plugin.ts
@@ -105,3 +105,42 @@ export interface PluginInstallRequest {
export interface PluginConfigRequest {
values: Record<string, unknown>;
}
+
+/** One completed hook call, as returned to whoever invoked it. */
+export interface PluginHookResult {
+ /**
+ * The HOST's classification, not the endpoint's. "refused" means the call was
+ * never made — a scope, a rate limit or a disabled install — which is a
+ * different problem for the reader than an endpoint that answered badly.
+ */
+ status: string;
+ output?: unknown;
+ error?: string;
+ latency_ms: number;
+ hook_key: string;
+ trigger: string;
+ attempts: number;
+}
+
+/**
+ * One recorded hook call. Operational telemetry, TTL-swept, and deliberately
+ * carrying no request or response body — a table that kept every payload would
+ * be a second copy of workspace content with none of its deletion paths.
+ */
+export interface PluginInvocation {
+ id: string;
+ hook_key: string;
+ trigger: string;
+ status: string;
+ event_type?: string;
+ attempt: number;
+ latency_ms: number;
+ error?: string;
+ created_at: string;
+}
+
+/** Both values are shown once, by the request that minted them. */
+export interface PluginTokenIssue {
+ token: string;
+ signing_secret: string;
+}
diff --git a/packages/core/workspace/hooks.ts b/packages/core/workspace/hooks.ts
index 9e97cc6beb..db81f71cb4 100644
--- a/packages/core/workspace/hooks.ts
+++ b/packages/core/workspace/hooks.ts
@@ -11,6 +11,9 @@ import {
workspaceListOptions,
} from "./queries";
import { resolvePublicFileUrl } from "./avatar-url";
+import { useFeatureEnabled } from "../config";
+import { PLUGINS_V1_FLAG } from "../feature-flags";
+import { pluginInstallationsOptions } from "../plugins";
// Stable empties for the still-loading directory queries. A fresh `= []`
// default allocates a new array on every render while `data` is undefined,
@@ -63,14 +66,26 @@ export function buildActorNameResolver(directories: {
members: readonly { user_id: string; name: string }[];
agents: readonly { id: string; name: string }[];
squads: readonly { id: string; name: string }[];
+ /**
+ * Installed plugins. Optional because most callers have no reason to load
+ * them, and an event-written row then falls back to a generic "Plugin" —
+ * vague, but not wrong the way "System" would be.
+ */
+ plugins?: readonly { id: string; name: string }[];
}) {
const memberNames = new Map(directories.members.map((m) => [m.user_id, m.name]));
const agentNames = new Map(directories.agents.map((a) => [a.id, a.name]));
const squadNames = new Map(directories.squads.map((s) => [s.id, s.name]));
+ const pluginNames = new Map((directories.plugins ?? []).map((p) => [p.id, p.name]));
return (type: string, id: string) => {
if (type === "member") return memberNames.get(id) ?? "Unknown";
if (type === "agent") return agentNames.get(id) ?? "Unknown Agent";
if (type === "squad") return squadNames.get(id) ?? "Unknown Squad";
+ // An event-triggered hook writes as the installation itself: there is no
+ // person behind it, and borrowing the last member who touched the issue
+ // would be a lie the audit trail cannot undo. An id that no longer
+ // resolves means the plugin was uninstalled — the row stays readable.
+ if (type === "plugin") return pluginNames.get(id) ?? "Plugin";
if (type === "system") return "Multica";
return "System";
};
@@ -81,6 +96,13 @@ export function useActorName() {
const { data: members = EMPTY_MEMBERS } = useQuery(memberListOptions(wsId));
const { data: agents = EMPTY_AGENTS } = useQuery(agentListOptions(wsId));
const { data: squads = EMPTY_SQUADS } = useQuery(squadListOptions(wsId));
+ // Only for naming a plugin-authored row. Gated on the flag so a workspace
+ // without plugins does not fetch a list it can never render an author from.
+ const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
+ const { data: pluginData } = useQuery({
+ ...pluginInstallationsOptions(wsId),
+ enabled: pluginsEnabled && wsId.length > 0,
+ });
const getMemberName = useCallback((userId: string) => {
const m = members.find((m) => m.user_id === userId);
@@ -98,8 +120,8 @@ export function useActorName() {
}, [squads]);
const getActorName = useMemo(
- () => buildActorNameResolver({ members, agents, squads }),
- [agents, members, squads],
+ () => buildActorNameResolver({ members, agents, squads, plugins: pluginData?.plugins }),
+ [agents, members, squads, pluginData],
);
const getActorInitials = useCallback((type: string, id: string) => {
diff --git a/packages/plugin-sdk/index.ts b/packages/plugin-sdk/index.ts
index c875a97bde..4410f67874 100644
--- a/packages/plugin-sdk/index.ts
+++ b/packages/plugin-sdk/index.ts
@@ -54,6 +54,17 @@ export interface Comment {
created_at: string;
}
+/** One completed hook call. `status` is the host's verdict, not the endpoint's. */
+export interface HookResult {
+ status: string;
+ output?: unknown;
+ error?: string;
+ latency_ms: number;
+ hook_key: string;
+ trigger: string;
+ attempts: number;
+}
+
export interface StorageKey {
key: string;
size_bytes: number;
@@ -275,6 +286,29 @@ export const multica = {
user: storageApi("user"),
},
+ hooks: {
+ /**
+ * Invokes one of THIS plugin's hooks — the `ui` trigger.
+ *
+ * The surface does not call its own backend directly, and this is not a
+ * detour for its own sake: routing through the host is what makes the call
+ * signed, rate limited, bounded to the granted `net:` domains, and issued a
+ * short-lived callback token. A surface that fetched its own server would
+ * have none of that, and the user would have no record it happened.
+ *
+ * The host refuses any hook this plugin's manifest did not declare with the
+ * `ui` trigger.
+ */
+ async invoke(hookKey: string, input?: unknown): Promise<HookResult> {
+ const issue = (await multica.context.get()).issue;
+ return bridge.request<HookResult>("POST", `/hooks/${encodeURIComponent(hookKey)}`, {
+ trigger: "ui",
+ issue_id: issue?.id,
+ input,
+ });
+ },
+ },
+
ui: {
/** Ask the host for a different frame height, in CSS pixels. */
resize(height: number) {
diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsx
index 113dbc8d2b..0e0debd49b 100644
--- a/packages/views/issues/actions/issue-actions-menu-items.tsx
+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx
@@ -48,6 +48,7 @@ import {
} from "@multica/ui/components/ui/context-menu";
import { copyText } from "@multica/ui/lib/clipboard";
import type { UseIssueActionsResult } from "./use-issue-actions";
+import { PluginHookMenuItems, PluginModalMenuItems } from "../../plugins";
import { useT } from "../../i18n";
// Both Dropdown and Context menu wrappers expose an API-compatible surface
@@ -335,6 +336,16 @@ export function IssueActionsMenuItems({
</P.SubContent>
</P.Sub>
+ {/* Manual plugin hooks. Rendered by the host rather than by the plugin
+ because the trigger decides identity: a `manual` call acts as the
+ person who picked it, so the entry has to live where the host can
+ prove somebody did. Renders nothing when no plugin declares one. */}
+ <PluginHookMenuItems issueId={issue.id} Item={P.Item} Separator={P.Separator} />
+ {/* Modal surfaces open from here for the same reason: a modal is a third
+ party's UI taking over the screen, so it opens because a person chose
+ it, never on the plugin's own initiative. */}
+ <PluginModalMenuItems issueId={issue.id} Item={P.Item} />
+
<P.Separator />
<P.Item
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 5676d7cd09..d0123264e7 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -804,6 +804,11 @@
"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."
+ "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."
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index af625f530a..c588960776 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -159,28 +159,94 @@
"navigation": "Navigation"
},
"actions": {
- "openSearch": { "label": "Open search", "description": "Search and run commands from anywhere." },
- "createIssue": { "label": "Create issue", "description": "Open your preferred issue creation flow." },
- "toggleSidebar": { "label": "Toggle sidebar", "description": "Show or hide the main sidebar." },
- "toggleChat": { "label": "Toggle chat window", "description": "Open or close the floating chat window. Opening it focuses the message input." },
- "findInIssue": { "label": "Find in issue", "description": "Search within the open issue detail." },
- "openThreadNav": { "label": "Open thread navigator", "description": "List, search, and jump between the comment threads of the open issue." },
- "archiveInboxItem": { "label": "Archive notification", "description": "Archive the open inbox notification, or restore it while reading the archive." },
- "send": { "label": "Send", "description": "Send chat messages, comments, replies, feedback, and prompts, and create issues in the create dialog." },
- "goBack": { "label": "Go back", "description": "Navigate back through history, like a browser." },
- "goForward": { "label": "Go forward", "description": "Navigate forward through history, like a browser." },
- "goInbox": { "label": "Go to Inbox", "description": "Open the workspace inbox." },
- "goChat": { "label": "Go to Chat", "description": "Open workspace chat." },
- "goMyIssues": { "label": "Go to My Issues", "description": "Open issues assigned to you." },
- "goIssues": { "label": "Go to Issues", "description": "Open the issue list." },
- "goProjects": { "label": "Go to Projects", "description": "Open the project list." },
- "goAutopilots": { "label": "Go to Autopilot", "description": "Open workspace automations." },
- "goAgents": { "label": "Go to Agents", "description": "Open the agent list." },
- "goSquads": { "label": "Go to Squads", "description": "Open the squad list." },
- "goUsage": { "label": "Go to Usage", "description": "Open usage analytics." },
- "goRuntimes": { "label": "Go to Runtimes", "description": "Open runtime configuration." },
- "goSkills": { "label": "Go to Skills", "description": "Open the skill library." },
- "goSettings": { "label": "Go to Settings", "description": "Open workspace settings." }
+ "openSearch": {
+ "label": "Open search",
+ "description": "Search and run commands from anywhere."
+ },
+ "createIssue": {
+ "label": "Create issue",
+ "description": "Open your preferred issue creation flow."
+ },
+ "toggleSidebar": {
+ "label": "Toggle sidebar",
+ "description": "Show or hide the main sidebar."
+ },
+ "toggleChat": {
+ "label": "Toggle chat window",
+ "description": "Open or close the floating chat window. Opening it focuses the message input."
+ },
+ "findInIssue": {
+ "label": "Find in issue",
+ "description": "Search within the open issue detail."
+ },
+ "openThreadNav": {
+ "label": "Open thread navigator",
+ "description": "List, search, and jump between the comment threads of the open issue."
+ },
+ "archiveInboxItem": {
+ "label": "Archive notification",
+ "description": "Archive the open inbox notification, or restore it while reading the archive."
+ },
+ "send": {
+ "label": "Send",
+ "description": "Send chat messages, comments, replies, feedback, and prompts, and create issues in the create dialog."
+ },
+ "goBack": {
+ "label": "Go back",
+ "description": "Navigate back through history, like a browser."
+ },
+ "goForward": {
+ "label": "Go forward",
+ "description": "Navigate forward through history, like a browser."
+ },
+ "goInbox": {
+ "label": "Go to Inbox",
+ "description": "Open the workspace inbox."
+ },
+ "goChat": {
+ "label": "Go to Chat",
+ "description": "Open workspace chat."
+ },
+ "goMyIssues": {
+ "label": "Go to My Issues",
+ "description": "Open issues assigned to you."
+ },
+ "goIssues": {
+ "label": "Go to Issues",
+ "description": "Open the issue list."
+ },
+ "goProjects": {
+ "label": "Go to Projects",
+ "description": "Open the project list."
+ },
+ "goAutopilots": {
+ "label": "Go to Autopilot",
+ "description": "Open workspace automations."
+ },
+ "goAgents": {
+ "label": "Go to Agents",
+ "description": "Open the agent list."
+ },
+ "goSquads": {
+ "label": "Go to Squads",
+ "description": "Open the squad list."
+ },
+ "goUsage": {
+ "label": "Go to Usage",
+ "description": "Open usage analytics."
+ },
+ "goRuntimes": {
+ "label": "Go to Runtimes",
+ "description": "Open runtime configuration."
+ },
+ "goSkills": {
+ "label": "Go to Skills",
+ "description": "Open the skill library."
+ },
+ "goSettings": {
+ "label": "Go to Settings",
+ "description": "Open workspace settings."
+ }
},
"fixed": {
"title": "Fixed system shortcuts",
@@ -258,9 +324,9 @@
"issue_statuses": "Issue Statuses",
"properties": "Properties",
"quick_actions": "Quick Actions",
- "plugins": "Plugins",
- "mcp": "MCP",
- "billing": "Billing"
+ "plugins": "Plugins",
+ "mcp": "MCP",
+ "billing": "Billing"
}
},
"plugins": {
@@ -324,7 +390,9 @@
"storage_workspace": "Store data shared by the workspace",
"net": "Send data to {{domain}}",
"unknown": "Unrecognized access — do not install"
- }
+ },
+ "hook_circuit_open": "Hook delivery has stopped after repeated failures.",
+ "hook_recent_failures": "{{count}} recent hook calls failed."
},
"properties": {
"title": "Properties",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 03476120fb..421e183068 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -774,6 +774,11 @@
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} のインターフェースを読み込めませんでした。",
- "surface_local_only": "{{name}} はローカルソースからインストールされているため、ブラウザでインターフェースを読み込めません。"
+ "surface_local_only": "{{name}} はローカルソースからインストールされているため、ブラウザでインターフェースを読み込めません。",
+ "hook_succeeded": "{{name}} が完了しました。",
+ "hook_failed": "{{name}} が失敗しました。",
+ "hook_refused": "{{name}} は実行されませんでした。",
+ "hook_activity": "最近の呼び出し",
+ "hook_never_run": "このフックはまだ実行されていません。"
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 175b1d9d38..107c848a79 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -159,28 +159,94 @@
"navigation": "ナビゲーション"
},
"actions": {
- "openSearch": { "label": "検索を開く", "description": "どこからでも検索やコマンドを実行します。" },
- "createIssue": { "label": "タスクを作成", "description": "優先するタスク作成フローを開きます。" },
- "toggleSidebar": { "label": "サイドバーを切り替え", "description": "メインサイドバーの表示を切り替えます。" },
- "toggleChat": { "label": "チャットウィンドウを切り替え", "description": "フローティングチャットを開閉します。開いたときは入力欄にフォーカスします。" },
- "findInIssue": { "label": "タスク内を検索", "description": "開いているタスクの詳細を検索します。" },
- "openThreadNav": { "label": "スレッドナビゲーターを開く", "description": "開いているタスクのコメントスレッドを一覧・検索して移動します。" },
- "archiveInboxItem": { "label": "通知をアーカイブ", "description": "開いているインボックス通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。" },
- "send": { "label": "送信", "description": "チャット、コメント、返信、フィードバック、プロンプトを送信し、作成ダイアログでタスクを作成します。" },
- "goBack": { "label": "戻る", "description": "ブラウザーのように履歴を戻ります。" },
- "goForward": { "label": "進む", "description": "ブラウザーのように履歴を進みます。" },
- "goInbox": { "label": "受信トレイへ移動", "description": "ワークスペースの受信トレイを開きます。" },
- "goChat": { "label": "チャットへ移動", "description": "ワークスペースのチャットを開きます。" },
- "goMyIssues": { "label": "自分のタスクへ移動", "description": "自分に割り当てられたタスクを開きます。" },
- "goIssues": { "label": "タスクへ移動", "description": "タスク一覧を開きます。" },
- "goProjects": { "label": "プロジェクトへ移動", "description": "プロジェクト一覧を開きます。" },
- "goAutopilots": { "label": "自動化へ移動", "description": "ワークスペースの自動化を開きます。" },
- "goAgents": { "label": "エージェントへ移動", "description": "エージェント一覧を開きます。" },
- "goSquads": { "label": "Squadsへ移動", "description": "Squad一覧を開きます。" },
- "goUsage": { "label": "使用量へ移動", "description": "使用量分析を開きます。" },
- "goRuntimes": { "label": "ランタイムへ移動", "description": "ランタイム設定を開きます。" },
- "goSkills": { "label": "Skillsへ移動", "description": "Skillライブラリを開きます。" },
- "goSettings": { "label": "設定へ移動", "description": "ワークスペース設定を開きます。" }
+ "openSearch": {
+ "label": "検索を開く",
+ "description": "どこからでも検索やコマンドを実行します。"
+ },
+ "createIssue": {
+ "label": "タスクを作成",
+ "description": "優先するタスク作成フローを開きます。"
+ },
+ "toggleSidebar": {
+ "label": "サイドバーを切り替え",
+ "description": "メインサイドバーの表示を切り替えます。"
+ },
+ "toggleChat": {
+ "label": "チャットウィンドウを切り替え",
+ "description": "フローティングチャットを開閉します。開いたときは入力欄にフォーカスします。"
+ },
+ "findInIssue": {
+ "label": "タスク内を検索",
+ "description": "開いているタスクの詳細を検索します。"
+ },
+ "openThreadNav": {
+ "label": "スレッドナビゲーターを開く",
+ "description": "開いているタスクのコメントスレッドを一覧・検索して移動します。"
+ },
+ "archiveInboxItem": {
+ "label": "通知をアーカイブ",
+ "description": "開いているインボックス通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。"
+ },
+ "send": {
+ "label": "送信",
+ "description": "チャット、コメント、返信、フィードバック、プロンプトを送信し、作成ダイアログでタスクを作成します。"
+ },
+ "goBack": {
+ "label": "戻る",
+ "description": "ブラウザーのように履歴を戻ります。"
+ },
+ "goForward": {
+ "label": "進む",
+ "description": "ブラウザーのように履歴を進みます。"
+ },
+ "goInbox": {
+ "label": "受信トレイへ移動",
+ "description": "ワークスペースの受信トレイを開きます。"
+ },
+ "goChat": {
+ "label": "チャットへ移動",
+ "description": "ワークスペースのチャットを開きます。"
+ },
+ "goMyIssues": {
+ "label": "自分のタスクへ移動",
+ "description": "自分に割り当てられたタスクを開きます。"
+ },
+ "goIssues": {
+ "label": "タスクへ移動",
+ "description": "タスク一覧を開きます。"
+ },
+ "goProjects": {
+ "label": "プロジェクトへ移動",
+ "description": "プロジェクト一覧を開きます。"
+ },
+ "goAutopilots": {
+ "label": "自動化へ移動",
+ "description": "ワークスペースの自動化を開きます。"
+ },
+ "goAgents": {
+ "label": "エージェントへ移動",
+ "description": "エージェント一覧を開きます。"
+ },
+ "goSquads": {
+ "label": "Squadsへ移動",
+ "description": "Squad一覧を開きます。"
+ },
+ "goUsage": {
+ "label": "使用量へ移動",
+ "description": "使用量分析を開きます。"
+ },
+ "goRuntimes": {
+ "label": "ランタイムへ移動",
+ "description": "ランタイム設定を開きます。"
+ },
+ "goSkills": {
+ "label": "Skillsへ移動",
+ "description": "Skillライブラリを開きます。"
+ },
+ "goSettings": {
+ "label": "設定へ移動",
+ "description": "ワークスペース設定を開きます。"
+ }
},
"fixed": {
"title": "固定のシステムショートカット",
@@ -258,9 +324,9 @@
"issue_statuses": "ステータス",
"properties": "プロパティ",
"quick_actions": "クイックアクション",
- "plugins": "Plugins",
- "mcp": "MCP",
- "billing": "請求とプラン"
+ "plugins": "Plugins",
+ "mcp": "MCP",
+ "billing": "請求とプラン"
}
},
"plugins": {
@@ -324,7 +390,9 @@
"storage_workspace": "ワークスペース共有のデータを保存する",
"net": "{{domain}} にデータを送信する",
"unknown": "認識できない権限です — インストールしないでください"
- }
+ },
+ "hook_circuit_open": "連続失敗のためフックの配信を停止しました。",
+ "hook_recent_failures": "最近 {{count}} 件のフック呼び出しが失敗しました。"
},
"properties": {
"title": "プロパティ",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 7ca35b145b..c43fdd38d9 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -774,6 +774,11 @@
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}}의 인터페이스를 불러오지 못했습니다.",
- "surface_local_only": "{{name}}은(는) 로컬 소스에서 설치되어 브라우저에서 인터페이스를 불러올 수 없습니다."
+ "surface_local_only": "{{name}}은(는) 로컬 소스에서 설치되어 브라우저에서 인터페이스를 불러올 수 없습니다.",
+ "hook_succeeded": "{{name}} 완료됨.",
+ "hook_failed": "{{name}} 실패함.",
+ "hook_refused": "{{name}}이(가) 실행되지 않았습니다.",
+ "hook_activity": "최근 호출",
+ "hook_never_run": "이 훅은 아직 실행되지 않았습니다."
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 2a5fa3b92b..07072a26f4 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -159,28 +159,94 @@
"navigation": "탐색"
},
"actions": {
- "openSearch": { "label": "검색 열기", "description": "어디서나 검색하고 명령을 실행합니다." },
- "createIssue": { "label": "태스크 만들기", "description": "선호하는 태스크 만들기 흐름을 엽니다." },
- "toggleSidebar": { "label": "사이드바 전환", "description": "기본 사이드바를 표시하거나 숨깁니다." },
- "toggleChat": { "label": "채팅 창 전환", "description": "플로팅 채팅 창을 열거나 닫습니다. 열면 메시지 입력란에 포커스합니다." },
- "findInIssue": { "label": "태스크에서 찾기", "description": "열린 태스크 상세 내용에서 검색합니다." },
- "openThreadNav": { "label": "스레드 내비게이터 열기", "description": "열린 태스크의 댓글 스레드를 나열하고 검색해 이동합니다." },
- "archiveInboxItem": { "label": "알림 보관", "description": "열린 인박스 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다." },
- "send": { "label": "보내기", "description": "채팅, 댓글, 답글, 피드백 및 프롬프트를 보내고, 생성 대화상자에서 태스크를 만듭니다." },
- "goBack": { "label": "뒤로 가기", "description": "브라우저처럼 기록을 따라 뒤로 이동합니다." },
- "goForward": { "label": "앞으로 가기", "description": "브라우저처럼 기록을 따라 앞으로 이동합니다." },
- "goInbox": { "label": "받은 편지함으로 이동", "description": "워크스페이스 받은 편지함을 엽니다." },
- "goChat": { "label": "채팅으로 이동", "description": "워크스페이스 채팅을 엽니다." },
- "goMyIssues": { "label": "내 태스크로 이동", "description": "나에게 할당된 태스크를 엽니다." },
- "goIssues": { "label": "태스크로 이동", "description": "태스크 목록을 엽니다." },
- "goProjects": { "label": "프로젝트로 이동", "description": "프로젝트 목록을 엽니다." },
- "goAutopilots": { "label": "자동화로 이동", "description": "워크스페이스 자동화를 엽니다." },
- "goAgents": { "label": "에이전트로 이동", "description": "에이전트 목록을 엽니다." },
- "goSquads": { "label": "스쿼드로 이동", "description": "스쿼드 목록을 엽니다." },
- "goUsage": { "label": "사용량으로 이동", "description": "사용량 분석을 엽니다." },
- "goRuntimes": { "label": "런타임으로 이동", "description": "런타임 설정을 엽니다." },
- "goSkills": { "label": "Skills로 이동", "description": "Skill 라이브러리를 엽니다." },
- "goSettings": { "label": "설정으로 이동", "description": "워크스페이스 설정을 엽니다." }
+ "openSearch": {
+ "label": "검색 열기",
+ "description": "어디서나 검색하고 명령을 실행합니다."
+ },
+ "createIssue": {
+ "label": "태스크 만들기",
+ "description": "선호하는 태스크 만들기 흐름을 엽니다."
+ },
+ "toggleSidebar": {
+ "label": "사이드바 전환",
+ "description": "기본 사이드바를 표시하거나 숨깁니다."
+ },
+ "toggleChat": {
+ "label": "채팅 창 전환",
+ "description": "플로팅 채팅 창을 열거나 닫습니다. 열면 메시지 입력란에 포커스합니다."
+ },
+ "findInIssue": {
+ "label": "태스크에서 찾기",
+ "description": "열린 태스크 상세 내용에서 검색합니다."
+ },
+ "openThreadNav": {
+ "label": "스레드 내비게이터 열기",
+ "description": "열린 태스크의 댓글 스레드를 나열하고 검색해 이동합니다."
+ },
+ "archiveInboxItem": {
+ "label": "알림 보관",
+ "description": "열린 인박스 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다."
+ },
+ "send": {
+ "label": "보내기",
+ "description": "채팅, 댓글, 답글, 피드백 및 프롬프트를 보내고, 생성 대화상자에서 태스크를 만듭니다."
+ },
+ "goBack": {
+ "label": "뒤로 가기",
+ "description": "브라우저처럼 기록을 따라 뒤로 이동합니다."
+ },
+ "goForward": {
+ "label": "앞으로 가기",
+ "description": "브라우저처럼 기록을 따라 앞으로 이동합니다."
+ },
+ "goInbox": {
+ "label": "받은 편지함으로 이동",
+ "description": "워크스페이스 받은 편지함을 엽니다."
+ },
+ "goChat": {
+ "label": "채팅으로 이동",
+ "description": "워크스페이스 채팅을 엽니다."
+ },
+ "goMyIssues": {
+ "label": "내 태스크로 이동",
+ "description": "나에게 할당된 태스크를 엽니다."
+ },
+ "goIssues": {
+ "label": "태스크로 이동",
+ "description": "태스크 목록을 엽니다."
+ },
+ "goProjects": {
+ "label": "프로젝트로 이동",
+ "description": "프로젝트 목록을 엽니다."
+ },
+ "goAutopilots": {
+ "label": "자동화로 이동",
+ "description": "워크스페이스 자동화를 엽니다."
+ },
+ "goAgents": {
+ "label": "에이전트로 이동",
+ "description": "에이전트 목록을 엽니다."
+ },
+ "goSquads": {
+ "label": "스쿼드로 이동",
+ "description": "스쿼드 목록을 엽니다."
+ },
+ "goUsage": {
+ "label": "사용량으로 이동",
+ "description": "사용량 분석을 엽니다."
+ },
+ "goRuntimes": {
+ "label": "런타임으로 이동",
+ "description": "런타임 설정을 엽니다."
+ },
+ "goSkills": {
+ "label": "Skills로 이동",
+ "description": "Skill 라이브러리를 엽니다."
+ },
+ "goSettings": {
+ "label": "설정으로 이동",
+ "description": "워크스페이스 설정을 엽니다."
+ }
},
"fixed": {
"title": "고정 시스템 단축키",
@@ -258,9 +324,9 @@
"issue_statuses": "이슈 상태",
"properties": "속성",
"quick_actions": "퀵 액션",
- "plugins": "Plugins",
- "mcp": "MCP",
- "billing": "결제 및 요금제"
+ "plugins": "Plugins",
+ "mcp": "MCP",
+ "billing": "결제 및 요금제"
}
},
"plugins": {
@@ -324,7 +390,9 @@
"storage_workspace": "워크스페이스 공유 데이터 저장",
"net": "{{domain}}(으)로 데이터 전송",
"unknown": "알 수 없는 권한 — 설치하지 마세요"
- }
+ },
+ "hook_circuit_open": "반복 실패로 훅 전달이 중단되었습니다.",
+ "hook_recent_failures": "최근 훅 호출 {{count}}건이 실패했습니다."
},
"properties": {
"title": "속성",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 456c2ca069..0169f3a834 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -774,6 +774,11 @@
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} 的界面加载失败。",
- "surface_local_only": "{{name}} 是从本地源安装的,界面无法在浏览器里加载。"
+ "surface_local_only": "{{name}} 是从本地源安装的,界面无法在浏览器里加载。",
+ "hook_succeeded": "{{name}} 已完成。",
+ "hook_failed": "{{name}} 执行失败。",
+ "hook_refused": "{{name}} 未被执行。",
+ "hook_activity": "最近调用",
+ "hook_never_run": "该 hook 尚未运行过。"
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 5c5768d17f..e0469af60b 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -159,28 +159,94 @@
"navigation": "导航"
},
"actions": {
- "openSearch": { "label": "打开搜索", "description": "随时搜索内容或运行命令。" },
- "createIssue": { "label": "新建任务", "description": "打开你常用的任务创建流程。" },
- "toggleSidebar": { "label": "显示或隐藏侧边栏", "description": "切换主侧边栏的显示状态。" },
- "toggleChat": { "label": "显示或隐藏聊天窗", "description": "打开或关闭悬浮聊天窗,打开时自动聚焦输入框。" },
- "findInIssue": { "label": "在任务中查找", "description": "搜索当前打开的任务详情。" },
- "openThreadNav": { "label": "打开讨论导航", "description": "列出、搜索并跳转当前任务的评论讨论。" },
- "archiveInboxItem": { "label": "归档通知", "description": "归档当前打开的收件箱通知;在归档列表中则取消归档。" },
- "send": { "label": "发送", "description": "发送聊天消息、评论、回复、反馈和提示词,并在创建弹窗中创建任务。" },
- "goBack": { "label": "后退", "description": "像浏览器一样在历史记录中后退。" },
- "goForward": { "label": "前进", "description": "像浏览器一样在历史记录中前进。" },
- "goInbox": { "label": "前往收件箱", "description": "打开工作区收件箱。" },
- "goChat": { "label": "前往聊天", "description": "打开工作区聊天。" },
- "goMyIssues": { "label": "前往我的任务", "description": "打开分配给你的任务。" },
- "goIssues": { "label": "前往任务", "description": "打开任务列表。" },
- "goProjects": { "label": "前往项目", "description": "打开项目列表。" },
- "goAutopilots": { "label": "前往自动化", "description": "打开工作区自动化。" },
- "goAgents": { "label": "前往智能体", "description": "打开智能体列表。" },
- "goSquads": { "label": "前往小队", "description": "打开小队列表。" },
- "goUsage": { "label": "前往用量", "description": "打开用量分析。" },
- "goRuntimes": { "label": "前往运行时", "description": "打开运行时配置。" },
- "goSkills": { "label": "前往 Skills", "description": "打开 skill 库。" },
- "goSettings": { "label": "前往设置", "description": "打开工作区设置。" }
+ "openSearch": {
+ "label": "打开搜索",
+ "description": "随时搜索内容或运行命令。"
+ },
+ "createIssue": {
+ "label": "新建任务",
+ "description": "打开你常用的任务创建流程。"
+ },
+ "toggleSidebar": {
+ "label": "显示或隐藏侧边栏",
+ "description": "切换主侧边栏的显示状态。"
+ },
+ "toggleChat": {
+ "label": "显示或隐藏聊天窗",
+ "description": "打开或关闭悬浮聊天窗,打开时自动聚焦输入框。"
+ },
+ "findInIssue": {
+ "label": "在任务中查找",
+ "description": "搜索当前打开的任务详情。"
+ },
+ "openThreadNav": {
+ "label": "打开讨论导航",
+ "description": "列出、搜索并跳转当前任务的评论讨论。"
+ },
+ "archiveInboxItem": {
+ "label": "归档通知",
+ "description": "归档当前打开的收件箱通知;在归档列表中则取消归档。"
+ },
+ "send": {
+ "label": "发送",
+ "description": "发送聊天消息、评论、回复、反馈和提示词,并在创建弹窗中创建任务。"
+ },
+ "goBack": {
+ "label": "后退",
+ "description": "像浏览器一样在历史记录中后退。"
+ },
+ "goForward": {
+ "label": "前进",
+ "description": "像浏览器一样在历史记录中前进。"
+ },
+ "goInbox": {
+ "label": "前往收件箱",
+ "description": "打开工作区收件箱。"
+ },
+ "goChat": {
+ "label": "前往聊天",
+ "description": "打开工作区聊天。"
+ },
+ "goMyIssues": {
+ "label": "前往我的任务",
+ "description": "打开分配给你的任务。"
+ },
+ "goIssues": {
+ "label": "前往任务",
+ "description": "打开任务列表。"
+ },
+ "goProjects": {
+ "label": "前往项目",
+ "description": "打开项目列表。"
+ },
+ "goAutopilots": {
+ "label": "前往自动化",
+ "description": "打开工作区自动化。"
+ },
+ "goAgents": {
+ "label": "前往智能体",
+ "description": "打开智能体列表。"
+ },
+ "goSquads": {
+ "label": "前往小队",
+ "description": "打开小队列表。"
+ },
+ "goUsage": {
+ "label": "前往用量",
+ "description": "打开用量分析。"
+ },
+ "goRuntimes": {
+ "label": "前往运行时",
+ "description": "打开运行时配置。"
+ },
+ "goSkills": {
+ "label": "前往 Skills",
+ "description": "打开 skill 库。"
+ },
+ "goSettings": {
+ "label": "前往设置",
+ "description": "打开工作区设置。"
+ }
},
"fixed": {
"title": "固定的系统快捷键",
@@ -258,9 +324,9 @@
"issue_statuses": "议题状态",
"properties": "属性",
"quick_actions": "快捷操作",
- "plugins": "Plugins",
- "mcp": "MCP",
- "billing": "账单与套餐"
+ "plugins": "Plugins",
+ "mcp": "MCP",
+ "billing": "账单与套餐"
}
},
"plugins": {
@@ -324,7 +390,9 @@
"storage_workspace": "存储工作区共享数据",
"net": "向 {{domain}} 发送数据",
"unknown": "无法识别的权限 — 请勿安装"
- }
+ },
+ "hook_circuit_open": "连续失败后已停止投递该 hook。",
+ "hook_recent_failures": "最近有 {{count}} 次 hook 调用失败。"
},
"properties": {
"title": "属性",
diff --git a/packages/views/plugins/index.ts b/packages/views/plugins/index.ts
index cacbcb8a49..21aa54395b 100644
--- a/packages/views/plugins/index.ts
+++ b/packages/views/plugins/index.ts
@@ -1,3 +1,20 @@
export { PluginPanelSection } from "./plugin-panel-section";
export { PluginSurfaceFrame } from "./plugin-surface-frame";
export { buildSurfaceCSP, buildSurfaceDocument, resolveSurfaceEntry, surfaceConnectSources } from "./surface-document";
+export {
+ PluginHookMenuItems,
+ collectManualHookActions,
+ pluginHookActionKey,
+ usePluginHookActions,
+ useRunPluginHook,
+} from "./plugin-hook-actions";
+export type { PluginHookAction } from "./plugin-hook-actions";
+export {
+ PluginModalMenuItems,
+ PluginModalSurface,
+ collectModalSurfaces,
+ pluginModalKey,
+ usePluginModalSurfaces,
+} from "./plugin-modal-surface";
+export type { PluginModalTarget } from "./plugin-modal-surface";
+export { PluginHookActivity, summarizeInvocations } from "./plugin-hook-activity";
diff --git a/packages/views/plugins/plugin-hook-actions.test.ts b/packages/views/plugins/plugin-hook-actions.test.ts
new file mode 100644
index 0000000000..32c55e959b
--- /dev/null
+++ b/packages/views/plugins/plugin-hook-actions.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { PluginInstallation } from "@multica/core/types";
+import { collectManualHookActions, pluginHookActionKey } from "./plugin-hook-actions";
+
+// The canonical matrix for which hooks become menu entries. The component
+// suite covers rendering and wiring; it does not re-run these cases.
+
+function installation(overrides: Partial<PluginInstallation> = {}): PluginInstallation {
+ return {
+ id: "install-1",
+ plugin_key: "com.example.one",
+ name: "Example",
+ version: "1.0.0",
+ source_url: "https://example.com/multica.plugin.json",
+ enabled: true,
+ granted_scopes: [],
+ config_schema: [],
+ config: {},
+ configured_secrets: [],
+ surfaces: [],
+ hooks: [],
+ resources: [],
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+}
+
+function hook(key: string, triggers: string[]) {
+ return { key, name: key, description: "", triggers, transport: "http" };
+}
+
+describe("collectManualHookActions", () => {
+ it("takes only hooks that declared the manual trigger", () => {
+ const actions = collectManualHookActions([
+ installation({
+ hooks: [
+ hook("manual_one", ["manual"]),
+ hook("ui_only", ["ui"]),
+ hook("event_only", ["event"]),
+ hook("agent_only", ["agent"]),
+ hook("manual_and_ui", ["ui", "manual"]),
+ ],
+ }),
+ ]);
+ expect(actions.map((a) => a.hook.key)).toEqual(["manual_one", "manual_and_ui"]);
+ });
+
+ it("skips a disabled installation entirely", () => {
+ const actions = collectManualHookActions([
+ installation({ enabled: false, hooks: [hook("manual_one", ["manual"])] }),
+ ]);
+ expect(actions).toEqual([]);
+ });
+
+ // Per the API compatibility rule: a backend that stops sending `enabled` must
+ // read as off. A truthy check would turn a dropped field into a live menu
+ // entry for a plugin the admin had switched off.
+ it("treats a missing enabled flag as off rather than truthy", () => {
+ const withoutFlag = installation({ hooks: [hook("manual_one", ["manual"])] });
+ delete (withoutFlag as { enabled?: boolean }).enabled;
+ expect(collectManualHookActions([withoutFlag])).toEqual([]);
+ });
+
+ it("survives an installation whose hooks or triggers are missing", () => {
+ const noHooks = installation();
+ delete (noHooks as { hooks?: unknown }).hooks;
+ const noTriggers = installation({
+ id: "install-2",
+ hooks: [{ key: "k", name: "k", description: "", transport: "http" } as never],
+ });
+ expect(collectManualHookActions([noHooks, noTriggers])).toEqual([]);
+ });
+
+ it("keeps entries from different installations distinct", () => {
+ const actions = collectManualHookActions([
+ installation({ id: "a", name: "Alpha", hooks: [hook("summarize", ["manual"])] }),
+ installation({ id: "b", name: "Beta", hooks: [hook("summarize", ["manual"])] }),
+ ]);
+ // Same hook key from two plugins: the key has to disambiguate, or React
+ // collapses them and only one is clickable.
+ const keys = actions.map(pluginHookActionKey);
+ expect(new Set(keys).size).toBe(2);
+ expect(actions.map((a) => a.installation.name)).toEqual(["Alpha", "Beta"]);
+ });
+});
diff --git a/packages/views/plugins/plugin-hook-actions.tsx b/packages/views/plugins/plugin-hook-actions.tsx
new file mode 100644
index 0000000000..f67e81f88b
--- /dev/null
+++ b/packages/views/plugins/plugin-hook-actions.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Loader2, Plug } from "lucide-react";
+import { toast } from "sonner";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { pluginInstallationsOptions, useInvokePluginHook } from "@multica/core/plugins";
+import type { PluginHook, PluginInstallation } from "@multica/core/types";
+import { useT } from "../i18n";
+
+/**
+ * Manual hook actions on an issue.
+ *
+ * `manual` is the trigger for "a person picked this from a menu", as opposed to
+ * `ui` (a button the plugin drew inside its own panel) and `event` (nobody
+ * picked anything). The distinction is not cosmetic — it decides which identity
+ * the resulting writes carry — so the HOST owns this list rather than letting a
+ * surface render its own menu entry.
+ *
+ * Like the Quick Actions list, this is NOT filtered by whether the call will
+ * succeed. Hiding an action whose endpoint is currently down would give two
+ * people on one issue different menus with nothing to explain the difference;
+ * a refusal explains itself when it happens.
+ */
+
+export interface PluginHookAction {
+ installation: PluginInstallation;
+ hook: PluginHook;
+}
+
+export function pluginHookActionKey(action: PluginHookAction): string {
+ return `${action.installation.id}:${action.hook.key}`;
+}
+
+/**
+ * Collects the manual hooks of every enabled installation.
+ *
+ * Exported for its own test: the filter is the product rule (enabled install,
+ * manual declared) and belongs in one place rather than re-derived per menu.
+ */
+export function collectManualHookActions(installations: readonly PluginInstallation[]): PluginHookAction[] {
+ const actions: PluginHookAction[] = [];
+ for (const installation of installations) {
+ // Explicit === true per the API compatibility rule: a backend that stops
+ // sending the field must read as "off", not as "truthy enough".
+ if (installation.enabled !== true) continue;
+ for (const hook of installation.hooks ?? []) {
+ if ((hook.triggers ?? []).includes("manual")) actions.push({ installation, hook });
+ }
+ }
+ return actions;
+}
+
+export function usePluginHookActions(): PluginHookAction[] {
+ const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const { data } = useQuery({
+ ...pluginInstallationsOptions(wsId),
+ enabled: pluginsEnabled && wsId.length > 0,
+ });
+
+ return useMemo(
+ () => (pluginsEnabled ? collectManualHookActions(data?.plugins ?? []) : []),
+ [data, pluginsEnabled],
+ );
+}
+
+/**
+ * Runs a manual hook and reports what happened.
+ *
+ * The message is outcome-specific on purpose. "refused" means the call never
+ * left us — a scope the admin did not grant, a rate limit, a disabled install —
+ * and telling somebody their plugin is broken when the real answer is "nobody
+ * approved this" sends them to debug the wrong system.
+ */
+export function useRunPluginHook() {
+ const { t } = useT("issues");
+ const invoke = useInvokePluginHook();
+ const [running, setRunning] = useState<string | null>(null);
+
+ const run = async (action: PluginHookAction, issueId?: string) => {
+ setRunning(pluginHookActionKey(action));
+ try {
+ const result = await invoke.mutateAsync({
+ installationId: action.installation.id,
+ hookKey: action.hook.key,
+ trigger: "manual",
+ issueId,
+ });
+ if (result.status === "ok") {
+ toast.success(t(($) => $.plugins.hook_succeeded, { name: action.hook.name }));
+ } else if (result.status === "refused") {
+ toast.error(t(($) => $.plugins.hook_refused, { name: action.hook.name }), {
+ description: result.error,
+ });
+ } else {
+ toast.error(t(($) => $.plugins.hook_failed, { name: action.hook.name }), {
+ description: result.error,
+ });
+ }
+ return result;
+ } catch (error) {
+ toast.error(t(($) => $.plugins.hook_failed, { name: action.hook.name }), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ return null;
+ } finally {
+ setRunning(null);
+ }
+ };
+
+ return { run, running };
+}
+
+interface PluginHookMenuItemsProps {
+ issueId: string;
+ /**
+ * The host menu's own Item component. Taken as a prop rather than imported so
+ * the same list renders in the dropdown and the context menu — the pattern
+ * `IssueActionsMenuItems` already uses, and the reason the two do not drift.
+ */
+ Item: React.ComponentType<{
+ onClick?: () => void;
+ disabled?: boolean;
+ children?: React.ReactNode;
+ }>;
+ Separator?: React.ComponentType<Record<string, never>>;
+}
+
+export function PluginHookMenuItems({ issueId, Item, Separator }: PluginHookMenuItemsProps) {
+ const actions = usePluginHookActions();
+ const { run, running } = useRunPluginHook();
+
+ if (actions.length === 0) return null;
+
+ return (
+ <>
+ {Separator ? <Separator /> : null}
+ {actions.map((action) => {
+ const key = pluginHookActionKey(action);
+ const isRunning = running === key;
+ return (
+ <Item key={key} disabled={isRunning} onClick={() => void run(action, issueId)}>
+ {isRunning ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plug className="h-3.5 w-3.5" />}
+ {/* The plugin's name, not just the action's: two installed plugins
+ may both contribute "Summarize", and a menu showing the same
+ word twice is a menu nobody can choose from. */}
+ <span className="truncate">{action.hook.name}</span>
+ <span className="ml-auto truncate pl-3 text-caption text-muted-foreground">
+ {action.installation.name}
+ </span>
+ </Item>
+ );
+ })}
+ </>
+ );
+}
diff --git a/packages/views/plugins/plugin-hook-activity.test.ts b/packages/views/plugins/plugin-hook-activity.test.ts
new file mode 100644
index 0000000000..f18e46aaee
--- /dev/null
+++ b/packages/views/plugins/plugin-hook-activity.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { PluginInvocation } from "@multica/core/types";
+import { summarizeInvocations } from "./plugin-hook-activity";
+
+// Canonical matrix for the failure summary. The component suite covers
+// rendering; it does not re-run these cases.
+
+function invocation(status: string, error?: string): PluginInvocation {
+ return {
+ id: Math.random().toString(36).slice(2),
+ hook_key: "triage",
+ trigger: "event",
+ status,
+ attempt: 1,
+ latency_ms: 5,
+ error,
+ created_at: "2026-08-19T00:00:00Z",
+ };
+}
+
+describe("summarizeInvocations", () => {
+ it("reports nothing when every recent call succeeded", () => {
+ const summary = summarizeInvocations([invocation("ok"), invocation("ok")]);
+ expect(summary.failures).toHaveLength(0);
+ expect(summary.consecutiveFailures).toBe(0);
+ });
+
+ // "Failing right now" and "failed once yesterday" are different stories, and
+ // only the first means delivery has stopped.
+ it("counts consecutive failures from the newest end only", () => {
+ const summary = summarizeInvocations([
+ invocation("failed"),
+ invocation("failed"),
+ invocation("ok"),
+ invocation("failed"),
+ ]);
+ expect(summary.consecutiveFailures).toBe(2);
+ expect(summary.failures).toHaveLength(3);
+ });
+
+ it("stops counting at a recovery", () => {
+ const summary = summarizeInvocations([invocation("ok"), invocation("failed"), invocation("failed")]);
+ expect(summary.consecutiveFailures).toBe(0);
+ });
+
+ it("surfaces the newest error, which is the one worth showing", () => {
+ const summary = summarizeInvocations([
+ invocation("failed", "hook endpoint returned 502"),
+ invocation("failed", "hook endpoint timed out"),
+ ]);
+ expect(summary.lastError).toBe("hook endpoint returned 502");
+ });
+
+ it("bounds what it reads so an old history cannot dominate", () => {
+ const summary = summarizeInvocations(Array.from({ length: 60 }, () => invocation("failed")));
+ expect(summary.total).toBe(20);
+ });
+
+ it("treats every non-ok status as a failure, not just 'failed'", () => {
+ const summary = summarizeInvocations([invocation("timeout"), invocation("refused")]);
+ expect(summary.failures).toHaveLength(2);
+ expect(summary.consecutiveFailures).toBe(2);
+ });
+});
diff --git a/packages/views/plugins/plugin-hook-activity.tsx b/packages/views/plugins/plugin-hook-activity.tsx
new file mode 100644
index 0000000000..ad3f4635a2
--- /dev/null
+++ b/packages/views/plugins/plugin-hook-activity.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { AlertTriangle } from "lucide-react";
+import { pluginInvocationsOptions } from "@multica/core/plugins";
+import type { PluginInvocation } from "@multica/core/types";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+
+/**
+ * Why a plugin's hook is failing, where the admin who installed it will look.
+ *
+ * An `event` hook fails silently by design — nothing blocks, nobody is watching
+ * the call, and after a few failures the circuit breaker stops even trying. All
+ * of that is correct behaviour and completely invisible without this: the plugin
+ * still says "enabled" while doing nothing at all.
+ *
+ * Shows nothing when the recent calls all succeeded. A working plugin does not
+ * need a panel about it.
+ */
+
+/** A breaker trips on this many failures inside its window; see plugin_hook.go. */
+const BREAKER_THRESHOLD = 5;
+
+export function summarizeInvocations(invocations: readonly PluginInvocation[]) {
+ const recent = invocations.slice(0, 20);
+ const failures = recent.filter((invocation) => invocation.status !== "ok");
+ return {
+ total: recent.length,
+ failures,
+ // Consecutive from the newest end: a hook that failed and then recovered is
+ // not the same story as one that is failing right now.
+ consecutiveFailures: countLeadingFailures(recent),
+ lastError: failures[0]?.error,
+ };
+}
+
+function countLeadingFailures(invocations: readonly PluginInvocation[]): number {
+ let count = 0;
+ for (const invocation of invocations) {
+ if (invocation.status === "ok") break;
+ count += 1;
+ }
+ return count;
+}
+
+export function PluginHookActivity({ wsId, installationId }: { wsId: string; installationId: string }) {
+ const { t } = useT("settings");
+ const { data } = useQuery(pluginInvocationsOptions(wsId, installationId));
+
+ const summary = summarizeInvocations(data ?? []);
+ if (summary.failures.length === 0) return null;
+
+ const tripped = summary.consecutiveFailures >= BREAKER_THRESHOLD;
+
+ return (
+ <div
+ className={cn(
+ "flex items-start gap-2 rounded-md border px-3 py-2 text-caption",
+ // Red only once delivery has actually stopped. A plugin whose endpoint
+ // blipped twice is worth mentioning, not worth alarming about — and a
+ // banner that is always red stops being read.
+ tripped
+ ? "border-destructive/40 bg-destructive/5 text-destructive"
+ : "border-surface-border text-muted-foreground",
+ )}
+ >
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ <div className="min-w-0 space-y-0.5">
+ <div className="font-medium">
+ {tripped
+ ? t(($) => $.plugins.hook_circuit_open)
+ : t(($) => $.plugins.hook_recent_failures, { count: summary.failures.length })}
+ </div>
+ {summary.lastError ? <div className="truncate">{summary.lastError}</div> : null}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/plugins/plugin-modal-surface.test.ts b/packages/views/plugins/plugin-modal-surface.test.ts
new file mode 100644
index 0000000000..49a9b09ca7
--- /dev/null
+++ b/packages/views/plugins/plugin-modal-surface.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { PluginInstallation } from "@multica/core/types";
+import { collectModalSurfaces, pluginModalKey } from "./plugin-modal-surface";
+
+// Canonical matrix for which surfaces become modal menu entries. The component
+// suite covers rendering; it does not re-run these cases.
+
+function installation(overrides: Partial<PluginInstallation> = {}): PluginInstallation {
+ return {
+ id: "install-1",
+ plugin_key: "com.example.one",
+ name: "Example",
+ version: "1.0.0",
+ source_url: "https://example.com/multica.plugin.json",
+ enabled: true,
+ granted_scopes: [],
+ config_schema: [],
+ config: {},
+ configured_secrets: [],
+ surfaces: [],
+ hooks: [],
+ resources: [],
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+}
+
+function surface(key: string, type: string) {
+ return { key, type, name: key, entry: "ui/main.js" };
+}
+
+describe("collectModalSurfaces", () => {
+ it("takes only modal surfaces, leaving panels to their own mount point", () => {
+ const targets = collectModalSurfaces([
+ installation({
+ surfaces: [surface("panel", "issue_panel"), surface("dialog", "modal"), surface("side", "sidebar_panel")],
+ }),
+ ]);
+ expect(targets.map((t) => t.surface.key)).toEqual(["dialog"]);
+ });
+
+ it("skips a disabled installation", () => {
+ expect(collectModalSurfaces([
+ installation({ enabled: false, surfaces: [surface("dialog", "modal")] }),
+ ])).toEqual([]);
+ });
+
+ // A dropped `enabled` field must read as off. Opening a third party's UI on a
+ // truthy check is the wrong direction to fail in.
+ it("treats a missing enabled flag as off", () => {
+ const withoutFlag = installation({ surfaces: [surface("dialog", "modal")] });
+ delete (withoutFlag as { enabled?: boolean }).enabled;
+ expect(collectModalSurfaces([withoutFlag])).toEqual([]);
+ });
+
+ it("keeps same-named surfaces from different plugins distinct", () => {
+ const targets = collectModalSurfaces([
+ installation({ id: "a", surfaces: [surface("dialog", "modal")] }),
+ installation({ id: "b", surfaces: [surface("dialog", "modal")] }),
+ ]);
+ expect(new Set(targets.map(pluginModalKey)).size).toBe(2);
+ });
+
+ it("survives an installation with no surfaces field", () => {
+ const bare = installation();
+ delete (bare as { surfaces?: unknown }).surfaces;
+ expect(collectModalSurfaces([bare])).toEqual([]);
+ });
+});
diff --git a/packages/views/plugins/plugin-modal-surface.tsx b/packages/views/plugins/plugin-modal-surface.tsx
new file mode 100644
index 0000000000..4f1c672137
--- /dev/null
+++ b/packages/views/plugins/plugin-modal-surface.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Plug } from "lucide-react";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { pluginInstallationsOptions } from "@multica/core/plugins";
+import type { PluginInstallation, PluginSurface } from "@multica/core/types";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { PluginSurfaceFrame } from "./plugin-surface-frame";
+
+/**
+ * The mount point for `modal` surfaces.
+ *
+ * A modal is the same sandboxed iframe as a panel — `allow-scripts` without
+ * `allow-same-origin`, host-generated srcdoc, CSP derived from the granted
+ * `net:` scopes — differing only in where it appears. What it is NOT is a way
+ * for a plugin to interrupt somebody: it opens because a person picked it from
+ * the issue menu, never on the plugin's own initiative.
+ */
+
+export interface PluginModalTarget {
+ installation: PluginInstallation;
+ surface: PluginSurface;
+}
+
+export function pluginModalKey(target: PluginModalTarget): string {
+ return `${target.installation.id}:${target.surface.key}`;
+}
+
+/**
+ * Collects modal surfaces from enabled installations.
+ *
+ * Exported for its own test: the filter is the product rule and belongs in one
+ * place rather than re-derived by each menu that offers these.
+ */
+export function collectModalSurfaces(installations: readonly PluginInstallation[]): PluginModalTarget[] {
+ const targets: PluginModalTarget[] = [];
+ for (const installation of installations) {
+ // Explicit === true: a backend that stops sending the field must read as
+ // off, not as truthy enough to open a third party's UI.
+ if (installation.enabled !== true) continue;
+ for (const surface of installation.surfaces ?? []) {
+ if (surface.type === "modal") targets.push({ installation, surface });
+ }
+ }
+ return targets;
+}
+
+export function usePluginModalSurfaces(): PluginModalTarget[] {
+ const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const { data } = useQuery({
+ ...pluginInstallationsOptions(wsId),
+ enabled: pluginsEnabled && wsId.length > 0,
+ });
+
+ return useMemo(
+ () => (pluginsEnabled ? collectModalSurfaces(data?.plugins ?? []) : []),
+ [data, pluginsEnabled],
+ );
+}
+
+interface PluginModalSurfaceProps {
+ target: PluginModalTarget | null;
+ issueId?: string;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function PluginModalSurface({ target, issueId, onOpenChange }: PluginModalSurfaceProps) {
+ if (!target) return null;
+ return (
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Plug className="size-4 text-muted-foreground" />
+ {target.surface.name}
+ </DialogTitle>
+ {/* Names the plugin, always. Someone looking at a dialog full of
+ third-party UI is entitled to know whose it is without guessing
+ from the styling. */}
+ <DialogDescription>{target.installation.name}</DialogDescription>
+ </DialogHeader>
+ <PluginSurfaceFrame
+ // Keyed on the issue as well as the surface: the frame carries the
+ // issue into its context call, and an unchanged document would not
+ // reload for a different one.
+ key={`${pluginModalKey(target)}:${issueId ?? ""}`}
+ installation={target.installation}
+ surface={target.surface}
+ issueId={issueId}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** Menu entries that open a modal, in the same shape the hook entries use. */
+export function PluginModalMenuItems({
+ issueId,
+ Item,
+}: {
+ issueId: string;
+ Item: React.ComponentType<{ onClick?: () => void; children?: React.ReactNode }>;
+}) {
+ const targets = usePluginModalSurfaces();
+ const [open, setOpen] = useState<PluginModalTarget | null>(null);
+
+ if (targets.length === 0) return null;
+
+ return (
+ <>
+ {targets.map((target) => (
+ <Item key={pluginModalKey(target)} onClick={() => setOpen(target)}>
+ <Plug className="h-3.5 w-3.5" />
+ <span className="truncate">{target.surface.name}</span>
+ <span className="ml-auto truncate pl-3 text-caption text-muted-foreground">
+ {target.installation.name}
+ </span>
+ </Item>
+ ))}
+ <PluginModalSurface target={open} issueId={issueId} onOpenChange={(next) => !next && setOpen(null)} />
+ </>
+ );
+}
diff --git a/packages/views/plugins/surface-bridge.ts b/packages/views/plugins/surface-bridge.ts
index 825b9d4d71..dd0d4f2303 100644
--- a/packages/views/plugins/surface-bridge.ts
+++ b/packages/views/plugins/surface-bridge.ts
@@ -32,6 +32,11 @@ const ALLOWED_PATHS: RegExp[] = [
/^\/issues\/[^/]+\/comments$/,
/^\/storage\/(workspace|user)$/,
/^\/storage\/(workspace|user)\/[^/]+$/,
+ // A surface invoking its OWN plugin's hook: the `ui` trigger. The server
+ // still checks the manifest declared it, and the installation is the one
+ // this bridge was created for — a surface cannot reach another plugin's
+ // hook by naming it here.
+ /^\/hooks\/[^/]+$/,
];
const MAX_RESIZE_PX = 4000;
diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsx
index d7e5690ede..13a2bc2a5c 100644
--- a/packages/views/settings/components/plugins-tab.tsx
+++ b/packages/views/settings/components/plugins-tab.tsx
@@ -29,6 +29,7 @@ import {
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Textarea } from "@multica/ui/components/ui/textarea";
import { Switch } from "@multica/ui/components/ui/switch";
+import { PluginHookActivity } from "../../plugins";
import { useT } from "../../i18n";
import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
@@ -352,6 +353,10 @@ function InstalledPlugin({
toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));
};
+ // Only rendered when a hook contributes one: a plugin with no hooks has no
+ // failing calls to report.
+ const hasHooks = (installation.hooks ?? []).length > 0;
+
const contributions = [
...installation.surfaces.map((surface) => `${surface.name} (${surface.type})`),
...installation.hooks.map((hook) => `${hook.name} (${hook.triggers.join(", ")})`),
@@ -361,6 +366,7 @@ function InstalledPlugin({
return (
<SettingsCard>
<div className="space-y-4 px-4 py-4">
+ {hasHooks ? <PluginHookActivity wsId={wsId} installationId={installation.id} /> : null}
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index c6a5f7f6c1..2b96705599 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -207,6 +207,8 @@ var concurrentIndexCleanups = map[string]string{
"357_webhook_delivery_replay_idempotency_index": "uq_webhook_delivery_replay_idempotency",
"358_autopilot_quota_reservation_state_index": "idx_autopilot_quota_reservation_state",
"361_issue_last_activity_index": "idx_issue_workspace_last_activity",
+ "363_plugin_invocation_installation_index": "idx_plugin_invocation_installation_created",
+ "364_plugin_invocation_created_at_index": "idx_plugin_invocation_created_at",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 781c9f2194..f246712b06 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1029,12 +1029,40 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Error("plugins: secretbox.New failed; Plugin secrets disabled", "error", err)
} else if h.PluginService != nil {
h.PluginService.Secrets = box
+ // The same deployment key, kept raw as well. Sealing and signing
+ // need different things from it: a secret config value is sealed
+ // and later opened, while a hook signature must be REPRODUCED on
+ // demand, which a box cannot do. Each installation's signing secret
+ // is derived from this rather than stored, so no row holds a usable
+ // one.
+ h.PluginService.DeploymentKey = pluginKey
slog.Info("Plugin secret encryption enabled")
}
} else {
slog.Info("Plugin secrets disabled (MULTICA_PLUGIN_SECRET_KEY not set)")
}
+ // Hook engine. Event-triggered hooks are dispatched off the bus onto a
+ // worker pool: Bus.Publish runs listeners inline on the publishing request's
+ // goroutine, so anything that dials a third-party endpoint from there would
+ // put an outside server on the critical path of creating an issue.
+ if h.PluginService != nil {
+ h.PluginService.Callbacks = service.NewCallbackTokens()
+ // Omitted rather than sent relative: a handler receiving
+ // "/api/v1/plugin" cannot call anything with it, and a broken absolute
+ // URL is harder to diagnose than an absent one.
+ if publicURL := strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")); publicURL != "" {
+ h.PluginService.CallbackBaseURL = strings.TrimSuffix(publicURL, "/") + "/api/v1/plugin"
+ } else {
+ slog.Warn("plugins: MULTICA_PUBLIC_URL is not set; hook callbacks will carry no callback_url")
+ }
+ // The flag reaches the event path only through the service: a worker has
+ // no request to read it from.
+ h.PluginService.FeatureFlags = h.FeatureFlags
+ pluginEvents := service.NewPluginEventDispatcher(h.PluginService)
+ service.SubscribePluginEvents(bus, pluginEvents)
+ }
+
if opts.HeartbeatScheduler != nil {
h.HeartbeatScheduler = opts.HeartbeatScheduler
}
@@ -1266,18 +1294,22 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
// Protected API routes
+ // Plugin Action API. Two kinds of caller reach these, and the difference is
+ // only in WHO the call acts as.
+ //
+ // A SURFACE has no credential: the iframe asks the host page over the
+ // postMessage bridge, and the host re-issues the call on the signed-in
+ // user's own session, naming the installation in a header the iframe cannot
+ // set for itself. That path goes through the ordinary Auth chain.
+ //
+ // A HOOK HANDLER — the plugin author's own server — has no session and
+ // never will, so it presents a plugin bearer token instead. PluginAuth
+ // routes that request past the session chain to the handler, which resolves
+ // the token itself; a request with neither credential is refused there.
+ //
+ // The workspace always comes from the installation, never from the client.
r.Group(func(r chi.Router) {
- r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))
- r.Use(middleware.RefreshCloudFrontCookies(cfSigner))
-
- // Plugin Action API. Called by the HOST PAGE on the signed-in user's
- // session after a surface asks for something over the postMessage
- // bridge — the iframe holds no credential and never reaches these
- // directly. Which installation is speaking arrives in a header the
- // host sets; the workspace is derived from that installation rather
- // than trusted from the client, and membership is then checked
- // against it. Sits in the user-scoped group for that reason: there is
- // no workspace in the path to gate on.
+ r.Use(middleware.PluginAuth(middleware.Auth(queries, patCache, cloudPATVerifier)))
r.Route("/api/v1/plugin", func(r chi.Router) {
r.Get("/context", h.GetPluginContext)
r.Get("/issues/{id}", h.GetPluginIssue)
@@ -1288,8 +1320,24 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/storage/{scope}/{key}", h.GetPluginStorage)
r.Put("/storage/{scope}/{key}", h.PutPluginStorage)
r.Delete("/storage/{scope}/{key}", h.DeletePluginStorage)
+ // ui / manual only. `event` is dispatched by the host off the event
+ // bus and never requested; `agent` arrives over MCP in PR 4.
+ r.Post("/hooks/{key}", h.InvokePluginHook)
})
+ })
+
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))
+ r.Use(middleware.RefreshCloudFrontCookies(cfSigner))
+ // Plugin Action API. Called by the HOST PAGE on the signed-in user's
+ // session after a surface asks for something over the postMessage
+ // bridge — the iframe holds no credential and never reaches these
+ // directly. Which installation is speaking arrives in a header the
+ // host sets; the workspace is derived from that installation rather
+ // than trusted from the client, and membership is then checked
+ // against it. Sits in the user-scoped group for that reason: there is
+ // no workspace in the path to gate on.
// --- User-scoped routes (no workspace context required) ---
r.Get("/api/me", h.GetMe)
r.Patch("/api/me", h.UpdateMe)
@@ -1395,6 +1443,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// show before an installation exists.
r.Post("/plugins/preview", h.PreviewPlugin)
r.Post("/plugins", h.InstallPlugin)
+ r.Get("/plugins/{installationId}/invocations", h.ListPluginInvocations)
+ r.Post("/plugins/{installationId}/token", h.RotatePluginToken)
+ r.Delete("/plugins/{installationId}/token", h.RevokePluginToken)
r.Put("/plugins/{installationId}/config", h.ConfigurePlugin)
r.Post("/plugins/{installationId}/enable", h.EnablePlugin)
r.Post("/plugins/{installationId}/disable", h.DisablePlugin)
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 02bf054d0b..11d8324b74 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -4,8 +4,11 @@ import (
"encoding/json"
"net/http"
+ "strings"
+
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -26,31 +29,73 @@ import (
// someone do what they could not already do themselves. One and two are what
// bound the plugin below that ceiling.
//
-// There is no plugin credential anywhere in this file. The iframe holds no
-// token; it posts a message to the host page, and the host re-issues the call
-// on the user's own session. That is why these routes sit under the normal
-// authenticated group and read the installation from a header the iframe
-// cannot set for itself.
+// A SURFACE still holds no credential. The iframe posts a message to the host
+// page, and the host re-issues the call on the user's own session, reading the
+// installation from a header the iframe cannot set for itself.
+//
+// Hooks add a second kind of caller: a plugin's own server, which has no
+// session and never will. It presents a bearer token instead, and that changes
+// only WHO the call acts as — the three checks above are the same either way.
+// See pluginActor for how identity is decided.
const pluginInstallationHeader = "X-Multica-Plugin-Installation"
+// pluginActor is who a call acts as, and it is decided by how the caller
+// authenticated rather than by anything the caller asks for.
+//
+// session, or a callback token from a ui/manual hook
+// -> the person. Writes are theirs, marked with via_plugin_id.
+// install token, or a callback token from an event hook
+// -> the installation. Writes are the plugin's own.
+//
+// The second case is why author_type gained a 'plugin' value: an event hook has
+// no person behind it, and attributing its writes to the last member who
+// happened to touch the issue would be a lie that the audit trail cannot undo.
+type pluginActor struct {
+ Type string
+ // Member is present only when Type is "member". A plugin-actor call has no
+ // member row to check permissions against, which is exactly why the
+ // endpoints that need one refuse it.
+ Member db.Member
+}
+
+func (a pluginActor) isMember() bool { return a.Type == "member" }
+
+// requireMember refuses an endpoint that has no meaning without a person.
+func (a pluginActor) requireMember(w http.ResponseWriter) bool {
+ if a.isMember() {
+ return true
+ }
+ writeError(w, http.StatusForbidden, "this endpoint requires a user; the presented token acts as the Plugin itself")
+ return false
+}
+
// pluginCaller runs checks 1 and 2 and returns the authorized caller.
-func (h *Handler) pluginCaller(w http.ResponseWriter, r *http.Request, scope string) (service.PluginActionCaller, db.Member, bool) {
+func (h *Handler) pluginCaller(w http.ResponseWriter, r *http.Request, scope string) (service.PluginActionCaller, pluginActor, bool) {
if !h.requirePluginsV1(w, r) {
- return service.PluginActionCaller{}, db.Member{}, false
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ if token := middleware.BearerToken(r); middleware.IsPluginBearerToken(token) {
+ return h.pluginTokenCaller(w, r, token, scope)
}
+ return h.pluginSessionCaller(w, r, scope)
+}
+
+// pluginSessionCaller is the surface path, unchanged: a real signed-in user
+// whose own permissions bound everything the plugin can reach.
+func (h *Handler) pluginSessionCaller(w http.ResponseWriter, r *http.Request, scope string) (service.PluginActionCaller, pluginActor, bool) {
userID, ok := requireUserID(w, r)
if !ok {
- return service.PluginActionCaller{}, db.Member{}, false
+ return service.PluginActionCaller{}, pluginActor{}, false
}
parsedUserID, ok := parseUUIDOrBadRequest(w, userID, "user_id")
if !ok {
- return service.PluginActionCaller{}, db.Member{}, false
+ return service.PluginActionCaller{}, pluginActor{}, false
}
caller, err := h.PluginService.AuthorizePluginAction(r.Context(), r.Header.Get(pluginInstallationHeader), parsedUserID, scope)
if err != nil {
writePluginError(w, err, "failed to authorize the Plugin call")
- return service.PluginActionCaller{}, db.Member{}, false
+ return service.PluginActionCaller{}, pluginActor{}, false
}
// The workspace comes from the installation, never from a client header:
@@ -58,9 +103,70 @@ func (h *Handler) pluginCaller(w http.ResponseWriter, r *http.Request, scope str
// installed in. Membership is then checked against that workspace.
member, ok := h.requireWorkspaceMember(w, r, uuidToString(caller.WorkspaceID), "workspace not found")
if !ok {
- return service.PluginActionCaller{}, db.Member{}, false
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ return caller, pluginActor{Type: "member", Member: member}, true
+}
+
+// pluginTokenCaller is the hook path: a plugin's own server calling in.
+//
+// A callback token is scoped to one INVOCATION, lives for minutes, and carries
+// the actor decided when the hook went out — so a ui-triggered hook writes back
+// as the person who pressed the button and cannot elect to write as anyone
+// else. An install token is standing access and always acts as the plugin.
+func (h *Handler) pluginTokenCaller(w http.ResponseWriter, r *http.Request, token, scope string) (service.PluginActionCaller, pluginActor, bool) {
+ var installationID pgtype.UUID
+ actor := pluginActor{Type: "plugin"}
+ var memberUserID pgtype.UUID
+ var issueScope pgtype.UUID
+
+ switch {
+ case strings.HasPrefix(token, "mpc_"):
+ if h.PluginService.Callbacks == nil {
+ writeError(w, http.StatusForbidden, "callback tokens are not enabled")
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ grant, err := h.PluginService.Callbacks.Resolve(token)
+ if err != nil {
+ writePluginError(w, err, "failed to authorize the Plugin call")
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ installationID = grant.InstallationID
+ issueScope = grant.IssueID
+ if grant.Actor.Type == "member" {
+ memberUserID = grant.Actor.ID
+ }
+ default:
+ installation, err := h.PluginService.AuthenticateInstallToken(r.Context(), token)
+ if err != nil {
+ writePluginError(w, err, "failed to authorize the Plugin call")
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ installationID = installation.ID
+ }
+
+ caller, err := h.PluginService.AuthorizePluginAction(r.Context(), uuidToString(installationID), memberUserID, scope)
+ if err != nil {
+ writePluginError(w, err, "failed to authorize the Plugin call")
+ return service.PluginActionCaller{}, pluginActor{}, false
}
- return caller, member, true
+
+ // The grant said which issue it was about. Carrying it here is what turns
+ // that from a comment into a check — see pluginIssueForUser.
+ caller.IssueScope = issueScope
+
+ // A callback token that stands for a person is only as good as that
+ // person's membership TODAY. Re-checking here means revoking someone's
+ // access takes effect on a token already in flight.
+ if memberUserID.Valid {
+ member, err := h.getWorkspaceMember(r.Context(), uuidToString(memberUserID), uuidToString(caller.WorkspaceID))
+ if err != nil {
+ writeError(w, http.StatusForbidden, "the user this callback acts for is no longer a member")
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
+ actor = pluginActor{Type: "member", Member: member}
+ }
+ return caller, actor, true
}
// pluginIssueForUser is check 3. The workspace comes from the installation, not
@@ -74,13 +180,37 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, cal
writeError(w, http.StatusNotFound, "issue not found")
return db.Issue{}, false
}
+ // Resolve first, then compare ids: a caller may name an issue by identifier
+ // (PLUG-12) or by uuid, and comparing raw strings would let the same issue
+ // pass under one spelling and fail under the other.
+ issue, ok := h.resolvePluginIssue(r, caller, issueID)
+ if !ok {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return db.Issue{}, false
+ }
+ // A callback grant issued about one issue reaches only that issue. Without
+ // this the grant is worth every issue in the workspace its actor can see,
+ // for the whole five minutes it lives.
+ //
+ // 404 rather than 403: the caller may well be able to see this issue by
+ // other means, and "you are scoped elsewhere" would confirm the id exists.
+ if caller.IssueScope.Valid && uuidToString(issue.ID) != uuidToString(caller.IssueScope) {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return db.Issue{}, false
+ }
+ return issue, true
+}
+
+// resolvePluginIssue finds an issue inside the caller's workspace, by
+// identifier or by uuid. Membership in that workspace was established by
+// pluginCaller, so this is exactly the reach the caller already has.
+func (h *Handler) resolvePluginIssue(r *http.Request, caller service.PluginActionCaller, issueID string) (db.Issue, bool) {
workspaceID := uuidToString(caller.WorkspaceID)
if issue, ok := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {
return issue, true
}
parsed, err := util.ParseUUID(issueID)
if err != nil {
- writeError(w, http.StatusNotFound, "issue not found")
return db.Issue{}, false
}
issue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
@@ -88,7 +218,6 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, cal
WorkspaceID: caller.WorkspaceID,
})
if err != nil {
- writeError(w, http.StatusNotFound, "issue not found")
return db.Issue{}, false
}
return issue, true
@@ -97,7 +226,7 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, cal
// GetPluginContext — GET /api/v1/plugin/context
func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {
// No scope: this is the page the user is already looking at.
- caller, member, ok := h.pluginCaller(w, r, "")
+ caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
return
}
@@ -106,10 +235,16 @@ func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to load the workspace")
return
}
- user, err := h.Queries.GetUser(r.Context(), member.UserID)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to load the user")
- return
+ // A plugin-actor call has no user to describe, and the payload says so
+ // rather than presenting an empty one that a handler might read as real.
+ var user *db.User
+ if actor.isMember() {
+ loaded, err := h.Queries.GetUser(r.Context(), actor.Member.UserID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load the user")
+ return
+ }
+ user = &loaded
}
var issue *db.Issue
@@ -273,7 +408,7 @@ type createPluginCommentRequest struct {
// to click a button in. Plugins that want to start work will get an explicit
// hook for it rather than inheriting it as a side effect of posting text.
func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
- caller, member, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsWrite)
+ caller, actor, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsWrite)
if !ok {
return
}
@@ -313,11 +448,23 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
rootComment = &parent
}
+ // Authorship follows the actor, and the actor was decided by how the caller
+ // authenticated — not by anything in this request body. A person behind the
+ // call keeps their own name on the comment (via_plugin_id records that a
+ // plugin produced it); an event hook writes as the installation, because
+ // there is nobody to attribute it to.
+ authorType := "member"
+ authorID := actor.Member.UserID
+ if !actor.isMember() {
+ authorType = "plugin"
+ authorID = caller.Installation.ID
+ }
+
createdComment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: caller.WorkspaceID,
- AuthorType: "member",
- AuthorID: member.UserID,
+ AuthorType: authorType,
+ AuthorID: authorID,
Content: content,
Type: "comment",
ParentID: parentID,
@@ -334,7 +481,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
// reply into a resolved thread without re-opening it — a comment that lands
// as the user should behave like the user's, minus only what was refused on
// purpose (mention dispatch).
- h.publish(protocol.EventCommentCreated, uuidToString(caller.WorkspaceID), "member", uuidToString(member.UserID), map[string]any{
+ h.publish(protocol.EventCommentCreated, uuidToString(caller.WorkspaceID), authorType, uuidToString(authorID), map[string]any{
"comment": commentToResponse(comment, nil, nil),
"issue_title": issue.Title,
"issue_assignee_type": textToPtr(issue.AssigneeType),
@@ -342,7 +489,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
"issue_status": issue.Status,
})
if rootComment != nil {
- h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(caller.WorkspaceID), "member", uuidToString(member.UserID))
+ h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(caller.WorkspaceID), authorType, uuidToString(authorID))
}
writeJSON(w, http.StatusCreated, pluginCommentResponse{
@@ -366,7 +513,7 @@ const maxPluginCommentsPerRead = 200
// --- Storage ---
-func (h *Handler) pluginStorageScope(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, member db.Member) (string, pgtype.UUID, bool) {
+func (h *Handler) pluginStorageScope(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, actor pluginActor) (string, pgtype.UUID, bool) {
scopeType := chi.URLParam(r, "scope")
required := plugincontract.ScopeStorageWorkspace
if scopeType == service.PluginStorageUser {
@@ -376,7 +523,13 @@ func (h *Handler) pluginStorageScope(w http.ResponseWriter, r *http.Request, cal
writeError(w, http.StatusForbidden, "this Plugin was not granted the "+required+" scope")
return "", pgtype.UUID{}, false
}
- scopeID, err := service.ResolveStorageScope(scopeType, caller.WorkspaceID, member.UserID)
+ // storage:user is per-member state, so a caller with no member has no such
+ // scope to resolve. Falling through would key every plugin-actor write to
+ // the zero UUID — one shared bucket masquerading as somebody's private one.
+ if scopeType == service.PluginStorageUser && !actor.requireMember(w) {
+ return "", pgtype.UUID{}, false
+ }
+ scopeID, err := service.ResolveStorageScope(scopeType, caller.WorkspaceID, actor.Member.UserID)
if err != nil {
writePluginError(w, err, "invalid storage scope")
return "", pgtype.UUID{}, false
@@ -395,11 +548,11 @@ func hasGrantedScope(scopes []string, want string) bool {
// ListPluginStorage — GET /api/v1/plugin/storage/{scope}
func (h *Handler) ListPluginStorage(w http.ResponseWriter, r *http.Request) {
- caller, member, ok := h.pluginCaller(w, r, "")
+ caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
return
}
- scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)
+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, actor)
if !ok {
return
}
@@ -413,11 +566,11 @@ func (h *Handler) ListPluginStorage(w http.ResponseWriter, r *http.Request) {
// GetPluginStorage — GET /api/v1/plugin/storage/{scope}/{key}
func (h *Handler) GetPluginStorage(w http.ResponseWriter, r *http.Request) {
- caller, member, ok := h.pluginCaller(w, r, "")
+ caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
return
}
- scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)
+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, actor)
if !ok {
return
}
@@ -435,11 +588,11 @@ type putPluginStorageRequest struct {
// PutPluginStorage — PUT /api/v1/plugin/storage/{scope}/{key}
func (h *Handler) PutPluginStorage(w http.ResponseWriter, r *http.Request) {
- caller, member, ok := h.pluginCaller(w, r, "")
+ caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
return
}
- scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)
+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, actor)
if !ok {
return
}
@@ -457,11 +610,11 @@ func (h *Handler) PutPluginStorage(w http.ResponseWriter, r *http.Request) {
// DeletePluginStorage — DELETE /api/v1/plugin/storage/{scope}/{key}
func (h *Handler) DeletePluginStorage(w http.ResponseWriter, r *http.Request) {
- caller, member, ok := h.pluginCaller(w, r, "")
+ caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
return
}
- scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)
+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, actor)
if !ok {
return
}
diff --git a/server/internal/handler/plugin_callback_test.go b/server/internal/handler/plugin_callback_test.go
new file mode 100644
index 0000000000..6961f9fb70
--- /dev/null
+++ b/server/internal/handler/plugin_callback_test.go
@@ -0,0 +1,302 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// The identity model, exercised through the path that actually decides it.
+//
+// A hook handler calls back with a token, and the token — not the request body,
+// not a header — says who the resulting writes belong to. This is the whole
+// reason the callback token exists instead of handing a plugin's server the
+// install token and trusting it to say who it is acting for.
+
+func callbackRequest(token, method, path string, body any, params map[string]string) *http.Request {
+ var payload []byte
+ if body != nil {
+ payload, _ = json.Marshal(body)
+ }
+ request := httptest.NewRequest(method, path, bytes.NewReader(payload))
+ request.Header.Set("Content-Type", "application/json")
+ // No X-User-ID: a plugin's own server has no session. The token is the
+ // entire credential, which is what these tests are about.
+ request.Header.Set("Authorization", "Bearer "+token)
+ routeContext := chi.NewRouteContext()
+ for key, value := range params {
+ routeContext.URLParams.Add(key, value)
+ }
+ return request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))
+}
+
+func issueCallbackToken(t *testing.T, installationID string, actor service.HookActor) string {
+ t.Helper()
+ installation, err := testHandler.PluginService.InstallationForWorkspace(
+ context.Background(), parseUUID(testWorkspaceID), installationID)
+ if err != nil {
+ t.Fatalf("load installation: %v", err)
+ }
+ token, err := testHandler.PluginService.Callbacks.Issue(context.Background(), service.HookInvocation{
+ Installation: installation,
+ Hook: plugincontract.Hook{Key: "summarize"},
+ Trigger: plugincontract.TriggerManual,
+ Actor: actor,
+ })
+ if err != nil {
+ t.Fatalf("issue callback token: %v", err)
+ }
+ return token
+}
+
+func withCallbackTokens(t *testing.T) {
+ t.Helper()
+ previous := testHandler.PluginService.Callbacks
+ testHandler.PluginService.Callbacks = service.NewCallbackTokens()
+ t.Cleanup(func() { testHandler.PluginService.Callbacks = previous })
+}
+
+// A ui/manual hook ran because a person asked. Its writes stay that person's,
+// with via_plugin_id recording that a plugin produced them — permission-wise
+// the write is the user's, audit-wise it stays traceable to the plugin.
+func TestCallbackFromAUserTriggeredHookWritesAsTheUser(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+ issueID := createTestIssue(t, "Callback attribution member", "todo", "none")
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
+ recorder := httptest.NewRecorder()
+ testHandler.CreatePluginComment(recorder, callbackRequest(token, http.MethodPost,
+ "/api/v1/plugin/issues/"+issueID+"/comments",
+ map[string]any{"content": "posted by a manual hook"},
+ map[string]string{"id": issueID}))
+ if recorder.Code != http.StatusCreated {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+
+ comment := latestComment(t, issueID)
+ if comment.AuthorType != "member" {
+ t.Fatalf("author_type = %q, want member: a hook the user triggered must stay attributed to them", comment.AuthorType)
+ }
+ if uuidToString(comment.AuthorID) != testUserID {
+ t.Fatalf("author_id = %s, want the triggering user %s", uuidToString(comment.AuthorID), testUserID)
+ }
+ if uuidToString(comment.ViaPluginID) != installationID {
+ t.Fatalf("via_plugin_id = %s, want %s: the plugin must stay traceable", uuidToString(comment.ViaPluginID), installationID)
+ }
+}
+
+// An event hook has nobody behind it. Attributing its writes to the last member
+// who happened to touch the issue would be a lie the audit trail cannot undo.
+func TestCallbackFromAnEventHookWritesAsThePlugin(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+ issueID := createTestIssue(t, "Callback attribution plugin", "todo", "none")
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
+ recorder := httptest.NewRecorder()
+ testHandler.CreatePluginComment(recorder, callbackRequest(token, http.MethodPost,
+ "/api/v1/plugin/issues/"+issueID+"/comments",
+ map[string]any{"content": "posted by an event hook"},
+ map[string]string{"id": issueID}))
+ if recorder.Code != http.StatusCreated {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+
+ comment := latestComment(t, issueID)
+ if comment.AuthorType != "plugin" {
+ t.Fatalf("author_type = %q, want plugin: an event hook must not borrow a person's identity", comment.AuthorType)
+ }
+ if uuidToString(comment.AuthorID) != installationID {
+ t.Fatalf("author_id = %s, want the installation %s", uuidToString(comment.AuthorID), installationID)
+ }
+}
+
+// A grant is good for the whole invocation, not one request. A handler that
+// reads an issue and then comments on it makes two calls, and the single-use
+// version of this refused the second — the failure a live run surfaced.
+func TestCallbackTokenServesTheWholeInvocation(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+ issueID := createTestIssue(t, "Callback single use", "todo", "none")
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
+ first := httptest.NewRecorder()
+ testHandler.GetPluginIssue(first, callbackRequest(token, http.MethodGet,
+ "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ if first.Code != http.StatusOK {
+ t.Fatalf("first use: status=%d body=%s", first.Code, first.Body.String())
+ }
+
+ // The read-then-write shape every non-trivial handler has.
+ second := httptest.NewRecorder()
+ testHandler.CreatePluginComment(second, callbackRequest(token, http.MethodPost,
+ "/api/v1/plugin/issues/"+issueID+"/comments",
+ map[string]any{"content": "and now a comment about what I read"},
+ map[string]string{"id": issueID}))
+ if second.Code != http.StatusCreated {
+ t.Fatalf("a handler must be able to write after reading: status=%d body=%s", second.Code, second.Body.String())
+ }
+
+ // Revoked once the invocation is over.
+ testHandler.PluginService.Callbacks.Revoke(token)
+ third := httptest.NewRecorder()
+ testHandler.GetPluginIssue(third, callbackRequest(token, http.MethodGet,
+ "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ if third.Code != http.StatusForbidden {
+ t.Fatalf("a revoked grant must be refused: status=%d body=%s", third.Code, third.Body.String())
+ }
+}
+
+// storage:user is per-member state. A caller with no member has no such scope
+// to resolve, and falling through would key every plugin-actor write to the
+// zero UUID — one shared bucket masquerading as somebody's private one.
+func TestPluginActorCannotReachUserStorage(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installPluginForAction(t, []string{"issues:read", "comments:write", "storage:user"})
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
+ recorder := httptest.NewRecorder()
+ testHandler.PutPluginStorage(recorder, callbackRequest(token, http.MethodPut,
+ "/api/v1/plugin/storage/user/pref",
+ map[string]any{"value": "x"},
+ map[string]string{"scope": "user", "key": "pref"}))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s, want 403", recorder.Code, recorder.Body.String())
+ }
+}
+
+// /context has no scope requirement, but it must not invent a user for a caller
+// that has none — a handler reading `user` would believe it is acting for
+// somebody.
+func TestPluginContextOmitsTheUserForAPluginActor(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
+ recorder := httptest.NewRecorder()
+ testHandler.GetPluginContext(recorder, callbackRequest(token, http.MethodGet, "/api/v1/plugin/context", nil, nil))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode context: %v", err)
+ }
+ if _, present := payload["user"]; present {
+ t.Fatalf("context carried a user for a plugin actor: %s", recorder.Body.String())
+ }
+ if payload["actor"] != "plugin" {
+ t.Fatalf("actor = %v, want plugin", payload["actor"])
+ }
+}
+
+// latestComment reads the row directly. The response body reports what the
+// handler decided to return; the row is what was actually written, and
+// attribution is only meaningful as stored.
+func latestComment(t *testing.T, issueID string) db.Comment {
+ t.Helper()
+ var comment db.Comment
+ err := testPool.QueryRow(context.Background(),
+ `SELECT id, author_type, author_id, via_plugin_id FROM comment WHERE issue_id = $1 ORDER BY created_at DESC LIMIT 1`,
+ issueID,
+ ).Scan(&comment.ID, &comment.AuthorType, &comment.AuthorID, &comment.ViaPluginID)
+ if err != nil {
+ t.Fatalf("read the written comment: %v", err)
+ }
+ return comment
+}
+
+// The narrowing that was only a comment until Fabel 5's review.
+//
+// A hook called about one issue has no business reaching another. Without this
+// check the grant was worth every issue in the workspace its actor could see,
+// for the whole five minutes it lived — and both the type's doc comment and the
+// PR description claimed otherwise.
+func TestCallbackTokenCannotReachAnotherIssue(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+ granted := createTestIssue(t, "Callback scope granted issue", "todo", "none")
+ other := createTestIssue(t, "Callback scope other issue", "todo", "none")
+
+ installation, err := testHandler.PluginService.InstallationForWorkspace(
+ context.Background(), parseUUID(testWorkspaceID), installationID)
+ if err != nil {
+ t.Fatalf("load installation: %v", err)
+ }
+ token, err := testHandler.PluginService.Callbacks.Issue(context.Background(), service.HookInvocation{
+ Installation: installation,
+ Hook: plugincontract.Hook{Key: "summarize"},
+ Trigger: plugincontract.TriggerManual,
+ Actor: service.HookActor{Type: "member", ID: parseUUID(testUserID)},
+ IssueID: parseUUID(granted),
+ })
+ if err != nil {
+ t.Fatalf("issue callback token: %v", err)
+ }
+
+ // The issue it was issued for: allowed.
+ ok := httptest.NewRecorder()
+ testHandler.GetPluginIssue(ok, callbackRequest(token, http.MethodGet,
+ "/api/v1/plugin/issues/"+granted, nil, map[string]string{"id": granted}))
+ if ok.Code != http.StatusOK {
+ t.Fatalf("the granted issue must be reachable: status=%d body=%s", ok.Code, ok.Body.String())
+ }
+
+ // Any other issue in the same workspace: refused, on both read and write.
+ refusedRead := httptest.NewRecorder()
+ testHandler.GetPluginIssue(refusedRead, callbackRequest(token, http.MethodGet,
+ "/api/v1/plugin/issues/"+other, nil, map[string]string{"id": other}))
+ if refusedRead.Code != http.StatusNotFound {
+ t.Fatalf("reading another issue must be refused: status=%d body=%s", refusedRead.Code, refusedRead.Body.String())
+ }
+
+ refusedWrite := httptest.NewRecorder()
+ testHandler.CreatePluginComment(refusedWrite, callbackRequest(token, http.MethodPost,
+ "/api/v1/plugin/issues/"+other+"/comments",
+ map[string]any{"content": "should never land"},
+ map[string]string{"id": other}))
+ if refusedWrite.Code != http.StatusNotFound {
+ t.Fatalf("commenting on another issue must be refused: status=%d body=%s", refusedWrite.Code, refusedWrite.Body.String())
+ }
+}
+
+// An invocation with no issue produces an unscoped grant. That is not a hole —
+// it simply means there was no issue to narrow to — and the workspace and
+// membership checks still apply.
+func TestCallbackTokenWithoutAnIssueIsNotNarrowed(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ withCallbackTokens(t)
+ installationID := installHookPlugin(t)
+ issueID := createTestIssue(t, "Callback unscoped grant", "todo", "none")
+
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
+ recorder := httptest.NewRecorder()
+ testHandler.GetPluginIssue(recorder, callbackRequest(token, http.MethodGet,
+ "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("an unscoped grant must still reach the workspace: status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
diff --git a/server/internal/handler/plugin_hook.go b/server/internal/handler/plugin_hook.go
new file mode 100644
index 0000000000..05e27668f1
--- /dev/null
+++ b/server/internal/handler/plugin_hook.go
@@ -0,0 +1,200 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// Hook invocation from a person: a button inside a surface (`ui`) or an entry in
+// the issue actions menu and command palette (`manual`).
+//
+// Both block — but only this request. A person is waiting for an answer they
+// asked for, so returning immediately would mean returning nothing useful. What
+// must never block is the host's own work, and that is the `event` trigger,
+// which does not come through here at all: it is dispatched off the event bus
+// onto a worker pool and no request ever waits for it.
+
+type invokePluginHookRequest struct {
+ // Trigger is which declared call site this is. The client says which one it
+ // is using, and the server checks the manifest declared it — a client
+ // cannot invent a trigger to reach a hook that never offered it.
+ Trigger string `json:"trigger"`
+ IssueID string `json:"issue_id,omitempty"`
+ Input json.RawMessage `json:"input,omitempty"`
+}
+
+// InvokePluginHook — POST /api/v1/plugin/hooks/{key}
+func (h *Handler) InvokePluginHook(w http.ResponseWriter, r *http.Request) {
+ // No scope of its own: a hook is the plugin's own capability, and what it
+ // may do on the way back is bounded by the installation's scopes when the
+ // callback token is redeemed.
+ caller, actor, ok := h.pluginCaller(w, r, "")
+ if !ok {
+ return
+ }
+ // A hook invoked from the UI is invoked BY somebody. A plugin's own server
+ // calling this would be asking us to call it back, which is a loop with no
+ // person in it and no reason to exist.
+ if !actor.requireMember(w) {
+ return
+ }
+
+ var req invokePluginHookRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ switch req.Trigger {
+ case plugincontract.TriggerUI, plugincontract.TriggerManual:
+ default:
+ // event is dispatched by the host, never asked for; agent arrives over
+ // MCP. Accepting either here would let a browser drive a call site that
+ // is supposed to have a different identity attached.
+ writeError(w, http.StatusBadRequest, "trigger must be ui or manual")
+ return
+ }
+
+ hook, err := service.FindHook(caller.Installation, chi.URLParam(r, "key"))
+ if err != nil {
+ writePluginError(w, err, "failed to load the hook")
+ return
+ }
+
+ invocation := service.HookInvocation{
+ Installation: caller.Installation,
+ Hook: hook,
+ Trigger: req.Trigger,
+ // The person who pressed it. Writes the handler makes with the callback
+ // token land as theirs, marked with via_plugin_id.
+ Actor: service.HookActor{Type: "member", ID: actor.Member.UserID},
+ Input: rawOrNil(req.Input),
+ }
+ if req.IssueID != "" {
+ issue, ok := h.pluginIssueForUser(w, r, caller, req.IssueID)
+ if !ok {
+ return
+ }
+ invocation.IssueID = issue.ID
+ }
+
+ result, err := h.PluginService.InvokeHook(r.Context(), invocation, 1)
+ if err != nil {
+ // The status matters to the person watching: "the admin did not grant
+ // this" and "the plugin author's server is down" are different problems
+ // with different owners, and a generic 500 hides which one it is.
+ writePluginError(w, err, "the hook call failed")
+ return
+ }
+ writeJSON(w, http.StatusOK, result)
+}
+
+// rawOrNil keeps an omitted input out of the request body entirely rather than
+// sending a literal null a handler has to special-case.
+func rawOrNil(raw json.RawMessage) any {
+ if len(raw) == 0 {
+ return nil
+ }
+ return raw
+}
+
+// --- Installation-scoped hook administration ---
+
+type pluginInvocationResponse struct {
+ ID string `json:"id"`
+ HookKey string `json:"hook_key"`
+ Trigger string `json:"trigger"`
+ Status string `json:"status"`
+ EventType *string `json:"event_type,omitempty"`
+ Attempt int `json:"attempt"`
+ LatencyMs int `json:"latency_ms"`
+ Error *string `json:"error,omitempty"`
+ CreatedAt string `json:"created_at"`
+}
+
+// ListPluginInvocations — GET /api/workspaces/{id}/plugins/{installationId}/invocations
+//
+// The triage view: why is this hook failing. Bodies were never stored, so this
+// answers "what happened and how often", not "what was sent".
+func (h *Handler) ListPluginInvocations(w http.ResponseWriter, r *http.Request) {
+ installation, ok := h.pluginInstallationFromURL(w, r)
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListPluginInvocations(r.Context(), db.ListPluginInvocationsParams{
+ InstallationID: installation.ID,
+ Limit: 100,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load the Plugin activity")
+ return
+ }
+ items := make([]pluginInvocationResponse, 0, len(rows))
+ for _, row := range rows {
+ item := pluginInvocationResponse{
+ ID: uuidToString(row.ID),
+ HookKey: row.HookKey,
+ Trigger: row.Trigger,
+ Status: row.Status,
+ Attempt: int(row.Attempt),
+ LatencyMs: int(row.LatencyMs),
+ CreatedAt: row.CreatedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00"),
+ }
+ if row.EventType.Valid {
+ value := row.EventType.String
+ item.EventType = &value
+ }
+ if row.Error.Valid {
+ value := row.Error.String
+ item.Error = &value
+ }
+ items = append(items, item)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"invocations": items})
+}
+
+type pluginTokenResponse struct {
+ // Token is returned exactly once, on the request that minted it. There is
+ // no read endpoint: an admin who loses it rotates rather than recovers.
+ Token string `json:"token"`
+ // SigningSecret is what the author configures on their own server to verify
+ // our signature. Derived from the deployment key rather than stored, so it
+ // is stable for an installation and reproducible without a database copy.
+ SigningSecret string `json:"signing_secret"`
+}
+
+// RotatePluginToken — POST /api/workspaces/{id}/plugins/{installationId}/token
+func (h *Handler) RotatePluginToken(w http.ResponseWriter, r *http.Request) {
+ installation, ok := h.pluginInstallationFromURL(w, r)
+ if !ok {
+ return
+ }
+ token, err := h.PluginService.IssueInstallToken(r.Context(), installation.ID)
+ if err != nil {
+ writePluginError(w, err, "failed to issue the Plugin token")
+ return
+ }
+ secret, err := h.PluginService.HookSigningSecret(installation.ID)
+ if err != nil {
+ writePluginError(w, err, "failed to derive the signing secret")
+ return
+ }
+ writeJSON(w, http.StatusOK, pluginTokenResponse{Token: token, SigningSecret: secret})
+}
+
+// RevokePluginToken — DELETE /api/workspaces/{id}/plugins/{installationId}/token
+func (h *Handler) RevokePluginToken(w http.ResponseWriter, r *http.Request) {
+ installation, ok := h.pluginInstallationFromURL(w, r)
+ if !ok {
+ return
+ }
+ if err := h.PluginService.RevokeInstallToken(r.Context(), installation.ID); err != nil {
+ writePluginError(w, err, "failed to revoke the Plugin token")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/server/internal/handler/plugin_hook_test.go b/server/internal/handler/plugin_hook_test.go
new file mode 100644
index 0000000000..93f47bb469
--- /dev/null
+++ b/server/internal/handler/plugin_hook_test.go
@@ -0,0 +1,339 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "github.com/multica-ai/multica/server/internal/service"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// hookHandlerTestManifest declares the three host-driven triggers. Its endpoint
+// is never reached in these tests — they cover the checks BEFORE the request
+// leaves, which is where a wrong answer is a security bug rather than a broken
+// integration. The wire format and signature are covered end-to-end against a
+// live server in internal/service.
+const hookHandlerTestManifest = `{
+ "manifest_version": 1,
+ "key": "com.example.hooked",
+ "name": "Hooked",
+ "version": "1.0.0",
+ "author": { "name": "example" },
+ "scopes": ["issues:read", "comments:write", "net:example.com"],
+ "contributes": {
+ "hooks": [{
+ "key": "summarize",
+ "name": "Summarize",
+ "description": "Compress the discussion.",
+ "triggers": ["ui", "manual", "event"],
+ "events": ["issue.created"],
+ "transport": { "type": "http", "url": "https://example.com/hooks/summarize" }
+ }, {
+ "key": "manual_only",
+ "name": "Manual only",
+ "description": "Only ever picked from a menu.",
+ "triggers": ["manual"],
+ "transport": { "type": "http", "url": "https://example.com/hooks/manual" }
+ }]
+ }
+}`
+
+func installHookPlugin(t *testing.T) string {
+ t.Helper()
+ source := withLocalPluginSource(t, hookHandlerTestManifest)
+ body, _ := json.Marshal(map[string]any{
+ "source_url": source,
+ "granted_scopes": []string{"issues:read", "comments:write", "net:example.com"},
+ })
+ recorder := httptest.NewRecorder()
+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))
+ if recorder.Code != http.StatusCreated {
+ t.Fatalf("install hook plugin: 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 invokeHookRequest(installationID, hookKey string, payload map[string]any) *http.Request {
+ body, _ := json.Marshal(payload)
+ request := httptest.NewRequest(http.MethodPost, "/api/v1/plugin/hooks/"+hookKey, bytes.NewReader(body))
+ request.Header.Set("X-User-ID", testUserID)
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set(pluginInstallationHeader, installationID)
+ routeContext := chi.NewRouteContext()
+ routeContext.URLParams.Add("key", hookKey)
+ return request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))
+}
+
+// `event` is dispatched by the host, off the event bus, precisely so that its
+// writes carry the plugin's identity rather than a person's. A browser asking
+// for one would be electing to run as somebody it is not.
+func TestInvokePluginHookRefusesHostDrivenTriggers(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+
+ for _, trigger := range []string{plugincontract.TriggerEvent, plugincontract.TriggerAgent, "", "nonsense"} {
+ recorder := httptest.NewRecorder()
+ testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "summarize", map[string]any{"trigger": trigger}))
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatalf("trigger %q: status=%d body=%s, want 400", trigger, recorder.Code, recorder.Body.String())
+ }
+ }
+}
+
+// A hook may only be reached through a trigger its own manifest declared, even
+// when the host supports that trigger in general.
+func TestInvokePluginHookRefusesTriggerTheManifestDidNotDeclare(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+
+ recorder := httptest.NewRecorder()
+ // manual_only declares manual, not ui.
+ testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "manual_only", map[string]any{"trigger": "ui"}))
+ if recorder.Code == http.StatusOK {
+ t.Fatalf("a hook was invoked through a trigger it never declared: %s", recorder.Body.String())
+ }
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s, want 403", recorder.Code, recorder.Body.String())
+ }
+}
+
+func TestInvokePluginHookRefusesUnknownHook(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+
+ recorder := httptest.NewRecorder()
+ testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "not_declared", map[string]any{"trigger": "manual"}))
+ if recorder.Code != http.StatusNotFound {
+ t.Fatalf("status=%d body=%s, want 404", recorder.Code, recorder.Body.String())
+ }
+}
+
+// The flag gates the hook endpoint like every other plugin route: fail closed,
+// not merely hidden from the UI.
+func TestInvokePluginHookRequiresTheFeatureFlag(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+
+ withPluginsV1Flag(t, testHandler, false)
+ recorder := httptest.NewRecorder()
+ testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "summarize", map[string]any{"trigger": "manual"}))
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status=%d body=%s, want 503", recorder.Code, recorder.Body.String())
+ }
+}
+
+// A disabled installation is off, not hidden. A stale tab must not keep
+// invoking hooks after an admin switches the plugin off.
+func TestInvokePluginHookRefusesDisabledInstallation(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+
+ disable := httptest.NewRecorder()
+ testHandler.DisablePlugin(disable, pluginHandlerRequest(http.MethodPost, "/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())
+ }
+
+ recorder := httptest.NewRecorder()
+ testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "summarize", map[string]any{"trigger": "manual"}))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s, want 403", recorder.Code, recorder.Body.String())
+ }
+}
+
+// The install token is returned once and stored only as a hash, so the same
+// token must never come back from a second rotation, and the old one must stop
+// working the moment a new one is issued.
+func TestRotatePluginTokenIssuesOnceAndInvalidatesThePrevious(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+ testHandler.PluginService.DeploymentKey = bytes.Repeat([]byte{9}, 32)
+ t.Cleanup(func() { testHandler.PluginService.DeploymentKey = nil })
+
+ first := rotateToken(t, installationID)
+ if first.Token == "" || first.SigningSecret == "" {
+ t.Fatalf("rotation returned nothing usable: %+v", first)
+ }
+
+ installation, err := testHandler.PluginService.AuthenticateInstallToken(context.Background(), first.Token)
+ if err != nil {
+ t.Fatalf("the freshly issued token must authenticate: %v", err)
+ }
+ if uuidToString(installation.ID) != installationID {
+ t.Fatalf("token resolved to the wrong installation: %s", uuidToString(installation.ID))
+ }
+
+ second := rotateToken(t, installationID)
+ if second.Token == first.Token {
+ t.Fatal("rotation reissued the same token")
+ }
+ if _, err := testHandler.PluginService.AuthenticateInstallToken(context.Background(), first.Token); err == nil {
+ t.Fatal("the previous token must stop working after a rotation")
+ }
+ // Derived from the deployment key and the installation, so it survives
+ // rotation — an author does not have to reconfigure their server every
+ // time an admin rotates the token.
+ if second.SigningSecret != first.SigningSecret {
+ t.Fatal("the signing secret must be stable across token rotations")
+ }
+}
+
+func TestRevokePluginTokenStopsAuthentication(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ installationID := installHookPlugin(t)
+ testHandler.PluginService.DeploymentKey = bytes.Repeat([]byte{9}, 32)
+ t.Cleanup(func() { testHandler.PluginService.DeploymentKey = nil })
+
+ issued := rotateToken(t, installationID)
+ recorder := httptest.NewRecorder()
+ testHandler.RevokePluginToken(recorder, pluginHandlerRequest(http.MethodDelete, "/token", nil, map[string]string{
+ "id": testWorkspaceID, "installationId": installationID,
+ }))
+ if recorder.Code != http.StatusNoContent {
+ t.Fatalf("revoke: status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ if _, err := testHandler.PluginService.AuthenticateInstallToken(context.Background(), issued.Token); err == nil {
+ t.Fatal("a revoked token must not authenticate")
+ }
+}
+
+// A garbage token must not resolve to some installation by accident — the
+// lookup is by hash, so an empty or malformed value must be refused before it
+// reaches the query.
+func TestAuthenticateInstallTokenRefusesMalformedValues(t *testing.T) {
+ for _, token := range []string{"", "mpi_", "not-a-token", "mpc_something", "Bearer mpi_x"} {
+ if _, err := testHandler.PluginService.AuthenticateInstallToken(context.Background(), token); err == nil {
+ t.Fatalf("token %q must not authenticate", token)
+ }
+ }
+}
+
+func rotateToken(t *testing.T, installationID string) pluginTokenResponse {
+ t.Helper()
+ recorder := httptest.NewRecorder()
+ testHandler.RotatePluginToken(recorder, pluginHandlerRequest(http.MethodPost, "/token", nil, map[string]string{
+ "id": testWorkspaceID, "installationId": installationID,
+ }))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("rotate: status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ var issued pluginTokenResponse
+ if err := json.Unmarshal(recorder.Body.Bytes(), &issued); err != nil {
+ t.Fatalf("decode token response: %v", err)
+ }
+ return issued
+}
+
+// The feature flag gates the EVENT path, observed where it matters: does a
+// request actually leave for the plugin's endpoint.
+//
+// Every other plugin surface is refused by a handler that can read the flag off
+// a request. An event hook has none — the dispatcher is subscribed at startup
+// and runs on a worker — so without a check inside it, turning plugins off
+// would hide the UI and refuse the Action API while the outbound calls kept
+// going. That is fail-open on the one path that reaches a third party.
+//
+// Needs a database because the dispatcher only calls anything when a real,
+// enabled installation declares an event hook.
+func TestEventDispatchRespectsTheFeatureFlagEndToEnd(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+
+ received := make(chan struct{}, 4)
+ endpoint := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ received <- struct{}{}
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true}`))
+ }))
+ t.Cleanup(endpoint.Close)
+
+ host := strings.Split(strings.TrimPrefix(endpoint.URL, "https://"), ":")[0]
+ manifest := strings.NewReplacer(
+ "https://example.com/hooks/summarize", endpoint.URL+"/hooks/summarize",
+ "https://example.com/hooks/manual", endpoint.URL+"/hooks/manual",
+ `"net:example.com"`, `"net:`+host+`"`,
+ ).Replace(hookHandlerTestManifest)
+
+ source := 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
+ previousClient := testHandler.PluginService.HookClient
+ previousFlags := testHandler.PluginService.FeatureFlags
+ previousKey := testHandler.PluginService.DeploymentKey
+ previousCallbacks := testHandler.PluginService.Callbacks
+ testHandler.PluginService.DevOrigins = []string{endpoint.URL}
+ testHandler.PluginService.HookClient = endpoint.Client()
+ // Without a deployment key there is nothing to sign with and the call is
+ // refused before it leaves — which would make this test pass for the wrong
+ // reason in the flag-off half.
+ testHandler.PluginService.DeploymentKey = bytes.Repeat([]byte{5}, 32)
+ testHandler.PluginService.Callbacks = service.NewCallbackTokens()
+ t.Cleanup(func() {
+ testHandler.PluginService.DevOrigins = previousOrigins
+ testHandler.PluginService.HookClient = previousClient
+ testHandler.PluginService.FeatureFlags = previousFlags
+ testHandler.PluginService.DeploymentKey = previousKey
+ testHandler.PluginService.Callbacks = previousCallbacks
+ })
+
+ body, _ := json.Marshal(map[string]any{
+ "source_url": source,
+ "granted_scopes": []string{"issues:read", "comments:write", "net:" + host},
+ })
+ install := httptest.NewRecorder()
+ testHandler.InstallPlugin(install, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))
+ if install.Code != http.StatusCreated {
+ t.Fatalf("install: status=%d body=%s", install.Code, install.Body.String())
+ }
+
+ dispatch := func() {
+ dispatcher := service.NewPluginEventDispatcher(testHandler.PluginService)
+ defer dispatcher.Close()
+ dispatcher.Dispatch(plugincontract.EventIssueCreated, testWorkspaceID, map[string]any{})
+ // Long enough for a worker to pick the job up and complete the call.
+ time.Sleep(2 * time.Second)
+ }
+
+ // Flag on: the endpoint is called.
+ testHandler.PluginService.FeatureFlags = testHandler.FeatureFlags
+ dispatch()
+ select {
+ case <-received:
+ default:
+ t.Fatal("with the flag on, an installed event hook was never called")
+ }
+
+ // Flag off: nothing leaves, even though the same installation is still
+ // enabled and still declares the hook.
+ withPluginsV1Flag(t, testHandler, false)
+ testHandler.PluginService.FeatureFlags = testHandler.FeatureFlags
+ dispatch()
+ select {
+ case <-received:
+ t.Fatal("with the flag off, an event hook still called out — the flag does not gate the outbound path")
+ default:
+ }
+}
diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.go
index e3a90a860e..d69ae66408 100644
--- a/server/internal/handler/plugin_test.go
+++ b/server/internal/handler/plugin_test.go
@@ -329,13 +329,22 @@ func TestPluginInstallRejectsMalformedManifest(t *testing.T) {
func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {
withPluginsV1Flag(t, testHandler, true)
cleanupPluginInstallations(t)
- // A hook is the contribution kind the host genuinely cannot run yet, so this
- // exercises the real shipped gate rather than a capability that happens to be
- // off today. Written against a still-gated kind on purpose: asserting on a
- // SHIPPED one turns every future capability flip into a test failure that
- // says nothing about the gate itself.
+ // Tests the WIRING — that install consults the capability gate and refuses
+ // what the host cannot run — against an explicitly narrowed host set rather
+ // than against whatever HostCapabilities happens to contain today.
+ //
+ // The earlier version picked a contribution kind that was unshipped at the
+ // time, so shipping it turned this red with a message about the flip instead
+ // 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)
- testHandler.PluginService.Host = plugincontract.HostCapabilities()
+ testHandler.PluginService.Host = plugincontract.Capabilities{
+ SurfaceTypes: map[string]bool{plugincontract.SurfaceIssuePanel: true},
+ HookTriggers: map[string]bool{},
+ HookTransport: map[string]bool{},
+ ResourceTypes: map[string]bool{},
+ }
body, _ := json.Marshal(map[string]any{
"source_url": source,
@@ -354,6 +363,28 @@ func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {
}
}
+// The gate must also let through what the host DOES ship, read from the real
+// set. Together with the test above this pins both directions: nothing
+// unrunnable installs, and nothing runnable is refused.
+func TestPluginInstallAcceptsEveryCapabilityThisHostShips(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
+ cleanupPluginInstallations(t)
+ source := withLocalPluginSource(t, hookOnlyTestManifest)
+ testHandler.PluginService.Host = plugincontract.HostCapabilities()
+
+ body, _ := json.Marshal(map[string]any{
+ "source_url": source,
+ "granted_scopes": []string{"issues:read", "net:example.com"},
+ })
+ recorder := httptest.NewRecorder()
+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))
+ // hookOnlyTestManifest declares ui + http, both shipped by the hook engine.
+ // If this starts failing, the gate is refusing something the host can run.
+ if recorder.Code != http.StatusCreated {
+ t.Fatalf("a manifest declaring only shipped capabilities was refused: status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
+
func TestPluginInstallAcceptsAShippedSurface(t *testing.T) {
withPluginsV1Flag(t, testHandler, true)
cleanupPluginInstallations(t)
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index b0972f3e00..e8d821521b 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -89,6 +89,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"personal_access_token": workspaceDeleteKeep,
"pinned_item": workspaceDelete,
"plugin_installation": workspaceDelete,
+ "plugin_invocation": workspaceDelete,
"plugin_storage": workspaceDelete,
"plugin_secret": workspaceDelete,
"project": workspaceDelete,
diff --git a/server/internal/middleware/plugin_auth.go b/server/internal/middleware/plugin_auth.go
new file mode 100644
index 0000000000..54f570acb5
--- /dev/null
+++ b/server/internal/middleware/plugin_auth.go
@@ -0,0 +1,58 @@
+package middleware
+
+import (
+ "net/http"
+ "strings"
+)
+
+// PluginAuth lets the Action API be reached two ways without weakening either.
+//
+// The original way is the only one a SURFACE has: no credential at all. The
+// iframe posts a message to the host page, the host re-issues the call on the
+// signed-in user's session, and this middleware sends it through the ordinary
+// Auth chain like any other request.
+//
+// Hooks add a second way. A plugin's own server has no session and never will,
+// so when it presents a plugin bearer token this middleware steps aside and
+// lets the handler resolve the token itself — which it must, because only the
+// handler knows which installation and which scopes that token stands for.
+//
+// Stepping aside is not the same as skipping authentication: every Action API
+// handler starts by resolving a caller, and a request that arrives with neither
+// a session nor a valid token fails there. What this avoids is the session
+// chain rejecting a token-bearing request before the handler can look at it.
+func PluginAuth(sessionAuth func(http.Handler) http.Handler) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ sessionProtected := sessionAuth(next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if IsPluginBearerToken(BearerToken(r)) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ sessionProtected.ServeHTTP(w, r)
+ })
+ }
+}
+
+// BearerToken pulls the raw credential out of an Authorization header.
+func BearerToken(r *http.Request) string {
+ header := strings.TrimSpace(r.Header.Get("Authorization"))
+ if header == "" {
+ return ""
+ }
+ const prefix = "Bearer "
+ if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
+ return ""
+ }
+ return strings.TrimSpace(header[len(prefix):])
+}
+
+// IsPluginBearerToken reports whether a credential is one of ours to resolve.
+//
+// Prefix-matched rather than validated: this only decides which code path gets
+// to look at the token, and an invalid token routed here is refused by the
+// handler a moment later. Deciding by prefix keeps a plugin token from being
+// tried against the PAT cache and a PAT from being tried against installations.
+func IsPluginBearerToken(token string) bool {
+ return strings.HasPrefix(token, "mpi_") || strings.HasPrefix(token, "mpc_")
+}
diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.go
index d5a5282dc9..a0eda41e30 100644
--- a/server/internal/service/plugin.go
+++ b/server/internal/service/plugin.go
@@ -2,10 +2,13 @@ package service
import (
"context"
+ "crypto/tls"
+ "crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
+ "log/slog"
"net/http"
"net/url"
"os"
@@ -19,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/internal/util/secretbox"
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"
)
@@ -46,16 +50,81 @@ type PluginService struct {
DevOrigins []string
// Host gates which declared contributions this build can actually run.
Host plugincontract.Capabilities
+ // DeploymentKey is the raw MULTICA_PLUGIN_SECRET_KEY, used to derive each
+ // installation's hook signing secret. Held separately from Secrets because
+ // signing needs a key it can reproduce, not a sealed box.
+ DeploymentKey []byte
+ // Callbacks issues the short-lived tokens a hook handler uses to call back.
+ // Nil means hooks go out without one.
+ Callbacks *CallbackTokens
+ // CallbackBaseURL is the Action API root a hook handler should call, sent
+ // alongside the callback token so a plugin does not hardcode our hostname.
+ CallbackBaseURL string
+ // FeatureFlags gates the hook engine. Held here because the EVENT path has
+ // no request to read the flag from: it runs on a worker, so the check has to
+ // live with the service rather than in a handler. Nil reads as disabled,
+ // which is the safe direction for the one path that reaches a third party.
+ FeatureFlags *featureflag.Service
+ // HookClient overrides the outbound client, and ONLY for an endpoint whose
+ // origin the operator already named in DevOrigins. Nil everywhere else, so
+ // a public endpoint always goes through the SSRF-guarded client and this
+ // field cannot widen what a deployment can reach.
+ HookClient *http.Client
}
func NewPluginService(queries *db.Queries, txStarter TxStarter) *PluginService {
- return &PluginService{
+ service := &PluginService{
Queries: queries,
TxStarter: txStarter,
LocalDir: strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_DIR")),
DevOrigins: parseDevOrigins(os.Getenv("MULTICA_PLUGIN_DEV_ORIGINS")),
Host: plugincontract.HostCapabilities(),
}
+ service.HookClient = devHookClient(service.DevOrigins, os.Getenv("MULTICA_PLUGIN_DEV_CA"))
+ return service
+}
+
+// devHookClient trusts an additional CA for dev-origin hook endpoints only.
+//
+// A hook URL must be HTTPS — the manifest requires it — so an author testing
+// against a local server needs its certificate trusted by something. This adds
+// a named CA file rather than turning verification off: the failure mode of
+// InsecureSkipVerify is that it survives into production behind a config flag
+// somebody forgot, and there is no way to tell from the code whether it is
+// active. A CA that has to be supplied by path cannot silently apply to
+// anything else.
+//
+// Nil unless BOTH an origin allowlist and a CA path are set, and it is only
+// ever consulted for an endpoint already inside that allowlist.
+func devHookClient(devOrigins []string, caPath string) *http.Client {
+ if len(devOrigins) == 0 || strings.TrimSpace(caPath) == "" {
+ return nil
+ }
+ pem, err := os.ReadFile(caPath)
+ if err != nil {
+ slog.Warn("plugins: MULTICA_PLUGIN_DEV_CA could not be read; dev hook endpoints will not be trusted", "path", caPath, "error", err)
+ return nil
+ }
+ pool := x509.NewCertPool()
+ if !pool.AppendCertsFromPEM(pem) {
+ slog.Warn("plugins: MULTICA_PLUGIN_DEV_CA contained no certificates", "path", caPath)
+ return nil
+ }
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}
+ slog.Info("plugins: dev hook endpoints will trust an additional CA", "path", caPath, "origins", devOrigins)
+ return &http.Client{
+ Timeout: 30 * time.Second,
+ Transport: transport,
+ // Refuse redirects, matching the secure client. A 302 from a dev
+ // endpoint would replay the SIGNED body and the callback token to
+ // wherever it pointed — the one destination check this path skipped is
+ // exactly the one a redirect would need.
+ CheckRedirect: func(*http.Request, []*http.Request) error {
+ return errors.New("hook endpoints must not redirect")
+ },
+ }
}
type PluginErrorKind string
@@ -694,6 +763,12 @@ func (s *PluginService) Uninstall(ctx context.Context, installation db.PluginIns
if err := queries.DeletePluginSecretsByInstallation(ctx, installation.ID); err != nil {
return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin secrets", Err: err}
}
+ // Hook records go too. They name an installation that is about to stop
+ // existing, and keeping them would leave rows nothing can attribute — the
+ // same reason storage and secrets are cleared here rather than swept later.
+ if err := queries.DeletePluginInvocationsByInstallation(ctx, installation.ID); err != nil {
+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin invocations", Err: err}
+ }
if err := queries.DeletePluginInstallation(ctx, installation.ID); err != nil {
return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin installation", Err: err}
}
diff --git a/server/internal/service/plugin_action.go b/server/internal/service/plugin_action.go
index 3f0e53271e..5757ff3866 100644
--- a/server/internal/service/plugin_action.go
+++ b/server/internal/service/plugin_action.go
@@ -25,6 +25,15 @@ type PluginActionCaller struct {
// Scopes is the consented set, read from the installation row rather than
// from the manifest the source URL serves today.
Scopes []string
+ // IssueScope, when set, is the ONLY issue this caller may touch.
+ //
+ // Set for a callback token issued against a specific issue. A hook called
+ // about one issue has no business reaching another: without this the grant
+ // is worth every issue in the workspace that its actor can see, for the
+ // whole five minutes it lives. Zero means unrestricted — a session caller,
+ // or an invocation that had no issue — and the ordinary workspace and
+ // membership checks still apply on top.
+ IssueScope pgtype.UUID
}
// AuthorizePluginAction performs the two checks that belong to the plugin: the
@@ -93,11 +102,17 @@ func parseInstallationID(value string) (pgtype.UUID, error) {
// because it contains nothing the user in front of the iframe cannot already
// see on the page around it.
type PluginContext struct {
- Workspace PluginContextWorkspace `json:"workspace"`
- User PluginContextUser `json:"user"`
- Issue *PluginContextIssue `json:"issue,omitempty"`
- Config map[string]any `json:"config"`
- GrantedURLs []string `json:"granted_net_domains"`
+ Workspace PluginContextWorkspace `json:"workspace"`
+ // User is absent when the caller is the plugin itself — an event hook or a
+ // standing install token has no person behind it, and inventing one here
+ // would let a handler believe it is acting for somebody.
+ User *PluginContextUser `json:"user,omitempty"`
+ Issue *PluginContextIssue `json:"issue,omitempty"`
+ Config map[string]any `json:"config"`
+ GrantedURLs []string `json:"granted_net_domains"`
+ // Actor names which of the two it is, so a handler can branch without
+ // inferring it from a missing field.
+ Actor string `json:"actor"`
}
type PluginContextWorkspace struct {
@@ -122,7 +137,7 @@ type PluginContextIssue struct {
// BuildPluginContext assembles the context payload. Config carries only the
// non-secret installation values — secrets live in their own table and have no
// read path, so there is no way for one to reach the iframe.
-func (s *PluginService) BuildPluginContext(caller PluginActionCaller, workspace db.Workspace, user db.User, issue *db.Issue) PluginContext {
+func (s *PluginService) BuildPluginContext(caller PluginActionCaller, workspace db.Workspace, user *db.User, issue *db.Issue) PluginContext {
config := map[string]any{}
if len(caller.Installation.Config) > 0 {
_ = json.Unmarshal(caller.Installation.Config, &config)
@@ -134,12 +149,16 @@ func (s *PluginService) BuildPluginContext(caller PluginActionCaller, workspace
Name: workspace.Name,
Slug: workspace.Slug,
},
- User: PluginContextUser{
- ID: uuidString(user.ID),
- Name: user.Name,
- },
Config: config,
GrantedURLs: plugincontract.NetDomains(caller.Scopes),
+ Actor: "plugin",
+ }
+ if user != nil {
+ payload.Actor = "member"
+ payload.User = &PluginContextUser{
+ ID: uuidString(user.ID),
+ Name: user.Name,
+ }
}
if issue != nil {
payload.Issue = &PluginContextIssue{
diff --git a/server/internal/service/plugin_event_bridge.go b/server/internal/service/plugin_event_bridge.go
new file mode 100644
index 0000000000..8f4f4cde14
--- /dev/null
+++ b/server/internal/service/plugin_event_bridge.go
@@ -0,0 +1,108 @@
+package service
+
+import (
+ "encoding/json"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Translating the internal event bus into the seven events a plugin may
+// subscribe to.
+//
+// Two vocabularies on purpose. The internal names are realtime transport
+// concerns and change when the frontend needs them to; the plugin names are a
+// published contract. Mapping in one place means a rename on our side is a
+// change to this file rather than a break in every installed plugin.
+
+// EventSink is the half of the dispatcher the bridge needs.
+//
+// An interface so the vocabulary mapping can be tested without a network: what
+// this file decides is WHICH plugin event an internal one becomes, and that is
+// worth asserting on its own rather than through a live endpoint.
+type EventSink interface {
+ Dispatch(eventType, workspaceID string, payload any)
+}
+
+// SubscribePluginEvents wires the dispatcher onto the bus.
+//
+// Bus.Publish calls its listeners INLINE, on the goroutine of the request that
+// published — so everything these closures do must be cheap and non-blocking.
+// They extract an id and hand off; the network call happens on a worker.
+func SubscribePluginEvents(bus *events.Bus, dispatcher EventSink) {
+ if bus == nil || dispatcher == nil {
+ return
+ }
+
+ // The listener does the least it possibly can: hand over the payload
+ // unexamined. Extracting the issue id here would put a JSON round-trip of a
+ // full issue body on the publishing request's goroutine, for every one of
+ // these events, in every workspace — including deployments where plugins are
+ // switched off entirely. It happens on a worker instead, after the flag
+ // check, where it costs nothing anyone is waiting for.
+ forward := func(pluginEvent string) events.Handler {
+ return func(e events.Event) {
+ dispatcher.Dispatch(pluginEvent, e.WorkspaceID, e.Payload)
+ }
+ }
+
+ bus.Subscribe(protocol.EventIssueCreated, forward(plugincontract.EventIssueCreated))
+ bus.Subscribe(protocol.EventCommentCreated, forward(plugincontract.EventCommentCreated))
+ bus.Subscribe(protocol.EventTaskRunning, forward(plugincontract.EventTaskStarted))
+ bus.Subscribe(protocol.EventTaskCompleted, forward(plugincontract.EventTaskCompleted))
+ bus.Subscribe(protocol.EventTaskFailed, forward(plugincontract.EventTaskFailed))
+
+ // issue.status_changed has no event of its own internally: a status change
+ // is an issue:updated carrying status_changed=true. Deriving it here rather
+ // than adding a second publish keeps one write producing one internal
+ // event, and lets a plugin subscribe to the specific thing it cares about
+ // instead of filtering every field change itself.
+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ dispatcher.Dispatch(plugincontract.EventIssueUpdated, e.WorkspaceID, e.Payload)
+ // A map lookup, not a parse: cheap enough for the request goroutine.
+ if payloadFlag(e.Payload, "status_changed") {
+ dispatcher.Dispatch(plugincontract.EventIssueStatusChanged, e.WorkspaceID, e.Payload)
+ }
+ })
+}
+
+// issueIDFromPayload finds the issue an event is about, so the callback token
+// issued for the hook can be narrowed to it. A payload with no issue yields the
+// zero UUID, which simply means the grant is not issue-scoped.
+func issueIDFromPayload(payload any) pgtype.UUID {
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return pgtype.UUID{}
+ }
+ var shape struct {
+ Issue struct {
+ ID string `json:"id"`
+ } `json:"issue"`
+ Comment struct {
+ IssueID string `json:"issue_id"`
+ } `json:"comment"`
+ IssueID string `json:"issue_id"`
+ }
+ if err := json.Unmarshal(encoded, &shape); err != nil {
+ return pgtype.UUID{}
+ }
+ for _, candidate := range []string{shape.Issue.ID, shape.Comment.IssueID, shape.IssueID} {
+ if candidate == "" {
+ continue
+ }
+ if parsed, err := parseUUIDValue(candidate); err == nil {
+ return parsed
+ }
+ }
+ return pgtype.UUID{}
+}
+
+func payloadFlag(payload any, key string) bool {
+ if fields, ok := payload.(map[string]any); ok {
+ flag, _ := fields[key].(bool)
+ return flag
+ }
+ return false
+}
diff --git a/server/internal/service/plugin_event_dispatch.go b/server/internal/service/plugin_event_dispatch.go
new file mode 100644
index 0000000000..6285d817f3
--- /dev/null
+++ b/server/internal/service/plugin_event_dispatch.go
@@ -0,0 +1,323 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// Event-triggered hooks.
+//
+// The rule this file exists to keep: an event hook NEVER blocks the host. The
+// event bus is synchronous — Bus.Publish runs its listeners inline, on the
+// goroutine of whatever request produced the event — so a listener that dialled
+// a third-party endpoint would put an outside server on the critical path of
+// creating an issue. Everything here therefore hands off to a bounded worker
+// pool and returns immediately.
+//
+// The same reasoning is why the agent execution path has no hook at all: a hook
+// that must run before or after every agent turn is a third party holding the
+// product's main loop open. Agents reach hooks in PR 4 by choosing to call one
+// as a tool, which is a call they can decline.
+
+const (
+ // Queue depth. Full means events are arriving faster than endpoints can
+ // answer; the overflow is dropped and counted rather than queued forever,
+ // because an unbounded queue turns a slow plugin into a memory leak.
+ dispatchQueueDepth = 512
+ dispatchWorkers = 4
+
+ // How long a hook call stays on record. This table is operational telemetry,
+ // not history: it answers "why is this endpoint failing right now", and the
+ // circuit breaker and rate limiter only ever look minutes back. Keeping it
+ // forever would grow an append-only table at the rate of the per-hook limit
+ // — 120/minute/hook — for no reader.
+ invocationRetention = 7 * 24 * time.Hour
+ invocationSweepEvery = time.Hour
+)
+
+// PluginEventDispatcher fans domain events out to the hooks that asked for them.
+type PluginEventDispatcher struct {
+ service *PluginService
+ queue chan dispatchJob
+ wg sync.WaitGroup
+ stop chan struct{}
+ once sync.Once
+
+ // dropped counts events shed under backpressure, surfaced for triage.
+ mu sync.Mutex
+ dropped int
+}
+
+type dispatchJob struct {
+ installation db.PluginInstallation
+ hook plugincontract.Hook
+ eventType string
+ issueID pgtype.UUID
+ payload any
+}
+
+func NewPluginEventDispatcher(service *PluginService) *PluginEventDispatcher {
+ dispatcher := &PluginEventDispatcher{
+ service: service,
+ queue: make(chan dispatchJob, dispatchQueueDepth),
+ stop: make(chan struct{}),
+ }
+ for i := 0; i < dispatchWorkers; i++ {
+ dispatcher.wg.Add(1)
+ go dispatcher.work()
+ }
+ dispatcher.wg.Add(1)
+ go dispatcher.sweepInvocations()
+ return dispatcher
+}
+
+// sweepInvocations makes the table's "TTL-swept" description true.
+//
+// Nothing reads a row older than the breaker and rate-limit windows, both of
+// which look minutes back, so without this the table only grows — at up to the
+// per-hook limit of 120 rows a minute, per hook, forever.
+//
+// Runs on the dispatcher's own lifecycle because it is the same concern:
+// bounded resources for something a third party's behaviour drives.
+//
+// The first sweep waits for the first tick rather than firing at construction.
+// An earlier version swept immediately, on the theory that a deployment down for
+// a week should not wait an hour — and it panicked in cmd/server's router test,
+// where the dispatcher is built over a Queries whose pool was never opened. The
+// benefit was one hour of retention on a cold start against a 7-day TTL; the
+// cost was a goroutine touching the database before the process is known to have
+// one.
+func (d *PluginEventDispatcher) sweepInvocations() {
+ defer d.wg.Done()
+ ticker := time.NewTicker(invocationSweepEvery)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-d.stop:
+ return
+ case <-ticker.C:
+ d.sweepOnce()
+ }
+ }
+}
+
+// sweepOnce deletes what has aged out.
+//
+// Panics are contained for the same reason runGuarded exists: this runs on a
+// bare goroutine, where an unrecovered panic is not a failed sweep but a dead
+// process. A nil check on Queries is NOT enough to prevent one — sqlc's Queries
+// wraps an executor, so a non-nil Queries over an unopened pool passes every
+// check available here and then dereferences inside pgxpool. That is exactly how
+// this took down cmd/server's test, and it is why the guard is a recover rather
+// than one more nil comparison.
+func (d *PluginEventDispatcher) sweepOnce() {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ slog.Error("plugins: panic while sweeping hook invocations", "recovered", recovered)
+ }
+ }()
+ if d.service == nil || d.service.Queries == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ cutoff := pgtype.Timestamptz{Time: time.Now().Add(-invocationRetention), Valid: true}
+ removed, err := d.service.Queries.DeleteExpiredPluginInvocations(ctx, cutoff)
+ if err != nil {
+ slog.Warn("plugins: invocation sweep failed", "error", err)
+ return
+ }
+ if removed > 0 {
+ slog.Info("plugins: swept expired hook invocations", "removed", removed)
+ }
+}
+
+// Dispatch is what the bus listener calls. It must return promptly: the caller
+// is a live request that has already done its real work.
+//
+// Note it takes no context from that request. Tying an outbound hook to the
+// request that triggered it would cancel the hook the moment the browser got
+// its response, which is exactly when the hook is only just starting.
+func (d *PluginEventDispatcher) Dispatch(eventType, workspaceID string, payload any) {
+ if d == nil || d.service == nil || workspaceID == "" {
+ return
+ }
+ parsedWorkspace, err := parseUUIDValue(workspaceID)
+ if err != nil {
+ return
+ }
+
+ // Nothing is inspected here. The installation lookup is a database read and
+ // finding the issue id is a JSON round-trip; both belong on a worker, and
+ // both sit behind the feature-flag check so a deployment with plugins off
+ // pays for neither.
+ select {
+ case d.queue <- dispatchJob{
+ installation: db.PluginInstallation{WorkspaceID: parsedWorkspace},
+ eventType: eventType,
+ payload: payload,
+ }:
+ default:
+ d.mu.Lock()
+ d.dropped++
+ dropped := d.dropped
+ d.mu.Unlock()
+ slog.Warn("plugins: event dispatch queue full, dropping event", "event_type", eventType, "dropped_total", dropped)
+ }
+}
+
+// Dropped reports how many events were shed under backpressure.
+func (d *PluginEventDispatcher) Dropped() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.dropped
+}
+
+func (d *PluginEventDispatcher) work() {
+ defer d.wg.Done()
+ for {
+ select {
+ case <-d.stop:
+ return
+ case job := <-d.queue:
+ d.runGuarded(job)
+ }
+ }
+}
+
+// runGuarded contains a panic to the delivery that caused it.
+//
+// Bus.Publish recovers panics in its listeners so one bad handler cannot take
+// down the request that published. Moving delivery onto a worker goroutine
+// steps outside that protection, and a panic on a bare goroutine is not a
+// failed hook but a dead process. Restoring the guarantee is the cost of the
+// hand-off, not an optional extra.
+func (d *PluginEventDispatcher) runGuarded(job dispatchJob) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ slog.Error("plugins: panic while delivering an event hook",
+ "event_type", job.eventType, "recovered", recovered)
+ }
+ }()
+ d.run(job)
+}
+
+// run resolves which hooks want this event and calls each one.
+func (d *PluginEventDispatcher) run(job dispatchJob) {
+ if d.service.Queries == nil {
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+
+ // The flag gates this path too, and checking it HERE rather than at
+ // subscription is the point: a deployment that turns plugins off after
+ // something was installed must stop the outbound calls, not just hide the
+ // UI. Reading it per delivery means the flip takes effect immediately
+ // instead of at the next restart.
+ //
+ // It also keeps the flag-off cost at zero. Without this every dispatched
+ // event ran a ListWorkspacePluginInstallations query to discover there was
+ // nothing to call.
+ if !featureflags.PluginsV1Enabled(ctx, d.service.FeatureFlags) {
+ return
+ }
+
+ // Only now, past the flag: the id is needed to narrow the callback grant,
+ // and finding it means parsing the payload.
+ job.issueID = issueIDFromPayload(job.payload)
+
+ installations, err := d.service.Queries.ListWorkspacePluginInstallations(ctx, job.installation.WorkspaceID)
+ if err != nil {
+ slog.Warn("plugins: event dispatch could not list installations", "error", err)
+ return
+ }
+ for _, installation := range installations {
+ if !installation.Enabled {
+ continue
+ }
+ manifest, err := ParseInstallationManifest(installation)
+ if err != nil {
+ continue
+ }
+ for _, hook := range manifest.Contributes.Hooks {
+ if !HookAllowsTrigger(hook, plugincontract.TriggerEvent) || !hookWantsEvent(hook, job.eventType) {
+ continue
+ }
+ d.deliver(ctx, installation, hook, job)
+ }
+ }
+}
+
+func hookWantsEvent(hook plugincontract.Hook, eventType string) bool {
+ for _, declared := range hook.Events {
+ if declared == eventType {
+ return true
+ }
+ }
+ return false
+}
+
+// deliver runs one hook with the event retry schedule.
+func (d *PluginEventDispatcher) deliver(ctx context.Context, installation db.PluginInstallation, hook plugincontract.Hook, job dispatchJob) {
+ // A hook whose endpoint has been failing is not retried on every event.
+ // Without this, an endpoint that has been down for an hour receives one
+ // doomed request per workspace event, forever.
+ if d.service.HookBreakerOpen(ctx, installation.ID, hook.Key) {
+ slog.Info("plugins: hook circuit open, skipping event", "hook", hook.Key, "event_type", job.eventType)
+ return
+ }
+
+ invocation := HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerEvent,
+ EventType: job.eventType,
+ // An event has no person behind it. Writes it produces are the
+ // plugin's own, attributed to the installation.
+ Actor: HookActor{Type: "plugin", ID: installation.ID},
+ IssueID: job.issueID,
+ Input: job.payload,
+ }
+
+ for attempt := 1; attempt <= hookEventAttempts; attempt++ {
+ _, err := d.service.InvokeHook(ctx, invocation, attempt)
+ if err == nil {
+ return
+ }
+ // A refusal is a decision, not an outage: retrying a hook that is
+ // disabled, out of scope or rate limited just burns the budget.
+ if hookFailureStatus(err) == "refused" {
+ slog.Info("plugins: event hook refused", "hook", hook.Key, "error", redactHookError(err))
+ return
+ }
+ if attempt == hookEventAttempts {
+ slog.Warn("plugins: event hook failed after retries", "hook", hook.Key, "event_type", job.eventType, "error", redactHookError(err))
+ return
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(time.Duration(attempt) * hookEventBackoff):
+ }
+ }
+}
+
+// Close stops the workers. Safe to call more than once.
+func (d *PluginEventDispatcher) Close() {
+ if d == nil {
+ return
+ }
+ d.once.Do(func() {
+ close(d.stop)
+ d.wg.Wait()
+ })
+}
diff --git a/server/internal/service/plugin_event_dispatch_test.go b/server/internal/service/plugin_event_dispatch_test.go
new file mode 100644
index 0000000000..0e0fe36c22
--- /dev/null
+++ b/server/internal/service/plugin_event_dispatch_test.go
@@ -0,0 +1,319 @@
+package service
+
+import (
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ 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/protocol"
+)
+
+// The promise this file exists to keep: publishing an event NEVER waits for a
+// third party.
+//
+// Bus.Publish calls listeners inline, on the goroutine of the request that
+// published, so a listener that dialled an endpoint would put an outside server
+// on the critical path of creating an issue. These tests hold the bus listener
+// against an endpoint that never answers.
+
+// A hung endpoint must not hold up the publisher. If Dispatch ever becomes
+// synchronous this test hangs for the endpoint's full duration rather than
+// returning in microseconds, which is the failure worth catching.
+func TestEventDispatchNeverBlocksThePublisher(t *testing.T) {
+ blocked := make(chan struct{})
+ t.Cleanup(func() { close(blocked) })
+
+ harness := newHookTestServer(t)
+ harness.respond = func(w http.ResponseWriter, _ []byte) {
+ // Hold the connection open until the test finishes.
+ <-blocked
+ w.WriteHeader(http.StatusOK)
+ }
+ service := hookTestService(t, harness)
+ dispatcher := NewPluginEventDispatcher(service)
+ t.Cleanup(dispatcher.Close)
+
+ bus := events.New()
+ SubscribePluginEvents(bus, dispatcher)
+
+ started := time.Now()
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueCreated,
+ WorkspaceID: "00000000-0000-4000-8000-000000000001",
+ ActorType: "member",
+ Payload: map[string]any{"issue": map[string]any{"id": "00000000-0000-4000-8000-000000000002"}},
+ })
+ elapsed := time.Since(started)
+
+ // Generous by three orders of magnitude: the point is "did not wait for the
+ // network", not a latency budget.
+ if elapsed > 250*time.Millisecond {
+ t.Fatalf("Publish took %v — an event hook is blocking the publishing request", elapsed)
+ }
+}
+
+// Backpressure is shed, not queued. An unbounded queue turns a slow plugin into
+// a memory leak; dropping and counting keeps the host healthy and the loss
+// visible rather than silent.
+//
+// Workers are stopped first so nothing drains — the same state a pool saturated
+// by slow endpoints reaches, reproduced without depending on timing.
+func TestEventDispatchShedsLoadRatherThanGrowingWithoutBound(t *testing.T) {
+ harness := newHookTestServer(t)
+ dispatcher := NewPluginEventDispatcher(hookTestService(t, harness))
+ dispatcher.Close()
+
+ // Well past the queue depth. Every call must return, none may panic, and
+ // Dispatch must stay safe after the pool has stopped.
+ for i := 0; i < dispatchQueueDepth*3; i++ {
+ dispatcher.Dispatch(plugincontract.EventIssueCreated, "00000000-0000-4000-8000-000000000001", nil)
+ }
+ dropped := dispatcher.Dropped()
+ if dropped == 0 {
+ t.Fatal("nothing was dropped past the queue depth — the queue is unbounded")
+ }
+ // Exactly the overflow: the queue holds its depth and sheds the rest.
+ if want := dispatchQueueDepth*3 - dispatchQueueDepth; dropped != want {
+ t.Fatalf("dropped %d, want %d — the queue is not bounded at its declared depth", dropped, want)
+ }
+}
+
+// The bus vocabulary and the plugin vocabulary are deliberately separate. This
+// pins the mapping, including the one event that has no internal equivalent:
+// issue.status_changed is derived from an issue:updated carrying
+// status_changed=true, so a plugin can subscribe to the specific thing it cares
+// about instead of filtering every field change itself.
+func TestEventBridgeMapsInternalEventsToThePublishedVocabulary(t *testing.T) {
+ seen := []string{}
+ bus := events.New()
+ SubscribePluginEvents(bus, recordingSink(func(eventType string) { seen = append(seen, eventType) }))
+
+ workspace := "00000000-0000-4000-8000-000000000001"
+ bus.Publish(events.Event{Type: protocol.EventIssueCreated, WorkspaceID: workspace})
+ bus.Publish(events.Event{Type: protocol.EventCommentCreated, WorkspaceID: workspace})
+ bus.Publish(events.Event{Type: protocol.EventTaskRunning, WorkspaceID: workspace})
+ bus.Publish(events.Event{Type: protocol.EventTaskCompleted, WorkspaceID: workspace})
+ bus.Publish(events.Event{Type: protocol.EventTaskFailed, WorkspaceID: workspace})
+ // A plain field edit is issue.updated only.
+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: workspace, Payload: map[string]any{"title_changed": true}})
+ // A status change is BOTH, so a subscriber to either sees it.
+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: workspace, Payload: map[string]any{"status_changed": true}})
+
+ want := []string{
+ plugincontract.EventIssueCreated,
+ plugincontract.EventCommentCreated,
+ plugincontract.EventTaskStarted,
+ plugincontract.EventTaskCompleted,
+ plugincontract.EventTaskFailed,
+ plugincontract.EventIssueUpdated,
+ plugincontract.EventIssueUpdated,
+ plugincontract.EventIssueStatusChanged,
+ }
+ if len(seen) != len(want) {
+ t.Fatalf("dispatched %v, want %v", seen, want)
+ }
+ for index, expected := range want {
+ if seen[index] != expected {
+ t.Fatalf("dispatched[%d] = %q, want %q (full: %v)", index, seen[index], expected, seen)
+ }
+ }
+
+ // Every published event name must be one a manifest may subscribe to, or a
+ // plugin could never receive it.
+ for _, eventType := range want {
+ if !plugincontract.IsKnownEvent(eventType) {
+ t.Fatalf("%q is dispatched but not a subscribable event", eventType)
+ }
+ }
+}
+
+// The issue id travels with the event so the callback token can be narrowed to
+// it. Each payload shape the product actually publishes is covered.
+func TestEventBridgeFindsTheIssueInEveryPayloadShape(t *testing.T) {
+ issueID := "3fa85f64-5717-4562-b3fc-2c963f66afa6"
+ for name, payload := range map[string]any{
+ "issue event": map[string]any{"issue": map[string]any{"id": issueID}},
+ "comment event": map[string]any{"comment": map[string]any{"issue_id": issueID}},
+ "task event": map[string]any{"issue_id": issueID},
+ } {
+ found := issueIDFromPayload(payload)
+ if uuidString(found) != issueID {
+ t.Fatalf("%s: issue id = %q, want %q", name, uuidString(found), issueID)
+ }
+ }
+
+ // A payload with no issue yields the zero UUID, which simply means the
+ // grant is not issue-scoped — not an error.
+ if issueIDFromPayload(map[string]any{"unrelated": true}).Valid {
+ t.Fatal("a payload with no issue must not produce an issue-scoped grant")
+ }
+ if issueIDFromPayload(nil).Valid {
+ t.Fatal("a nil payload must not produce an issue-scoped grant")
+ }
+ // Not a UUID: refuse rather than pass a malformed id into a grant.
+ if issueIDFromPayload(map[string]any{"issue_id": "not-a-uuid"}).Valid {
+ t.Fatal("a malformed id must not produce an issue-scoped grant")
+ }
+}
+
+// An event hook writes as the installation. This asserts the actor the
+// dispatcher stamps, which is what the callback token later carries.
+func TestEventDispatchStampsThePluginActor(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host,
+ []string{plugincontract.TriggerEvent})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ if _, err := service.callHookEndpoint(t.Context(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerEvent,
+ EventType: plugincontract.EventIssueCreated,
+ Actor: HookActor{Type: "plugin", ID: installation.ID},
+ }); err != nil {
+ t.Fatalf("event hook call: %v", err)
+ }
+
+ received := <-harness.received
+ var body hookRequestBody
+ if err := json.Unmarshal(received.Body, &body); err != nil {
+ t.Fatalf("decode delivered body: %v", err)
+ }
+ if body.Actor.Type != "plugin" {
+ t.Fatalf("actor.type = %q, want plugin: an event hook has no person behind it", body.Actor.Type)
+ }
+ if body.EventType != plugincontract.EventIssueCreated {
+ t.Fatalf("event_type = %q, want %q", body.EventType, plugincontract.EventIssueCreated)
+ }
+ if body.Trigger != plugincontract.TriggerEvent {
+ t.Fatalf("trigger = %q, want event", body.Trigger)
+ }
+
+ // Re-issued: callHookEndpoint revokes the grant once its call has returned.
+ token, err := service.Callbacks.Issue(t.Context(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerEvent,
+ Actor: HookActor{Type: "plugin", ID: installation.ID},
+ })
+ if err != nil {
+ t.Fatalf("issue: %v", err)
+ }
+ grant, err := service.Callbacks.Resolve(token)
+ if err != nil {
+ t.Fatalf("resolve: %v", err)
+ }
+ if grant.Actor.Type != "plugin" {
+ t.Fatalf("the grant must carry the plugin actor, got %q", grant.Actor.Type)
+ }
+}
+
+// recordingSink stands in for the dispatcher so the vocabulary mapping is
+// asserted directly, with no worker pool or endpoint in the way.
+type recordingSink func(eventType string)
+
+func (r recordingSink) Dispatch(eventType, _ string, _ any) { r(eventType) }
+
+// The shape that took down cmd/server's router test: a dispatcher built over a
+// Queries whose pool was never opened.
+//
+// A nil check on Queries does not catch it — sqlc wraps an executor, so the
+// value is non-nil and the nil pool is only reached inside pgxpool. Constructing
+// a dispatcher must therefore never touch the database on its own, and a sweep
+// that does must not be able to kill the process.
+func TestNewDispatcherDoesNotTouchTheDatabase(t *testing.T) {
+ // A Queries over a nil pool: exactly what NewRouter holds in a test that
+ // never opens one.
+ dispatcher := NewPluginEventDispatcher(&PluginService{Queries: db.New(nil)})
+ t.Cleanup(dispatcher.Close)
+
+ // Long enough that a construction-time sweep would already have panicked and
+ // taken the process with it.
+ time.Sleep(150 * time.Millisecond)
+
+ // And the sweep itself, called directly, must survive the same pool.
+ dispatcher.sweepOnce()
+}
+
+func testFlagService(enabled bool) *featureflag.Service {
+ provider := featureflag.NewStaticProvider()
+ provider.Set(featureflags.PluginsV1, featureflag.Rule{Default: enabled})
+ return featureflag.NewService(provider)
+}
+
+// Nil flags read as disabled. A deployment that never wired the flag service
+// must not have outbound hooks enabled by that omission.
+func TestEventDispatchTreatsMissingFlagsAsDisabled(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ service.Queries = db.New(nil)
+ service.FeatureFlags = nil
+
+ dispatcher := NewPluginEventDispatcher(service)
+ t.Cleanup(dispatcher.Close)
+ dispatcher.runGuarded(dispatchJob{
+ installation: db.PluginInstallation{WorkspaceID: testInstallationID(t)},
+ eventType: plugincontract.EventIssueCreated,
+ })
+
+ select {
+ case <-harness.received:
+ t.Fatal("a request left with no feature flag service configured")
+ default:
+ }
+}
+
+// countingPayload records how many times something serialized it.
+//
+// json.Marshal calls MarshalJSON, so this counts exactly the work the bus
+// listener used to do on the publishing request's goroutine.
+type countingPayload struct{ marshals *int }
+
+func (c countingPayload) MarshalJSON() ([]byte, error) {
+ *c.marshals++
+ return []byte(`{"issue":{"id":"3fa85f64-5717-4562-b3fc-2c963f66afa6"}}`), nil
+}
+
+// Publishing must not parse the payload.
+//
+// The listener used to pass issueIDFromPayload(e.Payload) as an argument, which
+// put a JSON marshal + unmarshal of a full issue body on the request goroutine
+// for seven event types, in every workspace — including deployments with plugins
+// switched off, where the flag check downstream then threw the result away.
+// Finding the id belongs on a worker, past the flag.
+func TestPublishingDoesNotParseThePayload(t *testing.T) {
+ marshals := 0
+ bus := events.New()
+ SubscribePluginEvents(bus, recordingSink(func(string) {}))
+
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueCreated,
+ WorkspaceID: "00000000-0000-4000-8000-000000000001",
+ Payload: countingPayload{marshals: &marshals},
+ })
+
+ if marshals != 0 {
+ t.Fatalf("the payload was serialized %d time(s) on the publishing goroutine; the id must be extracted on a worker instead", marshals)
+ }
+}
+
+// And the id still arrives — moved, not dropped. issueIDFromPayload remains the
+// one place that knows the payload shapes; only where it runs changed.
+func TestTheIssueIDIsStillFoundOnTheWorker(t *testing.T) {
+ issueID := "3fa85f64-5717-4562-b3fc-2c963f66afa6"
+ found := issueIDFromPayload(map[string]any{"issue": map[string]any{"id": issueID}})
+ if uuidString(found) != issueID {
+ t.Fatalf("issue id = %q, want %q", uuidString(found), issueID)
+ }
+}
diff --git a/server/internal/service/plugin_hook.go b/server/internal/service/plugin_hook.go
new file mode 100644
index 0000000000..b494287097
--- /dev/null
+++ b/server/internal/service/plugin_hook.go
@@ -0,0 +1,526 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/remotemcp"
+)
+
+// The hook engine: the one place Multica calls OUT to a plugin's own server.
+//
+// Everything before this ran the other way — a sandboxed surface asked the host
+// and the host acted on the signed-in user's session, so no request ever left
+// our infrastructure on a plugin's say-so. A hook does leave, which is why the
+// checks here are about the destination rather than the caller: the host must
+// be one the manifest declared through a `net:` scope, it must resolve to a
+// public address at dial time, and the body must be signed so the receiver can
+// tell our call from anyone else's.
+
+const (
+ // Signature scheme version, carried in the header so the scheme can change
+ // without every handler guessing which one it is looking at.
+ hookSignatureVersion = "v1"
+ // How far a request timestamp may be from our clock. Bounds replay: a
+ // captured request is only reusable inside this window, and a handler that
+ // also remembers signatures can close it entirely.
+ hookTimestampTolerance = 5 * time.Minute
+ // Fallback when a manifest omits timeout_ms.
+ hookDefaultTimeout = 10 * time.Second
+ // Response bodies are read for the caller, so they are capped. A hook that
+ // answers with a gigabyte should fail, not consume the host.
+ hookMaxResponseBytes = 1 << 20
+
+ // Event retry schedule. Three attempts total, then the call is abandoned.
+ hookEventAttempts = 3
+ hookEventBackoff = 2 * time.Second
+
+ // Circuit breaker. After this many failures inside the window, event
+ // delivery for the hook stops until the window rolls off — an endpoint that
+ // has been down for a minute does not need one request per event to notice.
+ hookBreakerThreshold = 5
+ hookBreakerWindow = 5 * time.Minute
+
+ // Per-hook rate limit, counted in attempts.
+ hookRateLimit = 120
+ hookRateWindow = time.Minute
+)
+
+// HookResult is what a completed hook call returns to whoever invoked it.
+type HookResult struct {
+ Status string `json:"status"`
+ Output json.RawMessage `json:"output,omitempty"`
+ Error string `json:"error,omitempty"`
+ Latency int `json:"latency_ms"`
+ HookKey string `json:"hook_key"`
+ Trigger string `json:"trigger"`
+ Attempts int `json:"attempts"`
+}
+
+// HookActor is who the resulting writes belong to.
+//
+// This is the whole identity model for hooks, and it follows the trigger rather
+// than the plugin: a ui/manual hook runs because a person pressed something, so
+// its writes stay that person's (marked via_plugin_id); an event hook has no
+// person behind it and must not borrow the last one who happened to touch the
+// issue.
+type HookActor struct {
+ Type string
+ ID pgtype.UUID
+}
+
+// HookInvocation is one call the engine has been asked to make.
+type HookInvocation struct {
+ Installation db.PluginInstallation
+ Hook plugincontract.Hook
+ Trigger string
+ // EventType is set only for the event trigger, and names what happened.
+ EventType string
+ Actor HookActor
+ // IssueID is the issue this call is about, when there is one. It narrows the
+ // callback token so a handler answering about one issue cannot use the same
+ // grant to reach across the workspace.
+ IssueID pgtype.UUID
+ Input any
+}
+
+// hookRequestBody is the wire format. Stable and small on purpose: a hook
+// handler written against v1 should not have to care what else the host learns
+// how to send later.
+type hookRequestBody struct {
+ Version int `json:"version"`
+ HookKey string `json:"hook_key"`
+ Trigger string `json:"trigger"`
+ EventType string `json:"event_type,omitempty"`
+ WorkspaceID string `json:"workspace_id"`
+ Installation string `json:"installation_id"`
+ // IssueID is the issue this call is about, as resolved and permission-checked
+ // by the host. Sent because the alternative is every handler reading it out
+ // of client-supplied `input` — unvalidated, and absent entirely for the event
+ // trigger, where no client was involved at all.
+ IssueID string `json:"issue_id,omitempty"`
+ Actor hookRequestActor `json:"actor"`
+ Input json.RawMessage `json:"input,omitempty"`
+ // CallbackToken lets the handler call the Action API back for the few
+ // minutes it is valid. Narrower than the installation's own token and tied
+ // to this one call, so a handler that leaks it leaks a few minutes of the
+ // scopes it was already using, not standing access.
+ CallbackToken string `json:"callback_token,omitempty"`
+ CallbackURL string `json:"callback_url,omitempty"`
+}
+
+type hookRequestActor struct {
+ Type string `json:"type"`
+ ID string `json:"id,omitempty"`
+}
+
+// FindHook returns the named hook from an installation's consented manifest.
+//
+// Read from the installation row, never from the manifest the source URL serves
+// right now: the admin consented to a specific set of endpoints, and a plugin
+// that later repoints its own hook at somewhere else must go through the
+// upgrade flow to have that take effect.
+func FindHook(installation db.PluginInstallation, hookKey string) (plugincontract.Hook, error) {
+ manifest, err := ParseInstallationManifest(installation)
+ if err != nil {
+ return plugincontract.Hook{}, pluginErrf(PluginErrorInvalid, "plugin manifest is unreadable")
+ }
+ for _, hook := range manifest.Contributes.Hooks {
+ if hook.Key == hookKey {
+ return hook, nil
+ }
+ }
+ return plugincontract.Hook{}, pluginErrf(PluginErrorNotFound, "this Plugin has no hook named %q", hookKey)
+}
+
+// HookAllowsTrigger reports whether the hook declared this trigger. A trigger
+// the manifest did not list is not a call site the host may invent.
+func HookAllowsTrigger(hook plugincontract.Hook, trigger string) bool {
+ for _, declared := range hook.Triggers {
+ if declared == trigger {
+ return true
+ }
+ }
+ return false
+}
+
+// InvokeHook performs one call and records it.
+//
+// Callers pick the blocking behaviour, not this function: ui/manual await the
+// result because a person is watching, and the event dispatcher runs it on its
+// own goroutine because the host request that produced the event must not wait
+// for a third party.
+func (s *PluginService) InvokeHook(ctx context.Context, invocation HookInvocation, attempt int) (HookResult, error) {
+ hook := invocation.Hook
+ result := HookResult{HookKey: hook.Key, Trigger: invocation.Trigger, Attempts: attempt}
+
+ if !invocation.Installation.Enabled {
+ return result, pluginErrf(PluginErrorForbidden, "this Plugin is disabled")
+ }
+ if !HookAllowsTrigger(hook, invocation.Trigger) {
+ return result, pluginErrf(PluginErrorForbidden, "hook %q does not declare the %s trigger", hook.Key, invocation.Trigger)
+ }
+ if hook.Transport.Type != plugincontract.TransportHTTP {
+ return result, pluginErrf(PluginErrorIncompatible, "hook transport %q is not supported yet", hook.Transport.Type)
+ }
+ if err := s.checkHookRate(ctx, invocation.Installation.ID, hook.Key); err != nil {
+ return result, err
+ }
+
+ started := time.Now()
+ output, callErr := s.callHookEndpoint(ctx, invocation)
+ latency := int(time.Since(started).Milliseconds())
+
+ result.Latency = latency
+ status := "ok"
+ message := ""
+ if callErr != nil {
+ status = hookFailureStatus(callErr)
+ message = redactHookError(callErr)
+ result.Error = message
+ } else {
+ result.Output = output
+ }
+ result.Status = status
+
+ s.recordInvocation(ctx, invocation, status, attempt, latency, message)
+ if callErr != nil {
+ return result, callErr
+ }
+ return result, nil
+}
+
+// callHookEndpoint is the network half: validate the destination, sign, send.
+func (s *PluginService) callHookEndpoint(ctx context.Context, invocation HookInvocation) (json.RawMessage, error) {
+ installation := invocation.Installation
+ granted := decodeScopes(installation.GrantedScopes)
+
+ // The destination must be inside the consented `net:` set. Passing the
+ // granted domains as the allowlist means the same string the admin approved
+ // on the consent screen is what bounds the request — there is no second
+ // list to fall out of sync.
+ domains := plugincontract.NetDomains(granted)
+ if len(domains) == 0 {
+ return nil, pluginErrf(PluginErrorForbidden, "this Plugin was granted no net: scope, so it cannot call out")
+ }
+
+ // Two ways to reach an endpoint, and only the network guard differs between
+ // them. The consent check does not: a destination outside the granted `net:`
+ // set is refused on both paths, because that is what the admin approved and
+ // no deployment setting may widen it.
+ var endpoint *url.URL
+ client := &http.Client{}
+ if s.isDevOrigin(invocation.Hook.Transport.URL) {
+ // The operator named this exact origin in MULTICA_PLUGIN_DEV_ORIGINS —
+ // the same opt-in that lets a manifest be served from a local dev
+ // server, for the same reason: an author building a hook has nowhere
+ // public to point it yet.
+ parsed, err := url.Parse(invocation.Hook.Transport.URL)
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "hook endpoint is not a valid URL", Err: err}
+ }
+ if !hostInNetScopes(parsed.Hostname(), domains) {
+ return nil, pluginErrf(PluginErrorForbidden, "hook endpoint host is not covered by a net: scope")
+ }
+ endpoint = parsed
+ if s.HookClient != nil {
+ client = s.HookClient
+ }
+ } else {
+ validated, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, invocation.Hook.Transport.URL, domains, nil)
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorForbidden, Message: "hook endpoint is not allowed", Err: err}
+ }
+ endpoint = validated
+ // NewSecureHTTPClient re-resolves at dial and refuses a non-public
+ // address, so a hostname that passed validation and then flipped to a
+ // private IP cannot be used to reach inside the network.
+ client = remotemcp.NewSecureHTTPClient(endpoint)
+ }
+
+ body, err := s.buildHookBody(ctx, invocation)
+ if err != nil {
+ return nil, err
+ }
+ // The grant lives exactly as long as the call it was issued for. Without
+ // this it would stay usable for the rest of its TTL after the handler has
+ // already answered.
+ if s.Callbacks != nil && body.CallbackToken != "" {
+ defer s.Callbacks.Revoke(body.CallbackToken)
+ }
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "encode hook request", Err: err}
+ }
+
+ timeout := hookDefaultTimeout
+ if invocation.Hook.TimeoutMs > 0 {
+ timeout = time.Duration(invocation.Hook.TimeoutMs) * time.Millisecond
+ }
+ callCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ request, err := http.NewRequestWithContext(callCtx, http.MethodPost, endpoint.String(), bytes.NewReader(encoded))
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "build hook request", Err: err}
+ }
+ timestamp := strconv.FormatInt(time.Now().Unix(), 10)
+ signature, err := s.SignHookPayload(installation.ID, timestamp, encoded)
+ if err != nil {
+ return nil, err
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("X-Multica-Timestamp", timestamp)
+ request.Header.Set("X-Multica-Signature", hookSignatureVersion+"="+signature)
+ request.Header.Set("X-Multica-Plugin-Installation", uuidString(installation.ID))
+ request.Header.Set("User-Agent", "Multica-Hooks/1")
+
+ response, err := client.Do(request)
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "hook endpoint did not answer", Err: err}
+ }
+ defer func() { _ = response.Body.Close() }()
+
+ payload, err := io.ReadAll(io.LimitReader(response.Body, hookMaxResponseBytes))
+ if err != nil {
+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read hook response", Err: err}
+ }
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ return nil, pluginErrf(PluginErrorUnavailable, "hook endpoint returned %d", response.StatusCode)
+ }
+ if len(bytes.TrimSpace(payload)) == 0 {
+ return nil, nil
+ }
+ if !json.Valid(payload) {
+ return nil, pluginErrf(PluginErrorInvalid, "hook endpoint returned a non-JSON body")
+ }
+ return json.RawMessage(payload), nil
+}
+
+func (s *PluginService) buildHookBody(ctx context.Context, invocation HookInvocation) (hookRequestBody, error) {
+ body := hookRequestBody{
+ Version: 1,
+ HookKey: invocation.Hook.Key,
+ Trigger: invocation.Trigger,
+ EventType: invocation.EventType,
+ WorkspaceID: uuidString(invocation.Installation.WorkspaceID),
+ Installation: uuidString(invocation.Installation.ID),
+ Actor: hookRequestActor{Type: invocation.Actor.Type, ID: uuidString(invocation.Actor.ID)},
+ }
+ if invocation.IssueID.Valid {
+ body.IssueID = uuidString(invocation.IssueID)
+ }
+ if invocation.Input != nil {
+ encoded, err := json.Marshal(invocation.Input)
+ if err != nil {
+ return hookRequestBody{}, &PluginError{Kind: PluginErrorInvalid, Message: "encode hook input", Err: err}
+ }
+ body.Input = encoded
+ }
+ if s.Callbacks != nil {
+ token, err := s.Callbacks.Issue(ctx, invocation)
+ if err != nil {
+ return hookRequestBody{}, err
+ }
+ body.CallbackToken = token
+ body.CallbackURL = s.CallbackBaseURL
+ }
+ return body, nil
+}
+
+// SignHookPayload produces the hex HMAC a receiver checks.
+//
+// The signed string joins the timestamp and the body with a separator that
+// cannot appear in the timestamp. Signing the body alone would let a captured
+// request be replayed forever; signing a plain concatenation would let a
+// crafted timestamp and body pair swap bytes between the two fields.
+func (s *PluginService) SignHookPayload(installationID pgtype.UUID, timestamp string, body []byte) (string, error) {
+ key, err := s.hookSigningKey(installationID)
+ if err != nil {
+ return "", err
+ }
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(timestamp))
+ mac.Write([]byte("."))
+ mac.Write(body)
+ return hex.EncodeToString(mac.Sum(nil)), nil
+}
+
+// hookSigningKey derives this installation's signing secret from the deployment
+// key.
+//
+// Derived rather than stored, and this is the asymmetry that decides it: the
+// host must PRODUCE this value to sign with it, so a one-way hash is not an
+// option, and storing a recoverable copy of it in every installation row would
+// put a usable secret in reach of any database read. The install token goes the
+// other way — the plugin produces it and the host only ever verifies — so that
+// one is stored hashed. Same deployment key, opposite directions.
+func (s *PluginService) hookSigningKey(installationID pgtype.UUID) ([]byte, error) {
+ if len(s.DeploymentKey) == 0 {
+ return nil, pluginErrf(PluginErrorUnavailable, "hooks are disabled: MULTICA_PLUGIN_SECRET_KEY is not configured")
+ }
+ mac := hmac.New(sha256.New, s.DeploymentKey)
+ mac.Write([]byte("multica-plugin-hook-signature:v1:"))
+ mac.Write([]byte(uuidString(installationID)))
+ return mac.Sum(nil), nil
+}
+
+// HookSigningSecret is the same value in the form an author configures on their
+// own server. Shown once at install time next to the install token.
+func (s *PluginService) HookSigningSecret(installationID pgtype.UUID) (string, error) {
+ key, err := s.hookSigningKey(installationID)
+ if err != nil {
+ return "", err
+ }
+ return "whsec_" + hex.EncodeToString(key), nil
+}
+
+// VerifyHookSignature is the receiver's half, exported so a plugin written in Go
+// and our own tests check signatures the same way — a scheme only one side can
+// implement is a scheme nobody can review.
+func VerifyHookSignature(secretHex, timestamp string, body []byte, presented string, now time.Time) error {
+ secretHex = strings.TrimPrefix(secretHex, "whsec_")
+ key, err := hex.DecodeString(secretHex)
+ if err != nil {
+ return errors.New("signing secret is not valid hex")
+ }
+ seconds, err := strconv.ParseInt(timestamp, 10, 64)
+ if err != nil {
+ return errors.New("timestamp is not an integer")
+ }
+ drift := now.Sub(time.Unix(seconds, 0))
+ if drift < 0 {
+ drift = -drift
+ }
+ if drift > hookTimestampTolerance {
+ return errors.New("timestamp is outside the accepted window")
+ }
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(timestamp))
+ mac.Write([]byte("."))
+ mac.Write(body)
+ expected := hex.EncodeToString(mac.Sum(nil))
+ presented = strings.TrimPrefix(presented, hookSignatureVersion+"=")
+ // Constant time: a byte-at-a-time comparison leaks how much of a guessed
+ // signature was right, which is enough to find the rest.
+ if subtle.ConstantTimeCompare([]byte(expected), []byte(presented)) != 1 {
+ return errors.New("signature does not match")
+ }
+ return nil
+}
+
+// checkHookRate caps how often one hook may be called.
+func (s *PluginService) checkHookRate(ctx context.Context, installationID pgtype.UUID, hookKey string) error {
+ since := pgtype.Timestamptz{Time: time.Now().Add(-hookRateWindow), Valid: true}
+ count, err := s.Queries.CountRecentPluginInvocations(ctx, db.CountRecentPluginInvocationsParams{
+ InstallationID: installationID,
+ HookKey: hookKey,
+ CreatedAt: since,
+ })
+ if err != nil {
+ // A telemetry read that fails must not take the feature down with it.
+ return nil
+ }
+ if count >= hookRateLimit {
+ return pluginErrf(PluginErrorQuota, "hook %q exceeded %d calls per minute", hookKey, hookRateLimit)
+ }
+ return nil
+}
+
+// HookBreakerOpen reports whether event delivery for this hook is currently
+// suspended after repeated failures.
+func (s *PluginService) HookBreakerOpen(ctx context.Context, installationID pgtype.UUID, hookKey string) bool {
+ since := pgtype.Timestamptz{Time: time.Now().Add(-hookBreakerWindow), Valid: true}
+ failures, err := s.Queries.CountRecentPluginFailures(ctx, db.CountRecentPluginFailuresParams{
+ InstallationID: installationID,
+ HookKey: hookKey,
+ CreatedAt: since,
+ })
+ if err != nil {
+ return false
+ }
+ return failures >= hookBreakerThreshold
+}
+
+func (s *PluginService) recordInvocation(ctx context.Context, invocation HookInvocation, status string, attempt, latency int, message string) {
+ params := db.CreatePluginInvocationParams{
+ InstallationID: invocation.Installation.ID,
+ WorkspaceID: invocation.Installation.WorkspaceID,
+ HookKey: invocation.Hook.Key,
+ Trigger: invocation.Trigger,
+ Status: status,
+ Attempt: int32(attempt),
+ LatencyMs: int32(latency),
+ }
+ if invocation.EventType != "" {
+ params.EventType = pgtype.Text{String: invocation.EventType, Valid: true}
+ }
+ if message != "" {
+ params.Error = pgtype.Text{String: truncate(message, 500), Valid: true}
+ }
+ // Best effort: telemetry must never fail the call it is describing.
+ _, _ = s.Queries.CreatePluginInvocation(ctx, params)
+}
+
+func hookFailureStatus(err error) string {
+ var pluginErr *PluginError
+ if errors.As(err, &pluginErr) {
+ switch pluginErr.Kind {
+ case PluginErrorForbidden, PluginErrorQuota, PluginErrorIncompatible:
+ return "refused"
+ }
+ }
+ if errors.Is(err, context.DeadlineExceeded) {
+ return "timeout"
+ }
+ return "failed"
+}
+
+// redactHookError keeps the host's own description and drops anything the
+// remote end supplied. An endpoint that echoes its input could otherwise write
+// issue content into a table that has no deletion path for it.
+func redactHookError(err error) string {
+ var pluginErr *PluginError
+ if errors.As(err, &pluginErr) {
+ return truncate(pluginErr.Message, 500)
+ }
+ if errors.Is(err, context.DeadlineExceeded) {
+ return "hook endpoint timed out"
+ }
+ return "hook call failed"
+}
+
+// hostInNetScopes is the exact-host check the consent screen promises. Never a
+// suffix match: one scope string must mean the same thing here as it does in
+// the surface CSP and on the authorization screen.
+func hostInNetScopes(host string, domains []string) bool {
+ host = strings.ToLower(strings.TrimSuffix(host, "."))
+ for _, domain := range domains {
+ if host == strings.ToLower(domain) {
+ return true
+ }
+ }
+ return false
+}
+
+func truncate(value string, limit int) string {
+ if len(value) <= limit {
+ return value
+ }
+ return value[:limit]
+}
diff --git a/server/internal/service/plugin_hook_test.go b/server/internal/service/plugin_hook_test.go
new file mode 100644
index 0000000000..d7360bbfa8
--- /dev/null
+++ b/server/internal/service/plugin_hook_test.go
@@ -0,0 +1,179 @@
+package service
+
+import (
+ "encoding/hex"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+func testInstallationID(t *testing.T) pgtype.UUID {
+ t.Helper()
+ parsed, err := parseUUIDValue("11111111-1111-4111-8111-111111111111")
+ if err != nil {
+ t.Fatalf("parse test uuid: %v", err)
+ }
+ return parsed
+}
+
+func testSigningService(t *testing.T) *PluginService {
+ t.Helper()
+ key := make([]byte, 32)
+ for i := range key {
+ key[i] = byte(i + 1)
+ }
+ return &PluginService{DeploymentKey: key}
+}
+
+// A signature only verifies against the exact bytes that were signed. These are
+// the two forgeries the scheme exists to stop: a changed body, and a captured
+// request replayed later.
+func TestVerifyHookSignatureRejectsTamperedBodyAndReplay(t *testing.T) {
+ service := testSigningService(t)
+ installationID := testInstallationID(t)
+ secret, err := service.HookSigningSecret(installationID)
+ if err != nil {
+ t.Fatalf("derive signing secret: %v", err)
+ }
+
+ timestamp := "1700000000"
+ body := []byte(`{"hook_key":"summarize","input":{"issue_id":"abc"}}`)
+ signature, err := service.SignHookPayload(installationID, timestamp, body)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ signedAt := time.Unix(1700000000, 0)
+
+ if err := VerifyHookSignature(secret, timestamp, body, signature, signedAt); err != nil {
+ t.Fatalf("a genuine request must verify: %v", err)
+ }
+
+ tampered := []byte(`{"hook_key":"summarize","input":{"issue_id":"someone-elses"}}`)
+ if err := VerifyHookSignature(secret, timestamp, tampered, signature, signedAt); err == nil {
+ t.Fatal("a body edited after signing must not verify")
+ }
+
+ // Same bytes, same signature, hours later. Without the timestamp in the
+ // signed string a captured request would stay valid forever.
+ late := signedAt.Add(2 * time.Hour)
+ if err := VerifyHookSignature(secret, timestamp, body, signature, late); err == nil {
+ t.Fatal("a replayed request outside the tolerance window must not verify")
+ }
+}
+
+// The signing secret is per installation. Two installations on the same
+// deployment must not be able to sign for each other.
+func TestHookSigningSecretIsPerInstallation(t *testing.T) {
+ service := testSigningService(t)
+ first := testInstallationID(t)
+ second, err := parseUUIDValue("22222222-2222-4222-8222-222222222222")
+ if err != nil {
+ t.Fatalf("parse uuid: %v", err)
+ }
+
+ firstSecret, err := service.HookSigningSecret(first)
+ if err != nil {
+ t.Fatalf("derive first: %v", err)
+ }
+ secondSecret, err := service.HookSigningSecret(second)
+ if err != nil {
+ t.Fatalf("derive second: %v", err)
+ }
+ if firstSecret == secondSecret {
+ t.Fatal("two installations must not share a signing secret")
+ }
+
+ timestamp := "1700000000"
+ body := []byte(`{"hook_key":"k"}`)
+ signature, err := service.SignHookPayload(first, timestamp, body)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ if err := VerifyHookSignature(secondSecret, timestamp, body, signature, time.Unix(1700000000, 0)); err == nil {
+ t.Fatal("one installation's signature must not verify against another's secret")
+ }
+}
+
+// Derivation is deterministic: an author configures the secret once and it keeps
+// working across restarts, because nothing about it is stored.
+func TestHookSigningSecretIsStableAcrossServiceInstances(t *testing.T) {
+ installationID := testInstallationID(t)
+ first, err := testSigningService(t).HookSigningSecret(installationID)
+ if err != nil {
+ t.Fatalf("derive: %v", err)
+ }
+ second, err := testSigningService(t).HookSigningSecret(installationID)
+ if err != nil {
+ t.Fatalf("derive: %v", err)
+ }
+ if first != second {
+ t.Fatal("the same deployment key and installation must derive the same secret")
+ }
+ if !strings.HasPrefix(first, "whsec_") {
+ t.Fatalf("signing secret should be prefixed for recognisability, got %q", first)
+ }
+ if _, err := hex.DecodeString(strings.TrimPrefix(first, "whsec_")); err != nil {
+ t.Fatalf("signing secret body must be hex: %v", err)
+ }
+}
+
+// Without a deployment key there is nothing to sign with, and the engine must
+// say so rather than send an unsigned request a handler would have to trust.
+func TestHookSigningFailsClosedWithoutDeploymentKey(t *testing.T) {
+ service := &PluginService{}
+ if _, err := service.SignHookPayload(testInstallationID(t), "1700000000", []byte("{}")); err == nil {
+ t.Fatal("signing without a deployment key must fail")
+ }
+}
+
+// A hook may only be invoked through a trigger its manifest declared. The host
+// does not get to invent a call site.
+func TestHookAllowsTriggerOnlyWhenDeclared(t *testing.T) {
+ hook := plugincontract.Hook{Triggers: []string{plugincontract.TriggerManual}}
+ if !HookAllowsTrigger(hook, plugincontract.TriggerManual) {
+ t.Fatal("a declared trigger must be allowed")
+ }
+ for _, undeclared := range []string{plugincontract.TriggerUI, plugincontract.TriggerEvent, plugincontract.TriggerAgent} {
+ if HookAllowsTrigger(hook, undeclared) {
+ t.Fatalf("%s was not declared and must not be allowed", undeclared)
+ }
+ }
+}
+
+// FindHook reads the CONSENTED manifest on the installation row. A hook that is
+// not in it does not exist, whatever the source URL serves today.
+func TestFindHookReadsTheConsentedManifest(t *testing.T) {
+ installation := db.PluginInstallation{
+ Manifest: []byte(`{
+ "manifest_version": 1,
+ "key": "com.example.hooks",
+ "name": "Hooks",
+ "description": "d",
+ "version": "1.0.0",
+ "author": {"name": "example"},
+ "scopes": ["net:example.com"],
+ "contributes": {"hooks": [{
+ "key": "summarize",
+ "name": "Summarize",
+ "description": "Summarize the thread.",
+ "triggers": ["manual"],
+ "transport": {"type": "http", "url": "https://example.com/hooks/summarize"}
+ }]}
+ }`),
+ }
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("declared hook must resolve: %v", err)
+ }
+ if hook.Transport.URL != "https://example.com/hooks/summarize" {
+ t.Fatalf("unexpected transport url %q", hook.Transport.URL)
+ }
+ if _, err := FindHook(installation, "not_declared"); err == nil {
+ t.Fatal("an undeclared hook key must not resolve")
+ }
+}
diff --git a/server/internal/service/plugin_hook_transport_test.go b/server/internal/service/plugin_hook_transport_test.go
new file mode 100644
index 0000000000..9fe050e7c1
--- /dev/null
+++ b/server/internal/service/plugin_hook_transport_test.go
@@ -0,0 +1,420 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// These exercise the real outbound path — a live HTTPS server, a real request,
+// a real signature — rather than the pieces in isolation. The endpoint runs on
+// loopback, which the SSRF guard refuses by design, so the test opts that exact
+// origin in through DevOrigins: the same switch a plugin author uses to develop
+// a hook against localhost. The consent check is NOT relaxed by it, which is
+// what TestHookRefusesEndpointOutsideNetScope pins down.
+
+type hookTestServer struct {
+ server *httptest.Server
+ received chan hookReceivedRequest
+ respond func(w http.ResponseWriter, body []byte)
+}
+
+type hookReceivedRequest struct {
+ Body []byte
+ Signature string
+ Timestamp string
+ Header http.Header
+}
+
+func newHookTestServer(t *testing.T) *hookTestServer {
+ t.Helper()
+ harness := &hookTestServer{received: make(chan hookReceivedRequest, 8)}
+ harness.server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ harness.received <- hookReceivedRequest{
+ Body: body,
+ Signature: r.Header.Get("X-Multica-Signature"),
+ Timestamp: r.Header.Get("X-Multica-Timestamp"),
+ Header: r.Header.Clone(),
+ }
+ if harness.respond != nil {
+ harness.respond(w, body)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true}`))
+ }))
+ t.Cleanup(harness.server.Close)
+ return harness
+}
+
+// hookTestService builds a service whose only outbound destination is the test
+// server, with signing enabled.
+func hookTestService(t *testing.T, harness *hookTestServer) *PluginService {
+ t.Helper()
+ service := testSigningService(t)
+ service.DevOrigins = []string{harness.server.URL}
+ service.HookClient = harness.server.Client()
+ service.Callbacks = NewCallbackTokens()
+ service.CallbackBaseURL = "https://multica.test/api/v1/plugin"
+ return service
+}
+
+// hookTestHost is the bare hostname of the test server, which is what a net:
+// scope names — the scope is an exact host, never a URL.
+func hookTestHost(harness *hookTestServer) string {
+ return strings.Split(strings.TrimPrefix(harness.server.URL, "https://"), ":")[0]
+}
+
+func hookTestInstallation(t *testing.T, endpoint, netScope string, triggers []string) db.PluginInstallation {
+ t.Helper()
+ triggerJSON, err := json.Marshal(triggers)
+ if err != nil {
+ t.Fatalf("marshal triggers: %v", err)
+ }
+ manifest := fmt.Sprintf(`{
+ "manifest_version": 1,
+ "key": "com.example.hooktest",
+ "name": "Hook Test",
+ "description": "d",
+ "version": "1.0.0",
+ "author": {"name": "example"},
+ "scopes": ["issues:read", "net:%s"],
+ "contributes": {"hooks": [{
+ "key": "summarize",
+ "name": "Summarize",
+ "description": "Summarize the thread.",
+ "triggers": %s,
+ "events": ["issue.created"],
+ "transport": {"type": "http", "url": "%s"}
+ }]}
+ }`, netScope, string(triggerJSON), endpoint)
+
+ scopes, err := json.Marshal([]string{"issues:read", "net:" + netScope})
+ if err != nil {
+ t.Fatalf("marshal scopes: %v", err)
+ }
+ return db.PluginInstallation{
+ ID: testInstallationID(t),
+ WorkspaceID: testInstallationID(t),
+ Enabled: true,
+ Manifest: []byte(manifest),
+ GrantedScopes: scopes,
+ }
+}
+
+// The receiving end must be able to prove the call came from us, using only the
+// signing secret it was configured with.
+func TestHookRequestIsSignedAndVerifiableByTheReceiver(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerManual})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ output, err := service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ Actor: HookActor{Type: "member", ID: testInstallationID(t)},
+ Input: map[string]string{"issue_id": "abc"},
+ })
+ if err != nil {
+ t.Fatalf("hook call: %v", err)
+ }
+ if string(output) != `{"ok":true}` {
+ t.Fatalf("unexpected output %q", string(output))
+ }
+
+ select {
+ case received := <-harness.received:
+ secret, err := service.HookSigningSecret(installation.ID)
+ if err != nil {
+ t.Fatalf("derive secret: %v", err)
+ }
+ if err := VerifyHookSignature(secret, received.Timestamp, received.Body, received.Signature, time.Now()); err != nil {
+ t.Fatalf("the receiver must be able to verify the signature: %v", err)
+ }
+ // One byte changed anywhere in the body must break it.
+ tampered := append([]byte{}, received.Body...)
+ tampered[len(tampered)-2] ^= 0xff
+ if err := VerifyHookSignature(secret, received.Timestamp, tampered, received.Signature, time.Now()); err == nil {
+ t.Fatal("a tampered body must not verify against the delivered signature")
+ }
+ default:
+ t.Fatal("the endpoint received no request")
+ }
+}
+
+// The `net:` scope is the whole promise made on the consent screen: this plugin
+// sends data to these hosts and no others. DevOrigins must not widen it.
+func TestHookRefusesEndpointOutsideNetScope(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ // Granted somewhere else entirely, while the transport points at the test
+ // server the operator did opt in to.
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", "elsewhere.example.com", []string{plugincontract.TriggerManual})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ _, err = service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ })
+ if err == nil {
+ t.Fatal("a destination outside the granted net: scope must be refused")
+ }
+ if !strings.Contains(err.Error(), "net:") {
+ t.Fatalf("the refusal should name the scope, got %v", err)
+ }
+ select {
+ case <-harness.received:
+ t.Fatal("no request may leave for an unapproved host")
+ default:
+ }
+}
+
+// An installation with no net: scope cannot call out at all.
+func TestHookRefusesWhenNoNetScopeGranted(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", "example.com", []string{plugincontract.TriggerManual})
+ installation.GrantedScopes = []byte(`["issues:read"]`)
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ if _, err := service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ }); err == nil {
+ t.Fatal("an installation with no net: scope must not reach the network")
+ }
+}
+
+// The callback token travels in the body, so a handler can answer without ever
+// being given standing access.
+//
+// Deliberately NOT single-use. A real handler reads the issue, decides, then
+// writes — two calls minimum. Making the token single-use looked stricter and
+// only pushed authors toward the installation's standing token, which never
+// expires; this test pins the looser bound as the intended one.
+func TestHookCarriesAnInvocationScopedCallbackToken(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerManual})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ actorID := testInstallationID(t)
+ if _, err := service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ Actor: HookActor{Type: "member", ID: actorID},
+ }); err != nil {
+ t.Fatalf("hook call: %v", err)
+ }
+
+ received := <-harness.received
+ var body hookRequestBody
+ if err := json.Unmarshal(received.Body, &body); err != nil {
+ t.Fatalf("decode delivered body: %v", err)
+ }
+ if body.CallbackToken == "" {
+ t.Fatal("the handler needs a callback token to answer with")
+ }
+ if body.CallbackURL != "https://multica.test/api/v1/plugin" {
+ t.Fatalf("unexpected callback url %q", body.CallbackURL)
+ }
+ if body.Actor.Type != "member" {
+ t.Fatalf("a manual trigger must carry the member actor, got %q", body.Actor.Type)
+ }
+
+ // Re-issued here because callHookEndpoint revokes the grant once the call it
+ // was issued for has returned.
+ token, err := service.Callbacks.Issue(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ Actor: HookActor{Type: "member", ID: actorID},
+ })
+ if err != nil {
+ t.Fatalf("issue: %v", err)
+ }
+
+ grant, err := service.Callbacks.Resolve(token)
+ if err != nil {
+ t.Fatalf("first resolve must succeed: %v", err)
+ }
+ if grant.Actor.Type != "member" || uuidString(grant.Actor.ID) != uuidString(actorID) {
+ t.Fatalf("the grant must carry the actor decided at dispatch, got %+v", grant.Actor)
+ }
+ // The second call is the one that used to fail. A handler that read the
+ // issue and then wanted to comment on it got a 403 here.
+ if _, err := service.Callbacks.Resolve(token); err != nil {
+ t.Fatalf("a handler must be able to make more than one call with one grant: %v", err)
+ }
+
+ // Revoked when the invocation is over, so it does not linger for its TTL.
+ service.Callbacks.Revoke(token)
+ if _, err := service.Callbacks.Resolve(token); err == nil {
+ t.Fatal("a revoked grant must stop resolving")
+ }
+}
+
+// The host resolved and permission-checked the issue, so it says which one this
+// call is about. Without it a handler has to read a client-supplied field —
+// unvalidated for ui/manual, and absent entirely for event, where no client was
+// involved.
+func TestHookBodyCarriesTheIssueTheHostResolved(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerEvent})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ issueID, err := parseUUIDValue("3fa85f64-5717-4562-b3fc-2c963f66afa6")
+ if err != nil {
+ t.Fatalf("parse issue id: %v", err)
+ }
+ if _, err := service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerEvent,
+ EventType: plugincontract.EventIssueCreated,
+ Actor: HookActor{Type: "plugin", ID: installation.ID},
+ IssueID: issueID,
+ }); err != nil {
+ t.Fatalf("hook call: %v", err)
+ }
+
+ received := <-harness.received
+ var body hookRequestBody
+ if err := json.Unmarshal(received.Body, &body); err != nil {
+ t.Fatalf("decode delivered body: %v", err)
+ }
+ if body.IssueID != uuidString(issueID) {
+ t.Fatalf("issue_id = %q, want %q — the handler has no other trustworthy way to know", body.IssueID, uuidString(issueID))
+ }
+}
+
+// A hook may not be reached through a trigger it never declared, even if the
+// caller asks for one the host supports.
+func TestInvokeHookRefusesUndeclaredTrigger(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerManual})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ if _, err := service.InvokeHook(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerEvent,
+ }, 1); err == nil {
+ t.Fatal("the event trigger was not declared and must be refused")
+ }
+ select {
+ case <-harness.received:
+ t.Fatal("no request may leave for an undeclared trigger")
+ default:
+ }
+}
+
+// A disabled installation is off, not merely hidden.
+func TestInvokeHookRefusesDisabledInstallation(t *testing.T) {
+ harness := newHookTestServer(t)
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerManual})
+ installation.Enabled = false
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ if _, err := service.InvokeHook(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ }, 1); err == nil {
+ t.Fatal("a disabled installation must not call out")
+ }
+}
+
+// A failing endpoint must produce an error the caller can act on, and must not
+// leak whatever the remote end said into our records.
+func TestHookFailureIsRedactedAndClassified(t *testing.T) {
+ harness := newHookTestServer(t)
+ harness.respond = func(w http.ResponseWriter, _ []byte) {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = w.Write([]byte("internal detail: secret-token-abc123 and an issue title"))
+ }
+ service := hookTestService(t, harness)
+ host := hookTestHost(harness)
+ installation := hookTestInstallation(t, harness.server.URL+"/hooks/summarize", host, []string{plugincontract.TriggerManual})
+
+ hook, err := FindHook(installation, "summarize")
+ if err != nil {
+ t.Fatalf("find hook: %v", err)
+ }
+ _, err = service.callHookEndpoint(context.Background(), HookInvocation{
+ Installation: installation,
+ Hook: hook,
+ Trigger: plugincontract.TriggerManual,
+ })
+ if err == nil {
+ t.Fatal("a 500 from the endpoint must be an error")
+ }
+ message := redactHookError(err)
+ if strings.Contains(message, "secret-token-abc123") || strings.Contains(message, "issue title") {
+ t.Fatalf("the recorded error must not echo the remote body, got %q", message)
+ }
+ if hookFailureStatus(err) != "failed" {
+ t.Fatalf("an unreachable-or-erroring endpoint is 'failed', got %q", hookFailureStatus(err))
+ }
+}
+
+// Refusals are decisions, not outages. The dispatcher relies on this to avoid
+// retrying a call that will be refused identically three times.
+func TestHookFailureStatusSeparatesRefusalsFromOutages(t *testing.T) {
+ refused := pluginErrf(PluginErrorForbidden, "not granted")
+ if hookFailureStatus(refused) != "refused" {
+ t.Fatalf("a forbidden error is a refusal, got %q", hookFailureStatus(refused))
+ }
+ quota := pluginErrf(PluginErrorQuota, "too many")
+ if hookFailureStatus(quota) != "refused" {
+ t.Fatalf("a quota error is a refusal, got %q", hookFailureStatus(quota))
+ }
+ outage := &PluginError{Kind: PluginErrorUnavailable, Message: "endpoint did not answer"}
+ if hookFailureStatus(outage) != "failed" {
+ t.Fatalf("an unavailable endpoint is a failure, got %q", hookFailureStatus(outage))
+ }
+}
diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.go
index c1e4902fed..f0f1c1fb6f 100644
--- a/server/internal/service/plugin_test.go
+++ b/server/internal/service/plugin_test.go
@@ -277,25 +277,54 @@ func TestCapabilityMessageNamesTheMissingCapabilities(t *testing.T) {
}
}
+// Binds every shipped capability to the host code that actually runs it.
+//
+// The gate is only meaningful if it tracks what renders. A capability enabled
+// here with no mount point installs successfully and then never appears — the
+// exact silent failure the gate exists to prevent — and nothing else in the
+// build would notice, because the manifest is valid and the install succeeds.
+//
+// Each line names the host code that makes it true. Flipping one on means
+// changing this file too, in the same commit as its runtime.
func TestShippedHostCapabilitiesRunTheSurfacesTheHostMounts(t *testing.T) {
- // The gate is only meaningful if it tracks what actually renders. A surface
- // type enabled here with no mount point installs successfully and then never
- // appears — the exact silent failure the gate exists to prevent.
shipped := plugincontract.HostCapabilities()
+
+ // packages/views/plugins/plugin-panel-section.tsx
if !shipped.SurfaceTypes[plugincontract.SurfaceIssuePanel] {
t.Fatal("issue_panel is mounted by PluginPanelSection and must be shipped")
}
+ // packages/views/plugins/plugin-modal-surface.tsx, opened from the issue
+ // actions menu by a person — never on the plugin's own initiative.
+ if !shipped.SurfaceTypes[plugincontract.SurfaceModal] {
+ t.Fatal("modal is mounted by PluginModalSurface and must be shipped")
+ }
+ // No host location exists for this one. Enabling it would install surfaces
+ // that never render.
if shipped.SurfaceTypes[plugincontract.SurfaceSidebarPanel] {
t.Fatal("sidebar_panel has no mount point yet; enabling it would install surfaces that never render")
}
- if shipped.SurfaceTypes[plugincontract.SurfaceModal] {
- t.Fatal("modal is opened by the manual trigger, which the hook engine has not landed")
- }
- for _, trigger := range []string{plugincontract.TriggerUI, plugincontract.TriggerManual, plugincontract.TriggerAgent, plugincontract.TriggerEvent} {
- if shipped.HookTriggers[trigger] {
- t.Fatalf("hook trigger %q is enabled but the hook engine has not landed", trigger)
+
+ // handler.InvokePluginHook serves ui and manual; service.PluginEventDispatcher
+ // serves event off the internal bus.
+ for _, trigger := range []string{plugincontract.TriggerUI, plugincontract.TriggerManual, plugincontract.TriggerEvent} {
+ if !shipped.HookTriggers[trigger] {
+ t.Fatalf("hook trigger %q has a host call site and must be shipped", trigger)
}
}
+ // The agent trigger is not a call site the host drives — it is a hook
+ // exposed to an agent as an MCP tool, which needs the daemon-side server.
+ if shipped.HookTriggers[plugincontract.TriggerAgent] {
+ t.Fatal("the agent trigger needs the daemon-side MCP server, which has not landed")
+ }
+
+ // service.callHookEndpoint speaks http and nothing else.
+ if !shipped.HookTransport[plugincontract.TransportHTTP] {
+ t.Fatal("the http transport is implemented by callHookEndpoint and must be shipped")
+ }
+ if shipped.HookTransport[plugincontract.TransportMCP] {
+ t.Fatal("the mcp transport has no implementation yet")
+ }
+
if shipped.ResourceTypes[plugincontract.ResourceSkill] {
t.Fatal("skill resources are enabled but the agent integration has not landed")
}
diff --git a/server/internal/service/plugin_token.go b/server/internal/service/plugin_token.go
new file mode 100644
index 0000000000..b2b1c77ac7
--- /dev/null
+++ b/server/internal/service/plugin_token.go
@@ -0,0 +1,217 @@
+package service
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Two credentials, moving in opposite directions.
+//
+// Neither one ever enters an iframe: a surface still holds nothing and still
+// reaches Multica only by asking the host page over postMessage. What changes
+// with hooks is that a plugin now has a SERVER, and that server needs a way to
+// be recognised. So the honest statement about the system is no longer "there
+// are no plugin credentials" but "plugin credentials only move between
+// servers".
+//
+// install token (mpi_…) plugin -> host, long-lived, rotatable.
+// The host only ever verifies it, so it is stored
+// hashed and cannot be recovered from the database.
+// callback token host -> plugin, minutes, one INVOCATION.
+// Handed to a hook handler so it can answer using the
+// Action API without being given standing access.
+
+const (
+ installTokenPrefix = "mpi_"
+ callbackTokenPrefix = "mpc_"
+ callbackTokenTTL = 5 * time.Minute
+ callbackTokenEntropy = 32
+)
+
+// IssueInstallToken mints a new install token and stores only its hash.
+//
+// Returned in plaintext exactly once. There is no endpoint that reads it back —
+// an admin who loses it rotates rather than recovers, which is the same trade
+// every other bearer credential in the product makes.
+func (s *PluginService) IssueInstallToken(ctx context.Context, installationID pgtype.UUID) (string, error) {
+ raw := make([]byte, callbackTokenEntropy)
+ if _, err := rand.Read(raw); err != nil {
+ return "", &PluginError{Kind: PluginErrorUnavailable, Message: "generate install token", Err: err}
+ }
+ token := installTokenPrefix + base64.RawURLEncoding.EncodeToString(raw)
+ if err := s.Queries.SetPluginInstallationToken(ctx, db.SetPluginInstallationTokenParams{
+ ID: installationID,
+ TokenHash: pgtype.Text{String: hashToken(token), Valid: true},
+ }); err != nil {
+ return "", &PluginError{Kind: PluginErrorUnavailable, Message: "store install token", Err: err}
+ }
+ return token, nil
+}
+
+// RevokeInstallToken drops the stored hash, so nothing presented afterwards
+// matches. Rotation is IssueInstallToken, which overwrites in place.
+func (s *PluginService) RevokeInstallToken(ctx context.Context, installationID pgtype.UUID) error {
+ if err := s.Queries.SetPluginInstallationToken(ctx, db.SetPluginInstallationTokenParams{
+ ID: installationID,
+ TokenHash: pgtype.Text{},
+ }); err != nil {
+ return &PluginError{Kind: PluginErrorUnavailable, Message: "revoke install token", Err: err}
+ }
+ return nil
+}
+
+// AuthenticateInstallToken resolves a presented token to its installation.
+func (s *PluginService) AuthenticateInstallToken(ctx context.Context, token string) (db.PluginInstallation, error) {
+ token = strings.TrimSpace(token)
+ if !strings.HasPrefix(token, installTokenPrefix) {
+ return db.PluginInstallation{}, pluginErrf(PluginErrorForbidden, "invalid plugin token")
+ }
+ installation, err := s.Queries.GetPluginInstallationByTokenHash(ctx, pgtype.Text{String: hashToken(token), Valid: true})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return db.PluginInstallation{}, pluginErrf(PluginErrorForbidden, "invalid plugin token")
+ }
+ if err != nil {
+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin installation", Err: err}
+ }
+ if !installation.Enabled {
+ return db.PluginInstallation{}, pluginErrf(PluginErrorForbidden, "this Plugin is disabled")
+ }
+ return installation, nil
+}
+
+func hashToken(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+// CallbackGrant is what a redeemed callback token proves.
+//
+// Its scopes are the installation's, never wider: the callback exists so a hook
+// handler can finish the job it was called for, not so an out-of-band request
+// can do more than the surface could.
+type CallbackGrant struct {
+ InstallationID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ HookKey string
+ Trigger string
+ // Actor is who the resulting writes belong to, decided when the hook was
+ // dispatched. A handler cannot choose to write as somebody else.
+ Actor HookActor
+ // IssueID narrows an event callback to the issue that produced it. Zero
+ // when the invocation had no issue.
+ IssueID pgtype.UUID
+ ExpiresAt time.Time
+}
+
+// CallbackTokens issues and resolves the per-invocation callback tokens.
+//
+// Scoped to one INVOCATION, not one request — and that distinction was found by
+// running a real handler rather than by reasoning about it. A single-use token
+// looked stricter and was: the reference handler reads the issue, decides, then
+// posts a comment, and the second call died on an already-spent token. Two calls
+// is the floor for any handler that does something with what it read.
+//
+// The trade that actually matters is not one-call versus several. It is this
+// token versus the installation's standing token: a handler that cannot finish
+// its job with the callback will simply be written against the install token
+// instead, which never expires and is not scoped to an invocation. A control
+// that pushes authors toward the stronger credential is worse than the slightly
+// looser one they will use.
+//
+// What still bounds it: minutes, this installation's granted scopes, the actor
+// decided at dispatch, and the issue the invocation was about.
+//
+// Held in memory. Across several instances or after a restart a token stops
+// resolving early rather than late, so the failure mode is a handler seeing 403
+// — visible and retriable — not a grant outliving its window.
+type CallbackTokens struct {
+ mu sync.Mutex
+ issued map[string]CallbackGrant
+}
+
+func NewCallbackTokens() *CallbackTokens {
+ return &CallbackTokens{issued: make(map[string]CallbackGrant)}
+}
+
+// Issue mints a token for one hook invocation.
+func (c *CallbackTokens) Issue(ctx context.Context, invocation HookInvocation) (string, error) {
+ raw := make([]byte, callbackTokenEntropy)
+ if _, err := rand.Read(raw); err != nil {
+ return "", &PluginError{Kind: PluginErrorUnavailable, Message: "generate callback token", Err: err}
+ }
+ token := callbackTokenPrefix + base64.RawURLEncoding.EncodeToString(raw)
+
+ grant := CallbackGrant{
+ InstallationID: invocation.Installation.ID,
+ WorkspaceID: invocation.Installation.WorkspaceID,
+ HookKey: invocation.Hook.Key,
+ Trigger: invocation.Trigger,
+ Actor: invocation.Actor,
+ IssueID: invocation.IssueID,
+ ExpiresAt: time.Now().Add(callbackTokenTTL),
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.sweepLocked()
+ c.issued[hashToken(token)] = grant
+ _ = ctx
+ return token, nil
+}
+
+// Resolve looks a token up. Valid for as many calls as the handler needs until
+// it expires; see the type comment for why that is the right bound.
+func (c *CallbackTokens) Resolve(token string) (CallbackGrant, error) {
+ token = strings.TrimSpace(token)
+ if !strings.HasPrefix(token, callbackTokenPrefix) {
+ return CallbackGrant{}, pluginErrf(PluginErrorForbidden, "invalid callback token")
+ }
+ key := hashToken(token)
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.sweepLocked()
+ grant, ok := c.issued[key]
+ if !ok {
+ return CallbackGrant{}, pluginErrf(PluginErrorForbidden, "callback token is expired or unknown")
+ }
+ if time.Now().After(grant.ExpiresAt) {
+ delete(c.issued, key)
+ return CallbackGrant{}, pluginErrf(PluginErrorForbidden, "callback token is expired or unknown")
+ }
+ return grant, nil
+}
+
+// Revoke drops a grant before its expiry. Called when a hook invocation has
+// finished, so a token stops working the moment the work it was issued for is
+// over rather than lingering for the rest of its window.
+func (c *CallbackTokens) Revoke(token string) {
+ if token == "" {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.issued, hashToken(strings.TrimSpace(token)))
+}
+
+// sweepLocked drops expired grants so the map cannot grow without bound on a
+// long-running server. Callers hold the mutex.
+func (c *CallbackTokens) sweepLocked() {
+ now := time.Now()
+ for key, grant := range c.issued {
+ if now.After(grant.ExpiresAt) {
+ delete(c.issued, key)
+ }
+ }
+}
diff --git a/server/migrations/362_plugin_hook_engine.down.sql b/server/migrations/362_plugin_hook_engine.down.sql
new file mode 100644
index 0000000000..3adea3d08c
--- /dev/null
+++ b/server/migrations/362_plugin_hook_engine.down.sql
@@ -0,0 +1,9 @@
+-- Note: this fails if any comment already has author_type = 'plugin'. That is
+-- the correct outcome — rolling back the constraint would otherwise leave rows
+-- the schema says cannot exist. Delete or re-attribute those rows first.
+ALTER TABLE comment DROP CONSTRAINT IF EXISTS comment_author_type_check;
+ALTER TABLE comment ADD CONSTRAINT comment_author_type_check
+ CHECK (author_type IN ('member', 'agent', 'system'));
+ALTER TABLE plugin_installation DROP COLUMN IF EXISTS token_rotated_at;
+ALTER TABLE plugin_installation DROP COLUMN IF EXISTS token_hash;
+DROP TABLE IF EXISTS plugin_invocation;
diff --git a/server/migrations/362_plugin_hook_engine.up.sql b/server/migrations/362_plugin_hook_engine.up.sql
new file mode 100644
index 0000000000..440cdd19e2
--- /dev/null
+++ b/server/migrations/362_plugin_hook_engine.up.sql
@@ -0,0 +1,64 @@
+-- Hook engine: the host calls out to a plugin's own server.
+--
+-- Everything before this shipped one direction only — a sandboxed surface asks
+-- the host, the host acts on the signed-in user's session. This is the reverse
+-- edge, so the two new things it needs are a record of what we sent (triage,
+-- rate limiting, circuit breaking) and a credential a plugin backend can present
+-- when it calls back.
+
+-- One row per hook call. Deliberately NOT an audit log: it is TTL-swept, it
+-- stores no request or response body, and nothing in the product reads it to
+-- decide what happened to a user's data. Its jobs are operational — show the
+-- author why their endpoint is failing, feed the per-hook rate limit, and let
+-- the event dispatcher decide when to trip a circuit breaker.
+--
+-- Bodies are omitted on purpose. A hook payload can carry issue text, and a
+-- table that keeps every payload forever is a second copy of workspace content
+-- with none of the deletion paths that the first copy has.
+CREATE TABLE plugin_invocation (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ installation_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ hook_key TEXT NOT NULL CHECK (char_length(hook_key) BETWEEN 1 AND 128),
+ trigger TEXT NOT NULL CHECK (trigger IN ('ui', 'manual', 'event', 'agent')),
+ status TEXT NOT NULL CHECK (status IN ('ok', 'failed', 'timeout', 'refused')),
+ -- Which event caused an event-triggered call. NULL for every other trigger.
+ event_type TEXT,
+ attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt BETWEEN 1 AND 10),
+ latency_ms INTEGER NOT NULL DEFAULT 0 CHECK (latency_ms >= 0),
+ -- Redacted, bounded, and only ever the host's own description of the
+ -- failure. Never a response body: an endpoint that echoes its input would
+ -- otherwise write issue content in here through the back door.
+ error TEXT CHECK (error IS NULL OR char_length(error) <= 500),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Install token: lets a plugin's own backend reach the Action API without a
+-- user in the loop. Only the hash is stored, so a database read cannot mint a
+-- working credential, and rotation is an UPDATE of this column.
+--
+-- This is the first credential in the system that is not the signed-in user's
+-- session. It does not weaken the surface rule — a token still never enters an
+-- iframe, and a surface still cannot obtain one — but the claim is now "tokens
+-- only move between servers" rather than "there are no tokens".
+ALTER TABLE plugin_installation ADD COLUMN IF NOT EXISTS token_hash TEXT;
+ALTER TABLE plugin_installation ADD COLUMN IF NOT EXISTS token_rotated_at TIMESTAMPTZ;
+
+-- A fourth comment author. Identity follows the trigger: a ui/manual hook acts
+-- for the person who pressed the button and stays attributed to them (with
+-- via_plugin_id naming the plugin), while an event hook has no person behind it
+-- and must not borrow one. author_id then holds the installation id.
+--
+-- Same reason as migration 107, which added 'system': a row the platform
+-- produced that would be a lie attributed to any member. NOT the same shape,
+-- though — 107 revalidated the whole table under ACCESS EXCLUSIVE, which was
+-- cheap on the comment table of that era and is not on today's. NOT VALID adds
+-- the constraint without a scan; migration 365 validates it under a lock that
+-- readers and writers can share.
+--
+-- New rows are checked from the moment this lands. NOT VALID only means "do not
+-- re-check the rows already here", and the widened set is a superset of the old
+-- one, so there is nothing here that could violate it.
+ALTER TABLE comment DROP CONSTRAINT IF EXISTS comment_author_type_check;
+ALTER TABLE comment ADD CONSTRAINT comment_author_type_check
+ CHECK (author_type IN ('member', 'agent', 'system', 'plugin')) NOT VALID;
diff --git a/server/migrations/363_plugin_invocation_installation_index.down.sql b/server/migrations/363_plugin_invocation_installation_index.down.sql
new file mode 100644
index 0000000000..853d259b90
--- /dev/null
+++ b/server/migrations/363_plugin_invocation_installation_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_invocation_installation_created;
diff --git a/server/migrations/363_plugin_invocation_installation_index.up.sql b/server/migrations/363_plugin_invocation_installation_index.up.sql
new file mode 100644
index 0000000000..5bb1e4d6c2
--- /dev/null
+++ b/server/migrations/363_plugin_invocation_installation_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_invocation_installation_created
+ ON plugin_invocation (installation_id, created_at DESC);
diff --git a/server/migrations/364_plugin_invocation_created_at_index.down.sql b/server/migrations/364_plugin_invocation_created_at_index.down.sql
new file mode 100644
index 0000000000..face5fe3ae
--- /dev/null
+++ b/server/migrations/364_plugin_invocation_created_at_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_invocation_created_at;
diff --git a/server/migrations/364_plugin_invocation_created_at_index.up.sql b/server/migrations/364_plugin_invocation_created_at_index.up.sql
new file mode 100644
index 0000000000..0e742200d6
--- /dev/null
+++ b/server/migrations/364_plugin_invocation_created_at_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_invocation_created_at
+ ON plugin_invocation (created_at);
diff --git a/server/migrations/365_plugin_comment_author_type_validate.down.sql b/server/migrations/365_plugin_comment_author_type_validate.down.sql
new file mode 100644
index 0000000000..e51a5ffa96
--- /dev/null
+++ b/server/migrations/365_plugin_comment_author_type_validate.down.sql
@@ -0,0 +1,3 @@
+-- Nothing to undo: a validated constraint cannot be returned to NOT VALID, and
+-- 362's down drops the constraint outright.
+SELECT 1;
diff --git a/server/migrations/365_plugin_comment_author_type_validate.up.sql b/server/migrations/365_plugin_comment_author_type_validate.up.sql
new file mode 100644
index 0000000000..c554811474
--- /dev/null
+++ b/server/migrations/365_plugin_comment_author_type_validate.up.sql
@@ -0,0 +1,6 @@
+-- Validates the constraint migration 362 added NOT VALID.
+--
+-- Split out because VALIDATE CONSTRAINT takes SHARE UPDATE EXCLUSIVE — readers
+-- and writers continue — while doing the scan that ADD CONSTRAINT would have
+-- done under ACCESS EXCLUSIVE, stopping the comment table for its duration.
+ALTER TABLE comment VALIDATE CONSTRAINT comment_author_type_check;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a59d77ddcc..0db6dc9a7f 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -940,18 +940,34 @@ 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"`
+ 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"`
+}
+
+type PluginInvocation struct {
+ ID pgtype.UUID `json:"id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ HookKey string `json:"hook_key"`
+ Trigger string `json:"trigger"`
+ Status string `json:"status"`
+ EventType pgtype.Text `json:"event_type"`
+ Attempt int32 `json:"attempt"`
+ LatencyMs int32 `json:"latency_ms"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type PluginSecret struct {
diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.go
index 74b3d976ee..ce35467298 100644
--- a/server/pkg/db/generated/plugin.sql.go
+++ b/server/pkg/db/generated/plugin.sql.go
@@ -11,11 +11,51 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const countRecentPluginFailures = `-- name: CountRecentPluginFailures :one
+SELECT count(*) FROM plugin_invocation
+WHERE installation_id = $1 AND hook_key = $2 AND created_at > $3 AND status <> 'ok'
+`
+
+type CountRecentPluginFailuresParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ HookKey string `json:"hook_key"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Consecutive-failure signal for the event circuit breaker. Bounded by time so
+// a breaker that tripped hours ago does not keep a hook shut forever.
+func (q *Queries) CountRecentPluginFailures(ctx context.Context, arg CountRecentPluginFailuresParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countRecentPluginFailures, arg.InstallationID, arg.HookKey, arg.CreatedAt)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countRecentPluginInvocations = `-- name: CountRecentPluginInvocations :one
+SELECT count(*) FROM plugin_invocation
+WHERE installation_id = $1 AND hook_key = $2 AND created_at > $3
+`
+
+type CountRecentPluginInvocationsParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ HookKey string `json:"hook_key"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Feeds the per-hook rate limit. Counts attempts, not distinct calls: a hook
+// retrying into a dead endpoint is exactly the traffic the limit exists to cap.
+func (q *Queries) CountRecentPluginInvocations(ctx context.Context, arg CountRecentPluginInvocationsParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countRecentPluginInvocations, arg.InstallationID, arg.HookKey, arg.CreatedAt)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
const createPluginInstallation = `-- name: CreatePluginInstallation :one
INSERT INTO plugin_installation (
workspace_id, plugin_key, source_url, 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
+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
`
type CreatePluginInstallationParams struct {
@@ -52,10 +92,73 @@ func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePlugin
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
+ )
+ return i, err
+}
+
+const createPluginInvocation = `-- name: CreatePluginInvocation :one
+INSERT INTO plugin_invocation (
+ installation_id, workspace_id, hook_key, trigger, status, event_type, attempt, latency_ms, error
+) VALUES ($1, $2, $3, $4, $5, $8, $6, $7, $9)
+RETURNING id, installation_id, workspace_id, hook_key, trigger, status, event_type, attempt, latency_ms, error, created_at
+`
+
+type CreatePluginInvocationParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ HookKey string `json:"hook_key"`
+ Trigger string `json:"trigger"`
+ Status string `json:"status"`
+ Attempt int32 `json:"attempt"`
+ LatencyMs int32 `json:"latency_ms"`
+ EventType pgtype.Text `json:"event_type"`
+ Error pgtype.Text `json:"error"`
+}
+
+func (q *Queries) CreatePluginInvocation(ctx context.Context, arg CreatePluginInvocationParams) (PluginInvocation, error) {
+ row := q.db.QueryRow(ctx, createPluginInvocation,
+ arg.InstallationID,
+ arg.WorkspaceID,
+ arg.HookKey,
+ arg.Trigger,
+ arg.Status,
+ arg.Attempt,
+ arg.LatencyMs,
+ arg.EventType,
+ arg.Error,
+ )
+ var i PluginInvocation
+ err := row.Scan(
+ &i.ID,
+ &i.InstallationID,
+ &i.WorkspaceID,
+ &i.HookKey,
+ &i.Trigger,
+ &i.Status,
+ &i.EventType,
+ &i.Attempt,
+ &i.LatencyMs,
+ &i.Error,
+ &i.CreatedAt,
)
return i, err
}
+const deleteExpiredPluginInvocations = `-- name: DeleteExpiredPluginInvocations :execrows
+DELETE FROM plugin_invocation WHERE created_at < $1
+`
+
+// TTL sweep. This table is operational telemetry, not history to keep.
+func (q *Queries) DeleteExpiredPluginInvocations(ctx context.Context, createdAt pgtype.Timestamptz) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteExpiredPluginInvocations, createdAt)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const deletePluginInstallation = `-- name: DeletePluginInstallation :exec
DELETE FROM plugin_installation WHERE id = $1
`
@@ -65,6 +168,15 @@ func (q *Queries) DeletePluginInstallation(ctx context.Context, id pgtype.UUID)
return err
}
+const deletePluginInvocationsByInstallation = `-- name: DeletePluginInvocationsByInstallation :exec
+DELETE FROM plugin_invocation WHERE installation_id = $1
+`
+
+func (q *Queries) DeletePluginInvocationsByInstallation(ctx context.Context, installationID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deletePluginInvocationsByInstallation, installationID)
+ return err
+}
+
const deletePluginSecret = `-- name: DeletePluginSecret :execrows
DELETE FROM plugin_secret WHERE installation_id = $1 AND key = $2
`
@@ -126,7 +238,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 FROM plugin_installation WHERE id = $1
+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 FROM plugin_installation WHERE id = $1
`
func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (PluginInstallation, error) {
@@ -145,6 +257,35 @@ func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (Pl
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
+ )
+ 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 FROM plugin_installation WHERE token_hash = $1
+`
+
+// Looked up by hash, so the plaintext token exists only in the caller's request.
+func (q *Queries) GetPluginInstallationByTokenHash(ctx context.Context, tokenHash pgtype.Text) (PluginInstallation, error) {
+ row := q.db.QueryRow(ctx, getPluginInstallationByTokenHash, tokenHash)
+ var i PluginInstallation
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.PluginKey,
+ &i.SourceUrl,
+ &i.Version,
+ &i.Manifest,
+ &i.GrantedScopes,
+ &i.Config,
+ &i.Enabled,
+ &i.InstalledBy,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
return i, err
}
@@ -242,7 +383,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 FROM plugin_installation
+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 FROM plugin_installation
WHERE workspace_id = $1 AND id = $2
`
@@ -267,12 +408,14 @@ func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWor
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
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 FROM plugin_installation
+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 FROM plugin_installation
WHERE workspace_id = $1 AND plugin_key = $2
`
@@ -297,10 +440,56 @@ func (q *Queries) GetWorkspacePluginInstallationByKey(ctx context.Context, arg G
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
return i, err
}
+const listPluginInvocations = `-- name: ListPluginInvocations :many
+SELECT id, installation_id, workspace_id, hook_key, trigger, status, event_type, attempt, latency_ms, error, created_at FROM plugin_invocation
+WHERE installation_id = $1
+ORDER BY created_at DESC
+LIMIT $2
+`
+
+type ListPluginInvocationsParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ Limit int32 `json:"limit"`
+}
+
+func (q *Queries) ListPluginInvocations(ctx context.Context, arg ListPluginInvocationsParams) ([]PluginInvocation, error) {
+ rows, err := q.db.Query(ctx, listPluginInvocations, arg.InstallationID, arg.Limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []PluginInvocation{}
+ for rows.Next() {
+ var i PluginInvocation
+ if err := rows.Scan(
+ &i.ID,
+ &i.InstallationID,
+ &i.WorkspaceID,
+ &i.HookKey,
+ &i.Trigger,
+ &i.Status,
+ &i.EventType,
+ &i.Attempt,
+ &i.LatencyMs,
+ &i.Error,
+ &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 :many
SELECT key, updated_at FROM plugin_secret
WHERE installation_id = $1
@@ -374,7 +563,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 FROM plugin_installation
+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 FROM plugin_installation
WHERE workspace_id = $1
ORDER BY created_at ASC
`
@@ -401,6 +590,8 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspac
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
); err != nil {
return nil, err
}
@@ -417,7 +608,7 @@ UPDATE plugin_installation
SET 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
+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
`
type SetPluginInstallationEnabledParams struct {
@@ -441,16 +632,34 @@ func (q *Queries) SetPluginInstallationEnabled(ctx context.Context, arg SetPlugi
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
return i, err
}
+const setPluginInstallationToken = `-- name: SetPluginInstallationToken :exec
+UPDATE plugin_installation
+SET token_hash = $2, token_rotated_at = now(), updated_at = now()
+WHERE id = $1
+`
+
+type SetPluginInstallationTokenParams struct {
+ ID pgtype.UUID `json:"id"`
+ TokenHash pgtype.Text `json:"token_hash"`
+}
+
+func (q *Queries) SetPluginInstallationToken(ctx context.Context, arg SetPluginInstallationTokenParams) error {
+ _, err := q.db.Exec(ctx, setPluginInstallationToken, arg.ID, arg.TokenHash)
+ return err
+}
+
const updatePluginInstallationConfig = `-- name: UpdatePluginInstallationConfig :one
UPDATE plugin_installation
SET 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
+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
`
type UpdatePluginInstallationConfigParams struct {
@@ -474,6 +683,8 @@ func (q *Queries) UpdatePluginInstallationConfig(ctx context.Context, arg Update
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
return i, err
}
@@ -487,7 +698,7 @@ SET source_url = $2,
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
+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
`
type UpdatePluginInstallationManifestParams struct {
@@ -525,6 +736,8 @@ func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg Upda
&i.InstalledBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.TokenHash,
+ &i.TokenRotatedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index c97c85aac9..e7a4da5a04 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -492,6 +492,10 @@ deleted_storage AS (
deleted_secrets AS (
DELETE FROM plugin_secret
WHERE installation_id IN (SELECT id FROM installations)
+),
+deleted_invocations AS (
+ DELETE FROM plugin_invocation
+ WHERE workspace_id = $1
)
DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)
`
@@ -499,6 +503,9 @@ DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)
// Plugin relationships have no foreign keys or cascades. Storage and secrets
// hang off the installation, so both leaf tables are cleared through the
// workspace's installation ids before the installations themselves.
+// 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.
func (q *Queries) DeleteWorkspacePluginData(ctx context.Context, workspaceID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteWorkspacePluginData, workspaceID)
return err
diff --git a/server/pkg/db/queries/plugin.sql b/server/pkg/db/queries/plugin.sql
index d39e497545..42fe9216e4 100644
--- a/server/pkg/db/queries/plugin.sql
+++ b/server/pkg/db/queries/plugin.sql
@@ -107,3 +107,43 @@ DELETE FROM plugin_secret WHERE installation_id = $1 AND key = $2;
-- name: DeletePluginSecretsByInstallation :exec
DELETE FROM plugin_secret WHERE installation_id = $1;
+
+-- name: SetPluginInstallationToken :exec
+UPDATE plugin_installation
+SET token_hash = $2, token_rotated_at = now(), updated_at = now()
+WHERE id = $1;
+
+-- name: GetPluginInstallationByTokenHash :one
+-- Looked up by hash, so the plaintext token exists only in the caller's request.
+SELECT * FROM plugin_installation WHERE token_hash = $1;
+
+-- name: CreatePluginInvocation :one
+INSERT INTO plugin_invocation (
+ installation_id, workspace_id, hook_key, trigger, status, event_type, attempt, latency_ms, error
+) VALUES ($1, $2, $3, $4, $5, sqlc.narg(event_type), $6, $7, sqlc.narg(error))
+RETURNING *;
+
+-- name: ListPluginInvocations :many
+SELECT * FROM plugin_invocation
+WHERE installation_id = $1
+ORDER BY created_at DESC
+LIMIT $2;
+
+-- name: CountRecentPluginInvocations :one
+-- Feeds the per-hook rate limit. Counts attempts, not distinct calls: a hook
+-- retrying into a dead endpoint is exactly the traffic the limit exists to cap.
+SELECT count(*) FROM plugin_invocation
+WHERE installation_id = $1 AND hook_key = $2 AND created_at > $3;
+
+-- name: CountRecentPluginFailures :one
+-- Consecutive-failure signal for the event circuit breaker. Bounded by time so
+-- a breaker that tripped hours ago does not keep a hook shut forever.
+SELECT count(*) FROM plugin_invocation
+WHERE installation_id = $1 AND hook_key = $2 AND created_at > $3 AND status <> 'ok';
+
+-- name: DeletePluginInvocationsByInstallation :exec
+DELETE FROM plugin_invocation WHERE installation_id = $1;
+
+-- name: DeleteExpiredPluginInvocations :execrows
+-- TTL sweep. This table is operational telemetry, not history to keep.
+DELETE FROM plugin_invocation WHERE created_at < $1;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 1f7ad4602d..45dad74770 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -591,6 +591,13 @@ deleted_storage AS (
deleted_secrets AS (
DELETE FROM plugin_secret
WHERE installation_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.
+deleted_invocations AS (
+ DELETE FROM plugin_invocation
+ WHERE workspace_id = $1
)
DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations);
diff --git a/server/pkg/plugincontract/capabilities.go b/server/pkg/plugincontract/capabilities.go
index ba20e84352..36a4bf6fcc 100644
--- a/server/pkg/plugincontract/capabilities.go
+++ b/server/pkg/plugincontract/capabilities.go
@@ -27,13 +27,23 @@ type Capabilities struct {
// resources land with the agent integration.
func HostCapabilities() Capabilities {
return Capabilities{
- // issue_panel only: PluginPanelSection is the one mount point that exists.
- // sidebar_panel has no host location yet, and enabling a surface the host
- // cannot render installs a plugin that silently never appears — precisely
- // what this gate exists to prevent.
- SurfaceTypes: map[string]bool{SurfaceIssuePanel: true},
- HookTriggers: map[string]bool{},
- HookTransport: map[string]bool{},
+ // issue_panel mounts in PluginPanelSection; modal opens from a manual
+ // hook action. sidebar_panel stays off — it has no host location, and
+ // enabling a surface the host cannot render installs a plugin that
+ // silently never appears, which is precisely what this gate prevents.
+ SurfaceTypes: map[string]bool{
+ SurfaceIssuePanel: true,
+ SurfaceModal: true,
+ },
+ // The agent trigger is not a fourth call site the host drives; it is a
+ // hook exposed to an agent as an MCP tool, which needs the daemon-side
+ // server that lands with the agent integration.
+ HookTriggers: map[string]bool{
+ TriggerUI: true,
+ TriggerManual: true,
+ TriggerEvent: true,
+ },
+ HookTransport: map[string]bool{TransportHTTP: true},
ResourceTypes: map[string]bool{},
}
}
diff --git a/server/pkg/plugincontract/examples_test.go b/server/pkg/plugincontract/examples_test.go
new file mode 100644
index 0000000000..def4249444
--- /dev/null
+++ b/server/pkg/plugincontract/examples_test.go
@@ -0,0 +1,63 @@
+package plugincontract_test
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+// The shipped examples are documentation, and documentation that does not parse
+// is worse than none: an author copies it, hits a validation error the docs said
+// nothing about, and concludes the contract is undocumented.
+//
+// This also catches the failure mode a capability flip introduces. An example
+// declaring something the host has not shipped yet would install nowhere, and
+// nothing else in the build would say so — the manifest is valid, it is the
+// gate that refuses it.
+func TestShippedExamplesParseAndInstallOnThisHost(t *testing.T) {
+ root := filepath.Join("..", "..", "..", "examples", "plugins")
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ t.Fatalf("read examples directory: %v", err)
+ }
+
+ found := 0
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ path := filepath.Join(root, entry.Name(), "multica.plugin.json")
+ raw, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ found++
+
+ t.Run(entry.Name(), func(t *testing.T) {
+ manifest, _, err := plugincontract.ParseManifest(raw)
+ if err != nil {
+ t.Fatalf("example manifest does not parse: %v", err)
+ }
+ if err := manifest.CheckCapabilities(plugincontract.HostCapabilities()); err != nil {
+ t.Fatalf("example declares something this host cannot run, so it could not be installed: %v", err)
+ }
+ // A surface entry that is not in the example's own directory is a
+ // broken example: the reader copies it and gets a blank panel.
+ for _, surface := range manifest.Contributes.Surfaces {
+ entryPath := filepath.Join(root, entry.Name(), surface.Entry)
+ if _, err := os.Stat(entryPath); err != nil {
+ t.Fatalf("surface %q points at %s, which is not in the example: %v", surface.Key, surface.Entry, err)
+ }
+ }
+ })
+ }
+
+ if found == 0 {
+ t.Fatal("no example manifests were found; this test would pass vacuously")
+ }
+}
diff --git a/server/pkg/plugincontract/manifest.go b/server/pkg/plugincontract/manifest.go
index 4d83ce5621..c78007d6f0 100644
--- a/server/pkg/plugincontract/manifest.go
+++ b/server/pkg/plugincontract/manifest.go
@@ -116,6 +116,27 @@ var fixedScopes = map[string]bool{
ScopeStorageWorkspace: true,
}
+func hasScope(scopes []string, want string) bool {
+ for _, scope := range scopes {
+ if scope == want {
+ return true
+ }
+ }
+ return false
+}
+
+// eventReadScope maps each event onto the scope a plugin would have needed to
+// read the same content through the Action API.
+var eventReadScope = map[string]string{
+ EventIssueCreated: ScopeIssuesRead,
+ EventIssueUpdated: ScopeIssuesRead,
+ EventIssueStatusChanged: ScopeIssuesRead,
+ EventCommentCreated: ScopeCommentsRead,
+ EventTaskStarted: ScopeTasksRead,
+ EventTaskCompleted: ScopeTasksRead,
+ EventTaskFailed: ScopeTasksRead,
+}
+
var knownEvents = map[string]bool{
EventIssueCreated: true,
EventIssueUpdated: true,
@@ -126,6 +147,11 @@ var knownEvents = map[string]bool{
EventTaskFailed: true,
}
+// IsKnownEvent reports whether an event may be subscribed to by a manifest.
+// Exported so the dispatcher cannot publish an event no plugin could ever
+// receive — the two lists have to agree, and only one of them is authoritative.
+func IsKnownEvent(event string) bool { return knownEvents[event] }
+
var (
pluginKeySegmentPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`)
contributionKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[_-][a-z0-9]+)*$`)
@@ -601,6 +627,15 @@ func (m Manifest) validateContributions() error {
return fmt.Errorf("%s.events contains duplicate event %q", field, event)
}
eventSeen[event] = true
+ // An event PUSHES the same content the Action API would have
+ // required a scope to pull: issue.* carries the description,
+ // comment.created carries the body. Without this, subscribing is
+ // a way to receive what reading was not granted — one dataset
+ // with two standards. Enforced at install, so the consent screen
+ // shows the read scope the subscription actually implies.
+ if required := eventReadScope[event]; required != "" && !hasScope(m.Scopes, required) {
+ return fmt.Errorf("%s.events subscribes to %q, which delivers content requiring the %s scope", field, event, required)
+ }
}
} else if len(hook.Events) > 0 {
return fmt.Errorf("%s.events requires the event trigger", field)
diff --git a/server/pkg/plugincontract/manifest_test.go b/server/pkg/plugincontract/manifest_test.go
index 5d96855ce1..2953911999 100644
--- a/server/pkg/plugincontract/manifest_test.go
+++ b/server/pkg/plugincontract/manifest_test.go
@@ -370,33 +370,72 @@ func TestNetDomainsOnlyReturnsNetScopes(t *testing.T) {
}
}
+// The gate's job, stated without naming today's configuration.
+//
+// An earlier version listed the specific contributions HostCapabilities had not
+// shipped yet, so every staged flip turned this red with a message about the
+// flip rather than about the gate. What has to stay true is the mechanism:
+// everything the host cannot run is reported, everything it can run is not, and
+// all of it arrives at once.
func TestCheckCapabilitiesReportsEveryUnavailableContribution(t *testing.T) {
manifest, _, err := ParseManifest([]byte(validManifest))
if err != nil {
t.Fatalf("ParseManifest: %v", err)
}
- // The shipped host set is what gates a staged rollout: a manifest naming a
- // capability this build cannot run must fail loudly, never install
- // half-working. Surfaces ship with the surface runtime; hooks and skill
- // resources are still ahead, so they are what must be reported here.
- err = manifest.CheckCapabilities(HostCapabilities())
+ // Against a host that supports nothing, every declared contribution in the
+ // fixture must be named — not the first one found.
+ err = manifest.CheckCapabilities(Capabilities{})
if err == nil {
- t.Fatal("CheckCapabilities accepted contributions the host cannot run")
+ t.Fatal("a host with no capabilities accepted contributions it cannot run")
}
var unavailable *ErrCapabilityUnavailable
if !asCapabilityError(err, &unavailable) {
t.Fatalf("error type = %T, want *ErrCapabilityUnavailable", err)
}
- for _, want := range []string{"hook trigger ui", "hook transport http", "resource skill"} {
+ wantAll := []string{}
+ for _, surface := range manifest.Contributes.Surfaces {
+ wantAll = append(wantAll, "surface "+surface.Type)
+ }
+ for _, hook := range manifest.Contributes.Hooks {
+ for _, trigger := range hook.Triggers {
+ wantAll = append(wantAll, "hook trigger "+trigger)
+ }
+ wantAll = append(wantAll, "hook transport "+hook.Transport.Type)
+ }
+ for _, resource := range manifest.Contributes.Resources {
+ wantAll = append(wantAll, "resource "+resource.Type)
+ }
+ for _, want := range wantAll {
if !containsString(unavailable.Missing, want) {
- t.Fatalf("missing = %v, want it to include %q", unavailable.Missing, want)
+ t.Fatalf("missing = %v, want it to include %q — every gap must be reported at once, not one install at a time", unavailable.Missing, want)
+ }
+ }
+
+ // Against the real host set: whatever is shipped must NOT be reported, and
+ // whatever is not shipped must be. Derived from HostCapabilities rather than
+ // restated, so a flip changes one place and this keeps testing the gate.
+ host := HostCapabilities()
+ hostErr := manifest.CheckCapabilities(host)
+ reported := []string{}
+ if hostErr != nil {
+ var hostUnavailable *ErrCapabilityUnavailable
+ if !asCapabilityError(hostErr, &hostUnavailable) {
+ t.Fatalf("error type = %T, want *ErrCapabilityUnavailable", hostErr)
}
+ reported = hostUnavailable.Missing
}
- // A shipped capability must NOT be reported, or every install of a plain
- // panel plugin would fail on a capability the host can actually run.
- if containsString(unavailable.Missing, "surface "+SurfaceIssuePanel) {
- t.Fatalf("missing = %v, want it to exclude the shipped issue_panel surface", unavailable.Missing)
+ for _, surface := range manifest.Contributes.Surfaces {
+ assertGateAgrees(t, reported, "surface "+surface.Type, host.SurfaceTypes[surface.Type])
+ }
+ for _, hook := range manifest.Contributes.Hooks {
+ for _, trigger := range hook.Triggers {
+ assertGateAgrees(t, reported, "hook trigger "+trigger, host.HookTriggers[trigger])
+ }
+ assertGateAgrees(t, reported, "hook transport "+hook.Transport.Type, host.HookTransport[hook.Transport.Type])
+ }
+ for _, resource := range manifest.Contributes.Resources {
+ assertGateAgrees(t, reported, "resource "+resource.Type, host.ResourceTypes[resource.Type])
}
full := Capabilities{
@@ -410,6 +449,20 @@ func TestCheckCapabilitiesReportsEveryUnavailableContribution(t *testing.T) {
}
}
+// assertGateAgrees pins the gate to the host set in both directions: a shipped
+// capability reported as missing would fail every install of a plugin the host
+// can actually run, and an unshipped one left unreported would install a
+// contribution that silently never fires.
+func assertGateAgrees(t *testing.T, reported []string, name string, shipped bool) {
+ t.Helper()
+ if shipped && containsString(reported, name) {
+ t.Fatalf("%q is shipped by this host but was reported unavailable", name)
+ }
+ if !shipped && !containsString(reported, name) {
+ t.Fatalf("%q is NOT shipped by this host but was not reported — it would install and never fire", name)
+ }
+}
+
func asCapabilityError(err error, target **ErrCapabilityUnavailable) bool {
candidate, ok := err.(*ErrCapabilityUnavailable)
if ok {
@@ -426,3 +479,55 @@ func containsString(values []string, want string) bool {
}
return false
}
+
+// An event subscription delivers the same content the Action API would have
+// required a scope to read: issue.* carries the description, comment.created
+// carries the body. Without this check, subscribing was a way to receive what
+// reading was never granted.
+func TestEventSubscriptionRequiresTheMatchingReadScope(t *testing.T) {
+ manifest := func(scopes, events string) []byte {
+ return []byte(`{
+ "manifest_version": 1,
+ "key": "com.example.events",
+ "name": "Events",
+ "description": "d",
+ "version": "1.0.0",
+ "author": {"name": "example"},
+ "scopes": ` + scopes + `,
+ "contributes": {"hooks": [{
+ "key": "watch",
+ "name": "Watch",
+ "description": "Watch things happen.",
+ "triggers": ["event"],
+ "events": ` + events + `,
+ "transport": {"type": "http", "url": "https://example.com/hooks/watch"}
+ }]}
+ }`)
+ }
+
+ for name, tc := range map[string]struct {
+ scopes string
+ events string
+ wantErr bool
+ }{
+ "issue event without issues:read": {`["net:example.com"]`, `["issue.created"]`, true},
+ "issue event with issues:read": {`["issues:read", "net:example.com"]`, `["issue.created"]`, false},
+ "comment event without comments:read": {`["issues:read", "net:example.com"]`, `["comment.created"]`, true},
+ "comment event with comments:read": {`["comments:read", "net:example.com"]`, `["comment.created"]`, false},
+ "task event without tasks:read": {`["net:example.com"]`, `["task.failed"]`, true},
+ "task event with tasks:read": {`["tasks:read", "net:example.com"]`, `["task.failed"]`, false},
+ "one of several events unscoped": {
+ `["issues:read", "net:example.com"]`, `["issue.created", "comment.created"]`, true,
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ _, _, err := ParseManifest(manifest(tc.scopes, tc.events))
+ if tc.wantErr && err == nil {
+ t.Fatal("subscribing to content the manifest may not read must be refused at install")
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("a properly scoped subscription must parse: %v", err)
+ }
+ })
+ }
+}