25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(plugins): check and update installed plugins with provenance guards
Abeautifulsnowcab674299aee
diff --git a/apps/desktop/src/components/layout/UpdateDialog.spec.ts b/apps/desktop/src/components/layout/UpdateDialog.spec.tsindex 1363259bf1..79b060b0c2 100644--- a/apps/desktop/src/components/layout/UpdateDialog.spec.ts+++ b/apps/desktop/src/components/layout/UpdateDialog.spec.ts@@ -512,4 +512,31 @@ describe("UpdateDialog aggregate update center", () => {expect(installComponentUpdates).toHaveBeenCalledWith("drivers");});++ it("marks only a plugin whose update source changed as needing confirmation in the Plugin Center", async () => {+ const listing = (id: string, provenance: Record<string, string>) => ({+ key: `official:${id}`,+ status: "update",+ artifact: { target: "universal", url: "https://example.com/plugin.dbxp", sha256: "hash", signingKeyId: "key-a" },+ repository: { id: "official" },+ plugin: { id, latestVersion: "1.1.0", publisher: "DBX" },+ installed: { manifest: { id, version: "1.0.0" }, provenance },+ name: `${id} plugin`,+ });+ await mountDialog(0, {}, undefined, {+ updateInfo: null,+ pluginUpdates: [listing("same", { repositoryId: "official" }), listing("moved", { repositoryId: "other-repo" })],+ });++ const pluginsTab = document.body.querySelector<HTMLButtonElement>('[data-update-tab="plugins"]');+ pluginsTab?.click();+ await flushDialog();++ // "Update all" skips the changed-source plugin, so the dialog has to explain why it stays.+ const hint = "Confirm the change in the Plugin Center first";+ const rows = [...document.body.querySelectorAll<HTMLElement>(".rounded-md.border.p-3")];+ const rowFor = (name: string) => rows.find((row) => row.textContent?.includes(name));+ expect(rowFor("moved plugin")?.textContent).toContain(hint);+ expect(rowFor("same plugin")?.textContent).not.toContain(hint);+ });});diff --git a/apps/desktop/src/components/layout/UpdateDialog.vue b/apps/desktop/src/components/layout/UpdateDialog.vueindex a98ce5a2fe..346c175e00 100644--- a/apps/desktop/src/components/layout/UpdateDialog.vue+++ b/apps/desktop/src/components/layout/UpdateDialog.vue@@ -8,7 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@import type { UpdateInfo } from "@/lib/backend/api";import type { AgentDriverInfo, McpServerStatus, UpdateDownloadSource } from "@/lib/backend/tauri";import type { JdbcPluginStatus } from "@/types/database";-import type { MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";+import { pluginSourceChange, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";import { mcpUpdateAvailability } from "@/lib/mcp/mcpUpdateStatus";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";import { isUpdatePreviewMockEnabled } from "@/lib/updates/updatePreviewMock";@@ -302,6 +302,9 @@ watch(<div class="min-w-0"><div class="truncate font-medium">{{ plugin.name }}</div><div class="mt-0.5 text-xs text-muted-foreground">{{ plugin.installed?.manifest.version || t("updates.notInstalled") }} → {{ plugin.plugin.latestVersion }}</div>+ <!-- "Update all" deliberately skips a changed source: the user has to confirm it in+ the Plugin Center, so say so instead of leaving an item that never updates. -->+ <div v-if="pluginSourceChange(plugin)" class="mt-1 text-xs text-amber-600 dark:text-amber-400">{{ t("pluginPlatform.updateSourceChangeRequired") }}</div></div><span class="shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">{{ t("settings.updateAvailable") }}</span></div>diff --git a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue b/apps/desktop/src/components/plugins/PluginContributionsPanel.vueindex 18160342b6..07d45f67d2 100644--- a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue+++ b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { computed, defineComponent, h, onBeforeUnmount, onMounted, ref, watch } from "vue";-import { BadgeCheck, Check, ChevronRight, CircleAlert, Download, ExternalLink, FileUp, FolderTree, Globe, Info, LayoutGrid, Link2, List, Loader2, PackageCheck, Pencil, Pin, PinOff, Plus, RefreshCw, RotateCcw, Search, Settings2, ShieldCheck, Store, Trash2 } from "@lucide/vue";+import { ArrowUp, BadgeCheck, Check, ChevronRight, CircleAlert, Download, ExternalLink, FileUp, FolderTree, Globe, Info, LayoutGrid, Link2, List, Loader2, PackageCheck, Pencil, Pin, PinOff, Plus, RefreshCw, RotateCcw, Search, Settings2, ShieldCheck, Store, Trash2 } from "@lucide/vue";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -8,6 +8,7 @@ import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useToast } from "@/composables/useToast";import PluginIcon from "@/components/plugins/PluginIcon.vue";@@ -17,9 +18,20 @@ import { loadPinnedPluginIds, savePinnedPluginIds, sortPluginsPinnedFirst } fromimport { isTauriRuntime } from "@/lib/backend/tauriRuntime";import { physicalDropPositionInsideRect } from "@/lib/ai/aiAttachments";import { createFrontendPluginRegistry, pluginConnectionProviderIcon } from "@/lib/plugins/frontendPlugin";-import { beaconPluginInstall, buildMarketplacePluginListings, filterMarketplacePluginListings, listingRepositoryCanVerify, marketplaceHomepageUrl, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";+import {+ beaconPluginInstall,+ buildInstalledUpdateIndex,+ buildMarketplacePluginListings,+ filterMarketplacePluginListings,+ listingRepositoryCanVerify,+ marketplaceHomepageUrl,+ pluginSourceChange,+ type InstalledPluginUpdateEntry,+ type MarketplacePluginListing,+ type PluginSourceChange,+} from "@/lib/plugins/pluginMarketplace";import { isBatchSelectableListing, runBatch } from "@/lib/plugins/pluginBatch";-import { COMPONENT_PLUGINS_UPDATED_EVENT, notifyComponentUpdatesChanged } from "@/lib/updates/componentUpdateEvents";+import { COMPONENT_PLUGINS_UPDATED_EVENT, notifyComponentPluginsUpdated, notifyComponentUpdatesChanged } from "@/lib/updates/componentUpdateEvents";import { formatBytes } from "@/lib/database/serverMetrics";import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";import { useConnectionStore } from "@/stores/connectionStore";@@ -74,6 +86,8 @@ const installUrl = ref("");const urlInstalling = ref(false);const urlDownloadProgress = ref<{ downloaded: number; total: number | null } | null>(null);const marketplaceInstallingKey = ref("");+const marketplaceUnavailable = ref(false);+const installedUpdateProgress = ref<{ current: number; total: number } | null>(null);const operating = ref(false);const error = ref("");const selectedPluginId = ref("");@@ -133,6 +147,41 @@ const batchUpdatableListings = computed(() => filteredMarketplaceListings.value.const batchSelectedListings = computed(() => filteredMarketplaceListings.value.filter((listing) => isBatchSelectableListing(listing.status) && selectedListingKeys.value.has(listing.key)));const batchSelectedInstalled = computed(() => definitions.value.filter((definition) => selectedInstalledIds.value.has(definition.plugin.manifest.id)));const catalogErrors = computed(() => catalogResults.value.filter((result) => result.error));+// Installed-tab update join: the same marketplace listings the store tab renders, indexed by+// plugin id so installed rows/detail can show "update available" without a second fetch.+const installedUpdateIndex = computed(() => buildInstalledUpdateIndex(marketplaceListings.value));+const installedUpdateCount = computed(() => installedUpdateIndex.value.size);+const installedUpdateEntries = computed(() => definitions.value.map((definition) => installedUpdateIndex.value.get(definition.plugin.manifest.id)).filter((entry): entry is InstalledPluginUpdateEntry => !!entry));+const selectedUpdateEntry = computed(() => (selectedDefinition.value && installedUpdateIndex.value.get(selectedDefinition.value.plugin.manifest.id)) || null);+const repositoriesEnabled = computed(() => repositories.value.some((repository) => repository.enabled));+// "Checked" means a catalog actually loaded: a failed/missing fetch must never read as up to date.+const catalogChecked = computed(() => !marketplaceLoading.value && !marketplaceUnavailable.value && repositoriesEnabled.value && catalogResults.value.some((result) => result.catalog));+// The backend answers a mixed fetch with successful catalogs AND per-repository errors, so+// "some catalog loaded" is not enough: one failing enabled repository makes the whole check+// incomplete (plugins whose only source is that repo would read as "not in repositories" /+// "all up to date").+const catalogPartialFailure = computed(() => repositoriesEnabled.value && catalogResults.value.some((result) => result.error));+function installedUpdateEntryFor(pluginId: string): InstalledPluginUpdateEntry | null {+ return installedUpdateIndex.value.get(pluginId) || null;+}+function pluginInCatalog(pluginId: string): boolean {+ return marketplaceListings.value.some((listing) => listing.plugin.id === pluginId);+}+// Catalog listings that do exist for an installed plugin but ship no artifact for this platform:+// their update status cannot be checked either, so it gets the same visible treatment as the+// "not in any catalog" case instead of reading as up to date.+const installedUnsupportedListings = computed(() => {+ const byId = new Map<string, MarketplacePluginListing>();+ for (const listing of marketplaceListings.value) {+ if (listing.status !== "unsupported" || !listing.installed) continue;+ if (!byId.has(listing.plugin.id)) byId.set(listing.plugin.id, listing);+ }+ return byId;+});+function installedUnsupportedListingFor(pluginId: string): MarketplacePluginListing | null {+ if (installedUpdateIndex.value.has(pluginId)) return null;+ return installedUnsupportedListings.value.get(pluginId) || null;+}const customRepositories = computed(() => repositories.value.filter((repository) => !repository.managed));const showCustomRepositoryTrustSettings = computed(() => customRepositories.value.length > 0 || trustedKeys.value.length > 0);const pluginDevelopmentDocsUrl = computed(() => `https://dbxio.com/${appLocale.value.startsWith("zh") ? "cn" : "en"}/docs/plugin-development`);@@ -175,8 +224,12 @@ async function refreshMarketplace() {marketplaceLoading.value = true;try {catalogResults.value = await api.fetchPluginMarketplaceCatalogs();+ marketplaceUnavailable.value = false;} catch (cause) {catalogResults.value = [];+ // Track total failure separately: catalogErrors is derived from catalogResults, which is+ // empty here, so without this flag the installed tab would silently read as "up to date".+ marketplaceUnavailable.value = true;toast(cause instanceof Error ? cause.message : String(cause), 5000);} finally {marketplaceLoading.value = false;@@ -198,24 +251,48 @@ function notifyPluginRuntimeReplaced(pluginId: string) {if (!isTauriRuntime()) emit("pluginRuntimeReplaced", pluginId);}-async function installListing(listing: MarketplacePluginListing): Promise<PluginInstallResult> {+// A recorded provenance that differs from the candidate listing (repository / publisher / signing+// key) requires an explicit confirmation before the plugin may be replaced. The backend enforces+// the same rule and rejects the install without allowSourceChange; this pre-check keeps that+// rejection out of the user's way by asking up front.+const pendingSourceChange = ref<{ listing: MarketplacePluginListing; change: PluginSourceChange } | null>(null);+function confirmUpdateSourceChange(listing: MarketplacePluginListing): boolean {+ const change = pluginSourceChange(listing);+ if (!change) return true;+ pendingSourceChange.value = { listing, change };+ return false;+}+function proceedUpdateSourceChange() {+ const pending = pendingSourceChange.value;+ pendingSourceChange.value = null;+ if (pending) void installMarketplaceListing(pending.listing, { allowSourceChange: true, skipSourceConfirmation: true });+}+function cancelUpdateSourceChange() {+ pendingSourceChange.value = null;+}++async function installListing(listing: MarketplacePluginListing, allowSourceChange = false): Promise<PluginInstallResult> {const result = await api.installMarketplacePlugin({repositoryId: listing.repository.id,pluginId: listing.plugin.id,version: listing.plugin.latestVersion,+ allowSourceChange: allowSourceChange || undefined,});notifyPluginRuntimeReplaced(result.plugin.manifest.id);beaconPluginInstall(listing.plugin.id, listing.plugin.latestVersion, listing.status === "update" ? "update" : "install");return result;}-async function installMarketplaceListing(listing: MarketplacePluginListing) {+async function installMarketplaceListing(listing: MarketplacePluginListing, options: { allowSourceChange?: boolean; skipSourceConfirmation?: boolean } = {}) {if (mutationRunning.value || !listing.artifact || !isBatchSelectableListing(listing.status)) return;+ if (!options.skipSourceConfirmation && !confirmUpdateSourceChange(listing)) return;marketplaceInstallingKey.value = listing.key;try {- const result = await installListing(listing);+ const result = await installListing(listing, options.allowSourceChange === true);toast(t(listing.status === "update" ? "pluginPlatform.updateSuccess" : "pluginPlatform.installSuccess", { name: result.plugin.manifest.name, version: result.plugin.manifest.version }));- installedPlugins.value = await api.listPlugins();+ // The COMPONENT_PLUGINS_UPDATED_EVENT handler does the panel-side refresh (icon cache ++ // installed list); notifyComponentUpdatesChanged drives the App-level update-center badge.+ notifyComponentPluginsUpdated();notifyComponentUpdatesChanged();selectPlugin(result.plugin.manifest.id);} catch (cause) {@@ -248,6 +325,44 @@ async function refreshAfterBatch() {}}+async function updateInstalledPlugin(pluginId: string) {+ const entry = installedUpdateEntryFor(pluginId);+ if (!entry || mutationRunning.value) return;+ await installMarketplaceListing(entry.listing);+}++async function runUpdateAllInstalled() {+ const entries = installedUpdateEntries.value.filter((entry) => !pluginSourceChange(entry.listing));+ const sourceChanged = installedUpdateEntries.value.filter((entry) => pluginSourceChange(entry.listing));+ if (sourceChanged.length) toast(t("pluginPlatform.batchSourceChangeSkipped", { names: sourceChanged.map((entry) => entry.listing.name).join("、") }), 8000);+ if (!entries.length || mutationRunning.value) return;+ batchRunning.value = true;+ error.value = "";+ installedUpdateProgress.value = { current: 0, total: entries.length };+ try {+ const outcome = await runBatch(+ entries,+ (entry) => entry.listing.name,+ async (entry) => {+ await installListing(entry.listing);+ },+ (current, total) => {+ installedUpdateProgress.value = { current, total };+ },+ );+ if (outcome.succeeded.length) {+ clearPluginIconCache();+ notifyComponentPluginsUpdated();+ notifyComponentUpdatesChanged();+ }+ reportBatchSummary(outcome);+ await refreshAfterBatch();+ } finally {+ batchRunning.value = false;+ installedUpdateProgress.value = null;+ }+}+async function refreshAfterExternalPluginUpdate() {clearPluginIconCache();try {@@ -314,6 +429,8 @@ async function runBatchInstallUpdate() {pluginIds.add(listing.plugin.id);}if (duplicateIds.size) return toast(t("pluginPlatform.batchDuplicateSources", { names: [...duplicateIds].join("、") }), 8000);+ const sourceChangedListings = targets.filter((listing) => pluginSourceChange(listing));+ if (sourceChangedListings.length) return toast(t("pluginPlatform.batchSourceChangeSkipped", { names: sourceChangedListings.map((listing) => listing.name).join("、") }), 8000);batchRunning.value = true;error.value = "";try {@@ -546,6 +663,7 @@ async function finishInstall(result: PluginInstallResult) {reportInstallBeacon(result);toast(t("pluginPlatform.installSuccess", { name: result.plugin.manifest.name, version: result.plugin.manifest.version }));clearPluginIconCache();+ notifyComponentPluginsUpdated();installedPlugins.value = await api.listPlugins();notifyComponentUpdatesChanged();selectPlugin(result.plugin.manifest.id);@@ -776,7 +894,10 @@ onBeforeUnmount(() => {<Tabs v-model="activeSection" class="min-h-0 flex-1 gap-3"><TabsList class="grid h-9 w-full grid-cols-3"><TabsTrigger value="marketplace" class="gap-1.5 text-xs"><Store class="size-3.5" />{{ t("pluginPlatform.marketplace") }}</TabsTrigger>- <TabsTrigger value="installed" class="gap-1.5 text-xs"><PackageCheck class="size-3.5" />{{ t("pluginPlatform.installed") }}</TabsTrigger>+ <TabsTrigger value="installed" class="gap-1.5 text-xs">+ <PackageCheck class="size-3.5" />{{ t("pluginPlatform.installed") }}+ <span v-if="installedUpdateCount" class="inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-semibold text-amber-950 dark:text-amber-950">{{ installedUpdateCount > 99 ? "99+" : installedUpdateCount }}</span>+ </TabsTrigger><TabsTrigger value="settings" class="gap-1.5 text-xs"><Settings2 class="size-3.5" />{{ t("pluginPlatform.settings") }}</TabsTrigger></TabsList>@@ -1019,6 +1140,55 @@ onBeforeUnmount(() => {</Button><Button variant="ghost" size="sm" class="h-8 text-xs" :disabled="batchRunning" @click="toggleBatchMode">{{ t("common.cancel") }}</Button></template>+ <Button variant="ghost" size="icon-sm" class="shrink-0" :class="batchMode ? '' : 'ml-auto'" :disabled="marketplaceLoading" :title="t('pluginPlatform.refresh')" :aria-label="t('pluginPlatform.refresh')" @click="refreshMarketplace"+ ><RefreshCw class="size-3.5" :class="marketplaceLoading ? 'animate-spin' : ''"+ /></Button>+ </div>++ <!-- Partial catalog failure (some enabled repositories errored): the check is incomplete,+ so it is surfaced on its own and must never degrade into "all up to date". -->+ <div v-if="catalogPartialFailure" class="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">+ <CircleAlert class="mt-0.5 size-3.5 shrink-0" />+ <div>{{ t("pluginPlatform.updateCheckPartialFailure") }}</div>+ </div>+ <div v-for="result in catalogErrors" :key="`installed-${result.repository.id}`" class="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">+ <CircleAlert class="mt-0.5 size-3.5 shrink-0" />+ <div>+ <span class="font-medium">{{ result.repository.name }}:</span> {{ result.error }}+ </div>+ </div>+ <!-- Honest update-check states: a failed or missing catalog must never read as "up to date". -->+ <div v-if="marketplaceUnavailable" class="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">+ <CircleAlert class="mt-0.5 size-3.5 shrink-0" />+ <div class="min-w-0 flex-1">+ <span class="font-medium">{{ t("pluginPlatform.updateCheckUnavailable") }}</span> · {{ t("pluginPlatform.updateCheckUnavailableDescription") }}+ </div>+ <Button variant="outline" size="sm" class="h-6 shrink-0 text-xs" :disabled="marketplaceLoading" @click="refreshMarketplace"><RefreshCw class="size-3" :class="marketplaceLoading ? 'animate-spin' : ''" />{{ t("pluginPlatform.refresh") }}</Button>+ </div>+ <div v-else-if="!repositoriesEnabled && installedPlugins.length" class="flex items-start gap-2 rounded-lg border px-3 py-2 text-xs text-muted-foreground">+ <CircleAlert class="mt-0.5 size-3.5 shrink-0" />+ <div>{{ t("pluginPlatform.noRepositoriesEnabled") }}</div>+ </div>+ <div v-else-if="installedUpdateCount" class="flex flex-wrap items-center gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-2.5">+ <div class="min-w-0">+ <div class="text-sm font-semibold">{{ t("pluginPlatform.installedUpdatesAvailableTitle", { count: installedUpdateCount }) }}</div>+ <p class="text-xs text-muted-foreground">{{ t("pluginPlatform.installedUpdatesAvailableDescription") }}</p>+ </div>+ <div class="ml-auto flex shrink-0 items-center gap-2">+ <Button size="sm" class="h-7 text-xs" :disabled="mutationRunning" @click="runUpdateAllInstalled">+ <Loader2 v-if="installedUpdateProgress" class="size-3 animate-spin" />+ <Download v-else class="size-3" />+ {{ installedUpdateProgress ? t("pluginPlatform.updatingProgress", installedUpdateProgress) : t("pluginPlatform.updateAll") }}+ </Button>+ </div>+ </div>+ <div v-else-if="catalogChecked && !catalogPartialFailure && installedPlugins.length" class="flex items-center gap-2 rounded-lg border px-3 py-2 text-xs text-muted-foreground">+ <BadgeCheck class="size-3.5 text-emerald-600 dark:text-emerald-400" />+ <div>{{ t("pluginPlatform.allPluginsUpToDate") }}</div>+ </div>+ <div v-else-if="marketplaceLoading && installedPlugins.length" class="flex items-center gap-2 rounded-lg border px-3 py-2 text-xs text-muted-foreground">+ <Loader2 class="size-3.5 animate-spin" />+ <div>{{ t("pluginPlatform.checkingForUpdates") }}</div></div><div class="grid min-h-0 flex-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]"><div class="space-y-1 rounded-lg border bg-muted/10 p-2">@@ -1042,7 +1212,24 @@ onBeforeUnmount(() => {<span class="block truncate text-sm font-medium">{{ definition.plugin.manifest.name }}</span><span class="mt-1 flex flex-wrap gap-1"><Badge variant="outline" class="h-4 px-1.5 text-[10px]">v{{ definition.plugin.manifest.version || "-" }}</Badge>+ <span+ v-if="installedUpdateEntryFor(definition.plugin.manifest.id)"+ class="inline-flex h-4 items-center gap-0.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-1.5 text-[10px] font-medium text-amber-700 dark:text-amber-300"+ :title="t('pluginPlatform.installedVersionUpdatable', { installed: definition.plugin.manifest.version || '0.0.0', latest: installedUpdateEntryFor(definition.plugin.manifest.id)?.listing.plugin.latestVersion })"+ >+ <ArrowUp class="size-2.5" />v{{ installedUpdateEntryFor(definition.plugin.manifest.id)?.listing.plugin.latestVersion }}+ </span><Badge :variant="definition.plugin.compatibility.compatible ? 'secondary' : 'destructive'" class="h-4 px-1.5 text-[10px]">{{ definition.plugin.compatibility.compatible ? t("pluginPlatform.compatible") : t("pluginPlatform.blocked") }}</Badge>+ <Badge v-if="catalogChecked && !catalogPartialFailure && !pluginInCatalog(definition.plugin.manifest.id)" variant="outline" class="h-4 border-dashed px-1.5 text-[10px] text-muted-foreground" :title="t('pluginPlatform.notInRepositoriesHint')">{{+ t("pluginPlatform.notInRepositories")+ }}</Badge>+ <Badge+ v-else-if="installedUnsupportedListingFor(definition.plugin.manifest.id)"+ variant="outline"+ class="h-4 border-dashed px-1.5 text-[10px] text-muted-foreground"+ :title="t('pluginPlatform.unsupportedTarget', { target: installedUnsupportedListingFor(definition.plugin.manifest.id)?.target })"+ >{{ t("pluginPlatform.marketplaceStatus.unsupported") }}</Badge+ ></span></span></button>@@ -1098,9 +1285,18 @@ onBeforeUnmount(() => {</div></div></div>- <div class="flex gap-2">- <Button size="sm" variant="outline" class="gap-1.5" :disabled="mutationRunning" @click="rollbackSelectedPlugin"><RotateCcw class="size-3.5" />{{ t("pluginPlatform.rollback") }}</Button>- <Button size="sm" variant="outline" class="gap-1.5 text-destructive" :disabled="mutationRunning" @click="uninstallSelectedPlugin"><Trash2 class="size-3.5" />{{ t("pluginPlatform.uninstall") }}</Button>+ <div class="flex flex-col items-end gap-1.5">+ <div class="flex gap-2">+ <Button v-if="selectedUpdateEntry" size="sm" class="gap-1.5" :disabled="mutationRunning" @click="updateInstalledPlugin(selectedUpdateEntry.listing.plugin.id)">+ <Loader2 v-if="marketplaceInstallingKey === selectedUpdateEntry.listing.key" class="size-3.5 animate-spin" />+ <Download v-else class="size-3.5" />{{ t("pluginPlatform.updateToVersion", { version: selectedUpdateEntry.listing.plugin.latestVersion }) }}+ </Button>+ <Button size="sm" variant="outline" class="gap-1.5" :disabled="mutationRunning" @click="rollbackSelectedPlugin"><RotateCcw class="size-3.5" />{{ t("pluginPlatform.rollback") }}</Button>+ <Button size="sm" variant="outline" class="gap-1.5 text-destructive" :disabled="mutationRunning" @click="uninstallSelectedPlugin"><Trash2 class="size-3.5" />{{ t("pluginPlatform.uninstall") }}</Button>+ </div>+ <span v-if="selectedUpdateEntry" class="text-[11px] text-muted-foreground"+ >{{ t("pluginPlatform.installedVersionUpdatable", { installed: selectedDefinition?.plugin.manifest.version || "0.0.0", latest: selectedUpdateEntry.listing.plugin.latestVersion }) }} · {{ selectedUpdateEntry.repositoryName }}</span+ ></div></div>@@ -1278,6 +1474,62 @@ onBeforeUnmount(() => {</TabsContent></Tabs>+ <Dialog+ :open="!!pendingSourceChange"+ @update:open="+ (open: boolean) => {+ if (!open) cancelUpdateSourceChange();+ }+ "+ >+ <DialogContent class="max-w-md gap-4">+ <DialogHeader>+ <DialogTitle class="text-sm">{{ t("pluginPlatform.updateSourceChangeTitle") }}</DialogTitle>+ <DialogDescription class="text-xs leading-5">{{ t("pluginPlatform.updateSourceChangeBody") }}</DialogDescription>+ </DialogHeader>+ <div v-if="pendingSourceChange" class="grid grid-cols-2 gap-2 text-xs">+ <div class="rounded-lg border p-3">+ <div class="mb-2 text-[11px] font-semibold text-muted-foreground">{{ t("pluginPlatform.provenanceCurrentInstall") }}</div>+ <dl class="space-y-1">+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenanceRepository") }}</dt>+ <dd class="truncate">{{ pendingSourceChange.listing.installed?.provenance?.repositoryId || "-" }}</dd>+ </div>+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenancePublisher") }}</dt>+ <dd class="truncate">{{ pendingSourceChange.listing.installed?.provenance?.publisher || "-" }}</dd>+ </div>+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenanceSigningKey") }}</dt>+ <dd class="truncate font-mono text-[10px]">{{ pendingSourceChange.listing.installed?.provenance?.signingKeyId || "-" }}</dd>+ </div>+ </dl>+ </div>+ <div class="rounded-lg border border-amber-500/40 p-3">+ <div class="mb-2 text-[11px] font-semibold text-amber-700 dark:text-amber-300">{{ t("pluginPlatform.provenanceCandidate") }}</div>+ <dl class="space-y-1">+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenanceRepository") }}</dt>+ <dd class="truncate">{{ pendingSourceChange.listing.repository.id }}</dd>+ </div>+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenancePublisher") }}</dt>+ <dd class="truncate">{{ pendingSourceChange.listing.plugin.publisher }}</dd>+ </div>+ <div class="flex justify-between gap-2">+ <dt class="shrink-0 text-muted-foreground">{{ t("pluginPlatform.provenanceSigningKey") }}</dt>+ <dd class="truncate font-mono text-[10px]">{{ pendingSourceChange.listing.artifact?.signingKeyId || "-" }}</dd>+ </div>+ </dl>+ </div>+ </div>+ <DialogFooter class="gap-2">+ <Button variant="outline" size="sm" @click="cancelUpdateSourceChange">{{ t("common.cancel") }}</Button>+ <Button size="sm" :disabled="mutationRunning" @click="proceedUpdateSourceChange">{{ t("pluginPlatform.updateSourceChangeConfirm") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<div v-if="draggingPackage" class="pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-primary/60 bg-primary/5"><FileUp class="size-8 text-primary" /><div class="text-sm font-medium text-primary">{{ t("pluginPlatform.dropToInstall") }}</div>diff --git a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.tsindex 95c7483c81..8cce58250c 100644--- a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts+++ b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts@@ -68,6 +68,7 @@ type PanelState = {marketplaceListings: MarketplacePluginListing[];catalogResults: PluginRepositoryCatalogResult[];installedPlugins: InstalledPlugin[];+ repositories: PluginRepositoryCatalogResult["repository"][];selectedListingKeys: Set<string>;selectedInstalledIds: Set<string>;selectedPluginId: string;@@ -94,6 +95,18 @@ type PanelState = {removeTrustedKey: (keyId: string) => Promise<void>;toggleBatchMode: () => void;toggleInstalledSelection: (pluginId: string) => void;+ installedUpdateIndex: Map<string, { listing: MarketplacePluginListing; repositoryName: string }>;+ installedUpdateCount: number;+ installedUpdateProgress: { current: number; total: number } | null;+ catalogChecked: boolean;+ marketplaceUnavailable: boolean;+ catalogPartialFailure: boolean;+ pendingSourceChange: { listing: MarketplacePluginListing } | null;+ installedUnsupportedListingFor: (pluginId: string) => MarketplacePluginListing | null;+ updateInstalledPlugin: (pluginId: string) => Promise<void>;+ runUpdateAllInstalled: () => Promise<void>;+ proceedUpdateSourceChange: () => void;+ refreshMarketplace: () => Promise<void>;};function installed(id: string, version = "1.0.0"): InstalledPlugin {@@ -125,6 +138,14 @@ function catalog(repositoryId: string, ids: string[], version = "3.0.0"): Plugin};}+function unsupportedCatalog(repositoryId: string, ids: string[], version = "3.0.0"): PluginRepositoryCatalogResult {+ const result = catalog(repositoryId, ids, version);+ // No artifact for this platform on the catalog's latest version: the listing is "unsupported"+ // rather than updatable, so the installed tab has to say so instead of reading as up to date.+ for (const plugin of result.catalog!.plugins) plugin.versions[0].artifacts = [];+ return result;+}+function deferred<T>() {let resolve!: (value: T) => void;let reject!: (cause: unknown) => void;@@ -318,6 +339,117 @@ describe("PluginContributionsPanel installed plugin pin controls", () => {});});+describe("PluginContributionsPanel installed-tab updates", () => {+ it("updates an installed plugin through the marketplace install path", async () => {+ state.batchMode = false;+ state.selectedPluginId = "a";+ await nextTick();+ expect(state.installedUpdateCount).toBe(3);++ await state.updateInstalledPlugin("a");+ expect(mocks.installMarketplacePlugin).toHaveBeenCalledExactlyOnceWith({ repositoryId: "first", pluginId: "a", version: "3.0.0" });+ expect(mocks.listPlugins).toHaveBeenCalledTimes(1);+ });++ it("updates all installed updatable plugins in one batch run", async () => {+ state.batchMode = false;+ mocks.installMarketplacePlugin.mockRejectedValueOnce(new Error("update denied"));+ await state.runUpdateAllInstalled();+ expect(mocks.installMarketplacePlugin).toHaveBeenCalledTimes(3);+ expect(state.error).toBe("a: update denied");+ expect(state.installedUpdateProgress).toBeNull();+ expect(state.batchRunning).toBe(false);+ });++ it("keeps source-changed plugins out of batch update and reports them", async () => {+ const moved = installed("a");+ moved.provenance = { repositoryId: "other-repo", publisher: "DBX", signingKeyId: "test.key", source: "marketplace" };+ state.installedPlugins = [moved, installed("b"), installed("c")];+ await nextTick();+ state.batchMode = false;++ await state.runUpdateAllInstalled();+ expect(mocks.installMarketplacePlugin).toHaveBeenCalledTimes(2);+ expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("pluginPlatform.batchSourceChangeSkipped"), 8000);+ });++ it("confirms a source change before updating with allowSourceChange", async () => {+ const moved = installed("a");+ moved.provenance = { repositoryId: "other-repo", publisher: "DBX", signingKeyId: "test.key", source: "marketplace" };+ state.installedPlugins = [moved, installed("b"), installed("c")];+ await nextTick();+ state.batchMode = false;+ state.selectedPluginId = "a";++ await state.updateInstalledPlugin("a");+ expect(mutationCount()).toBe(0);+ expect(state.pendingSourceChange).not.toBeNull();++ state.proceedUpdateSourceChange();+ await flushUi();+ expect(mocks.installMarketplacePlugin).toHaveBeenCalledExactlyOnceWith({ repositoryId: "first", pluginId: "a", version: "3.0.0", allowSourceChange: true });+ expect(state.pendingSourceChange).toBeNull();+ });++ it("treats a failing enabled repository as an incomplete check, not as up to date", async () => {+ state.batchMode = false;+ state.repositories = [+ { id: "first", name: "first", kind: "custom", enabled: true, managed: false },+ { id: "second", name: "second", kind: "custom", enabled: true, managed: false },+ ];+ // "first" answers fine (a is up to date through it); "second" — b's only source — errors.+ state.catalogResults = [catalog("first", ["a"]), { ...catalog("second", ["b"]), catalog: undefined, error: "catalog offline" }];+ state.installedPlugins = [installed("a", "3.0.0"), installed("b", "1.0.0")];+ await nextTick();++ expect(state.catalogPartialFailure).toBe(true);+ // a is up to date via the first catalog, but the check is incomplete: no "all up to date".+ expect(host.textContent).not.toContain("pluginPlatform.allPluginsUpToDate");+ // b's only repository failed: it must not be labelled "not in repositories".+ expect(host.textContent).not.toContain("pluginPlatform.notInRepositories");+ // The incomplete state is surfaced instead, with the failing repository named.+ expect(host.textContent).toContain("pluginPlatform.updateCheckPartialFailure");+ expect(host.textContent).toContain("second: catalog offline");+ });++ it("flips to the up-to-date state only after a real catalog check", async () => {+ state.batchMode = false;+ state.repositories = [{ id: "first", name: "first", kind: "custom", enabled: true, managed: false }];+ await nextTick();+ expect(state.catalogChecked).toBe(true);+ expect(state.installedUpdateCount).toBe(3);++ mocks.fetchPluginMarketplaceCatalogs.mockRejectedValueOnce(new Error("offline"));+ await state.refreshMarketplace();+ expect(state.marketplaceUnavailable).toBe(true);+ expect(state.catalogChecked).toBe(false);++ await state.refreshMarketplace();+ expect(state.marketplaceUnavailable).toBe(false);++ state.installedPlugins = [installed("a", "3.0.0"), installed("b", "3.0.0"), installed("c", "3.0.0")];+ await nextTick();+ expect(state.catalogChecked).toBe(true);+ expect(state.installedUpdateCount).toBe(0);+ });++ it("surfaces installed plugins whose catalog version has no artifact for this platform", async () => {+ state.batchMode = false;+ state.catalogResults = [unsupportedCatalog("first", ["a", "b", "c"])];+ await nextTick();++ expect(state.installedUpdateCount).toBe(0);+ expect(state.installedUnsupportedListingFor("a")?.target).toBe("darwin-arm64");+ expect(host.querySelector('[data-plugin-id="a"]')?.textContent).toContain("pluginPlatform.marketplaceStatus.unsupported:");++ // The unsupported badge replaces the amber update marker, never both.+ state.catalogResults = [catalog("first", ["a", "b", "c"])];+ await nextTick();+ expect(state.installedUnsupportedListingFor("a")).toBeNull();+ expect(host.querySelector('[data-plugin-id="a"]')?.textContent).not.toContain("pluginPlatform.marketplaceStatus.unsupported:");+ });+});+describe("PluginContributionsPanel external component updates", () => {it("refreshes installed plugins when the update center updates plugins", async () => {expect(state.marketplaceListings.every((listing) => listing.status === "update")).toBe(true);diff --git a/apps/desktop/src/composables/__tests__/useComponentUpdates.spec.ts b/apps/desktop/src/composables/__tests__/useComponentUpdates.spec.tsindex 0866fb15e3..f051ca5728 100644--- a/apps/desktop/src/composables/__tests__/useComponentUpdates.spec.ts+++ b/apps/desktop/src/composables/__tests__/useComponentUpdates.spec.ts@@ -28,7 +28,7 @@ const settings = {vi.mock("@/lib/backend/api", () => mocks);vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => settings }));vi.mock("@/i18n", () => ({ currentLocale: () => "zh-CN" }));-vi.mock("@/lib/plugins/pluginMarketplace", () => ({ buildMarketplacePluginListings: mocks.buildMarketplacePluginListings }));+vi.mock("@/lib/plugins/pluginMarketplace", async (importOriginal) => ({ ...(await importOriginal<object>()), buildMarketplacePluginListings: mocks.buildMarketplacePluginListings }));const mcpStatus = {installed: true,diff --git a/apps/desktop/src/composables/useComponentUpdates.ts b/apps/desktop/src/composables/useComponentUpdates.tsindex 2a3d6d35b7..b46ec6d41d 100644--- a/apps/desktop/src/composables/useComponentUpdates.ts+++ b/apps/desktop/src/composables/useComponentUpdates.ts@@ -1,7 +1,7 @@import { computed, ref } from "vue";import * as api from "@/lib/backend/api";import { currentLocale } from "@/i18n";-import { buildMarketplacePluginListings, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";+import { buildMarketplacePluginListings, pluginSourceChange, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";import { mcpUpdateAvailability } from "@/lib/mcp/mcpUpdateStatus";import { useSettingsStore } from "@/stores/settingsStore";import { isUpdatePreviewMockEnabled, previewDriverUpdates, previewJdbcUpdate, previewMcpUpdate, previewPluginUpdates } from "@/lib/updates/updatePreviewMock";@@ -150,7 +150,10 @@ export function useComponentUpdates(options: { isDesktop: boolean }) {}async function updatePlugins(result: ComponentUpdateResult) {- const updatable = pluginUpdates.value.filter((item) => item.artifact);+ // Listings whose recorded provenance differs from the offering repository/publisher/key need an+ // explicit confirmation, which the automatic path cannot give: keep them visible in the update+ // center (they still count) but let the user confirm them in the Plugin Center instead.+ const updatable = pluginUpdates.value.filter((item) => item.artifact && !pluginSourceChange(item));if (isUpdatePreviewMockEnabled()) {result.plugins += updatable.length;return;diff --git a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts b/apps/desktop/src/i18n/__tests__/backendErrors.spec.tsindex 9dadfb7278..f7ed22d16c 100644--- a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts+++ b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts@@ -71,6 +71,16 @@ const CASES: { name: string; message: string; key: string; params?: Record<strinmessage: "Plugin update blocked by active operations. Please wait for them to finish.",key: "pluginPlatform.updateBlockedByOperations",},+ {+ name: "plugin update from a changed source needs confirmation",+ message: "Plugin update source change requires confirmation: the offering repository, publisher, or signing key differs from the recorded install",+ key: "pluginPlatform.updateSourceChangeRequired",+ },+ {+ name: "plugin downgrade is rejected",+ message: "Plugin downgrade to version 1.0.5 is not allowed (installed 1.1.0)",+ key: "pluginPlatform.updateDowngradeRejected",+ },{name: "connection admission waits for plugin update",message: "Plugin update is in progress. Please try again after it finishes.",@@ -611,6 +621,8 @@ describe("backend error wording is pinned to the Rust sources", () => {["crates/dbx-drivers/src/agent_service.rs", "is in use by drivers: "],["crates/dbx-drivers/src/agent_service.rs", "agent-registry.json not found in the ZIP; not a valid offline driver package."],["crates/dbx-core/src/admin/mq/adapters/kafka.rs", "Kafka does not support unloading topics"],+ ["crates/dbx-plugin-runtime/src/plugins/installer.rs", "Plugin update source change requires confirmation:"],+ ["crates/dbx-plugin-runtime/src/plugins/installer.rs", "Plugin downgrade to version "],["crates/dbx-web/src/auth.rs", "Please try again in {remaining}s"],["crates/dbx-web/src/routes/agents.rs", "Close these database connections before updating drivers: "],["src-tauri/src/commands/agents.rs", "Close these database connections before updating drivers: "],diff --git a/apps/desktop/src/i18n/backend-errors.ts b/apps/desktop/src/i18n/backend-errors.tsindex f08427413b..12186996d4 100644--- a/apps/desktop/src/i18n/backend-errors.ts+++ b/apps/desktop/src/i18n/backend-errors.ts@@ -90,6 +90,9 @@ const exactMessageKeys: Record<string, string> = {const patterns: [RegExp, string][] = [[/^Plugin update blocked by active connections: ([\s\S]+)$/, "pluginPlatform.updateBlockedByConnections"],+ // crates/dbx-plugin-runtime provenance guard (installer.rs / marketplace.rs)+ [/^Plugin update source change requires confirmation:/, "pluginPlatform.updateSourceChangeRequired"],+ [/^Plugin downgrade to version .+ is not allowed/, "pluginPlatform.updateDowngradeRejected"],[/^(.+?) driver is not installed\. Please install it from the Driver Manager\.$/, "connection.driverNotInstalled"],[/^JRE (.+?) runtime is not installed\. Please install it from the Driver Manager\.$/, "connection.jreNotInstalled"],[/^System Java runtime was not found:/, "connection.systemJavaNotFound"],diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 66d14d28fe..b543cf9f8b 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -195,6 +195,30 @@ export default {unsupported: "Unsupported",},updateSuccess: "Updated {name} to {version}",+ installedUpdatesAvailableTitle: "Plugin updates available ({count})",+ installedUpdatesAvailableDescription: "Updates verify signatures and checksums, and keep the previous version for one-click rollback.",+ updateAll: "Update all",+ updatingProgress: "Updating ({current}/{total})",+ updateToVersion: "Update to v{version}",+ checkingForUpdates: "Checking for plugin updates…",+ allPluginsUpToDate: "All installed plugins are up to date.",+ updateCheckUnavailable: "Plugin updates cannot be checked",+ updateCheckUnavailableDescription: "The plugin catalog could not be loaded, so update status may be outdated.",+ updateCheckPartialFailure: "Some plugin repositories failed to check; update status may be incomplete.",+ noRepositoriesEnabled: "No plugin repositories are enabled",+ notInRepositories: "Not in repositories",+ notInRepositoriesHint: "Installed outside the configured repositories (local .dbxp or repository disabled); update status unknown.",+ updateSourceChangeTitle: "Confirm changing the plugin update source?",+ updateSourceChangeBody: "The candidate update comes from a different repository, publisher, or signing key than the recorded install. Updating replaces the plugin and records the new source.",+ updateSourceChangeConfirm: "Update anyway (record new source)",+ provenanceCurrentInstall: "Current install",+ provenanceCandidate: "Candidate update",+ provenanceRepository: "Repository",+ provenancePublisher: "Publisher",+ provenanceSigningKey: "Signing key",+ batchSourceChangeSkipped: "These plugins changed update source and need per-plugin confirmation: {names}",+ updateSourceChangeRequired: "The update source has changed. Confirm the change in the Plugin Center first.",+ updateDowngradeRejected: "Downgrading to an older plugin version is not allowed.",updateBlockedByConnections: "Close these connections before updating or rolling back the plugin: {labels}",updateBlockedByOperations: "Wait for this plugin's active operations to finish before updating or rolling back.",updateInProgress: "This plugin is being updated. Try again after the update finishes.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex e599455eb5..9f18aa759e 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -193,6 +193,30 @@ export default withEnglishFallback({pluginHomepage: "Página principal",marketplaceStatus: { install: "Instalar", installed: "Instalado", update: "Actualizar", unsupported: "No compatible" },updateSuccess: "Se actualizó {name} a {version}",+ installedUpdatesAvailableTitle: "Actualizaciones de plugins disponibles ({count})",+ installedUpdatesAvailableDescription: "Las actualizaciones verifican firmas y sumas de comprobación, y conservan la versión anterior para revertir con un clic.",+ updateAll: "Actualizar todo",+ updatingProgress: "Actualizando ({current}/{total})",+ updateToVersion: "Actualizar a la v{version}",+ checkingForUpdates: "Buscando actualizaciones de plugins…",+ allPluginsUpToDate: "Todos los plugins instalados están actualizados.",+ updateCheckUnavailable: "No se pueden comprobar las actualizaciones de plugins",+ updateCheckUnavailableDescription: "No se pudo cargar el catálogo de plugins; el estado de actualización puede ser inexacto.",+ updateCheckPartialFailure: "Algunos repositorios de plugins no se pudieron comprobar; el estado de actualización puede estar incompleto.",+ noRepositoriesEnabled: "No hay repositorios de plugins habilitados",+ notInRepositories: "Fuera de repositorios",+ notInRepositoriesHint: "Instalado fuera de los repositorios configurados (archivo .dbxp local o repositorio deshabilitado); estado de actualización desconocido.",+ updateSourceChangeTitle: "¿Confirmar el cambio de origen de actualización del plugin?",+ updateSourceChangeBody: "La actualización candidata procede de un repositorio, editor o clave de firma distintos de la instalación registrada. Al actualizar se reemplaza el plugin y se registra el nuevo origen.",+ updateSourceChangeConfirm: "Actualizar igualmente (registrar nuevo origen)",+ provenanceCurrentInstall: "Instalación actual",+ provenanceCandidate: "Actualización candidata",+ provenanceRepository: "Repositorio",+ provenancePublisher: "Editor",+ provenanceSigningKey: "Clave de firma",+ batchSourceChangeSkipped: "Estos plugins cambiaron de origen de actualización y requieren confirmación individual: {names}",+ updateSourceChangeRequired: "El origen de actualización ha cambiado. Confirma el cambio en el Centro de plugins antes de actualizar.",+ updateDowngradeRejected: "No se permite volver a una versión anterior del plugin.",pinPlugin: "Fijar plugin",unpinPlugin: "Quitar fijación",noInstalledPlugins: "No hay plugins instalados",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 779913fc02..92a08911d6 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -192,6 +192,30 @@ export default withEnglishFallback({pluginHomepage: "Sito web",marketplaceStatus: { install: "Installa", installed: "Installato", update: "Aggiorna", unsupported: "Non supportato" },updateSuccess: "{name} aggiornato alla versione {version}",+ installedUpdatesAvailableTitle: "Aggiornamenti plugin disponibili ({count})",+ installedUpdatesAvailableDescription: "Gli aggiornamenti verificano firme e checksum e conservano la versione precedente per il rollback con un clic.",+ updateAll: "Aggiorna tutto",+ updatingProgress: "Aggiornamento ({current}/{total})",+ updateToVersion: "Aggiorna alla v{version}",+ checkingForUpdates: "Verifica degli aggiornamenti dei plugin…",+ allPluginsUpToDate: "Tutti i plugin installati sono aggiornati.",+ updateCheckUnavailable: "Impossibile verificare gli aggiornamenti dei plugin",+ updateCheckUnavailableDescription: "Impossibile caricare il catalogo dei plugin; lo stato degli aggiornamenti potrebbe non essere accurato.",+ updateCheckPartialFailure: "Alcuni repository di plugin non sono stati controllati; lo stato degli aggiornamenti potrebbe essere incompleto.",+ noRepositoriesEnabled: "Nessun repository di plugin abilitato",+ notInRepositories: "Non nei repository",+ notInRepositoriesHint: "Installato al di fuori dei repository configurati (.dbxp locale o repository disabilitato); stato di aggiornamento sconosciuto.",+ updateSourceChangeTitle: "Confermare la modifica dell'origine di aggiornamento del plugin?",+ updateSourceChangeBody: "L'aggiornamento candidato proviene da un repository, un publisher o una chiave di firma diversi da quelli registrati. L'aggiornamento sostituisce il plugin e registra la nuova origine.",+ updateSourceChangeConfirm: "Aggiorna comunque (registra nuova origine)",+ provenanceCurrentInstall: "Installazione attuale",+ provenanceCandidate: "Aggiornamento candidato",+ provenanceRepository: "Repository",+ provenancePublisher: "Publisher",+ provenanceSigningKey: "Chiave di firma",+ batchSourceChangeSkipped: "Questi plugin hanno cambiato origine di aggiornamento e richiedono conferma individuale: {names}",+ updateSourceChangeRequired: "L'origine di aggiornamento è cambiata. Conferma la modifica nel Centro plugin prima di aggiornare.",+ updateDowngradeRejected: "Non è possibile tornare a una versione precedente del plugin.",pinPlugin: "Fissa il plugin",unpinPlugin: "Togli fissaggio",noInstalledPlugins: "Nessun plugin installato",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex f5bce378f2..ddbc15153b 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -193,6 +193,30 @@ export default withEnglishFallback({pluginHomepage: "ホームページ",marketplaceStatus: { install: "インストール", installed: "インストール済み", update: "更新", unsupported: "非対応" },updateSuccess: "{name} を {version} に更新しました",+ installedUpdatesAvailableTitle: "プラグインの更新があります ({count})",+ installedUpdatesAvailableDescription: "更新前には署名とチェックサムを検証し、旧バージョンを保持してワンクリックでロールバックできます。",+ updateAll: "すべて更新",+ updatingProgress: "更新中 ({current}/{total})",+ updateToVersion: "v{version} に更新",+ checkingForUpdates: "プラグインの更新を確認中…",+ allPluginsUpToDate: "すべてのプラグインは最新です。",+ updateCheckUnavailable: "プラグインの更新を確認できません",+ updateCheckUnavailableDescription: "プラグインカタログの読み込みに失敗したため、更新状態が不正確な可能性があります。",+ updateCheckPartialFailure: "一部のプラグインリポジトリの確認に失敗したため、更新状態が不完全な可能性があります。",+ noRepositoriesEnabled: "有効なプラグインリポジトリがありません",+ notInRepositories: "リポジトリ外",+ notInRepositoriesHint: "ローカルインストールまたはリポジトリが無効のため、更新を確認できません。",+ updateSourceChangeTitle: "プラグインの更新元の変更を確認しますか?",+ updateSourceChangeBody: "候補の更新は、記録されたインストール元と異なるリポジトリ・公開者・署名鍵から提供されています。更新すると置き換わり、新しい更新元が記録されます。",+ updateSourceChangeConfirm: "更新する(新しい更新元を記録)",+ provenanceCurrentInstall: "現在のインストール",+ provenanceCandidate: "候補の更新",+ provenanceRepository: "リポジトリ",+ provenancePublisher: "公開者",+ provenanceSigningKey: "署名鍵",+ batchSourceChangeSkipped: "次のプラグインは更新元が変更されたため、個別に確認が必要です:{names}",+ updateSourceChangeRequired: "更新元が変更されています。プラグインセンターで確認してから更新してください。",+ updateDowngradeRejected: "古いプラグインバージョンへのダウングレードはできません。",pinPlugin: "プラグインをピン留め",unpinPlugin: "ピン留めを解除",noInstalledPlugins: "プラグインはまだありません",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex e7b3a9c63d..1ce0374a86 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -197,6 +197,30 @@ export default withEnglishFallback({unsupported: "지원되지 않음",},updateSuccess: "{name} 업데이트 완료: {version}",+ installedUpdatesAvailableTitle: "플러그인 업데이트 있음 ({count})",+ installedUpdatesAvailableDescription: "업데이트 전 서명과 체크섬을 검증하고, 이전 버전을 보관하여 한 번에 롤백할 수 있습니다.",+ updateAll: "모두 업데이트",+ updatingProgress: "업데이트 중 ({current}/{total})",+ updateToVersion: "v{version}(으)로 업데이트",+ checkingForUpdates: "플러그인 업데이트 확인 중…",+ allPluginsUpToDate: "모든 플러그인이 최신 버전입니다.",+ updateCheckUnavailable: "플러그인 업데이트를 확인할 수 없음",+ updateCheckUnavailableDescription: "플러그인 카탈로그를 불러오지 못해 업데이트 상태가 부정확할 수 있습니다.",+ updateCheckPartialFailure: "일부 플러그인 저장소 확인에 실패하여 업데이트 상태가 불완전할 수 있습니다.",+ noRepositoriesEnabled: "활성화된 플러그인 저장소가 없습니다",+ notInRepositories: "저장소에 없음",+ notInRepositoriesHint: "로컬 설치이거나 저장소가 비활성화되어 업데이트를 확인할 수 없습니다.",+ updateSourceChangeTitle: "플러그인 업데이트 출처 변경을 확인하시겠습니까?",+ updateSourceChangeBody: "후보 업데이트는 기록된 설치 출처와 다른 저장소·게시자·서명 키에서 제공됩니다. 업데이트하면 교체되며 새 출처가 기록됩니다.",+ updateSourceChangeConfirm: "업데이트(새 출처 기록)",+ provenanceCurrentInstall: "현재 설치",+ provenanceCandidate: "후보 업데이트",+ provenanceRepository: "저장소",+ provenancePublisher: "게시자",+ provenanceSigningKey: "서명 키",+ batchSourceChangeSkipped: "다음 플러그인은 업데이트 출처가 변경되어 개별 확인이 필요합니다: {names}",+ updateSourceChangeRequired: "업데이트 출처가 변경되었습니다. 플러그인 센터에서 확인 후 업데이트하세요.",+ updateDowngradeRejected: "이전 플러그인 버전으로 다운그레이드할 수 없습니다.",pinPlugin: "플러그인 고정",unpinPlugin: "고정 해제",noInstalledPlugins: "설치된 플러그인이 없습니다",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 97347f8e40..d118dd0cbf 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -193,6 +193,30 @@ export default withEnglishFallback({pluginHomepage: "Página inicial",marketplaceStatus: { install: "Instalar", installed: "Instalado", update: "Atualizar", unsupported: "Não compatível" },updateSuccess: "{name} atualizado para {version}",+ installedUpdatesAvailableTitle: "Atualizações de plugins disponíveis ({count})",+ installedUpdatesAvailableDescription: "As atualizações verificam assinaturas e checksums e mantêm a versão anterior para reversão com um clique.",+ updateAll: "Atualizar tudo",+ updatingProgress: "Atualizando ({current}/{total})",+ updateToVersion: "Atualizar para v{version}",+ checkingForUpdates: "Verificando atualizações de plugins…",+ allPluginsUpToDate: "Todos os plugins instalados estão atualizados.",+ updateCheckUnavailable: "Não é possível verificar atualizações de plugins",+ updateCheckUnavailableDescription: "O catálogo de plugins não pôde ser carregado; o status de atualização pode estar impreciso.",+ updateCheckPartialFailure: "Alguns repositórios de plugins falharam na verificação; o status de atualização pode estar incompleto.",+ noRepositoriesEnabled: "Nenhum repositório de plugins habilitado",+ notInRepositories: "Fora dos repositórios",+ notInRepositoriesHint: "Instalado fora dos repositórios configurados (.dbxp local ou repositório desabilitado); status de atualização desconhecido.",+ updateSourceChangeTitle: "Confirmar a alteração da origem de atualização do plugin?",+ updateSourceChangeBody: "A atualização candidata vem de um repositório, editor ou chave de assinatura diferentes da instalação registrada. Atualizar substitui o plugin e registra a nova origem.",+ updateSourceChangeConfirm: "Atualizar mesmo assim (registrar nova origem)",+ provenanceCurrentInstall: "Instalação atual",+ provenanceCandidate: "Atualização candidata",+ provenanceRepository: "Repositório",+ provenancePublisher: "Editor",+ provenanceSigningKey: "Chave de assinatura",+ batchSourceChangeSkipped: "Esses plugins mudaram de origem de atualização e exigem confirmação individual: {names}",+ updateSourceChangeRequired: "A origem de atualização mudou. Confirme a alteração no Central de Plugins antes de atualizar.",+ updateDowngradeRejected: "Não é permitido voltar a uma versão anterior do plugin.",pinPlugin: "Fixar plugin",unpinPlugin: "Desafixar",noInstalledPlugins: "Nenhum plugin instalado",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex b068ccb97e..064a94d55d 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -115,6 +115,30 @@ export default withEnglishFallback({pluginHomepage: "主页",marketplaceStatus: { install: "安装", installed: "已安装", update: "更新", unsupported: "不支持" },updateSuccess: "已将 {name} 更新到 {version}",+ installedUpdatesAvailableTitle: "插件更新可用 ({count})",+ installedUpdatesAvailableDescription: "更新前将校验包签名与校验和;自动保留上一版本,支持一键回滚。",+ updateAll: "全部更新",+ updatingProgress: "更新中 ({current}/{total})",+ updateToVersion: "更新至 v{version}",+ checkingForUpdates: "正在检查插件更新…",+ allPluginsUpToDate: "所有插件均已是最新版本。",+ updateCheckUnavailable: "无法检查插件更新",+ updateCheckUnavailableDescription: "插件目录加载失败,更新状态可能不准确。",+ updateCheckPartialFailure: "部分插件仓库检查失败,更新状态可能不完整。",+ noRepositoriesEnabled: "未启用任何插件仓库",+ notInRepositories: "不在仓库",+ notInRepositoriesHint: "本地安装或所在仓库已停用,无法检查更新。",+ updateSourceChangeTitle: "确认更换插件的更新来源?",+ updateSourceChangeBody: "候选更新的仓库、发布者或签名密钥与已记录的安装来源不一致;更新将替换当前插件并记录新来源。",+ updateSourceChangeConfirm: "仍要更新(记录新来源)",+ provenanceCurrentInstall: "当前安装",+ provenanceCandidate: "候选更新",+ provenanceRepository: "仓库",+ provenancePublisher: "发布者",+ provenanceSigningKey: "签名密钥",+ batchSourceChangeSkipped: "以下插件的更新来源有变更,请逐个确认更新:{names}",+ updateSourceChangeRequired: "更新来源有变更,请先在插件中心确认。",+ updateDowngradeRejected: "不能降级到更旧的插件版本。",updateBlockedByConnections: "请先关闭以下连接后再更新或回滚插件:{labels}",updateBlockedByOperations: "该插件仍有操作正在执行,请等待完成后再更新或回滚。",updateInProgress: "该插件正在更新,请等待完成后重试。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 517191eb21..896dcce098 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -193,6 +193,30 @@ export default withEnglishFallback({pluginHomepage: "主頁",marketplaceStatus: { install: "安裝", installed: "已安裝", update: "更新", unsupported: "不支援" },updateSuccess: "已將 {name} 更新至 {version}",+ installedUpdatesAvailableTitle: "外掛更新可用 ({count})",+ installedUpdatesAvailableDescription: "更新前會校驗套件簽章與校驗和;自動保留上一版本,支援一鍵回復。",+ updateAll: "全部更新",+ updatingProgress: "更新中 ({current}/{total})",+ updateToVersion: "更新至 v{version}",+ checkingForUpdates: "正在檢查外掛更新…",+ allPluginsUpToDate: "所有外掛均已是最新版本。",+ updateCheckUnavailable: "無法檢查外掛更新",+ updateCheckUnavailableDescription: "外掛目錄載入失敗,更新狀態可能不準確。",+ updateCheckPartialFailure: "部分外掛倉庫檢查失敗,更新狀態可能不完整。",+ noRepositoriesEnabled: "未啟用任何外掛倉庫",+ notInRepositories: "不在倉庫",+ notInRepositoriesHint: "本機安裝或所在倉庫已停用,無法檢查更新。",+ updateSourceChangeTitle: "確認更換外掛的更新來源?",+ updateSourceChangeBody: "候選更新的倉庫、發布者或簽署金鑰與已記錄的安裝來源不一致;更新將替換目前外掛並記錄新來源。",+ updateSourceChangeConfirm: "仍要更新(記錄新來源)",+ provenanceCurrentInstall: "目前安裝",+ provenanceCandidate: "候選更新",+ provenanceRepository: "倉庫",+ provenancePublisher: "發布者",+ provenanceSigningKey: "簽署金鑰",+ batchSourceChangeSkipped: "以下外掛的更新來源有變更,請逐個確認更新:{names}",+ updateSourceChangeRequired: "更新來源有變更,請先在外掛中心確認。",+ updateDowngradeRejected: "無法降級至較舊的外掛版本。",updateBlockedByConnections: "請先關閉以下連線後再更新或回復外掛:{labels}",updateBlockedByOperations: "此外掛仍有操作正在執行,請等待完成後再更新或回復。",updateInProgress: "此外掛正在更新,請等待完成後重試。",diff --git a/apps/desktop/src/lib/plugins/pluginBatch.ts b/apps/desktop/src/lib/plugins/pluginBatch.tsindex 2c6532d2ec..4beaa5e1e3 100644--- a/apps/desktop/src/lib/plugins/pluginBatch.ts+++ b/apps/desktop/src/lib/plugins/pluginBatch.ts@@ -17,10 +17,12 @@ export interface BatchOutcome {/*** Run `action` over `items` sequentially, recording per-item success/failure. A failing item is* captured and the batch continues; nothing is rolled back. `nameOf` supplies a human label used- * in the summary. Empty input yields an empty outcome.+ * in the summary. `onProgress` fires after every item (success or failure) so callers can render+ * live "(current/total)" progress. Empty input yields an empty outcome.*/-export async function runBatch<T>(items: readonly T[], nameOf: (item: T) => string, action: (item: T) => Promise<void>): Promise<BatchOutcome> {+export async function runBatch<T>(items: readonly T[], nameOf: (item: T) => string, action: (item: T) => Promise<void>, onProgress?: (completed: number, total: number) => void): Promise<BatchOutcome> {const results: BatchItemOutcome[] = [];+ let completed = 0;for (const item of items) {const name = nameOf(item);try {@@ -29,6 +31,8 @@ export async function runBatch<T>(items: readonly T[], nameOf: (item: T) => stri} catch (cause) {results.push({ name, ok: false, error: cause instanceof Error ? cause.message : String(cause) });}+ completed += 1;+ onProgress?.(completed, items.length);}return {results,diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.tsindex cee1a7adb7..b16b47a987 100644--- a/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { buildMarketplacePluginListings, filterMarketplacePluginListings, marketplaceHomepageUrl, selectMarketplaceArtifact } from "./pluginMarketplace";+import { buildInstalledUpdateIndex, buildMarketplacePluginListings, compareVersions, filterMarketplacePluginListings, marketplaceHomepageUrl, pluginSourceChange, selectMarketplaceArtifact } from "./pluginMarketplace";import type { InstalledPlugin, PluginRepositoryCatalogResult } from "@/types/database";const result: PluginRepositoryCatalogResult = {@@ -50,6 +50,17 @@ function installed(version: string): InstalledPlugin {};}+function repositoryResult(repositoryId: string, repositoryName: string, latestVersion: string, verified = true): PluginRepositoryCatalogResult {+ const copy = structuredClone(result);+ copy.repository = { id: repositoryId, name: repositoryName, kind: verified ? "official" : "custom", enabled: true, managed: !verified ? false : true };+ copy.catalog!.repository = { id: repositoryId, name: repositoryName };+ copy.catalog!.plugins[0].verified = verified;+ // Catalog validation requires latestVersion to exist in versions, so keep both in sync.+ copy.catalog!.plugins[0].latestVersion = latestVersion;+ copy.catalog!.plugins[0].versions[0].version = latestVersion;+ return copy;+}+describe("plugin marketplace listings", () => {it("localizes, detects updates, and filters by repository", () => {const listings = buildMarketplacePluginListings([result], [installed("1.0.0")], "zh-CN");@@ -97,3 +108,66 @@ describe("plugin marketplace listings", () => {expect(marketplaceHomepageUrl("https://github.com/dbxio/example", "https://dbxio.com/plugins/example")).toBe("https://dbxio.com/plugins/example");});});++describe("buildInstalledUpdateIndex", () => {+ it("indexes only update-bearing listings by plugin id", () => {+ const index = buildInstalledUpdateIndex(buildMarketplacePluginListings([result], [installed("1.0.0")], "en"));+ expect(index.get("example.hello")).toMatchObject({ repositoryName: "DBX Marketplace" });+ expect(index.get("example.hello")?.listing.plugin.latestVersion).toBe("1.1.0");++ // Already up to date (or not installed) → no entry.+ expect(buildInstalledUpdateIndex(buildMarketplacePluginListings([result], [installed("1.1.0")], "en")).size).toBe(0);+ expect(buildInstalledUpdateIndex(buildMarketplacePluginListings([result], [], "en")).size).toBe(0);+ });++ it("resolves duplicate plugin ids to one source: verifiable repository first, then the higher version", () => {+ const official = repositoryResult("dbx-official", "DBX Marketplace", "1.1.0", true);+ const custom = repositoryResult("acme", "Acme Repo", "1.3.0", false);+ // The unverified custom repository advertises a higher version, but the verifiable official+ // repository wins so the installed tab cannot silently steer users to an unverified source.+ const index = buildInstalledUpdateIndex(buildMarketplacePluginListings([custom, official], [installed("1.0.0")], "en"));+ expect(index.get("example.hello")?.listing.repository.id).toBe("dbx-official");++ const customA = repositoryResult("acme-a", "Acme A", "1.2.0", false);+ const customB = repositoryResult("acme-b", "Acme B", "1.3.0", false);+ const noVerifyIndex = buildInstalledUpdateIndex(buildMarketplacePluginListings([customA, customB], [installed("1.0.0")], "en"));+ expect(noVerifyIndex.get("example.hello")?.listing.plugin.latestVersion).toBe("1.3.0");+ });+});++describe("pluginSourceChange", () => {+ it("returns null when nothing was recorded or the candidate matches the provenance", () => {+ const noProvenance = buildMarketplacePluginListings([result], [installed("1.0.0")], "en")[0];+ expect(pluginSourceChange(noProvenance)).toBeNull();++ const withProvenance = installed("1.0.0");+ withProvenance.provenance = { repositoryId: "dbx-official", publisher: "DBX", signingKeyId: "dbx.release", source: "marketplace" };+ const same = buildMarketplacePluginListings([result], [withProvenance], "en")[0];+ expect(pluginSourceChange(same)).toBeNull();+ });++ it("flags repository, publisher, and signing-key changes individually", () => {+ const moved = installed("1.0.0");+ moved.provenance = { repositoryId: "other-repo", publisher: "DBX", signingKeyId: "dbx.release", source: "marketplace" };+ expect(pluginSourceChange(buildMarketplacePluginListings([result], [moved], "en")[0])).toEqual({ repositoryChanged: true, publisherChanged: false, signingKeyChanged: false });++ const renamed = installed("1.0.0");+ renamed.provenance = { repositoryId: "dbx-official", publisher: "Other", signingKeyId: "dbx.release", source: "marketplace" };+ expect(pluginSourceChange(buildMarketplacePluginListings([result], [renamed], "en")[0])).toEqual({ repositoryChanged: false, publisherChanged: true, signingKeyChanged: false });++ const rekeyed = installed("1.0.0");+ rekeyed.provenance = { repositoryId: "dbx-official", publisher: "DBX", signingKeyId: "dbx.release-2023", source: "marketplace" };+ expect(pluginSourceChange(buildMarketplacePluginListings([result], [rekeyed], "en")[0])).toEqual({ repositoryChanged: false, publisherChanged: false, signingKeyChanged: true });+ });+});++describe("compareVersions", () => {+ it("orders semver, ranks release above prerelease, and falls back for unparsable versions", () => {+ expect(compareVersions("1.10.0", "1.9.0")).toBeGreaterThan(0);+ expect(compareVersions("1.0.0", "1.0.0")).toBe(0);+ expect(compareVersions("1.0.0", "1.0.0-beta")).toBeGreaterThan(0);+ // Legacy migrated installs can carry non-semver manifest versions; the numeric-aware+ // fallback must still rank the catalog version above them.+ expect(compareVersions("1.1.0", "0.9")).toBeGreaterThan(0);+ });+});diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.tsindex 1c2d98ed78..335892af03 100644--- a/apps/desktop/src/lib/plugins/pluginMarketplace.ts+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.ts@@ -61,6 +61,55 @@ export function selectMarketplaceArtifact(artifacts: readonly PluginMarketplaceAreturn artifacts.find((candidate) => candidate.target === target) || artifacts.find((candidate) => candidate.target === UNIVERSAL_PLUGIN_TARGET);}+export interface InstalledPluginUpdateEntry {+ listing: MarketplacePluginListing;+ repositoryName: string;+}++// Same plugin id can be published by several enabled repositories. Prefer a repository allowed to+// verify the plugin (official/enterprise), then the higher latestVersion, so every consumer of the+// catalog join (marketplace cards, installed tab, batch) resolves the same single source.+function preferredUpdateListing(left: MarketplacePluginListing, right: MarketplacePluginListing): MarketplacePluginListing {+ if (left.verified !== right.verified) return left.verified ? left : right;+ return compareVersions(right.plugin.latestVersion, left.plugin.latestVersion) > 0 ? right : left;+}++/**+ * Catalog join for the installed tab: update-bearing listings indexed by plugin id, with at most+ * one entry per id (see preferredUpdateListing for the multi-repository collision rule).+ */+export function buildInstalledUpdateIndex(listings: readonly MarketplacePluginListing[]): Map<string, InstalledPluginUpdateEntry> {+ const index = new Map<string, InstalledPluginUpdateEntry>();+ for (const listing of listings) {+ if (listing.status !== "update") continue;+ const existing = index.get(listing.plugin.id);+ if (existing && preferredUpdateListing(existing.listing, listing) === existing.listing) continue;+ index.set(listing.plugin.id, { listing, repositoryName: listing.repository.name });+ }+ return index;+}++export interface PluginSourceChange {+ repositoryChanged: boolean;+ publisherChanged: boolean;+ signingKeyChanged: boolean;+}++/**+ * Compare the provenance recorded at install time against the candidate listing. Null means "no+ * confirmation needed": nothing recorded yet (installs from before provenance existed stay+ * unconstrained), or the recorded repository/publisher/signing key all match the candidate.+ */+export function pluginSourceChange(listing: MarketplacePluginListing): PluginSourceChange | null {+ const provenance = listing.installed?.provenance;+ if (!provenance) return null;+ const repositoryChanged = !!provenance.repositoryId && provenance.repositoryId !== listing.repository.id;+ const publisherChanged = !!provenance.publisher && !!listing.plugin.publisher && provenance.publisher !== listing.plugin.publisher;+ const signingKeyChanged = !!provenance.signingKeyId && !!listing.artifact?.signingKeyId && provenance.signingKeyId !== listing.artifact.signingKeyId;+ if (!repositoryChanged && !publisherChanged && !signingKeyChanged) return null;+ return { repositoryChanged, publisherChanged, signingKeyChanged };+}+export function listingRepositoryCanVerify(repository: PluginRepository): boolean {return repository.kind === "official" || repository.kind === "enterprise";}@@ -124,7 +173,37 @@ function marketplacePluginLocalization(plugin: PluginMarketplacePlugin, locale:};}-function compareVersions(left: string, right: string): number {+// Semver prerelease ordering: an identifier pair compares numerically when both are numeric,+// numeric ranks below alphanumeric, a shorter identifier list ranks lower, and a version WITHOUT+// a prerelease ranks above any prerelease. Plain localeCompare gets the last rule backwards+// ("~" collates below letters), which used to rank releases below their own betas.+function comparePrerelease(left: string, right: string): number {+ if (left === right) return 0;+ if (left === "~") return 1;+ if (right === "~") return -1;+ const leftIds = left.split(".");+ const rightIds = right.split(".");+ for (let index = 0; index < Math.max(leftIds.length, rightIds.length); index += 1) {+ const leftId = leftIds[index];+ const rightId = rightIds[index];+ if (leftId === undefined) return -1;+ if (rightId === undefined) return 1;+ const leftNumber = Number(leftId);+ const rightNumber = Number(rightId);+ const leftNumeric = leftId !== "" && !Number.isNaN(leftNumber);+ const rightNumeric = rightId !== "" && !Number.isNaN(rightNumber);+ if (leftNumeric && rightNumeric) {+ if (leftNumber !== rightNumber) return leftNumber - rightNumber;+ } else if (leftNumeric !== rightNumeric) {+ return leftNumeric ? -1 : 1;+ } else if (leftId !== rightId) {+ return leftId < rightId ? -1 : 1;+ }+ }+ return 0;+}++export function compareVersions(left: string, right: string): number {const leftParts = parseVersion(left);const rightParts = parseVersion(right);if (!leftParts || !rightParts) return left.localeCompare(right, undefined, { numeric: true, sensitivity: "base" });@@ -133,7 +212,7 @@ function compareVersions(left: string, right: string): number {for (let index = 0; index < leftNumbers.length; index += 1) {if (leftNumbers[index] !== rightNumbers[index]) return leftNumbers[index] - rightNumbers[index];}- return leftParts[3].localeCompare(rightParts[3]);+ return comparePrerelease(leftParts[3], rightParts[3]);}function parseVersion(version: string): [number, number, number, string] | null {diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 5a3e0201fb..e0b26390af 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -552,10 +552,18 @@ export interface PluginManifest {localizations?: Record<string, PluginManifestLocalization>;}+export interface PluginInstallProvenance {+ repositoryId?: string;+ publisher?: string;+ signingKeyId?: string;+ source?: "marketplace" | "url" | "file" | "unknown";+}+export interface InstalledPlugin {manifest: PluginManifest;compatibility: PluginCompatibility;path?: string;+ provenance?: PluginInstallProvenance;}export interface PluginTrustedKey {@@ -635,6 +643,7 @@ export interface PluginMarketplaceInstallRequest {repositoryId: string;pluginId: string;version?: string;+ allowSourceChange?: boolean;}export interface ActivePluginSession {diff --git a/crates/dbx-core/examples/plugin_marketplace_smoke.rs b/crates/dbx-core/examples/plugin_marketplace_smoke.rsindex 6f7baff2a7..2c9359a0ea 100644--- a/crates/dbx-core/examples/plugin_marketplace_smoke.rs+++ b/crates/dbx-core/examples/plugin_marketplace_smoke.rs@@ -41,6 +41,7 @@ async fn run() -> Result<(), String> {repository_id: OFFICIAL_PLUGIN_REPOSITORY_ID.to_string(),plugin_id: plugin_id.clone(),version,+ allow_source_change: false,}).await?;if installed.plugin.manifest.id != plugin_id {diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex 69edcf3607..9788b9ddfc 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -9415,6 +9415,7 @@ for line in sys.stdin:backend_executable: Some(dir.join("plugin.sh")),..Default::default()},+ provenance: None,};let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).await@@ -9521,6 +9522,7 @@ for line in sys.stdin:backend_executable: Some(dir.join("plugin.sh")),..Default::default()},+ provenance: None,};let session = Arc::new(PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())@@ -9638,6 +9640,7 @@ for line in sys.stdin:backend_executable: Some(dir.join("plugin.sh")),..Default::default()},+ provenance: None,};let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).await@@ -9702,6 +9705,7 @@ for line in sys.stdin:backend_executable: Some(dir.join("plugin.sh")),..Default::default()},+ provenance: None,};let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).awaitdiff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 407ce04a1a..69dee5bdc6 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -3603,6 +3603,7 @@ donebackend_executable: Some(dir.join("plugin.sh")),..Default::default()},+ provenance: None,};let session = std::sync::Arc::new(PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).await.unwrap(),@@ -3718,6 +3719,7 @@ donebackend_executable: Some(executable),..Default::default()},+ provenance: None,};let session = std::sync::Arc::new(PluginDriverSession::start_for_test(plugin, "jdbc".into(), PluginRuntimeEnv::default()).await.unwrap(),diff --git a/crates/dbx-plugin-runtime/src/plugins.rs b/crates/dbx-plugin-runtime/src/plugins.rsindex 158cbe6cfc..c58cec4236 100644--- a/crates/dbx-plugin-runtime/src/plugins.rs+++ b/crates/dbx-plugin-runtime/src/plugins.rs@@ -27,9 +27,9 @@ pub use host::{ActivePluginSession, PluginConnectionActionResult, PluginConnectionHandle, PluginHost, PluginRuntimeProxy,};pub use installer::{- PluginInstallPolicy, PluginInstallResponse, PluginInstallResult, PluginPackageInstaller, PluginRollbackResponse,- PluginRollbackResult, PluginSignatureStatus, PluginTrustStore, PluginTrustedKey, DBXP_EXTENSION,- MAX_PLUGIN_PACKAGE_BYTES, PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE,+ PluginInstallPolicy, PluginInstallProvenance, PluginInstallResponse, PluginInstallResult, PluginInstallSource,+ PluginPackageInstaller, PluginRollbackResponse, PluginRollbackResult, PluginSignatureStatus, PluginTrustStore,+ PluginTrustedKey, DBXP_EXTENSION, MAX_PLUGIN_PACKAGE_BYTES, PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE,};pub use lifecycle::PluginLifecycle;pub use marketplace::{@@ -62,6 +62,10 @@ pub struct InstalledPlugin {pub manifest: PluginManifest,pub path: PathBuf,pub compatibility: PluginCompatibility,+ /// Where the active installation came from (repository / publisher / signing key / source).+ /// `None` for installs recorded before provenance existed; those stay unconstrained until the+ /// next install records fresh provenance.+ pub provenance: Option<PluginInstallProvenance>,}#[derive(Debug, Clone, Serialize)]@@ -69,6 +73,8 @@ pub struct InstalledPlugin {pub struct InstalledPluginInfo {pub manifest: PluginManifest,pub compatibility: PluginCompatibilityInfo,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub provenance: Option<PluginInstallProvenance>,}#[derive(Debug, Clone, Serialize)]@@ -86,7 +92,13 @@ pub struct PluginCompatibilityInfo {impl InstalledPlugin {pub fn new(manifest: PluginManifest, path: PathBuf, app_version: &str) -> Self {let compatibility = manifest.compatibility(&path, app_version);- Self { manifest, path, compatibility }+ Self { manifest, path, compatibility, provenance: None }+ }++ /// Attaches the recorded install provenance (see `installer::read_container_provenance`).+ pub fn with_provenance(mut self, provenance: Option<PluginInstallProvenance>) -> Self {+ self.provenance = provenance;+ self}pub fn info(&self) -> InstalledPluginInfo {@@ -98,6 +110,7 @@ impl InstalledPlugin {warnings: self.compatibility.warnings.clone(),target: self.compatibility.target.clone(),},+ provenance: self.provenance.clone(),}}}@@ -221,7 +234,10 @@ impl PluginRegistry {continue;}};- plugins.push(InstalledPlugin::new(manifest, path, &self.app_version));+ plugins.push(+ InstalledPlugin::new(manifest, path, &self.app_version)+ .with_provenance(PluginPackageInstaller::read_container_provenance(&container_path)?),+ );}plugins.sort_by(|a, b| a.manifest.id.cmp(&b.manifest.id));Ok(plugins)@@ -340,6 +356,7 @@ fn unavailable_plugin(path: PathBuf, error: String) -> InstalledPlugin {target: Some(current_plugin_target()),..PluginCompatibility::default()},+ provenance: None,}}diff --git a/crates/dbx-plugin-runtime/src/plugins/installer.rs b/crates/dbx-plugin-runtime/src/plugins/installer.rsindex a94b5f4bd0..2ae8dd9ab4 100644--- a/crates/dbx-plugin-runtime/src/plugins/installer.rs+++ b/crates/dbx-plugin-runtime/src/plugins/installer.rs@@ -123,6 +123,41 @@ struct PluginPackageSignature {signature: String,}+/// Where an installed plugin came from. Recorded with every activation so an update can detect a+/// changed repository / publisher / signing key instead of silently replacing the plugin.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct PluginInstallProvenance {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub repository_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub publisher: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub signing_key_id: Option<String>,+ #[serde(default)]+ pub source: PluginInstallSource,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "camelCase")]+pub enum PluginInstallSource {+ Marketplace,+ Url,+ File,+ #[default]+ Unknown,+}++/// The active installation of one plugin id: the semver activation version plus whatever+/// provenance was recorded when it was installed. Provenance is `None` for installs made before+/// provenance existed (and for legacy migrated containers); those stay unconstrained until the+/// next install records fresh provenance.+#[derive(Debug, Clone)]+pub(crate) struct PluginInstallIdentity {+ pub version: String,+ pub provenance: Option<PluginInstallProvenance>,+}+#[derive(Debug, Clone, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]struct PluginActivationRecord {@@ -132,6 +167,8 @@ struct PluginActivationRecord {previous_version: Option<String>,package_sha256: String,activated_at: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ provenance: Option<PluginInstallProvenance>,}pub struct PluginPackageInstaller {@@ -145,11 +182,56 @@ pub struct PluginPackageInstaller {pub(super) struct PluginPackageExpectation {pub id: String,pub version: String,+ pub repository_id: Option<String>,pub publisher: String,pub permissions: BTreeSet<String>,pub signing_key_id: String,}+/// Read-only identity lookup for one plugin id under the store root: the activation version plus+/// the recorded provenance. Free function so the marketplace pre-flight can call it without+/// constructing an installer (which would load the user trust store as a side effect).+pub(crate) fn read_install_identity(root_dir: &Path, plugin_id: &str) -> Result<Option<PluginInstallIdentity>, String> {+ validate_plugin_id(plugin_id)?;+ let Some(record) = read_latest_activation(&root_dir.join(plugin_id))? else { return Ok(None) };+ Ok(Some(PluginInstallIdentity { version: record.version, provenance: record.provenance }))+}++/// Rejects an update whose repository / publisher / signing key differs from the recorded+/// provenance, or that would downgrade below the active version, unless `allow` is set (the+/// user confirmed the change in the UI). The marketplace pre-flight calls this before any+/// download; `install_bytes_locked` re-checks under the store lock.+pub(crate) fn ensure_update_continuity(+ provenance: &PluginInstallProvenance,+ active_version: &str,+ repository_id: Option<&str>,+ publisher: &str,+ signing_key_id: &str,+ candidate_version: &str,+ allow: bool,+) -> Result<(), String> {+ // Compare against the activation version (always semver); a legacy manifest version string+ // that fails to parse simply skips the downgrade check.+ if let (Ok(active), Ok(candidate)) = (Version::parse(active_version), Version::parse(candidate_version)) {+ if candidate < active && !allow {+ return Err(format!(+ "Plugin downgrade to version {candidate_version} is not allowed (installed {active_version})"+ ));+ }+ }+ let repository_changed =+ provenance.repository_id.as_deref().is_some_and(|recorded| Some(recorded) != repository_id);+ let publisher_changed = provenance.publisher.as_deref().is_some_and(|recorded| recorded != publisher);+ let key_changed = provenance.signing_key_id.as_deref().is_some_and(|recorded| recorded != signing_key_id);+ if (repository_changed || publisher_changed || key_changed) && !allow {+ return Err(+ "Plugin update source change requires confirmation: the offering repository, publisher, or signing key differs from the recorded install"+ .to_string(),+ );+ }+ Ok(())+}+impl PluginTrustStore {pub fn load(root_dir: &Path) -> Result<Self, String> {let document = read_trust_document(root_dir)?;@@ -291,22 +373,33 @@ impl PluginPackageInstaller {}pub fn install_bytes(&self, package: &[u8], policy: PluginInstallPolicy) -> Result<PluginInstallResult, String> {- self.install_bytes_with_expectation(package, policy, None)+ self.install_bytes_with_expectation(package, policy, None, PluginInstallSource::File, false)}pub(super) fn install_marketplace_bytes(&self,package: &[u8],expectation: &PluginPackageExpectation,+ allow_source_change: bool,) -> Result<PluginInstallResult, String> {- self.install_bytes_with_expectation(package, PluginInstallPolicy::LocalSigned, Some(expectation))+ self.install_bytes_with_expectation(+ package,+ PluginInstallPolicy::LocalSigned,+ Some(expectation),+ PluginInstallSource::Marketplace,+ allow_source_change,+ )}- fn install_bytes_with_expectation(+ /// Shared entry point for every install path: `PluginPackageExpectation` (and therefore this+ /// signature) stays inside the `plugins` module, exactly like the expectation type.+ pub(super) fn install_bytes_with_expectation(&self,package: &[u8],policy: PluginInstallPolicy,expectation: Option<&PluginPackageExpectation>,+ source: PluginInstallSource,+ allow_source_change: bool,) -> Result<PluginInstallResult, String> {if package.len() > MAX_PLUGIN_PACKAGE_BYTES {return Err(format!("Plugin package exceeds {MAX_PLUGIN_PACKAGE_BYTES} bytes"));@@ -314,7 +407,7 @@ impl PluginPackageInstaller {std::fs::create_dir_all(&self.root_dir).map_err(|error| error.to_string())?;let lock = open_install_lock(&self.root_dir)?;lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;- let result = self.install_bytes_locked(package, policy, expectation);+ let result = self.install_bytes_locked(package, policy, expectation, source, allow_source_change);let _ = FileExt::unlock(&lock);result}@@ -343,11 +436,18 @@ impl PluginPackageInstaller {result}+ /// Recorded provenance of one container's active installation, if any.+ pub(super) fn read_container_provenance(container_dir: &Path) -> Result<Option<PluginInstallProvenance>, String> {+ Ok(read_latest_activation(container_dir)?.and_then(|record| record.provenance))+ }+fn install_bytes_locked(&self,package: &[u8],policy: PluginInstallPolicy,expectation: Option<&PluginPackageExpectation>,+ source: PluginInstallSource,+ allow_source_change: bool,) -> Result<PluginInstallResult, String> {let package_sha256 = sha256_hex(package);let staging = tempfile::Builder::new()@@ -393,6 +493,26 @@ impl PluginPackageInstaller {let version_string = version.to_string();let version_dir = versions_dir.join(&version_string);let current = read_latest_activation(&container_dir)?;+ // Update continuity (crate::plugins::installer::ensure_update_continuity): a marketplace+ // update whose recorded repository / publisher / signing key differs from the offering one,+ // or that would downgrade the active version, is rejected unless the user explicitly+ // confirmed. Installs without recorded provenance stay unconstrained until the next+ // install records fresh provenance.+ if let (Some(expectation), Some(record)) = (expectation, current.as_ref()) {+ if !matches!(policy, PluginInstallPolicy::LocalDevelopment) {+ if let Some(provenance) = &record.provenance {+ ensure_update_continuity(+ provenance,+ &record.version,+ expectation.repository_id.as_deref(),+ &expectation.publisher,+ &expectation.signing_key_id,+ &version_string,+ allow_source_change,+ )?;+ }+ }+ }// Only the version the newest activation record resolves to *and* that is still a usable// install counts as "already installed". Directory existence alone is not enough: rollback// deliberately retains the version it replaces as the next rollback target, so an@@ -444,12 +564,37 @@ impl PluginPackageInstaller {return Err(message);}+ let provenance = match expectation {+ Some(expectation) => PluginInstallProvenance {+ repository_id: expectation.repository_id.clone(),+ publisher: Some(expectation.publisher.clone()),+ signing_key_id: Some(expectation.signing_key_id.clone()),+ source: PluginInstallSource::Marketplace,+ },+ None => {+ let previous = current.as_ref().and_then(|record| record.provenance.as_ref());+ PluginInstallProvenance {+ // A file/URL replacement carries the recorded repository forward so a+ // non-marketplace overwrite cannot silently erase a marketplace install's+ // source identity; publisher and signing key record what is actually+ // being installed now.+ repository_id: previous.and_then(|provenance| provenance.repository_id.clone()),+ publisher: Some(manifest.publisher.clone()),+ signing_key_id: match &signature {+ PluginSignatureStatus::Trusted { key_id } => Some(key_id.clone()),+ PluginSignatureStatus::Unsigned => None,+ },+ source,+ }+ }+ };let activation = PluginActivationRecord {sequence: current.as_ref().map_or(1, |record| record.sequence.saturating_add(1)),version: version_string,previous_version: previous_version.clone(),package_sha256: package_sha256.clone(),activated_at: Utc::now().to_rfc3339(),+ provenance: Some(provenance),};if let Err(error) = write_activation_record(&container_dir, &activation) {let _ = std::fs::remove_dir_all(&version_dir);@@ -469,7 +614,8 @@ impl PluginPackageInstaller {if let Err(error) = prune_plugin_history(&container_dir, &activation) {log::warn!("Failed to prune plugin '{}' install history: {error}", manifest.id);}- let plugin = InstalledPlugin::new(manifest, version_dir, &self.app_version);+ let plugin = InstalledPlugin::new(manifest, version_dir, &self.app_version)+ .with_provenance(activation.provenance.clone());Ok(PluginInstallResult { plugin, previous_version, package_sha256, signature, _update_guard: update_guard })}@@ -500,13 +646,18 @@ impl PluginPackageInstaller {));}let target_record = read_latest_activation_for_version(&container_dir, &previous_version)?;+ let plugin = plugin.with_provenance(target_record.as_ref().and_then(|record| record.provenance.clone()));let activation = PluginActivationRecord {sequence: current.sequence.saturating_add(1),version: previous_version.clone(),previous_version: Some(current.version),package_sha256: target_record- .map_or_else(|| "legacy-unmanaged".to_string(), |record| record.package_sha256),+ .as_ref()+ .map_or_else(|| "legacy-unmanaged".to_string(), |record| record.package_sha256.clone()),activated_at: Utc::now().to_rfc3339(),+ // Roll the target version's own provenance forward: a rollback re-activates that+ // version, so its recorded source identity is the truthful one to keep guarding with.+ provenance: target_record.as_ref().and_then(|record| record.provenance.clone()),};write_activation_record(&container_dir, &activation)?;if let Err(error) = prune_plugin_history(&container_dir, &activation) {@@ -853,6 +1004,7 @@ fn migrate_legacy_container(container_dir: &Path) -> Result<(), String> {previous_version: None,package_sha256: "legacy-unmanaged".to_string(),activated_at: Utc::now().to_rfc3339(),+ provenance: None,},)})();@@ -1024,9 +1176,9 @@ mod tests {use zip::write::SimpleFileOptions;use super::{- is_activation_record_file, sha256_hex, validate_package_expectation, PluginInstallPolicy,- PluginPackageExpectation, PluginPackageInstaller, PluginSignatureStatus, PluginTrustStore, ACTIVATIONS_DIR,- PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE, VERSIONS_DIR,+ is_activation_record_file, read_install_identity, sha256_hex, validate_package_expectation,+ PluginInstallPolicy, PluginPackageExpectation, PluginPackageInstaller, PluginSignatureStatus, PluginTrustStore,+ ACTIVATIONS_DIR, PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE, VERSIONS_DIR,};use crate::plugins::{PluginManifest, PluginRegistry};@@ -1092,15 +1244,19 @@ mod tests {.unwrap_err().contains("active operations"));let expectation = PluginPackageExpectation {+ repository_id: None,id: "sample.hello".to_string(),version: "1.1.0".to_string(),publisher: "sample".to_string(),permissions: BTreeSet::from(["host.events".to_string()]),signing_key_id: "test".to_string(),};- assert!(installer.install_marketplace_bytes(&bytes, &expectation).unwrap_err().contains("active operations"));+ assert!(installer+ .install_marketplace_bytes(&bytes, &expectation, false)+ .unwrap_err()+ .contains("active operations"));drop(operation);- installer.install_marketplace_bytes(&bytes, &expectation).unwrap();+ installer.install_marketplace_bytes(&bytes, &expectation, false).unwrap();assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.1.0");}@@ -1287,6 +1443,7 @@ mod tests {let trust = PluginTrustStore::from_base64_keys(keys).unwrap();let installer = PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", trust);let expectation = PluginPackageExpectation {+ repository_id: None,id: "sample.hello".to_string(),version: "1.0.0".to_string(),publisher: "sample".to_string(),@@ -1294,10 +1451,10 @@ mod tests {signing_key_id: "sample-key".to_string(),};let unsigned = package("1.0.0", None, false);- assert!(installer.install_marketplace_bytes(&unsigned, &expectation).is_err());+ assert!(installer.install_marketplace_bytes(&unsigned, &expectation, false).is_err());let signed = package("1.0.0", Some((&signing_key, "sample-key")), false);- let result = installer.install_marketplace_bytes(&signed, &expectation).unwrap();+ let result = installer.install_marketplace_bytes(&signed, &expectation, false).unwrap();assert_eq!(result.signature, PluginSignatureStatus::Trusted { key_id: "sample-key".to_string() });}@@ -1410,6 +1567,7 @@ mod tests {.unwrap();let signature = PluginSignatureStatus::Trusted { key_id: "sample-key".to_string() };let expectation = PluginPackageExpectation {+ repository_id: None,id: "sample.hello".to_string(),version: "1.0.0".to_string(),publisher: "sample".to_string(),@@ -1490,6 +1648,146 @@ mod tests {(installer, signing_key)}+ #[test]+ fn rejects_source_changed_update_unless_confirmed() {+ let root = tempfile::tempdir().unwrap();+ let (installer, signing_key) = signed_installer(root.path(), [21u8; 32]);+ let signed = |version: &str| package(version, Some((&signing_key, "sample-key")), false);+ let expectation = |repository: &str, version: &str| PluginPackageExpectation {+ id: "sample.hello".to_string(),+ version: version.to_string(),+ repository_id: Some(repository.to_string()),+ publisher: "sample".to_string(),+ permissions: BTreeSet::from(["host.events".to_string()]),+ signing_key_id: "sample-key".to_string(),+ };++ installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("repo-a", "1.0.0"), false).unwrap();++ // The recorded install came from repo-a; a repo-b update needs the explicit confirmation.+ let rejected =+ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("repo-b", "1.1.0"), false).unwrap_err();+ assert!(rejected.contains("source change requires confirmation"), "{rejected}");+ assert_eq!(read_install_identity(root.path(), "sample.hello").unwrap().unwrap().version, "1.0.0");++ let confirmed =+ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("repo-b", "1.1.0"), true).unwrap();+ assert_eq!(+ confirmed.plugin.provenance.as_ref().and_then(|provenance| provenance.repository_id.clone()).as_deref(),+ Some("repo-b")+ );++ // A downgrade below the confirmed active version needs the same explicit confirmation.+ let downgraded =+ installer.install_marketplace_bytes(&signed("1.0.5"), &expectation("repo-b", "1.0.5"), false).unwrap_err();+ assert!(downgraded.contains("downgrade"), "{downgraded}");+ }++ #[test]+ fn rollback_carries_the_target_versions_provenance_forward() {+ let root = tempfile::tempdir().unwrap();+ let (installer, signing_key) = signed_installer(root.path(), [22u8; 32]);+ let signed = |version: &str| package(version, Some((&signing_key, "sample-key")), false);+ let expectation = |repository: &str, version: &str| PluginPackageExpectation {+ id: "sample.hello".to_string(),+ version: version.to_string(),+ repository_id: Some(repository.to_string()),+ publisher: "sample".to_string(),+ permissions: BTreeSet::from(["host.events".to_string()]),+ signing_key_id: "sample-key".to_string(),+ };++ installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("repo-a", "1.0.0"), false).unwrap();+ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("repo-b", "1.1.0"), true).unwrap();+ assert_eq!(installer.rollback("sample.hello").unwrap().previous_version, "1.0.0");++ // After rolling back to the repo-a version, the recorded provenance is repo-a again, so a+ // repo-a update proceeds without confirmation while repo-b still requires one.+ let identity = read_install_identity(root.path(), "sample.hello").unwrap().unwrap();+ assert_eq!(identity.version, "1.0.0");+ assert_eq!(identity.provenance.and_then(|provenance| provenance.repository_id), Some("repo-a".to_string()));+ installer.install_marketplace_bytes(&signed("1.2.0"), &expectation("repo-a", "1.2.0"), false).unwrap();+ let rejected =+ installer.install_marketplace_bytes(&signed("1.3.0"), &expectation("repo-b", "1.3.0"), false).unwrap_err();+ assert!(rejected.contains("source change requires confirmation"), "{rejected}");+ }++ /// Rewrites the newest activation record without its `provenance` field: the on-disk shape an+ /// activation written by a build that predates provenance has.+ fn strip_latest_activation_provenance(container: &Path) {+ let mut records = std::fs::read_dir(container.join(ACTIVATIONS_DIR))+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .filter(|path| is_activation_record_file(path))+ .collect::<Vec<_>>();+ records.sort();+ let path = records.pop().expect("activation record");+ let mut value: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert!(value.as_object_mut().unwrap().remove("provenance").is_some());+ std::fs::write(&path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();+ }++ #[test]+ fn a_pre_provenance_activation_stays_unconstrained_until_the_next_install() {+ let root = tempfile::tempdir().unwrap();+ let (installer, signing_key) = signed_installer(root.path(), [23u8; 32]);+ let signed = |version: &str| package(version, Some((&signing_key, "sample-key")), false);+ let expectation = |repository: &str, version: &str| PluginPackageExpectation {+ id: "sample.hello".to_string(),+ version: version.to_string(),+ repository_id: Some(repository.to_string()),+ publisher: "sample".to_string(),+ permissions: BTreeSet::from(["host.events".to_string()]),+ signing_key_id: "sample-key".to_string(),+ };++ installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("repo-a", "1.0.0"), false).unwrap();+ strip_latest_activation_provenance(&root.path().join("sample.hello"));++ // An activation record without provenance still parses (serde default) and records no source.+ let identity = read_install_identity(root.path(), "sample.hello").unwrap().unwrap();+ assert_eq!(identity.version, "1.0.0");+ assert!(identity.provenance.is_none());++ // Nothing was recorded, so the next install from any repository proceeds without a+ // confirmation and starts recording provenance again.+ let updated =+ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("repo-b", "1.1.0"), false).unwrap();+ assert_eq!(+ updated.plugin.provenance.and_then(|provenance| provenance.repository_id).as_deref(),+ Some("repo-b")+ );+ }++ #[test]+ fn updating_a_plugin_leaves_its_data_directory_untouched() {+ let root = tempfile::tempdir().unwrap();+ // The registry root sits beside plugin-data/, exactly like the app layout, so+ // `PluginRegistry::plugin_data_dir("sample.hello")` resolves to the path below.+ let plugins_root = root.path().join("plugins");+ let (installer, signing_key) = signed_installer(&plugins_root, [24u8; 32]);+ let signed = |version: &str| package(version, Some((&signing_key, "sample-key")), false);+ let expectation = |repository: &str, version: &str| PluginPackageExpectation {+ id: "sample.hello".to_string(),+ version: version.to_string(),+ repository_id: Some(repository.to_string()),+ publisher: "sample".to_string(),+ permissions: BTreeSet::from(["host.events".to_string()]),+ signing_key_id: "sample-key".to_string(),+ };++ installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("repo-a", "1.0.0"), false).unwrap();+ let data_dir = root.path().join("plugin-data").join("sample.hello");+ std::fs::create_dir_all(&data_dir).unwrap();+ std::fs::write(data_dir.join("state.json"), b"{\"rows\":1}").unwrap();++ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("repo-a", "1.1.0"), false).unwrap();+ installer.rollback("sample.hello").unwrap();++ // Plugin user data lives outside the versioned container and must survive update + rollback.+ assert_eq!(std::fs::read(data_dir.join("state.json")).unwrap(), b"{\"rows\":1}");+ }+fn activation_record_count(container: &Path) -> usize {std::fs::read_dir(container.join(ACTIVATIONS_DIR)).unwrap()@@ -1512,6 +1810,7 @@ mod tests {let (installer, signing_key) = signed_installer(root.path(), [13u8; 32]);let signed = |version: &str| package(version, Some((&signing_key, "sample-key")), false);let expectation = |version: &str| PluginPackageExpectation {+ repository_id: None,id: "sample.hello".to_string(),version: version.to_string(),publisher: "sample".to_string(),@@ -1519,13 +1818,13 @@ mod tests {signing_key_id: "sample-key".to_string(),};- installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("1.0.0")).unwrap();- installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("1.1.0")).unwrap();+ installer.install_marketplace_bytes(&signed("1.0.0"), &expectation("1.0.0"), false).unwrap();+ installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("1.1.0"), false).unwrap();assert_eq!(installer.rollback("sample.hello").unwrap().previous_version, "1.0.0");// 1.1.0 is installed but inactive after the rollback: reinstalling it has to replace the// retained directory instead of failing with "already installed".- let reinstalled = installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("1.1.0")).unwrap();+ let reinstalled = installer.install_marketplace_bytes(&signed("1.1.0"), &expectation("1.1.0"), false).unwrap();assert_eq!(reinstalled.previous_version.as_deref(), Some("1.0.0"));let container = root.path().join("sample.hello");diff --git a/crates/dbx-plugin-runtime/src/plugins/marketplace.rs b/crates/dbx-plugin-runtime/src/plugins/marketplace.rsindex 47352df59c..60d497f19c 100644--- a/crates/dbx-plugin-runtime/src/plugins/marketplace.rs+++ b/crates/dbx-plugin-runtime/src/plugins/marketplace.rs@@ -12,7 +12,7 @@ use semver::Version;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};-use super::installer::{validate_key_id, PluginPackageExpectation};+use super::installer::{ensure_update_continuity, validate_key_id, PluginPackageExpectation};use super::manifest::{parse_host_network_permission, MAX_PLUGIN_NETWORK_ORIGINS};use super::{current_plugin_target, PluginInstallPolicy, PluginInstallResult, PluginPackageInstaller, PluginTrustStore,@@ -155,6 +155,10 @@ pub struct PluginMarketplaceInstallRequest {pub plugin_id: String,#[serde(default, skip_serializing_if = "Option::is_none")]pub version: Option<String>,+ /// Set after the user explicitly confirmed a changed update source (repository / publisher /+ /// signing key) or an intentional downgrade; the install is rejected without it.+ #[serde(default)]+ pub allow_source_change: bool,}#[derive(Debug, Default, Serialize, Deserialize)]@@ -408,6 +412,22 @@ impl PluginMarketplace {let artifact = select_marketplace_artifact(version, &target).ok_or_else(|| {format!("Plugin '{}' version '{}' does not support target '{}'", plugin.id, version.version, target)})?;+ // Read-only provenance pre-flight: reject a source-changed or downgraded update before any+ // download or runtime teardown happens. install_bytes_locked re-checks under the lock.+ let allow_source_change = request.allow_source_change;+ if let Some(identity) = super::installer::read_install_identity(&self.root_dir, &request.plugin_id)? {+ if let Some(provenance) = &identity.provenance {+ ensure_update_continuity(+ provenance,+ &identity.version,+ Some(&repository.id),+ &plugin.publisher,+ &artifact.signing_key_id,+ requested_version,+ allow_source_change,+ )?;+ }+ }let artifact_url =Url::parse(&artifact.url).map_err(|error| format!("Invalid plugin artifact URL: {error}"))?;let package = self.download_limited(artifact_url, MAX_PLUGIN_PACKAGE_BYTES, "Plugin package").await?;@@ -416,6 +436,7 @@ impl PluginMarketplace {let expectation = PluginPackageExpectation {id: plugin.id.clone(),version: version.version.clone(),+ repository_id: Some(repository.id.clone()),publisher: plugin.publisher.clone(),permissions: plugin.permissions.iter().cloned().collect(),signing_key_id: artifact.signing_key_id.clone(),@@ -425,7 +446,7 @@ impl PluginMarketplace {self.app_version.clone(),trust_store,))- .install_marketplace_bytes(&package, &expectation)+ .install_marketplace_bytes(&package, &expectation, allow_source_change)}/// Downloads a .dbxp package from a direct http(s) URL and installs it with@@ -467,7 +488,7 @@ impl PluginMarketplace {on_progress(bytes.len() as u64, total);}self.guard_installer(PluginPackageInstaller::new(self.root_dir.clone(), self.app_version.clone())?)- .install_bytes(&bytes, policy)+ .install_bytes_with_expectation(&bytes, policy, None, super::installer::PluginInstallSource::Url, false)}async fn download_limited(&self, url: Url, max_bytes: usize, label: &str) -> Result<Vec<u8>, String> {@@ -1166,6 +1187,7 @@ mod tests {repository_id: repository.id,plugin_id: "marketplace.install".to_string(),version: None,+ allow_source_change: false,}).await.unwrap();@@ -1336,6 +1358,7 @@ mod tests {repository_id: "not-configured".to_string(),plugin_id: "marketplace.install".to_string(),version: None,+ allow_source_change: false,}).await.unwrap_err();