Files
kandev/apps/web/lib/plugins/host.test.ts
T
João Salavisa e145d48f22 feat: add plugin system with grpc runtime and native ui plugins (#1742)
* feat: add plugin system with grpc runtime and native ui plugins

- go plugin backends ship as release tarballs (per-platform binaries, checksums) that
  kandev installs from url/upload or filesystem sideload+sync, then spawns and
  supervises via hashicorp/go-plugin (unix socket / loopback tcp+automtls)
- strict typed grpc contract (kandev.plugin.v1): DeliverEvent/InvokeTool/HandleWebhook
  plus a capability-gated host service (state, secrets, emit); author sdk in
  pkg/pluginsdk; packaging cli in cmd/plugin-pack
- native frontend bundles: window.registerKandevPlugin + registry/host loader with
  dynamic routes, nav items, slots and ws handlers; plugins settings page with
  install dialog, sync button and enable/disable/uninstall
- gated behind the plugins feature flag (prod off, dev/e2e on); covered by unit and
  integration tests plus playwright e2e against a real packaged fixture plugin

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): hydrate base app context on plugin routes

Plugin-owned SPA routes classify as RouteUnknown, so the boot payload shipped
only feature flags — no workspaces, workflows, or kanban context. Native plugin
UI (e.g. host.ui.TaskCreateDialog) then had an empty store. Hydrate the same
base context as the Home route for unknown SPA routes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(plugins): expose TaskCreateDialog on host.ui

Lets a native plugin open kandev's real create-task modal (prefilled via
initialValues) instead of POSTing directly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): harden filesystem/URL sinks against CodeQL findings

Add sink-level guards on the plugin trust boundary: securejoin containment on
archive extraction (zip-slip), plugin-id validation before every fs_store path,
http/https scheme validation on install-from-URL, and non-interpolated ws-handler
error logging.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address review findings (races, resource caps, lifecycle)

- serialize per-plugin startup to close a TOCTOU double-spawn race, and let a
  plugin restart after exhausting attempts
- bound plugin startup with an explicit 30s timeout
- reject backslash paths and cap decompressed bytes by actual size in pkgtar;
  only mark a package Signed when a verifier actually ran and passed
- delete plugin_state on uninstall; validate webhook keys against the manifest
  and cap webhook body size; restart an active plugin when a new version installs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): sanitize plugin-id path sinks for CodeQL

Pin the plugin id to a single path segment with filepath.Base at recordPath/
configPath and pkgtar.Remove — a barrier the taint analysis recognizes.
Behaviour-identical for valid ids (already validated by safePluginID); clears
the go/path-injection alerts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): inline plugin-id validation at path sinks for CodeQL

filepath.Base does not strip '..', so it is not a path-injection barrier. Call
the recognized safePluginID / id-pattern guard inline in Delete/GetConfig/
SetConfig and pkgtar.Remove — the same barrier that already cleared the Get sink.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address code-review findings (backend)

- add capability-gating tests for the Host RPC service (was untested)
- close a stop-during-start orphan race so Disable/Uninstall can't leave a
  supervised subprocess behind
- on failed upgrade, remove only the new version dir (not all versions + data);
  restart the prior version
- validate manifest version and reject ids ending in .config (record-file alias)
- make Deliverer.Refresh non-blocking and cancel in-flight delivery on worker stop
- clamp out-of-range webhook status, skip-and-warn corrupt records in List,
  write records atomically, semver-aware sideload version pick

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address code-review findings (frontend)

- wrap plugin routes + settings routes in a shared PluginErrorBoundary so a
  throwing plugin page shows a fallback instead of white-screening the SPA
- fix disable/re-enable in one session: keep the cached registration and
  re-run initialize instead of relying on a cached ES-module re-import
- prefix root-relative bundle/style URLs with apiBaseUrl (split-origin/Tauri)
- surface partial-install warnings via toast.warning instead of a bare success
- dedupe/remove injected style links on unload; gate PluginNavItems on the flag

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): serialize per-plugin lifecycle + guard config writes

- add a per-plugin keyed lock in Service so concurrent Enable/Disable/Install/
  Uninstall/UpdateConfig for one id are serialized (no status-machine race)
- take s.mu in SetConfig/GetConfig and write config atomically
- bound each plugin initialize() with a timeout so one hung bundle can't stall
  the rest of the boot load

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(plugins): split service_test.go to satisfy file-length lint

Move the install/URL test group into service_install_test.go; no logic change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: build and ship the e2e fixture plugin package to E2E shards

The plugin E2E specs' global-setup requires apps/backend/.build/kandev-plugin-e2e-1.0.0.tar.gz.
Build it in the E2E build job, upload it as an artifact, and download it in both
the regular and container shard jobs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 12:00:26 +01:00

423 lines
14 KiB
TypeScript

import { describe, it, expect, vi, afterEach } from "vitest";
import type { Window as HappyDOMWindow } from "happy-dom";
import { loadPlugins, unloadPlugin } from "./host";
import { pluginRegistry } from "./registry";
import type { ActivePlugin, PluginHostApi, PluginRegistry } from "./types";
let mockApiBaseUrl = "";
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: mockApiBaseUrl }),
}));
const PLUGIN_SCOPE_A_ID = "plugin-scope-a";
const BUNDLE_JS_URL = "/bundle.js";
const PLUGIN_UNLOAD_A_ID = "plugin-unload-a";
const PLUGIN_UNLOAD_THROW_A_ID = "plugin-unload-throw-a";
const PLUGIN_UNLOAD_STYLE_A_ID = "plugin-unload-style-a";
const PLUGIN_REENABLE_A_ID = "plugin-reenable-a";
const PLUGIN_REENABLE_A_PATH = "/plugin-reenable-a";
const NAV_REENABLE_A_ID = "nav-reenable-a";
const PLUGIN_HANG_A_ID = "plugin-hang-a";
const PLUGIN_HANG_B_ID = "plugin-hang-b";
function makeHostFactory(pluginId: string): PluginHostApi {
return {
pluginId,
React: {} as PluginHostApi["React"],
jsx: {} as PluginHostApi["jsx"],
store: {
getState: () => ({}) as never,
setState: () => {},
subscribe: () => () => {},
},
api: { fetch: async () => new Response() },
ui: {},
theme: "light",
};
}
type FakeWindow = Window & {
registerKandevPlugin: (id: string, plugin: unknown) => void;
};
/** Fake importer that synchronously invokes window.registerKandevPlugin, no real dynamic import. */
function fakeImporterFor(
bundles: Record<string, (win: Window) => void>,
): (url: string) => Promise<unknown> {
return async (url: string) => {
const run = bundles[url];
if (!run) throw new Error(`no fake bundle for ${url}`);
run(window);
return {};
};
}
function activePlugin(overrides: Partial<ActivePlugin> = {}): ActivePlugin {
return {
id: "plugin-a",
name: "Plugin A",
bundleUrl: "/api/plugins/plugin-a/bundle",
...overrides,
};
}
function registerFake(id: string, plugin: unknown) {
(window as unknown as FakeWindow).registerKandevPlugin(id, plugin);
}
afterEach(() => {
mockApiBaseUrl = "";
});
describe("loadPlugins", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_SCOPE_A_ID);
pluginRegistry.unregisterPlugin("plugin-style-a");
pluginRegistry.unregisterPlugin("plugin-throw-a");
pluginRegistry.unregisterPlugin("plugin-throw-b");
pluginRegistry.unregisterPlugin("plugin-silent-a");
document.head.querySelectorAll("link[rel='stylesheet']").forEach((el) => el.remove());
});
it("imports the bundle, then calls initialize(registry, host) with a registry scoped to the plugin", async () => {
const initialize = vi.fn((registry: PluginRegistry, _host: PluginHostApi) => {
registry.registerNavItem({ id: "nav-scope-a", label: "A", path: "/plugin-scope-a" });
});
const importer = fakeImporterFor({
"/api/plugins/plugin-scope-a/bundle": (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_SCOPE_A_ID, { initialize }),
});
await loadPlugins(
[activePlugin({ id: PLUGIN_SCOPE_A_ID, bundleUrl: "/api/plugins/plugin-scope-a/bundle" })],
makeHostFactory,
importer,
);
expect(initialize).toHaveBeenCalledTimes(1);
const [, host] = initialize.mock.calls[0];
expect(host.pluginId).toBe(PLUGIN_SCOPE_A_ID);
expect(pluginRegistry.getNavItems()).toContainEqual({
id: "nav-scope-a",
label: "A",
path: "/plugin-scope-a",
});
});
it("injects styleUrls as <link> elements before importing the bundle", async () => {
// happy-dom eagerly loads real <link rel="stylesheet"> hrefs over the network;
// disable that for this test so it doesn't attempt (and 404-log) a real fetch.
const happyDOMWindow = window as unknown as HappyDOMWindow;
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = true;
const importer = fakeImporterFor({
[BUNDLE_JS_URL]: (win) =>
(win as unknown as FakeWindow).registerKandevPlugin("plugin-style-a", {
initialize: () => {},
}),
});
await loadPlugins(
[
activePlugin({
id: "plugin-style-a",
bundleUrl: BUNDLE_JS_URL,
styleUrls: ["/plugin-a.css"],
}),
],
makeHostFactory,
importer,
);
const link = document.head.querySelector("link[href='/plugin-a.css']");
expect(link).not.toBeNull();
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = false;
});
it("isolates a throwing plugin: logs and does not stop other plugins from loading", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const goodInitialize = vi.fn();
const importer = fakeImporterFor({
"/bad-bundle.js": (win) =>
(win as unknown as FakeWindow).registerKandevPlugin("plugin-throw-a", {
initialize: () => {
throw new Error("boom");
},
}),
"/good-bundle.js": (win) =>
(win as unknown as FakeWindow).registerKandevPlugin("plugin-throw-b", {
initialize: goodInitialize,
}),
});
await loadPlugins(
[
activePlugin({ id: "plugin-throw-a", bundleUrl: "/bad-bundle.js" }),
activePlugin({ id: "plugin-throw-b", bundleUrl: "/good-bundle.js" }),
],
makeHostFactory,
importer,
);
expect(errorSpy).toHaveBeenCalled();
expect(goodInitialize).toHaveBeenCalledTimes(1);
errorSpy.mockRestore();
});
it("logs and continues when a bundle never calls registerKandevPlugin", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const importer = fakeImporterFor({ "/silent-bundle.js": () => {} });
await loadPlugins(
[activePlugin({ id: "plugin-silent-a", bundleUrl: "/silent-bundle.js" })],
makeHostFactory,
importer,
);
expect(errorSpy).toHaveBeenCalled();
errorSpy.mockRestore();
});
});
describe("loadPlugins — asset URL prefixing", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin("plugin-prefix-a");
pluginRegistry.unregisterPlugin("plugin-bare-a");
document.head.querySelectorAll("link[rel='stylesheet']").forEach((el) => el.remove());
});
it("prefixes a root-relative bundleUrl and style href with the backend apiBaseUrl when set (split-origin dev, Tauri)", async () => {
mockApiBaseUrl = "http://localhost:38429";
const happyDOMWindow = window as unknown as HappyDOMWindow;
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = true;
const importedUrls: string[] = [];
const importer = async (url: string) => {
importedUrls.push(url);
registerFake("plugin-prefix-a", { initialize: () => {} });
return {};
};
await loadPlugins(
[
activePlugin({
id: "plugin-prefix-a",
bundleUrl: "/api/plugins/plugin-prefix-a/bundle",
styleUrls: ["/api/plugins/plugin-prefix-a/ui/style.css"],
}),
],
makeHostFactory,
importer,
);
expect(importedUrls).toEqual(["http://localhost:38429/api/plugins/plugin-prefix-a/bundle"]);
const link = document.head.querySelector(
"link[href='http://localhost:38429/api/plugins/plugin-prefix-a/ui/style.css']",
);
expect(link).not.toBeNull();
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = false;
});
it("leaves a root-relative bundleUrl unprefixed when apiBaseUrl is empty (same-origin production)", async () => {
mockApiBaseUrl = "";
const importedUrls: string[] = [];
const importer = async (url: string) => {
importedUrls.push(url);
registerFake("plugin-bare-a", { initialize: () => {} });
return {};
};
await loadPlugins(
[
activePlugin({
id: "plugin-bare-a",
bundleUrl: "/api/plugins/plugin-bare-a/bundle",
}),
],
makeHostFactory,
importer,
);
expect(importedUrls).toEqual(["/api/plugins/plugin-bare-a/bundle"]);
});
});
describe("unloadPlugin", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_UNLOAD_A_ID);
pluginRegistry.unregisterPlugin(PLUGIN_UNLOAD_THROW_A_ID);
pluginRegistry.unregisterPlugin(PLUGIN_UNLOAD_STYLE_A_ID);
document.head.querySelectorAll("link[rel='stylesheet']").forEach((el) => el.remove());
});
it("calls destroy() and bulk-revokes the plugin's registrations", async () => {
const destroy = vi.fn();
const importer = fakeImporterFor({
[BUNDLE_JS_URL]: (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_UNLOAD_A_ID, {
initialize: (registry: { registerNavItem: (item: unknown) => void }) => {
registry.registerNavItem({ id: "nav-a", label: "A", path: "/plugin-a" });
},
destroy,
}),
});
await loadPlugins(
[activePlugin({ id: PLUGIN_UNLOAD_A_ID, bundleUrl: BUNDLE_JS_URL })],
makeHostFactory,
importer,
);
expect(pluginRegistry.getNavItems()).toContainEqual({
id: "nav-a",
label: "A",
path: "/plugin-a",
});
unloadPlugin(PLUGIN_UNLOAD_A_ID);
expect(destroy).toHaveBeenCalledTimes(1);
expect(pluginRegistry.getNavItems().find((item) => item.id === "nav-a")).toBeUndefined();
});
it("swallows a throwing destroy() and still bulk-revokes registrations", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const importer = fakeImporterFor({
[BUNDLE_JS_URL]: (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_UNLOAD_THROW_A_ID, {
initialize: (registry: { registerNavItem: (item: unknown) => void }) => {
registry.registerNavItem({ id: "nav-a", label: "A", path: "/plugin-a" });
},
destroy: () => {
throw new Error("destroy boom");
},
}),
});
await loadPlugins(
[activePlugin({ id: PLUGIN_UNLOAD_THROW_A_ID, bundleUrl: BUNDLE_JS_URL })],
makeHostFactory,
importer,
);
expect(() => unloadPlugin(PLUGIN_UNLOAD_THROW_A_ID)).not.toThrow();
expect(errorSpy).toHaveBeenCalled();
expect(pluginRegistry.getNavItems().find((item) => item.id === "nav-a")).toBeUndefined();
errorSpy.mockRestore();
});
it("removes the plugin's injected <link> stylesheet tags so disable/enable cycles don't accumulate duplicates", async () => {
const happyDOMWindow = window as unknown as HappyDOMWindow;
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = true;
const importer = fakeImporterFor({
[BUNDLE_JS_URL]: (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_UNLOAD_STYLE_A_ID, {
initialize: () => {},
}),
});
await loadPlugins(
[
activePlugin({
id: PLUGIN_UNLOAD_STYLE_A_ID,
bundleUrl: BUNDLE_JS_URL,
styleUrls: ["/plugin-unload-style-a.css"],
}),
],
makeHostFactory,
importer,
);
expect(document.head.querySelector("link[href='/plugin-unload-style-a.css']")).not.toBeNull();
unloadPlugin(PLUGIN_UNLOAD_STYLE_A_ID);
expect(document.head.querySelector("link[href='/plugin-unload-style-a.css']")).toBeNull();
happyDOMWindow.happyDOM.settings.disableCSSFileLoading = false;
});
});
describe("loadPlugins — initialize() timeout isolation", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_HANG_A_ID);
pluginRegistry.unregisterPlugin(PLUGIN_HANG_B_ID);
});
it("does not let a plugin whose initialize() never resolves block a subsequent plugin", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const secondInitialize = vi.fn((registry: PluginRegistry) => {
registry.registerNavItem({ id: "nav-hang-b", label: "B", path: "/plugin-hang-b" });
});
const importer = fakeImporterFor({
"/hang-bundle.js": (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_HANG_A_ID, {
// Never resolves — simulates a hung plugin initialize().
initialize: () => new Promise<void>(() => {}),
}),
"/second-bundle.js": (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_HANG_B_ID, {
initialize: secondInitialize,
}),
});
await loadPlugins(
[
activePlugin({ id: PLUGIN_HANG_A_ID, bundleUrl: "/hang-bundle.js" }),
activePlugin({ id: PLUGIN_HANG_B_ID, bundleUrl: "/second-bundle.js" }),
],
makeHostFactory,
importer,
window,
10, // short per-test timeout instead of the 10s default
);
expect(secondInitialize).toHaveBeenCalledTimes(1);
expect(pluginRegistry.getNavItems()).toContainEqual({
id: "nav-hang-b",
label: "B",
path: "/plugin-hang-b",
});
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(PLUGIN_HANG_A_ID));
warnSpy.mockRestore();
});
});
describe("disable then re-enable in the same session", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_REENABLE_A_ID);
});
it("re-initializes from the cached registration when the bundle's module-eval side effect only fires once (ESM import caching)", async () => {
const initialize = vi.fn((registry: PluginRegistry) => {
registry.registerNavItem({ id: NAV_REENABLE_A_ID, label: "A", path: PLUGIN_REENABLE_A_PATH });
});
let importCount = 0;
const importer = vi.fn(async (_url: string) => {
importCount += 1;
// The real browser only runs a module's top-level side effect on the
// *first* resolution of a given specifier — a second `import(url)`
// resolves from the module cache without re-executing
// `window.registerKandevPlugin(...)`.
if (importCount === 1) {
registerFake(PLUGIN_REENABLE_A_ID, { initialize });
}
return {};
});
await loadPlugins([activePlugin({ id: PLUGIN_REENABLE_A_ID })], makeHostFactory, importer);
expect(initialize).toHaveBeenCalledTimes(1);
expect(pluginRegistry.getNavItems()).toContainEqual({
id: NAV_REENABLE_A_ID,
label: "A",
path: PLUGIN_REENABLE_A_PATH,
});
unloadPlugin(PLUGIN_REENABLE_A_ID);
expect(
pluginRegistry.getNavItems().find((item) => item.id === NAV_REENABLE_A_ID),
).toBeUndefined();
await loadPlugins([activePlugin({ id: PLUGIN_REENABLE_A_ID })], makeHostFactory, importer);
expect(initialize).toHaveBeenCalledTimes(2);
expect(pluginRegistry.getNavItems()).toContainEqual({
id: NAV_REENABLE_A_ID,
label: "A",
path: PLUGIN_REENABLE_A_PATH,
});
});
});