feat(plugins): console-hosted plugin UI surface (host registry + SDK servePluginUi + console proxy/nav)

Implements planning/design/plugin-ui-surface.md (U1-U3):

- host: in-memory lease-based plugin registry (mgmt/plugins.rs) — PUT/GET/DELETE
  /api/v1/plugins + GET /plugins/{id}/ui-credential; bearer+loopback only (not on
  the mTLS read-only allowlist); plugins.changed event; port-only registration
  (proxy always dials 127.0.0.1); secret never in the listing.
- sdk: servePluginUi — loopback ephemeral bind + per-boot secret + constant-time
  check + /__health + static/SPA-fallback + register/renew(30s)/deregister via
  pf.request (skew-proof, D7). Example + tests.
- console: /plugin-ui/{id}/** reverse proxy (server-side secret injection, cookie
  strip, SSE streaming, stale-secret 401-retry) + credential cache; BFF denylist
  for the credential endpoint; dynamic Plugins nav (desktop + mobile) fed by a
  polled list; iframe-in-shell page with health probe, offline card, open-in-tab,
  deep-link sync. Dev-mode /plugin-ui middleware in vite.config.ts.

OpenAPI regen for the new endpoints follows in the next commit (built on Linux).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-18 01:49:42 +02:00
parent d579cd318e
commit ec84b30eae
19 changed files with 1674 additions and 6 deletions
+10
View File
@@ -14,6 +14,16 @@ import { isLoopbackUrl, mgmtToken, mgmtUrl } from "../../util/auth";
export default defineEventHandler((event) => {
const { pathname, search } = getRequestURL(event);
// A plugin UI's proxy credential (its per-boot secret) is fetched server-side by the
// /plugin-ui proxy and must NEVER reach a browser — deny it on the generic passthrough so a
// session-authed page can't read it (plugin-ui-surface §5, D6). The secret-free list at
// /api/v1/plugins is fine; only the {id}/ui-credential leaf is blocked.
if (/^\/api\/v1\/plugins\/[^/]+\/ui-credential\/?$/.test(pathname)) {
setResponseStatus(event, 403);
return {
error: "plugin UI credentials are not accessible from the browser",
};
}
const base = mgmtUrl();
const target = `${base}${pathname}${search}`;
const token = mgmtToken();
+78
View File
@@ -0,0 +1,78 @@
// /plugin-ui/<id>/** → a plugin's loopback UI server (plugin-ui-surface §5). By the time we get
// here the gate (middleware/auth.ts) has confirmed a session — a plugin UI is reachable only by the
// logged-in operator, on the console's own origin, with no separate password. We look up the
// plugin's `{port, secret}` server-side, inject the secret as a bearer, strip the browser's cookie,
// and stream the response through (SSE included). The plugin only ever gets dialed on 127.0.0.1.
//
// This route runs in the built Bun/Nitro server. In `vite dev` a small middleware in vite.config.ts
// handles `/plugin-ui` instead (it intercepts before this route, like the /api dev proxy).
import {
defineEventHandler,
getProxyRequestHeaders,
getRequestURL,
readRawBody,
sendWebResponse,
setResponseStatus,
} from "h3";
import {
bustCredential,
fetchUiCredential,
PLUGIN_ID_RE,
} from "../../util/pluginProxy";
export default defineEventHandler(async (event) => {
const { pathname, search } = getRequestURL(event);
// /plugin-ui/<id>/<rest…>
const m = pathname.match(/^\/plugin-ui\/([^/]+)(\/.*)?$/);
const id = m?.[1];
if (!id || !PLUGIN_ID_RE.test(id)) {
setResponseStatus(event, 404);
return { error: "not a valid plugin-ui path" };
}
const rest = m?.[2] ?? "/";
const prefix = `/plugin-ui/${id}`;
// Forwardable request headers (h3 strips hop-by-hop + host); we set our own auth and drop the
// session cookie so plugin code never sees it.
const headers = getProxyRequestHeaders(event) as Record<string, string>;
delete headers.cookie;
delete headers.authorization;
headers["x-forwarded-prefix"] = prefix;
const method = event.method;
const body =
method === "GET" || method === "HEAD"
? undefined
: ((await readRawBody(event, false)) as Uint8Array | undefined);
// One proxied attempt; `null` means the plugin is unreachable (unregistered, or its port died).
const attempt = async (bustCache: boolean): Promise<Response | null> => {
const cred = await fetchUiCredential(id, { bustCache });
if (!cred) return null;
const target = `http://127.0.0.1:${cred.port}${rest}${search}`;
try {
return await fetch(target, {
method,
headers: { ...headers, authorization: `Bearer ${cred.secret}` },
body: body as BodyInit | undefined,
redirect: "manual",
});
} catch {
// The port is dead (plugin crashed/restarted on a new port): drop the stale credential so
// the next request re-resolves it.
bustCredential(id);
return null;
}
};
let resp = await attempt(false);
// Stale secret after a plugin restart (S7): the plugin rejects our cached secret — re-fetch once.
if (resp?.status === 401) {
const retry = await attempt(true);
if (retry) resp = retry;
}
if (!resp) {
setResponseStatus(event, 502);
return { error: `plugin "${id}" is not running` };
}
return sendWebResponse(event, resp);
});
+74
View File
@@ -0,0 +1,74 @@
// Server-side helper for the plugin-UI reverse proxy (plugin-ui-surface §5). The console proxies
// `/plugin-ui/<id>/**` to a plugin's loopback UI server, injecting the plugin's per-boot secret —
// which it fetches here, from the management API, **server-side only** (the secret never reaches the
// browser; the BFF additionally denylists the credential endpoint from the generic passthrough).
//
// The credential is cached briefly so a burst of iframe asset requests doesn't hammer the host. On a
// 401 from the plugin (its secret rotated on restart within the cache window) the proxy busts this
// cache and re-fetches once — see the route.
import { isLoopbackUrl, mgmtToken, mgmtUrl } from "./auth";
/** A plugin id — its `definePlugin` name; the same shape the host validates. */
export const PLUGIN_ID_RE = /^[a-z][a-z0-9-]*$/;
/** The proxy credential for a plugin's loopback UI. */
export interface UiCredential {
port: number;
secret: string;
}
const TTL_MS = 15_000;
const cache = new Map<string, { cred: UiCredential | null; at: number }>();
/** Drop a cached credential (called when a plugin's secret proved stale). */
export function bustCredential(id: string): void {
cache.delete(id);
}
/**
* Fetch `{port, secret}` for a plugin's UI from the management API (bearer, loopback). Returns
* `null` when the plugin isn't registered / has no UI (a 404). Results are cached for {@link TTL_MS};
* pass `bustCache` to force a fresh read (the stale-secret retry). Throws only on a missing mgmt
* token (a deploy misconfig) — a transient upstream error resolves to `null` (treated as offline)
* and is not cached.
*/
export async function fetchUiCredential(
id: string,
opts?: { bustCache?: boolean },
): Promise<UiCredential | null> {
const now = Date.now();
if (!opts?.bustCache) {
const hit = cache.get(id);
if (hit && now - hit.at < TTL_MS) return hit.cred;
}
const base = mgmtUrl();
const token = mgmtToken();
if (!token) {
throw new Error(
"management token not configured (PUNKTFUNK_MGMT_TOKEN / ~/.config/punktfunk/mgmt-token)",
);
}
// The host serves the credential over HTTPS with its self-signed loopback cert; relax
// verification for that one loopback hop only (the same scoping the /api BFF uses).
const fetchOptions = isLoopbackUrl(base)
? ({ tls: { rejectUnauthorized: false } } as unknown as RequestInit)
: undefined;
const resp = await fetch(`${base}/api/v1/plugins/${id}/ui-credential`, {
...fetchOptions,
headers: { authorization: `Bearer ${token}` },
});
if (resp.ok) {
const cred = (await resp.json()) as UiCredential;
cache.set(id, { cred, at: now });
return cred;
}
if (resp.status === 404) {
// Definitively not running / no UI — cache the negative so a dead iframe doesn't spin.
cache.set(id, { cred: null, at: now });
return null;
}
// Transient (401/5xx): don't cache, let the next request retry.
return null;
}