Files
kandev/apps/web/components/settings/plugins/marketplace-browser.tsx
T
João Salavisa bc2f310e73 feat(plugins): add plugin marketplace with curated registry and updates (#1798)
* feat(plugins): add plugin marketplace with curated registry and updates

Discover and install plugins from inside kandev instead of only by URL/upload.

- Backend marketplace subpackage: SQLite-backed sources, catalog fetch/merge
  (dedup, install_state, degraded-source handling), and the /api/plugins/
  marketplace[/sources] API. Install reuses the existing install-by-URL pipeline.
- Frontend: Settings > Plugins gains a Browse tab (search/category/star sort),
  source management, one-click install, and an Update button on the Installed
  tab when the catalog has a newer version. Plugins may ship an icon (manifest
  `icon` -> catalog icon_url) with a letter-tile fallback.
- Registry infra: plugin-registry/ (curated plugins.yaml + schema.json) and two
  GitHub Actions (zero-dependency Node build-index.mjs -> index.json on Pages,
  daily star refresh). Ships empty at launch; the empty catalog is valid.
- Spec: docs/specs/plugins/marketplace.md. No download telemetry; stars only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): address marketplace PR review feedback

- CodeQL: stub fetch routers keyed off a path segment, not a hostname substring.
- Nullable stars end to end: a failed star lookup stays unknown (not 0) and
  sorts last, instead of decoding null -> 0 and corrupting ranking.
- Fetch marketplace sources concurrently and dedupe identical in-flight
  downloads (singleflight), so a slow source can't serialize the Browse tab.
- Register /marketplace routes before the /:id wildcard (gin tree ordering).
- Duplicate source URL returns 409 ErrDuplicateSource, not a raw SQL error.
- Browse: filter category client-side so the category dropdown never collapses.
- marketplaceInstall swallows after toasting (no unhandled promise rejection).
- Source badge keys off source_id, not a name substring.
- build-index: read block-sequence manifest categories, not just inline.
- Registry index workflow validates on pull_request; Pages deploy gated to
  push/schedule/dispatch. Spec: align package_sha256 (advisory in v1) + sort enum.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): guard catalog repo_url against javascript: href injection

repo_url comes from an untrusted index.json, so a malicious/compromised source
could set a javascript: URL that runs in the operator's session when the Repo
link is clicked (rel/target don't block it). Only render the anchor for http(s)
schemes. Adds regression tests for the scheme guard and null-star rendering.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): require https for remote sources; test oversized download

- Reject remote plain-http marketplace sources (MITM catalog-poisoning risk);
  loopback http stays allowed for local dev/e2e fixtures.
- Add the missing oversized-response assertion to TestDownloadRejectsNon200AndOversized
  so the maxIndexBytes memory bound has coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): detach source download from singleflight leader's context

Two concurrent Browse opens after a cache Refresh share one singleflight
download; if the leader's request context is canceled (it navigates away), the
waiters must not inherit that cancellation. Use context.WithoutCancel so values
are preserved but the leader can't cancel everyone; the client's 20s timeout
still bounds the download.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 17:10:53 +01:00

236 lines
7.4 KiB
TypeScript

"use client";
import { useMemo, useState } from "react";
import { IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { useMarketplace } from "@/hooks/domains/plugins/use-marketplace";
import type { CatalogQuery } from "@/lib/api/domains/marketplace-api";
import type { MarketplaceCatalog, MarketplaceEntry } from "@/lib/types/plugins";
import { MarketplaceEntryRow } from "./marketplace-entry-row";
import { MarketplaceSourcesDialog } from "./marketplace-sources-dialog";
const ALL_CATEGORIES = "__all__";
type MarketplaceBrowserProps = {
/** Installs a plugin from its package URL; resolves when the install settles. */
onInstallUrl: (url: string) => Promise<void>;
};
/** The "Browse" tab: search/filter/sort the catalog and install from it. */
export function MarketplaceBrowser({ onInstallUrl }: MarketplaceBrowserProps) {
const [text, setText] = useState("");
const [category, setCategory] = useState<string>(ALL_CATEGORIES);
const [sort, setSort] = useState<CatalogQuery["sort"]>("stars");
const [sourcesOpen, setSourcesOpen] = useState(false);
const [installingId, setInstallingId] = useState<string | null>(null);
// Category is filtered client-side (not sent to the server): otherwise a
// category-narrowed catalog would shrink the category dropdown to just the
// selected value, trapping the user. Search + sort stay server-side.
const { catalog, loading, error, reload, softReload } = useMarketplace({
q: text.trim() || undefined,
sort,
});
const categories = useCatalogCategories(catalog);
const visible =
category === ALL_CATEGORIES
? catalog.plugins
: catalog.plugins.filter((entry) => entry.categories.includes(category));
const install = async (entry: MarketplaceEntry) => {
setInstallingId(entry.id);
try {
await onInstallUrl(entry.package_url);
softReload();
} finally {
setInstallingId(null);
}
};
return (
<div className="space-y-4">
<MarketplaceToolbar
text={text}
onText={setText}
category={category}
onCategory={setCategory}
categories={categories}
sort={sort}
onSort={setSort}
onManageSources={() => setSourcesOpen(true)}
onRefresh={reload}
/>
<DegradedSourcesBanner catalog={catalog} />
<MarketplaceList
entries={visible}
loading={loading}
error={error}
filtered={Boolean(text.trim() || category !== ALL_CATEGORIES)}
installingId={installingId}
onInstall={install}
/>
<MarketplaceSourcesDialog
open={sourcesOpen}
sources={catalog.sources}
onOpenChange={setSourcesOpen}
onChanged={reload}
/>
</div>
);
}
function useCatalogCategories(catalog: MarketplaceCatalog): string[] {
return useMemo(() => {
const set = new Set<string>();
for (const entry of catalog.plugins) {
for (const cat of entry.categories) set.add(cat);
}
return Array.from(set).sort();
}, [catalog.plugins]);
}
type ToolbarProps = {
text: string;
onText: (v: string) => void;
category: string;
onCategory: (v: string) => void;
categories: string[];
sort: CatalogQuery["sort"];
onSort: (v: CatalogQuery["sort"]) => void;
onManageSources: () => void;
onRefresh: () => void;
};
function MarketplaceToolbar(props: ToolbarProps) {
return (
<div className="flex flex-wrap items-center gap-2">
<Input
placeholder="Search plugins…"
value={props.text}
onChange={(e) => props.onText(e.target.value)}
className="max-w-xs"
data-testid="marketplace-search"
/>
<Select value={props.category} onValueChange={props.onCategory}>
<SelectTrigger className="w-40" data-testid="marketplace-category">
<SelectValue placeholder="Category" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL_CATEGORIES}>All categories</SelectItem>
{props.categories.map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={props.sort} onValueChange={(v) => props.onSort(v as CatalogQuery["sort"])}>
<SelectTrigger className="w-36" data-testid="marketplace-sort">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stars">Most stars</SelectItem>
<SelectItem value="recent">Recently updated</SelectItem>
<SelectItem value="name">Name</SelectItem>
</SelectContent>
</Select>
<div className="ml-auto flex items-center gap-2">
<Button variant="secondary" onClick={props.onRefresh} className="cursor-pointer">
<IconRefresh className="h-4 w-4" />
Refresh
</Button>
<Button
variant="outline"
onClick={props.onManageSources}
className="cursor-pointer"
data-testid="marketplace-manage-sources"
>
Sources
</Button>
</div>
</div>
);
}
function DegradedSourcesBanner({ catalog }: { catalog: MarketplaceCatalog }) {
const degraded = catalog.sources.filter((s) => s.enabled && s.healthy === false);
if (degraded.length === 0) return null;
return (
<div
data-testid="marketplace-degraded-sources"
className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400 space-y-1"
>
{degraded.map((s) => (
<div key={s.id}>
<span className="font-medium">{s.name}</span> is unreachable
{s.error ? `: ${s.error}` : ""} — its plugins are hidden.
</div>
))}
</div>
);
}
type ListProps = {
entries: MarketplaceEntry[];
loading: boolean;
error: string | null;
filtered: boolean;
installingId: string | null;
onInstall: (entry: MarketplaceEntry) => void;
};
function MarketplaceList({
entries,
loading,
error,
filtered,
installingId,
onInstall,
}: ListProps) {
if (error) {
return (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-6 text-sm text-destructive">
{error}
</div>
);
}
if (loading && entries.length === 0) {
return (
<div className="rounded-lg border border-dashed border-border/70 p-6 text-sm text-muted-foreground">
Loading marketplace…
</div>
);
}
if (entries.length === 0) {
return (
<div className="rounded-xl border border-dashed border-border/70 p-10 text-center text-sm text-muted-foreground">
{filtered
? "No plugins match your search. Try clearing the filters."
: "No plugins available yet. Check back soon, or add a marketplace source with your own."}
</div>
);
}
return (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
{entries.length} {entries.length === 1 ? "plugin" : "plugins"} available
</p>
<div className="grid gap-3 md:grid-cols-2">
{entries.map((entry) => (
<MarketplaceEntryRow
key={`${entry.source_id}:${entry.id}`}
entry={entry}
busy={installingId === entry.id}
onInstall={onInstall}
/>
))}
</div>
</div>
);
}