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:
@@ -9,6 +9,11 @@
|
||||
"nav_clients": "Gekoppelte Geräte",
|
||||
"nav_pairing": "Kopplung",
|
||||
"nav_library": "Bibliothek",
|
||||
"nav_plugins": "Plugins",
|
||||
"plugin_offline_title": "Dieses Plugin läuft nicht",
|
||||
"plugin_offline_hint": "Starte den Scripting-Runner und versuche es erneut.",
|
||||
"plugin_retry": "Erneut versuchen",
|
||||
"plugin_open_new_tab": "In neuem Tab öffnen",
|
||||
"nav_settings": "Einstellungen",
|
||||
"nav_more": "Mehr",
|
||||
"status_title": "Live-Status",
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
"nav_library": "Library",
|
||||
"nav_settings": "Settings",
|
||||
"nav_more": "More",
|
||||
"nav_plugins": "Plugins",
|
||||
"plugin_offline_title": "This plugin isn't running",
|
||||
"plugin_offline_hint": "Start the scripting runner, then retry.",
|
||||
"plugin_retry": "Retry",
|
||||
"plugin_open_new_tab": "Open in new tab",
|
||||
"status_title": "Live status",
|
||||
"status_video": "Video",
|
||||
"status_audio": "Audio",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// The plugin directory the console reads to grow its nav (plugin-ui-surface §5). This is a
|
||||
// hand-written client (not orval-generated) so the nav works without regenerating the API client
|
||||
// for the new endpoints; it rides the same `/api` BFF path as every other call, so the bearer token
|
||||
// is injected server-side and the browser only ever sends its session cookie.
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Blocks,
|
||||
Boxes,
|
||||
Clapperboard,
|
||||
Database,
|
||||
FolderCog,
|
||||
Gamepad2,
|
||||
Home,
|
||||
type LucideIcon,
|
||||
Plug,
|
||||
Puzzle,
|
||||
Wrench,
|
||||
} from "lucide-react";
|
||||
import { apiFetch } from "@/api/fetcher";
|
||||
|
||||
export interface PluginUiSummary {
|
||||
port: number;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface PluginSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
version?: string;
|
||||
/** Present iff the plugin serves a UI (and thus gets a nav entry). */
|
||||
ui?: PluginUiSummary;
|
||||
}
|
||||
|
||||
// A curated lucide set for plugin nav icons. Importing lucide's full dynamic icon map would defeat
|
||||
// tree-shaking (U-S4), so a plugin picks a name from here; anything unknown falls back to Puzzle.
|
||||
const ICONS: Record<string, LucideIcon> = {
|
||||
"gamepad-2": Gamepad2,
|
||||
puzzle: Puzzle,
|
||||
wrench: Wrench,
|
||||
database: Database,
|
||||
home: Home,
|
||||
blocks: Blocks,
|
||||
boxes: Boxes,
|
||||
plug: Plug,
|
||||
"folder-cog": FolderCog,
|
||||
clapperboard: Clapperboard,
|
||||
};
|
||||
|
||||
/** Resolve a registered icon name to a component (Puzzle fallback). */
|
||||
export const pluginIcon = (name?: string): LucideIcon =>
|
||||
(name ? ICONS[name] : undefined) ?? Puzzle;
|
||||
|
||||
/** Live plugin registrations, polled (and refetched on window focus) so the nav stays current. */
|
||||
export function usePlugins() {
|
||||
return useQuery({
|
||||
queryKey: ["plugins"],
|
||||
queryFn: () => apiFetch<PluginSummary[]>("/api/v1/plugins"),
|
||||
refetchInterval: 30_000,
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Only the plugins that surface a UI — the ones that get a nav entry. */
|
||||
export const uiPlugins = (list: PluginSummary[] | undefined): PluginSummary[] =>
|
||||
(list ?? []).filter((p) => p.ui);
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { motion, stagger } from "motion/react";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { pluginIcon, uiPlugins, usePlugins } from "@/api/plugins";
|
||||
import { BrandMark } from "@/components/brand-mark";
|
||||
import { Wordmark } from "@/components/wordmark";
|
||||
import { changeLocale, type Locale, locales, useLocale } from "@/lib/i18n";
|
||||
@@ -91,6 +92,7 @@ export function AppShell({ children }: { children: ReactNode }) {
|
||||
</MLink>
|
||||
))}
|
||||
</motion.nav>
|
||||
<PluginNavSection />
|
||||
<div className="mt-auto pt-4">
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
@@ -119,14 +121,54 @@ export function AppShell({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Desktop sidebar: the dynamic "Plugins" group, fed by the plugin directory. Renders nothing until
|
||||
* at least one plugin surfaces a UI — a host with no plugins sees zero extra chrome. */
|
||||
function PluginNavSection() {
|
||||
const { data } = usePlugins();
|
||||
const plugins = uiPlugins(data);
|
||||
if (plugins.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-6 flex flex-col gap-1">
|
||||
<p className="px-3 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground/70">
|
||||
{m.nav_plugins()}
|
||||
</p>
|
||||
{plugins.map((p) => {
|
||||
const Icon = pluginIcon(p.ui?.icon);
|
||||
return (
|
||||
<Link
|
||||
key={p.id}
|
||||
to="/plugins/$pluginId/$"
|
||||
params={{ pluginId: p.id, _splat: "" }}
|
||||
className="group relative flex items-center gap-3 rounded-md px-3 py-2 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||
activeProps={{
|
||||
className: "bg-primary/15 text-foreground font-medium",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 rounded-md bg-primary/0 transition-colors duration-200 group-hover:bg-primary/15"
|
||||
/>
|
||||
<Icon className="relative size-4" />
|
||||
<span className="relative truncate">{p.title}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Mobile bottom navigation (< sm): four pinned tabs + a "More" tab whose sheet holds the rest. */
|
||||
function MobileNav() {
|
||||
const [moreOpen, setMoreOpen] = useState(false);
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname });
|
||||
// Highlight "More" when the current route lives in the overflow.
|
||||
const overflowActive = MOBILE_OVERFLOW.some(
|
||||
(n) => pathname === n.to || pathname.startsWith(`${n.to}/`),
|
||||
);
|
||||
const { data } = usePlugins();
|
||||
const plugins = uiPlugins(data);
|
||||
// Highlight "More" when the current route lives in the overflow — plugins included.
|
||||
const overflowActive =
|
||||
pathname.startsWith("/plugins/") ||
|
||||
MOBILE_OVERFLOW.some(
|
||||
(n) => pathname === n.to || pathname.startsWith(`${n.to}/`),
|
||||
);
|
||||
// Fixed two-line-tall label box so a 1- or 2-line label (labels vary by locale) keeps every icon
|
||||
// at the same height.
|
||||
const tab =
|
||||
@@ -164,6 +206,22 @@ function MobileNav() {
|
||||
<span className={lbl}>{label()}</span>
|
||||
</Link>
|
||||
))}
|
||||
{plugins.map((p) => {
|
||||
const Icon = pluginIcon(p.ui?.icon);
|
||||
return (
|
||||
<Link
|
||||
key={p.id}
|
||||
to="/plugins/$pluginId/$"
|
||||
params={{ pluginId: p.id, _splat: "" }}
|
||||
onClick={() => setMoreOpen(false)}
|
||||
className={cn(tab, "rounded-md")}
|
||||
activeProps={{ className: "text-[var(--brand-light)]" }}
|
||||
>
|
||||
<Icon className="size-5 shrink-0" />
|
||||
<span className={lbl}>{p.title}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { SectionPlugin } from "@/sections/Plugins";
|
||||
|
||||
// A plugin's console-hosted UI (plugin-ui-surface). The `$` splat carries the plugin's own path so
|
||||
// deep links survive a reload; the section maps it to the iframe src and keeps it in sync.
|
||||
export const Route = createFileRoute("/plugins/$pluginId/$")({
|
||||
component: SectionPlugin,
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
// A plugin's UI, embedded in the console (plugin-ui-surface §5). We probe the plugin's liveness
|
||||
// first and only mount the iframe when it answers — otherwise the iframe would show the proxy's raw
|
||||
// 502. The iframe is same-origin (proxied through /plugin-ui), so the plugin can talk to its own
|
||||
// loopback REST with the operator's session and, optionally, keep the address bar in sync by posting
|
||||
// `{ type: "pf-ui:navigate", path }` to the parent.
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRouteApi, useNavigate } from "@tanstack/react-router";
|
||||
import { ExternalLink, RefreshCw } from "lucide-react";
|
||||
import { type FC, useEffect, useMemo, useRef } from "react";
|
||||
import { pluginIcon, usePlugins } from "@/api/plugins";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLocale } from "@/lib/i18n";
|
||||
import { m } from "@/paraglide/messages";
|
||||
|
||||
const route = getRouteApi("/plugins/$pluginId/$");
|
||||
|
||||
export const SectionPlugin: FC = () => {
|
||||
useLocale();
|
||||
const { pluginId, _splat } = route.useParams();
|
||||
const navigate = useNavigate();
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
|
||||
// Header metadata (title/version/icon) from the directory; falls back to the id.
|
||||
const { data: plugins } = usePlugins();
|
||||
const meta = plugins?.find((p) => p.id === pluginId);
|
||||
const Icon = pluginIcon(meta?.ui?.icon);
|
||||
const title = meta?.title ?? pluginId;
|
||||
|
||||
// Liveness: a 200 from /__health means the plugin is up. On failure we stop polling and show the
|
||||
// offline card (the manual Retry re-probes).
|
||||
const health = useQuery({
|
||||
queryKey: ["plugin-health", pluginId],
|
||||
queryFn: async () => {
|
||||
const r = await fetch(`/plugin-ui/${pluginId}/__health`, {
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!r.ok) throw new Error(`health ${r.status}`);
|
||||
return true;
|
||||
},
|
||||
retry: false,
|
||||
refetchInterval: (q) => (q.state.status === "error" ? false : 20_000),
|
||||
});
|
||||
|
||||
// The iframe src is fixed at the initial deep-link path; the plugin's own in-app navigation drives
|
||||
// the console URL via postMessage (below), never the src — so there's no reload loop.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: intentionally pinned to the initial path
|
||||
const initialSrc = useMemo(
|
||||
() => `/plugin-ui/${pluginId}/${_splat ?? ""}`,
|
||||
[pluginId],
|
||||
);
|
||||
|
||||
// Keep the console address bar in sync with the plugin's internal routing.
|
||||
useEffect(() => {
|
||||
const onMessage = (e: MessageEvent) => {
|
||||
if (e.source !== iframeRef.current?.contentWindow) return;
|
||||
const data = e.data as { type?: string; path?: string };
|
||||
if (data?.type === "pf-ui:navigate" && typeof data.path === "string") {
|
||||
navigate({
|
||||
to: "/plugins/$pluginId/$",
|
||||
params: { pluginId, _splat: data.path.replace(/^\//, "") },
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, [pluginId, navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100dvh-7rem)] min-h-[480px] flex-col gap-3 sm:h-[calc(100dvh-5rem)]">
|
||||
{/* Header strip: identity + open-in-new-tab (the plugin stands alone full-window too). */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Icon className="size-5 text-muted-foreground" />
|
||||
<h1 className="text-lg font-semibold">{title}</h1>
|
||||
{meta?.version && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
|
||||
v{meta.version}
|
||||
</span>
|
||||
)}
|
||||
<a
|
||||
href={`/plugin-ui/${pluginId}/`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="ml-auto inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ExternalLink className="size-4" />
|
||||
{m.plugin_open_new_tab()}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{health.isError ? (
|
||||
<OfflineCard title={title} onRetry={() => health.refetch()} />
|
||||
) : health.isSuccess ? (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={initialSrc}
|
||||
title={title}
|
||||
className="w-full flex-1 rounded-lg border bg-card"
|
||||
// The plugin is operator-installed code on our own origin (no new trust boundary —
|
||||
// plugin-ui-surface §7.4); allow it to run scripts, forms, popups, and full-window.
|
||||
sandbox="allow-scripts allow-forms allow-popups allow-same-origin allow-modals"
|
||||
allow="fullscreen"
|
||||
/>
|
||||
) : (
|
||||
// Probing: a calm shimmer rather than a flash of empty frame.
|
||||
<div className="flex-1 animate-pulse rounded-lg border bg-card/50" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const OfflineCard: FC<{ title: string; onRetry: () => void }> = ({
|
||||
title,
|
||||
onRetry,
|
||||
}) => (
|
||||
<div className="flex flex-1 items-center justify-center rounded-lg border border-dashed">
|
||||
<div className="flex max-w-md flex-col items-center gap-3 p-8 text-center">
|
||||
<h2 className="text-base font-semibold">{m.plugin_offline_title()}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{title}</span> —{" "}
|
||||
{m.plugin_offline_hint()}
|
||||
</p>
|
||||
{/* The exact runner commands, so the operator can act without leaving the page. */}
|
||||
<pre className="w-full overflow-x-auto rounded-md bg-muted p-3 text-left text-xs text-muted-foreground">
|
||||
<code>
|
||||
systemctl --user status punktfunk-scripting{"\n"}
|
||||
Get-ScheduledTask PunktfunkScripting{" # Windows"}
|
||||
</code>
|
||||
</pre>
|
||||
<Button variant="outline" size="sm" onClick={onRetry}>
|
||||
<RefreshCw className="size-4" />
|
||||
{m.plugin_retry()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
+102
-1
@@ -1,10 +1,12 @@
|
||||
import * as nodeHttp from "node:http";
|
||||
import * as nodeHttps from "node:https";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { paraglideVitePlugin } from "@inlang/paraglide-js";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { nitroV2Plugin } from "@tanstack/nitro-v2-vite-plugin";
|
||||
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
|
||||
import viteReact from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vite";
|
||||
import { defineConfig, type Plugin } from "vite";
|
||||
import viteTsConfigPaths from "vite-tsconfig-paths";
|
||||
|
||||
// Absolute path to our Nitro server source (middleware + routes). Passed as a scanDir
|
||||
@@ -16,6 +18,103 @@ const serverDir = fileURLToPath(new URL("./server", import.meta.url));
|
||||
// route-rule proxies it (below). Override the upstream with PUNKTFUNK_MGMT_URL.
|
||||
const MGMT_URL = process.env.PUNKTFUNK_MGMT_URL ?? "https://127.0.0.1:47990";
|
||||
|
||||
// Dev-only `/plugin-ui/<id>/**` reverse proxy — the vite-dev counterpart of the Bun/Nitro route
|
||||
// (server/routes/plugin-ui/[...].ts), which can't run in dev because it uses Bun's `tls` fetch
|
||||
// option. Same contract: look up the plugin's {port, secret} from the management API server-side,
|
||||
// inject the secret, strip the cookie, dial 127.0.0.1 only, stream the response (SSE included).
|
||||
// Needs PUNKTFUNK_MGMT_TOKEN in the dev environment (like talking to any token-required host).
|
||||
function pluginUiDevProxy(): Plugin {
|
||||
const fetchCred = (
|
||||
id: string,
|
||||
token: string,
|
||||
): Promise<{ port: number; secret: string } | null> =>
|
||||
new Promise((resolve) => {
|
||||
const u = new URL(`${MGMT_URL}/api/v1/plugins/${id}/ui-credential`);
|
||||
const mod = u.protocol === "https:" ? nodeHttps : nodeHttp;
|
||||
const r = mod.request(
|
||||
u,
|
||||
{
|
||||
method: "GET",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
rejectUnauthorized: false, // host's self-signed loopback cert
|
||||
} as nodeHttps.RequestOptions,
|
||||
(resp) => {
|
||||
let data = "";
|
||||
resp.on("data", (c) => {
|
||||
data += c;
|
||||
});
|
||||
resp.on("end", () => {
|
||||
if (resp.statusCode === 200) {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
} else resolve(null);
|
||||
});
|
||||
},
|
||||
);
|
||||
r.on("error", () => resolve(null));
|
||||
r.end();
|
||||
});
|
||||
|
||||
return {
|
||||
name: "punktfunk-plugin-ui-dev-proxy",
|
||||
configureServer(server) {
|
||||
server.middlewares.use("/plugin-ui", async (req, res) => {
|
||||
const raw = req.url ?? "/"; // connect strips the /plugin-ui mount prefix
|
||||
const m = raw.match(/^\/([a-z][a-z0-9-]*)(\/[^?]*)?(\?.*)?$/);
|
||||
const id = m?.[1];
|
||||
if (!id) {
|
||||
res.statusCode = 404;
|
||||
res.end("bad plugin-ui path");
|
||||
return;
|
||||
}
|
||||
const rest = m?.[2] ?? "/";
|
||||
const search = m?.[3] ?? "";
|
||||
const token = process.env.PUNKTFUNK_MGMT_TOKEN;
|
||||
if (!token) {
|
||||
res.statusCode = 503;
|
||||
res.end("dev plugin-ui proxy: set PUNKTFUNK_MGMT_TOKEN");
|
||||
return;
|
||||
}
|
||||
const cred = await fetchCred(id, token);
|
||||
if (!cred) {
|
||||
res.statusCode = 502;
|
||||
res.end(`plugin "${id}" is not running`);
|
||||
return;
|
||||
}
|
||||
const headers = { ...req.headers } as Record<string, string | string[]>;
|
||||
delete headers.host;
|
||||
delete headers.cookie;
|
||||
delete headers.authorization;
|
||||
headers["x-forwarded-prefix"] = `/plugin-ui/${id}`;
|
||||
const proxyReq = nodeHttp.request(
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port: cred.port,
|
||||
method: req.method,
|
||||
path: rest + search,
|
||||
headers: { ...headers, authorization: `Bearer ${cred.secret}` },
|
||||
},
|
||||
(pr) => {
|
||||
res.statusCode = pr.statusCode ?? 502;
|
||||
for (const [k, v] of Object.entries(pr.headers)) {
|
||||
if (v !== undefined) res.setHeader(k, v);
|
||||
}
|
||||
pr.pipe(res); // stream (SSE included)
|
||||
},
|
||||
);
|
||||
proxyReq.on("error", () => {
|
||||
res.statusCode = 502;
|
||||
res.end("plugin unreachable");
|
||||
});
|
||||
req.pipe(proxyReq);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
@@ -24,6 +123,8 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
// First, so it intercepts /plugin-ui before the SSR catch-all in dev.
|
||||
pluginUiDevProxy(),
|
||||
viteTsConfigPaths({ projects: ["./tsconfig.json"] }),
|
||||
tailwindcss(),
|
||||
paraglideVitePlugin({
|
||||
|
||||
Reference in New Issue
Block a user