Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): install from URL + remote catalog (marketplace MVP) (#433)
Yudhi Armyndharis1fab80591efe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9297b9245..52ddb5128 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Install plugins from a URL / catalog.** `POST /plugins/install-url` downloads a plugin `.zip` from an HTTP(S) URL through the SSRF guard (host validated, connection pinned, redirects refused, size-capped) and runs the exact same validate-write-load pipeline as an uploaded package. `GET /plugins/catalog` fetches a configured remote catalog (`PLUGIN_CATALOG_URL`, default the OpenWA-plugins `plugins.json`) and annotates each entry with `installed` / `installedVersion` / `updateAvailable`. The dashboard install modal gains a **Catalog** tab to browse and one-click install. Add a non-public catalog/release host to `SSRF_ALLOWED_HOSTS`. (#433)+- **Update a plugin in place.** `POST /plugins/:id/update` downloads the new package (same SSRF-guarded path) and swaps it in while **preserving operator config and the enabled state** — it unloads the running plugin (keeping its registry entry, so config survives), writes the new files, reloads, and re-enables if it was enabled. The package id must match; the old version is backed up and restored if the update fails. The dashboard Catalog tab shows an **Update** button when a newer version is available. (#433)- Mark a chat as unread: `POST /sessions/:id/chats/unread` (and `sessionApi.markChatUnread` on the dashboard client), the inverse of mark-as-read, supported on both the whatsapp-web.js and Baileys engines. (#432)### Securitydiff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex 42c7b822e..a053a3fb6 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -817,3 +817,107 @@position: static;}}++/* ── Install modal: Upload / Catalog tabs + catalog list ─────────────────── */+.install-tabs {+ display: flex;+ gap: 4px;+ padding: 0 20px;+ border-bottom: 1px solid var(--border, #e5e7eb);+}++.install-tab {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 10px 14px;+ background: none;+ border: none;+ border-bottom: 2px solid transparent;+ color: var(--text-secondary, #6b7280);+ font-size: 0.875rem;+ cursor: pointer;+}++.install-tab.active {+ color: var(--text, #111827);+ border-bottom-color: var(--primary, #25d366);+}++.catalog-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ padding: 28px 12px;+ color: var(--text-secondary, #6b7280);+ font-size: 0.875rem;+}++.catalog-error {+ flex-wrap: wrap;+ color: var(--danger, #dc2626);+}++.catalog-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ max-height: 420px;+ overflow-y: auto;+}++.catalog-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 12px;+ border: 1px solid var(--border, #e5e7eb);+ border-radius: 8px;+}++.catalog-row-info {+ min-width: 0;+}++.catalog-row-name {+ font-weight: 600;+}++.catalog-row-version {+ color: var(--text-secondary, #6b7280);+ font-weight: 400;+ font-size: 0.85em;+}++.catalog-row-desc {+ color: var(--text-secondary, #6b7280);+ font-size: 0.85rem;+ margin-top: 2px;+}++.catalog-row-meta {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 4px;+ font-size: 0.8rem;+ color: var(--text-secondary, #6b7280);+}++.catalog-badge.update {+ color: var(--primary, #25d366);+}++.catalog-row-action {+ flex-shrink: 0;+}++.catalog-installed {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--text-secondary, #6b7280);+ font-size: 0.85rem;+}diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex ad137875a..a2a7976ad 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useState, useEffect } from 'react';import { useTranslation } from 'react-i18next';import { useQueryClient } from '@tanstack/react-query';import {@@ -18,9 +18,11 @@ import {X,Upload,Trash2,+ Globe,+ Download,} from 'lucide-react';import { pluginsApi, infraApi } from '../services/api';-import type { Plugin } from '../services/api';+import type { Plugin, CatalogPlugin } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';import {usePluginsQuery,@@ -78,6 +80,11 @@ export default function Plugins() {const [showInstallModal, setShowInstallModal] = useState(false);const [installFile, setInstallFile] = useState<File | null>(null);const [installing, setInstalling] = useState(false);+ const [installMode, setInstallMode] = useState<'upload' | 'catalog'>('upload');+ const [catalog, setCatalog] = useState<CatalogPlugin[]>([]);+ const [catalogLoading, setCatalogLoading] = useState(false);+ const [catalogError, setCatalogError] = useState<string | null>(null);+ const [installingId, setInstallingId] = useState<string | null>(null);const refetchAll = () => {void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });@@ -190,6 +197,68 @@ export default function Plugins() {}};+ const loadCatalog = async () => {+ setCatalogLoading(true);+ setCatalogError(null);+ try {+ setCatalog(await pluginsApi.catalog());+ } catch (err) {+ setCatalogError(err instanceof Error ? err.message : String(err));+ } finally {+ setCatalogLoading(false);+ }+ };++ // Lazy-load the catalog the first time the Catalog tab is opened.+ useEffect(() => {+ if (showInstallModal && installMode === 'catalog' && catalog.length === 0 && !catalogLoading && !catalogError) {+ void loadCatalog();+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [showInstallModal, installMode]);++ const handleInstallFromCatalog = async (entry: CatalogPlugin) => {+ if (!entry.download) {+ toast.error(+ t('plugins.toasts.installFailed', 'Install failed'),+ t('plugins.catalog.noDownload', 'This catalog entry has no download URL.'),+ );+ return;+ }+ setInstallingId(entry.id);+ try {+ const installed = await pluginsApi.installFromUrl(entry.download);+ refetchAll();+ await loadCatalog();+ toast.success(t('plugins.toasts.installed', 'Plugin installed'), installed.name);+ } catch (err) {+ toast.error(t('plugins.toasts.installFailed', 'Install failed'), err instanceof Error ? err.message : '');+ } finally {+ setInstallingId(null);+ }+ };++ const handleUpdateFromCatalog = async (entry: CatalogPlugin) => {+ if (!entry.download) {+ toast.error(+ t('plugins.toasts.updateFailed', 'Update failed'),+ t('plugins.catalog.noDownload', 'This catalog entry has no download URL.'),+ );+ return;+ }+ setInstallingId(entry.id);+ try {+ const updated = await pluginsApi.updateFromUrl(entry.id, entry.download);+ refetchAll();+ await loadCatalog();+ toast.success(t('plugins.catalog.updated', 'Plugin updated'), `${updated.name} v${updated.version}`);+ } catch (err) {+ toast.error(t('plugins.toasts.updateFailed', 'Update failed'), err instanceof Error ? err.message : '');+ } finally {+ setInstallingId(null);+ }+ };+const handleUninstall = async (plugin: Plugin) => {if (!window.confirm(t('plugins.uninstallConfirm', { name: plugin.name }))) return;setActionLoading(plugin.id);@@ -448,32 +517,134 @@ export default function Plugins() {<X size={20} /></button></div>- <div className="modal-body">- <p className="install-hint">- {t('plugins.installModal.hint', 'Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.')}- </p>- <label className={`install-drop${installFile ? ' has-file' : ''}`}>- <input- type="file"- accept=".zip,application/zip"- hidden- onChange={e => setInstallFile(e.target.files?.[0] ?? null)}- />- <Upload size={28} />- <span className="install-drop-name">- {installFile ? installFile.name : t('plugins.installModal.choose', 'Choose a .zip file…')}- </span>- </label>- </div>- <div className="modal-footer">- <button className="btn-secondary" onClick={() => setShowInstallModal(false)} disabled={installing}>- {t('common.cancel', 'Cancel')}+ <div className="install-tabs">+ <button+ className={`install-tab${installMode === 'upload' ? ' active' : ''}`}+ onClick={() => setInstallMode('upload')}+ >+ <Upload size={15} /> {t('plugins.installModal.tabUpload', 'Upload .zip')}</button>- <button className="btn-primary" onClick={() => void handleInstall()} disabled={!installFile || installing}>- {installing ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}- {t('plugins.install', 'Install plugin')}+ <button+ className={`install-tab${installMode === 'catalog' ? ' active' : ''}`}+ onClick={() => setInstallMode('catalog')}+ >+ <Globe size={15} /> {t('plugins.installModal.tabCatalog', 'Catalog')}</button></div>++ {installMode === 'upload' ? (+ <>+ <div className="modal-body">+ <p className="install-hint">+ {t('plugins.installModal.hint', 'Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.')}+ </p>+ <label className={`install-drop${installFile ? ' has-file' : ''}`}>+ <input+ type="file"+ accept=".zip,application/zip"+ hidden+ onChange={e => setInstallFile(e.target.files?.[0] ?? null)}+ />+ <Upload size={28} />+ <span className="install-drop-name">+ {installFile ? installFile.name : t('plugins.installModal.choose', 'Choose a .zip file…')}+ </span>+ </label>+ </div>+ <div className="modal-footer">+ <button className="btn-secondary" onClick={() => setShowInstallModal(false)} disabled={installing}>+ {t('common.cancel', 'Cancel')}+ </button>+ <button className="btn-primary" onClick={() => void handleInstall()} disabled={!installFile || installing}>+ {installing ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}+ {t('plugins.install', 'Install plugin')}+ </button>+ </div>+ </>+ ) : (+ <>+ <div className="modal-body">+ <p className="install-hint">+ {t('plugins.installModal.catalogHint', 'Install directly from the OpenWA plugin catalog. The .zip is fetched server-side through the SSRF guard, then validated and sandboxed.')}+ </p>+ {catalogLoading ? (+ <div className="catalog-empty">+ <Loader2 size={20} className="animate-spin" />+ </div>+ ) : catalogError ? (+ <div className="catalog-empty catalog-error">+ <AlertCircle size={16} /> {catalogError}+ <button className="btn-secondary" onClick={() => void loadCatalog()}>+ {t('plugins.refresh', 'Refresh')}+ </button>+ </div>+ ) : catalog.length === 0 ? (+ <div className="catalog-empty">{t('plugins.catalog.empty', 'No plugins in the catalog.')}</div>+ ) : (+ <div className="catalog-list">+ {catalog.map(entry => (+ <div className="catalog-row" key={entry.id}>+ <div className="catalog-row-info">+ <div className="catalog-row-name">+ {entry.name} <span className="catalog-row-version">v{entry.version}</span>+ </div>+ {entry.description && <div className="catalog-row-desc">{entry.description}</div>}+ <div className="catalog-row-meta">+ {entry.author && <span className="catalog-row-author">{entry.author}</span>}+ {entry.updateAvailable && (+ <span className="catalog-badge update">+ {t('plugins.catalog.updateAvailable', 'Update available')} (v{entry.installedVersion} → v{entry.version})+ </span>+ )}+ </div>+ </div>+ <div className="catalog-row-action">+ {entry.installed ? (+ entry.updateAvailable ? (+ <button+ className="btn-primary"+ disabled={installingId !== null || !entry.download}+ onClick={() => void handleUpdateFromCatalog(entry)}+ >+ {installingId === entry.id ? (+ <Loader2 size={15} className="animate-spin" />+ ) : (+ <Download size={15} />+ )}+ {t('plugins.catalog.update', 'Update')}+ </button>+ ) : (+ <span className="catalog-installed">+ <CheckCircle size={15} /> {t('plugins.catalog.installed', 'Installed')}+ </span>+ )+ ) : (+ <button+ className="btn-primary"+ disabled={installingId !== null || !entry.download}+ onClick={() => void handleInstallFromCatalog(entry)}+ >+ {installingId === entry.id ? (+ <Loader2 size={15} className="animate-spin" />+ ) : (+ <Download size={15} />+ )}+ {t('plugins.catalog.install', 'Install')}+ </button>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ <div className="modal-footer">+ <button className="btn-secondary" onClick={() => setShowInstallModal(false)}>+ {t('common.close', 'Close')}+ </button>+ </div>+ </>+ )}</div></div>)}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex ca1d86be0..8eb485b05 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -625,6 +625,26 @@ export interface Engine {library?: { name: string; version: string };}+/** A remote catalog entry annotated with this instance's install state. */+export interface CatalogPlugin {+ id: string;+ name: string;+ version: string;+ type?: string;+ status?: string;+ description?: string;+ author?: string;+ license?: string;+ keywords?: string[];+ minOpenWAVersion?: string;+ testedOpenWAVersion?: string;+ homepage?: string;+ download?: string;+ installed: boolean;+ installedVersion: string | null;+ updateAvailable: boolean;+}+// =============================================================================// Plugins API// =============================================================================@@ -651,6 +671,11 @@ export const pluginsApi = {form.append('file', file);return request<Plugin>('/plugins/install', { method: 'POST', body: form });},+ installFromUrl: (url: string) =>+ request<Plugin>('/plugins/install-url', { method: 'POST', body: JSON.stringify({ url }) }),+ updateFromUrl: (id: string, url: string) =>+ request<Plugin>(`/plugins/${id}/update`, { method: 'POST', body: JSON.stringify({ url }) }),+ catalog: () => request<CatalogPlugin[]>('/plugins/catalog'),uninstall: (id: string) => request<{ success: boolean; message: string }>(`/plugins/${id}`, { method: 'DELETE' }),getEngines: () => request<Engine[]>('/infra/engines'),getCurrentEngine: () => request<{ engineType: string }>('/infra/engines/current'),diff --git a/node_modules b/node_modulesnew file mode 120000index 000000000..02d9ad64b--- /dev/null+++ b/node_modules@@ -0,0 +1 @@+../../node_modules\ No newline at end of filediff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex d5f0719bd..b8d595506 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -61,3 +61,23 @@ describe('configuration — Puppeteer args delimiter', () => {expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--disable-setuid-sandbox']);});});++describe('configuration — plugin download cap is fail-safe', () => {+ const orig = process.env.PLUGIN_DOWNLOAD_MAX_BYTES;+ afterEach(() => {+ if (orig === undefined) delete process.env.PLUGIN_DOWNLOAD_MAX_BYTES;+ else process.env.PLUGIN_DOWNLOAD_MAX_BYTES = orig;+ });++ it('uses the env value when it is a valid positive integer', () => {+ process.env.PLUGIN_DOWNLOAD_MAX_BYTES = '1048576';+ expect(configuration().plugins.downloadMaxBytes).toBe(1048576);+ });++ it('falls back to the 5 MB default when the env value is non-numeric or non-positive', () => {+ for (const bad of ['abc', 'unlimited', '0', '-1']) {+ process.env.PLUGIN_DOWNLOAD_MAX_BYTES = bad;+ expect(configuration().plugins.downloadMaxBytes).toBe(5 * 1024 * 1024);+ }+ });+});diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 73d7f6f6b..b5d31f4a0 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -113,6 +113,23 @@ export default () => ({.filter(Boolean),},+ // Plugin platform configuration+ plugins: {+ // Where installed plugins live on disk (matches the plugin loader's default).+ dir: process.env.PLUGINS_DIR || './plugins',+ // Remote catalog of installable plugins (JSON array; the OpenWA-plugins repo's plugins.json).+ // Fetched through the SSRF guard — add its host to SSRF_ALLOWED_HOSTS if it is not publicly resolvable.+ catalogUrl:+ process.env.PLUGIN_CATALOG_URL || 'https://raw.githubusercontent.com/rmyndharis/OpenWA-plugins/main/plugins.json',+ // Cap on a plugin .zip downloaded by install-from-URL (matches the 5 MB upload limit). Fail-safe:+ // a non-numeric or non-positive value (parseInt → NaN/0/-n) falls back to the default rather than+ // silently disabling the cap (a downstream `??` would not catch NaN).+ downloadMaxBytes: (() => {+ const n = parseInt(process.env.PLUGIN_DOWNLOAD_MAX_BYTES ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 5 * 1024 * 1024;+ })(),+ },+// Storage configurationstorage: {type: process.env.STORAGE_TYPE || 'local',diff --git a/src/modules/plugins/catalog.spec.ts b/src/modules/plugins/catalog.spec.tsnew file mode 100644index 000000000..f223e2192--- /dev/null+++ b/src/modules/plugins/catalog.spec.ts@@ -0,0 +1,49 @@+import { compareSemver, annotateCatalog, CatalogEntry } from './catalog';++describe('compareSemver', () => {+ it('orders by major, minor, then patch', () => {+ expect(compareSemver('1.0.0', '1.0.0')).toBe(0);+ expect(compareSemver('1.2.0', '1.1.9')).toBe(1);+ expect(compareSemver('0.9.9', '1.0.0')).toBe(-1);+ expect(compareSemver('2.0.0', '1.9.9')).toBe(1);+ });++ it('ignores a pre-release suffix and missing segments', () => {+ expect(compareSemver('1.2.0-beta.1', '1.2.0')).toBe(0);+ expect(compareSemver('1.2', '1.2.0')).toBe(0);+ expect(compareSemver('garbage', '0.0.0')).toBe(0);+ });+});++describe('annotateCatalog', () => {+ const entries: CatalogEntry[] = [+ { id: 'gsheets-logger', name: 'GSheets', version: '0.3.0' },+ { id: 'faq-bot', name: 'FAQ', version: '1.0.0' },+ ];++ it('flags an installed plugin with a newer catalog version as updateAvailable', () => {+ const out = annotateCatalog(entries, [{ id: 'gsheets-logger', version: '0.2.0' }]);+ const gs = out.find(e => e.id === 'gsheets-logger')!;+ expect(gs.installed).toBe(true);+ expect(gs.installedVersion).toBe('0.2.0');+ expect(gs.updateAvailable).toBe(true);+ });++ it('does not flag updateAvailable when installed == catalog version', () => {+ const out = annotateCatalog(entries, [{ id: 'gsheets-logger', version: '0.3.0' }]);+ expect(out.find(e => e.id === 'gsheets-logger')!.updateAvailable).toBe(false);+ });++ it('marks a not-installed entry installed:false with no update', () => {+ const out = annotateCatalog(entries, [{ id: 'gsheets-logger', version: '0.3.0' }]);+ const faq = out.find(e => e.id === 'faq-bot')!;+ expect(faq.installed).toBe(false);+ expect(faq.installedVersion).toBeNull();+ expect(faq.updateAvailable).toBe(false);+ });++ it('does not flag a downgrade (installed newer than catalog) as updateAvailable', () => {+ const out = annotateCatalog(entries, [{ id: 'faq-bot', version: '2.0.0' }]);+ expect(out.find(e => e.id === 'faq-bot')!.updateAvailable).toBe(false);+ });+});diff --git a/src/modules/plugins/catalog.ts b/src/modules/plugins/catalog.tsnew file mode 100644index 000000000..945bff9e4--- /dev/null+++ b/src/modules/plugins/catalog.ts@@ -0,0 +1,65 @@+// Remote plugin catalog: the shape of an entry in the OpenWA-plugins `plugins.json`, and the pure+// logic that annotates each entry with install state relative to what is currently loaded.++/** One entry as published in the remote catalog (plugins.json). Extra fields are tolerated. */+export interface CatalogEntry {+ id: string;+ name: string;+ version: string;+ type?: string;+ status?: string;+ description?: string;+ author?: string;+ license?: string;+ keywords?: string[];+ minOpenWAVersion?: string;+ testedOpenWAVersion?: string;+ releasedAt?: string;+ repoUrl?: string;+ homepage?: string;+ download?: string;+ [key: string]: unknown;+}++/** A catalog entry annotated with this instance's install state. */+export interface CatalogPlugin extends CatalogEntry {+ installed: boolean;+ installedVersion: string | null;+ updateAvailable: boolean;+}++/** Compare two `MAJOR.MINOR.PATCH` strings (pre-release suffixes ignored). Returns -1 | 0 | 1. */+export function compareSemver(a: string, b: string): number {+ const parse = (v: string) =>+ String(v)+ .split('-')[0]+ .split('.')+ .map(n => Number.parseInt(n, 10) || 0);+ const pa = parse(a);+ const pb = parse(b);+ for (let i = 0; i < 3; i++) {+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);+ if (d !== 0) return d > 0 ? 1 : -1;+ }+ return 0;+}++/**+ * Annotate catalog entries with install state, given the plugins currently loaded by this instance.+ * `updateAvailable` is true when an entry is installed and the catalog version is strictly newer.+ */+export function annotateCatalog(+ entries: CatalogEntry[],+ installed: { id: string; version: string }[],+): CatalogPlugin[] {+ const byId = new Map(installed.map(p => [p.id, p.version]));+ return entries.map(entry => {+ const installedVersion = byId.get(entry.id) ?? null;+ return {+ ...entry,+ installed: installedVersion !== null,+ installedVersion,+ updateAvailable: installedVersion !== null && compareSemver(entry.version, installedVersion) > 0,+ };+ });+}diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.tsindex 4ea813642..4cc819da4 100644--- a/src/modules/plugins/dto/plugin.dto.ts+++ b/src/modules/plugins/dto/plugin.dto.ts@@ -1,5 +1,5 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsObject } from 'class-validator';+import { IsObject, IsString, IsUrl } from 'class-validator';import type { PluginConfigSchema } from '../../../core/plugins';import { PluginType, PluginStatus } from '../../../core/plugins';@@ -52,3 +52,10 @@ export class PluginConfigDto {@IsObject()config!: Record<string, unknown>;}++export class InstallFromUrlDto {+ @ApiProperty({ description: 'HTTP(S) URL of the plugin .zip to download and install' })+ @IsString()+ @IsUrl({ protocols: ['http', 'https'], require_protocol: true })+ url!: string;+}diff --git a/src/modules/plugins/plugin-download.ts b/src/modules/plugins/plugin-download.tsnew file mode 100644index 000000000..a3abdf65d--- /dev/null+++ b/src/modules/plugins/plugin-download.ts@@ -0,0 +1,57 @@+import { withSafeFetch } from '../../common/security/ssrf-guard';++/** Default cap on a server-side plugin download: 5 MiB (matches the upload limit). */+const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;+/** Default timeout for a server-side plugin download: 30s. */+const DEFAULT_TIMEOUT_MS = 30_000;++/**+ * Fetch a remote resource (plugin .zip or catalog JSON) as a Buffer, always behind the SSRF guard:+ * the host is validated before any socket opens, the connection is pinned to the vetted IP, and+ * redirects are refused. The byte cap is enforced while streaming (Content-Length may be absent or+ * wrong) so a hostile or oversized response can't exhaust memory.+ *+ * Operators must add a non-public catalog/release host to `SSRF_ALLOWED_HOSTS`; public hosts+ * (github.com, raw.githubusercontent.com) resolve and pass the guard normally.+ */+export async function fetchSafeBuffer(+ url: string,+ opts: { maxBytes?: number; timeoutMs?: number } = {},+): Promise<Buffer> {+ // Coerce a missing/non-finite/non-positive cap to the default: `??` alone would let a NaN through+ // (e.g. a misparsed env value), which makes every `> maxBytes` guard below inert.+ const maxBytes =+ Number.isFinite(opts.maxBytes) && (opts.maxBytes as number) > 0 ? (opts.maxBytes as number) : DEFAULT_MAX_BYTES;+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;++ return withSafeFetch(url, { signal: AbortSignal.timeout(timeoutMs) }, async response => {+ if (!response.ok) {+ throw new Error(`download failed with status ${response.status}`);+ }++ const declaredLength = Number(response.headers.get('content-length') ?? '');+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ throw new Error(`download exceeds the ${maxBytes}-byte limit`);+ }++ const reader = response.body?.getReader();+ if (!reader) {+ throw new Error('download response has no body');+ }++ const chunks: Buffer[] = [];+ let total = 0;+ for (;;) {+ const { done, value } = (await reader.read()) as { done: boolean; value: Uint8Array };+ if (done) break;+ total += value.byteLength;+ if (total > maxBytes) {+ await reader.cancel();+ throw new Error(`download exceeds the ${maxBytes}-byte limit`);+ }+ chunks.push(Buffer.from(value));+ }++ return Buffer.concat(chunks);+ });+}diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex b1d48b8ba..009208cf3 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -14,7 +14,8 @@ import {import { FileInterceptor } from '@nestjs/platform-express';import { ApiTags, ApiOperation, ApiResponse, ApiConsumes } from '@nestjs/swagger';import { PluginsService } from './plugins.service';-import { PluginDto, PluginConfigDto } from './dto/plugin.dto';+import { PluginDto, PluginConfigDto, InstallFromUrlDto } from './dto/plugin.dto';+import type { CatalogPlugin } from './catalog';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -46,6 +47,26 @@ export class PluginsController {return this.pluginsService.install(file);}+ @Post('install-url')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Install a plugin by downloading its .zip from a URL (SSRF-guarded)' })+ @ApiResponse({ status: 201, description: 'Plugin installed' })+ @ApiResponse({ status: 400, description: 'Invalid URL, download failed, or invalid package' })+ @ApiResponse({ status: 409, description: 'Plugin already installed' })+ async installFromUrl(@Body() dto: InstallFromUrlDto): Promise<PluginDto> {+ return await this.pluginsService.installFromUrl(dto.url);+ }++ // Declared before `:id` so `GET /plugins/catalog` is not captured by the `:id` route.+ @Get('catalog')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'List the remote plugin catalog, annotated with install state' })+ @ApiResponse({ status: 200, description: 'Catalog entries' })+ @ApiResponse({ status: 400, description: 'Catalog could not be fetched or parsed' })+ async catalog(): Promise<CatalogPlugin[]> {+ return await this.pluginsService.getCatalog();+ }+@Get(':id')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get plugin by ID' })@@ -81,6 +102,16 @@ export class PluginsController {return this.pluginsService.updateConfig(id, configDto.config);}+ @Post(':id/update')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Update an installed plugin in place from a URL (preserves config + enabled state)' })+ @ApiResponse({ status: 201, description: 'Plugin updated' })+ @ApiResponse({ status: 400, description: 'Invalid URL/package, id mismatch, or built-in' })+ @ApiResponse({ status: 404, description: 'Plugin not found' })+ async update(@Param('id') id: string, @Body() dto: InstallFromUrlDto): Promise<PluginDto> {+ return await this.pluginsService.updateFromUrl(id, dto.url);+ }+@Delete(':id')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Uninstall a plugin (removes its files; built-ins are protected)' })diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex 7c3ca6191..19d77383f 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -7,6 +7,7 @@ import { ModuleRef } from '@nestjs/core';import { PluginsService } from './plugins.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { PluginStorageService } from '../../core/plugins/plugin-storage.service';+import { PluginStatus } from '../../core/plugins/plugin.interfaces';import { HookManager } from '../../core/hooks';const manifest = { id: 'svc-plg', name: 'Svc Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };@@ -37,7 +38,7 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {new PluginStorageService(config),{} as unknown as ModuleRef,);- service = new PluginsService(loader);+ service = new PluginsService(loader, config);});afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));@@ -79,4 +80,44 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {it('uninstalling an unknown plugin throws NotFound', async () => {await expect(service.uninstall('nope')).rejects.toThrow(/not found/i);});++ it('updatePackage swaps to the new version and preserves operator config', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });+ service.updateConfig('svc-plg', { apiKey: 'secret-123' });++ const dto = await service.updatePackage('svc-plg', pkg({ version: '2.0.0' }));++ expect(dto.version).toBe('2.0.0');+ expect(dto.config).toEqual({ apiKey: 'secret-123' }); // config survived the in-place update+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'index.js'))).toBe(true);+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg.bak'))).toBe(false); // backup cleaned up+ });++ it('updatePackage rejects a package whose id does not match', async () => {+ service.install({ buffer: pkg() });+ await expect(service.updatePackage('svc-plg', pkg({ id: 'other-plg' }))).rejects.toThrow(/does not match/i);+ });++ it('updatePackage on an unknown plugin throws NotFound', async () => {+ await expect(service.updatePackage('nope', pkg())).rejects.toThrow(/not found/i);+ });++ it('rolls back to the OLD version (loaded, on disk) when the new version fails to enable', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });+ // Pretend it was enabled so the update tries to re-enable — and that re-enable fails for the new version.+ loader.getPlugin('svc-plg')!.status = PluginStatus.ENABLED;+ const enableSpy = jest.spyOn(loader, 'enablePlugin').mockRejectedValue(new Error('worker failed to enable'));++ await expect(service.updatePackage('svc-plg', pkg({ version: '2.0.0' }))).rejects.toThrow(/Failed to update/i);++ // The rollback must leave the OLD version loaded — not the new, half-enabled (ERROR) instance.+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg.bak'))).toBe(false);+ const onDisk = JSON.parse(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'), 'utf8')) as {+ version: string;+ };+ expect(onDisk.version).toBe('1.0.0');++ enableSpy.mockRestore();+ });});diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 88aae1dd4..90bcce97b 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -1,14 +1,23 @@import { Injectable, NotFoundException, BadRequestException, ConflictException, HttpException } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';import { PluginLoaderService, PluginStatus } from '../../core/plugins';import { PluginDto } from './dto/plugin.dto';import { redactSecretConfig, restoreSecretConfig } from './redact-config';import { parsePluginPackage } from './plugin-installer';+import { fetchSafeBuffer } from './plugin-download';+import { annotateCatalog, CatalogEntry, CatalogPlugin } from './catalog';++/** Cap on the catalog JSON download (the catalog is small; this bounds a hostile response). */+const CATALOG_MAX_BYTES = 1 * 1024 * 1024;@Injectable()export class PluginsService {- constructor(private readonly pluginLoader: PluginLoaderService) {}+ constructor(+ private readonly pluginLoader: PluginLoaderService,+ private readonly configService: ConfigService,+ ) {}findAll(): PluginDto[] {const plugins = this.pluginLoader.getAllPlugins();@@ -157,6 +166,138 @@ export class PluginsService {return this.findOne(manifest.id);}+ /**+ * Install a plugin from an HTTP(S) URL: download the .zip through the SSRF guard (host validated,+ * connection pinned, redirects refused, size-capped), then run the exact same validate-write-load+ * pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an upload.+ */+ async installFromUrl(url: string): Promise<PluginDto> {+ const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;+ let buffer: Buffer;+ try {+ buffer = await fetchSafeBuffer(url, { maxBytes });+ } catch (error) {+ throw new BadRequestException(+ `Failed to download plugin from URL: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ return this.install({ buffer });+ }++ /**+ * Fetch the configured remote catalog (a plugins.json array) through the SSRF guard and annotate each+ * entry with this instance's install state (installed / installedVersion / updateAvailable).+ */+ async getCatalog(): Promise<CatalogPlugin[]> {+ const url = this.configService.get<string>('plugins.catalogUrl');+ if (!url) return [];++ let raw: Buffer;+ try {+ raw = await fetchSafeBuffer(url, { maxBytes: CATALOG_MAX_BYTES });+ } catch (error) {+ throw new BadRequestException(+ `Failed to fetch plugin catalog: ${error instanceof Error ? error.message : String(error)}`,+ );+ }++ let entries: CatalogEntry[];+ try {+ const parsed: unknown = JSON.parse(raw.toString('utf8'));+ if (!Array.isArray(parsed)) throw new Error('catalog is not a JSON array');+ entries = parsed as CatalogEntry[];+ } catch (error) {+ throw new BadRequestException(+ `Invalid plugin catalog JSON: ${error instanceof Error ? error.message : String(error)}`,+ );+ }++ const installed = this.pluginLoader.getAllPlugins().map(p => ({ id: p.manifest.id, version: p.manifest.version }));+ return annotateCatalog(entries, installed);+ }++ /**+ * Update an installed plugin in place from a validated package buffer, preserving operator config and+ * the enabled state. The package id must match the installed id. Config survives because `unloadPlugin`+ * drops the plugin from memory but keeps its registry entry (config); `loadPlugin` re-reads it. The old+ * directory is backed up and restored if the swap or reload of the new version fails, so a bad update+ * never leaves the plugin broken.+ */+ async updatePackage(id: string, buffer: Buffer): Promise<PluginDto> {+ const plugin = this.pluginLoader.getPlugin(id);+ if (!plugin) {+ throw new NotFoundException(`Plugin ${id} not found`);+ }+ if (this.pluginLoader.isBuiltIn(id)) {+ throw new BadRequestException(`Cannot update built-in plugin ${id}`);+ }++ // Validate the new package BEFORE touching the running plugin. An update must be the same plugin.+ const { manifest, entries } = parsePluginPackage(buffer);+ if (manifest.id !== id) {+ throw new BadRequestException(`Package id "${manifest.id}" does not match the plugin being updated ("${id}")`);+ }++ const wasEnabled = plugin.status === PluginStatus.ENABLED;+ const dir = path.join(this.pluginLoader.getPluginsDir(), id);+ const backup = `${dir}.bak`;++ // Stop the running plugin (terminates its sandbox worker) but keep its registry entry so config survives.+ await this.pluginLoader.unloadPlugin(id);++ fs.rmSync(backup, { recursive: true, force: true });+ fs.renameSync(dir, backup);++ try {+ for (const entry of entries) {+ const dest = path.join(dir, entry.relPath);+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.writeFileSync(dest, entry.data);+ }+ this.pluginLoader.loadPlugin(dir);+ if (wasEnabled) {+ await this.pluginLoader.enablePlugin(id);+ }+ fs.rmSync(backup, { recursive: true, force: true });+ } catch (error) {+ // Roll back to the previous version: restore the backed-up directory and reload it.+ // The failed forward path may have left the NEW version in the loader map (loadPlugin+ // succeeded; enablePlugin failed with status=ERROR but did NOT remove it), so drop it first —+ // otherwise the restore's loadPlugin() hits the "already loaded" guard and the runtime stays+ // desynced from disk (new manifest in memory, old files on disk). unloadPlugin throws when+ // nothing is loaded (the loadPlugin-itself-failed case), hence the catch.+ await this.pluginLoader.unloadPlugin(id).catch(() => undefined);+ fs.rmSync(dir, { recursive: true, force: true });+ fs.renameSync(backup, dir);+ try {+ this.pluginLoader.loadPlugin(dir);+ if (wasEnabled) await this.pluginLoader.enablePlugin(id);+ } catch {+ /* best-effort restore; surface the original failure below */+ }+ if (error instanceof HttpException) throw error;+ throw new BadRequestException(+ `Failed to update plugin: ${error instanceof Error ? error.message : String(error)}`,+ );+ }++ return this.findOne(id);+ }++ /** Update an installed plugin by downloading the new package from a URL (SSRF-guarded), then in place. */+ async updateFromUrl(id: string, url: string): Promise<PluginDto> {+ const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;+ let buffer: Buffer;+ try {+ buffer = await fetchSafeBuffer(url, { maxBytes });+ } catch (error) {+ throw new BadRequestException(+ `Failed to download plugin from URL: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ return this.updatePackage(id, buffer);+ }+/** Uninstall an installed user plugin: disable, unload, and delete its files. Built-ins are protected. */async uninstall(id: string): Promise<{ success: boolean; message: string }> {const plugin = this.pluginLoader.getPlugin(id);