mirror of
https://gh-proxy.org/https://github.com/klinsmaya/multica.git
synced 2026-11-08 17:36:45 +08:00
* feat(plugins): host plugin artifacts, bind installs to immutable versions A plugin used to be a URL. The manifest was frozen at install, but the surface script was fetched from the author's server every time a panel opened, with no integrity check — so an administrator consented to a manifest while the browser ran whatever that host served that day, inside the scopes already granted. The author's uptime was our uptime, every panel open leaked the reader's IP and "who read which issue" to the author, and publishing at all required a public HTTPS domain, which is why the repo's own deploy-sentinel example never ran. The author now uploads an artifact bundle and Multica stores it: - plugin_package / plugin_package_version / plugin_package_file. A version is insert-only, and the (package_id, version) unique index is what makes immutability a database rule rather than a convention. - An installation names one version. Publishing another changes nothing for a workspace until an administrator upgrades, which is a second consent. - The bundle is validated once, at publish: the manifest parses, every file it declares is present and loadable, and a surface entry with a top-level import is refused with the line named. That failure used to surface months later in a reader's browser. - The host inlines the surface script into the document it generates, so the CSP names no remote script origin at all. `connect-src 'none'` now means it: a surface with no net: scope cannot reach anywhere, including its author. - Install-by-URL is gone rather than kept alongside. Two paths would make "is this code frozen?" depend on how the plugin was installed. - MULTICA_PLUGIN_DIR stays the development channel, but publishes an ordinary immutable version instead of being a second render path; re-publishing an unchanged version lands as `+dev.N`. Hook endpoints and MCP servers remain on the author's own infrastructure. Migration 376 drops existing installations: they name a source URL that is no longer a concept, and the code they would run was never published here. plugins_v1 has never left its feature flag and holds no production data — the same call migration 344 made. Closes MUL-6469 Co-authored-by: multica-agent <[email protected]> * fix(plugins): serialize publish/install/delete, correct the isolation claim Review of #7321 found five problems. Four are fixed here; the fifth is real, needs its own design pass, and is now tracked and described honestly in the code instead of claimed away. Migration prefix collision. main took 376 for agent_task_durable_work_dir while this branch was open, so `migration prefix 376 is reused` failed backend-tests. Rebased and renumbered the six migrations to 377-382. TOCTOU between delete and install/publish. Relationships are application-owned by repository policy, so nothing made "the version this installation names still exists" true across statements: `delete counts zero installs` -> `install reads the version` -> `delete commits` -> `install commits` left an installation whose panel 404s forever, and a publish racing a delete left a version whose package row was gone. Publish, install and delete now hold a (workspace, plugin key) advisory lock for their whole transaction, and delete counts installations inside it. Both interleavings have regression tests that reproduce the bug with the lock removed. Failed publishes moved package state. upsertPackage ran before the version transaction, so a republish that lost the unique index had already renamed the package, and a first publish that failed afterwards left a plugin with zero versions. It now runs inside the same transaction. The top-level import check was wrong in BOTH directions. It read line prefixes, so it missed ` import x` and `/* c */ import x` — and it refused a valid file whose template literal contained the word at a line start, which is ordinary in a surface that renders code samples. A refusal blocks a publish with no way around it, so that false positive was the worse half. Replaced with a scanner that skips comments and string/template literals; where it is imprecise it is imprecise safely (`/` always reads as division), so a mistake can only cost a detection, never invent one. Sandbox self-navigation is NOT fixed. `sandbox="allow-scripts"` permits `_self` navigation by design, no shipped CSP directive covers it, and contentWindow is unchanged across it — so a hostile artifact can still reach its author once and hand the replacement document the bridge port. Closing it needs an embedder frame-src policy or a handshake a navigated document cannot complete; both are decisions of their own. What lands here is damage control, labelled as such: the generated document beacons on pagehide from a listener the plugin cannot detach, and the embedder drops the bridge and unmounts the frame. The "a surface cannot reach its author" wording is removed from the SDK README and the tests. Closes MUL-6469 Refs MUL-6485 Co-authored-by: multica-agent <[email protected]> * feat(plugins): isolate hosted surfaces (MUL-6485) Co-authored-by: multica-agent <[email protected]> * feat(plugins): host plugin artifacts, bind installs to immutable versions A plugin used to be a URL. The manifest was frozen at install, but the surface script was fetched from the author's server every time a panel opened, with no integrity check — so an administrator consented to a manifest while the browser ran whatever that host served that day, inside the scopes already granted. The author's uptime was our uptime, every panel open leaked the reader's IP and "who read which issue" to the author, and publishing at all required a public HTTPS domain, which is why the repo's own deploy-sentinel example never ran. The author now uploads an artifact bundle and Multica stores it: - plugin_package / plugin_package_version / plugin_package_file. A version is insert-only, and the (package_id, version) unique index is what makes immutability a database rule rather than a convention. - An installation names one version. Publishing another changes nothing for a workspace until an administrator upgrades, which is a second consent. - The bundle is validated once, at publish: the manifest parses, every file it declares is present and loadable, and a surface entry with a top-level import is refused with the line named. That failure used to surface months later in a reader's browser. - The host inlines the surface script into the document it generates, so the CSP names no remote script origin at all. `connect-src 'none'` now means it: a surface with no net: scope cannot reach anywhere, including its author. - Install-by-URL is gone rather than kept alongside. Two paths would make "is this code frozen?" depend on how the plugin was installed. - MULTICA_PLUGIN_DIR stays the development channel, but publishes an ordinary immutable version instead of being a second render path; re-publishing an unchanged version lands as `+dev.N`. Hook endpoints and MCP servers remain on the author's own infrastructure. Migration 376 drops existing installations: they name a source URL that is no longer a concept, and the code they would run was never published here. plugins_v1 has never left its feature flag and holds no production data — the same call migration 344 made. Closes MUL-6469 Co-authored-by: multica-agent <[email protected]> * fix(plugins): serialize publish/install/delete, correct the isolation claim Review of #7321 found five problems. Four are fixed here; the fifth is real, needs its own design pass, and is now tracked and described honestly in the code instead of claimed away. Migration prefix collision. main took 376 for agent_task_durable_work_dir while this branch was open, so `migration prefix 376 is reused` failed backend-tests. Rebased and renumbered the six migrations to 377-382. TOCTOU between delete and install/publish. Relationships are application-owned by repository policy, so nothing made "the version this installation names still exists" true across statements: `delete counts zero installs` -> `install reads the version` -> `delete commits` -> `install commits` left an installation whose panel 404s forever, and a publish racing a delete left a version whose package row was gone. Publish, install and delete now hold a (workspace, plugin key) advisory lock for their whole transaction, and delete counts installations inside it. Both interleavings have regression tests that reproduce the bug with the lock removed. Failed publishes moved package state. upsertPackage ran before the version transaction, so a republish that lost the unique index had already renamed the package, and a first publish that failed afterwards left a plugin with zero versions. It now runs inside the same transaction. The top-level import check was wrong in BOTH directions. It read line prefixes, so it missed ` import x` and `/* c */ import x` — and it refused a valid file whose template literal contained the word at a line start, which is ordinary in a surface that renders code samples. A refusal blocks a publish with no way around it, so that false positive was the worse half. Replaced with a scanner that skips comments and string/template literals; where it is imprecise it is imprecise safely (`/` always reads as division), so a mistake can only cost a detection, never invent one. Sandbox self-navigation is NOT fixed. `sandbox="allow-scripts"` permits `_self` navigation by design, no shipped CSP directive covers it, and contentWindow is unchanged across it — so a hostile artifact can still reach its author once and hand the replacement document the bridge port. Closing it needs an embedder frame-src policy or a handshake a navigated document cannot complete; both are decisions of their own. What lands here is damage control, labelled as such: the generated document beacons on pagehide from a listener the plugin cannot detach, and the embedder drops the bridge and unmounts the frame. The "a surface cannot reach its author" wording is removed from the SDK README and the tests. Closes MUL-6469 Refs MUL-6485 Co-authored-by: multica-agent <[email protected]> * fix(plugins): harden surface validation and error reporting * fix(migrations): renumber plugin package migrations * fix(plugins): validate classic surfaces and reset failures * fix(plugins): refresh issue-scoped surface launches Co-authored-by: multica-agent <[email protected]> * feat(plugins): isolate hosted surfaces (MUL-6485) Co-authored-by: multica-agent <[email protected]> * fix(plugins): refresh issue-scoped surface launches Co-authored-by: multica-agent <[email protected]> * fix(plugins): make surface termination event-driven Co-authored-by: multica-agent <[email protected]> * feat(plugins): isolate hosted surfaces (MUL-6485) Co-authored-by: multica-agent <[email protected]> * fix(plugins): refresh issue-scoped surface launches Co-authored-by: multica-agent <[email protected]> * fix(plugins): make surface termination event-driven Co-authored-by: multica-agent <[email protected]> --------- Co-authored-by: Lambda <[email protected]> Co-authored-by: multica-agent <[email protected]>
163 lines
7.0 KiB
TypeScript
163 lines
7.0 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { pluginSurfaceLaunchOptions } from "@multica/core/plugins";
|
|
import type { PluginInstallation, PluginSurface } from "@multica/core/types";
|
|
import { cn } from "@multica/ui/lib/utils";
|
|
import { useT } from "../i18n";
|
|
import { buildSurfaceFrameDocument, readThemeTokens } from "./surface-document";
|
|
import { createSurfaceBridge } from "./surface-bridge";
|
|
|
|
const DEFAULT_HEIGHT = 220;
|
|
|
|
interface PluginSurfaceFrameProps {
|
|
wsId: string;
|
|
installation: PluginInstallation;
|
|
surface: PluginSurface;
|
|
issueId?: string;
|
|
className?: string;
|
|
}
|
|
|
|
/**
|
|
* Mounts one plugin surface.
|
|
*
|
|
* This element is a TRUSTED wrapper. Its nested plugin iframe is the isolation
|
|
* boundary and is always `sandbox="allow-scripts"` without
|
|
* `allow-same-origin`; see buildSurfaceFrameDocument.
|
|
*/
|
|
export function PluginSurfaceFrame({ wsId, installation, surface, issueId, className }: PluginSurfaceFrameProps) {
|
|
const frameRef = useRef<HTMLIFrameElement>(null);
|
|
const anchorRef = useRef<HTMLDivElement>(null);
|
|
const [height, setHeight] = useState(DEFAULT_HEIGHT);
|
|
const launchInstance = useId();
|
|
|
|
// Every mounted frame gets its own launch. The artifact is immutable, but the
|
|
// bridge proof is deliberately neither cacheable nor shareable.
|
|
const { data: launch, isPending, isError } = useQuery(
|
|
pluginSurfaceLaunchOptions(wsId, installation.id, surface.key, installation.package_version_id, launchInstance, issueId),
|
|
);
|
|
|
|
const surfaceDocument = useMemo(() => {
|
|
if (!launch?.url || !launch.bridge_token) return null;
|
|
try {
|
|
return buildSurfaceFrameDocument({ url: launch.url, bridgeToken: launch.bridge_token });
|
|
} catch {
|
|
return null;
|
|
}
|
|
}, [launch?.url, launch?.bridge_token]);
|
|
|
|
// Terminal state belongs to one rendered document on one issue. Comparing
|
|
// the instance keeps an old failure/navigation from surviving a replacement
|
|
// launch even though the new iframe is running normally.
|
|
const surfaceInstance = useMemo(() => ({ issueId, surfaceDocument }), [issueId, surfaceDocument]);
|
|
const [failedSurfaceInstance, setFailedSurfaceInstance] = useState<typeof surfaceInstance | null>(null);
|
|
const [navigatedSurfaceInstance, setNavigatedSurfaceInstance] = useState<typeof surfaceInstance | null>(null);
|
|
const failed = failedSurfaceInstance === surfaceInstance;
|
|
const navigated = navigatedSurfaceInstance === surfaceInstance;
|
|
|
|
// One bridge per rendered document. srcDoc changing reloads the frame — and
|
|
// therefore restarts the guest's handshake — so the old bridge is finished:
|
|
// close() is terminal, and reusing a closed one across a document change is
|
|
// exactly how the panel ends up permanently blank.
|
|
const bridge = useMemo(
|
|
() => createSurfaceBridge({
|
|
installationId: installation.id,
|
|
bridgeToken: launch?.bridge_token ?? "",
|
|
issueId,
|
|
onResize: setHeight,
|
|
}),
|
|
[installation.id, launch?.bridge_token, issueId],
|
|
);
|
|
|
|
// The listener is armed BEFORE srcdoc is assigned. That makes the guest-first
|
|
// one-shot port transfer race-free without retries or a reusable token.
|
|
useEffect(() => {
|
|
const frame = frameRef.current;
|
|
if (!frame || !surfaceDocument) return () => bridge.close();
|
|
const onMessage = (event: MessageEvent) => {
|
|
const type = (event.data as { type?: string } | null)?.type;
|
|
if (type !== "multica:plugin-surface-error" &&
|
|
type !== "multica:plugin-surface-navigated" &&
|
|
type !== "multica:plugin-surface-navigation-blocked") return;
|
|
// Same window-identity rule as the bridge: without it any frame on the
|
|
// page could light up the failure banner on every other panel.
|
|
if (!frame.contentWindow || event.source !== frame.contentWindow) return;
|
|
if (type === "multica:plugin-surface-error") setFailedSurfaceInstance(surfaceInstance);
|
|
else setNavigatedSurfaceInstance(surfaceInstance);
|
|
};
|
|
// Terminal events and the bridge are both armed before srcdoc is assigned,
|
|
// so even a first-line plugin failure or navigation cannot outrun the host.
|
|
window.addEventListener("message", onMessage);
|
|
bridge.connect(frame, readThemeTokens(anchorRef.current));
|
|
frame.srcdoc = surfaceDocument;
|
|
return () => {
|
|
window.removeEventListener("message", onMessage);
|
|
bridge.close();
|
|
frame.removeAttribute("srcdoc");
|
|
};
|
|
}, [bridge, surfaceDocument, surfaceInstance]);
|
|
|
|
useEffect(() => {
|
|
if (navigated) bridge.close();
|
|
}, [navigated, bridge]);
|
|
|
|
if (navigated) {
|
|
return (
|
|
<div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>
|
|
<PluginSurfaceNotice installation={installation} kind="navigated" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!surfaceDocument) {
|
|
return (
|
|
<div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>
|
|
{/* Three states share this box on purpose: still loading, the request
|
|
failed, and the installed version carries no code for this surface.
|
|
All three mean "nothing to render yet"; only the last is permanent,
|
|
and none of them should show an empty frame the reader cannot act
|
|
on. */}
|
|
<PluginSurfaceNotice installation={installation} kind={isPending && !isError ? "loading" : "unavailable"} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div ref={anchorRef} className={cn("overflow-hidden rounded-lg border border-surface-border", className)}>
|
|
{failed ? (
|
|
<div className="px-4 py-3 text-caption text-muted-foreground">
|
|
<PluginSurfaceNotice installation={installation} kind="failed" />
|
|
</div>
|
|
) : null}
|
|
<iframe
|
|
// Keyed on the issue as well: a new bridge is created when issueId
|
|
// changes, but an unchanged document would not reload, and the guest
|
|
// stops announcing once answered — the fresh bridge would wait forever.
|
|
key={`${installation.id}:${surface.key}:${issueId ?? ""}`}
|
|
ref={frameRef}
|
|
title={`${installation.name} — ${surface.name}`}
|
|
// This is the host-authored wrapper, so same-origin is intentional. Its
|
|
// nested plugin iframe remains opaque and owns no app credential.
|
|
sandbox="allow-scripts allow-same-origin"
|
|
className="w-full border-0 bg-transparent"
|
|
style={{ height }}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function PluginSurfaceNotice({
|
|
installation,
|
|
kind,
|
|
}: {
|
|
installation: PluginInstallation;
|
|
kind: "unavailable" | "failed" | "loading" | "navigated";
|
|
}) {
|
|
const { t } = useT("issues");
|
|
if (kind === "failed") return <>{t(($) => $.plugins.surface_failed, { name: installation.name })}</>;
|
|
if (kind === "loading") return <>{t(($) => $.plugins.surface_loading, { name: installation.name })}</>;
|
|
if (kind === "navigated") return <>{t(($) => $.plugins.surface_navigated, { name: installation.name })}</>;
|
|
return <>{t(($) => $.plugins.surface_unavailable, { name: installation.name })}</>;
|
|
}
|