Phase 3: Plugin-UI-System (WordPress-Style)
Backend: - PluginManifest um 5 neue UI-Felder erweitert: menu_items, page_routes, detail_tabs, settings_pages, dashboard_widgets (FrontendMenuItem, FrontendPageRoute, FrontendDetailTab, FrontendSettingsPage, FrontendDashboardWidget) - GET /api/v1/plugins/active-manifests Endpoint liefert UI-Manifeste aller aktiven Plugins - Registry.get_active_manifests() + PluginService.get_active_manifests() - 12 Built-in Plugins mit UI-Manifest-Daten gefuellt (menu_items, page_routes, detail_tabs, settings_pages) - Plugin-Install-System: POST /upload (ZIP), POST /install-url (URL) mit Validierung (Manifest, dangerous imports, SQL migrations) Frontend: - pluginStore.ts (Zustand) mit PluginUiManifest Typen + Selektoren - useActivePluginManifests() React Query Hook - PluginRegistry.tsx — fetcht Manifeste beim App-Start - PluginLoader.tsx — dynamisches React.lazy() mit ErrorBoundary - PluginRouteRenderer.tsx — Catch-all fuer Plugin-Routes - routes/index.tsx — Catch-all Routes fuer Plugin-Pages + Settings - Sidebar.tsx — dynamische Plugin Menu-Items mit Grouping + Icons - Settings.tsx — dynamische Plugin Settings-Pages - ContactDetail.tsx — dynamische Plugin Detail-Tabs mit Permissions - AppShell.tsx — PluginRegistry Provider eingebunden - SettingsPlugins.tsx — Install-UI (ZIP Upload + URL Install) - plugins.ts — useUploadPlugin() + useInstallPluginFromUrl() Hooks Docs & Templates: - docs/plugin-development-guide.md — komplette Entwickler-Doku - templates/plugin-template/ — Boilerplate mit allen Manifest-Feldern Tests: - 34 Vitest-Tests (PluginRegistry, PluginLoader, PluginRouteRenderer, pluginStore) — alle bestanden - TSC: keine neuen Errors (nur pre-existing Dms.tsx)
This commit is contained in:
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendSettingsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,6 +40,15 @@ class AIAssistantPlugin(BasePlugin):
|
||||
"ai:tools",
|
||||
],
|
||||
is_core=True,
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.aiAssistant', label='AI Assistant', path='/ai-assistant', icon='Bot', order=90),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/ai-assistant', component='@/pages/AIAssistant', protected=True),
|
||||
],
|
||||
settings_pages=[
|
||||
FrontendSettingsPage(path='ai', label_key='settings.ai', label='AI Settings', component='@/pages/AISettings', icon='Bot', order=60),
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
@@ -11,7 +11,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendSettingsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -43,6 +43,9 @@ class AIProactivePlugin(BasePlugin):
|
||||
"ai_proactive:config",
|
||||
],
|
||||
is_core=False,
|
||||
settings_pages=[
|
||||
FrontendSettingsPage(path='ai-proactive', label_key='settings.aiProactive', label='Proactive AI', component='@/pages/ProactiveAISettings', icon='Sparkles', order=61),
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendDetailTab
|
||||
|
||||
|
||||
class CalendarPlugin(BasePlugin):
|
||||
@@ -41,4 +41,15 @@ class CalendarPlugin(BasePlugin):
|
||||
"calendar:share",
|
||||
"calendar:admin",
|
||||
],
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.calendar', label='Calendar', path='/calendar', icon='Calendar', order=20),
|
||||
FrontendMenuItem(label_key='nav.calendarKanban', label='Calendar Kanban', path='/calendar/kanban', icon='KanbanSquare', group='nav.calendar', order=21),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/calendar', component='@/pages/Calendar', protected=True),
|
||||
FrontendPageRoute(path='/calendar/kanban', component='@/pages/CalendarKanban', protected=True),
|
||||
],
|
||||
detail_tabs=[
|
||||
FrontendDetailTab(entity_type='contact', label_key='tabs.calendar', label='Calendar', component='@/components/contact/ContactCalendarTab', icon='Calendar', order=30, permission='calendar:read'),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendDetailTab
|
||||
|
||||
|
||||
class DmsPlugin(BasePlugin):
|
||||
@@ -31,4 +31,15 @@ class DmsPlugin(BasePlugin):
|
||||
"dms:share",
|
||||
"dms:admin",
|
||||
],
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.files', label='Files', path='/dms', icon='FolderOpen', order=40),
|
||||
FrontendMenuItem(label_key='nav.trash', label='Trash', path='/dms/trash', icon='Trash2', group='nav.files', order=41),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/dms', component='@/pages/Dms', protected=True),
|
||||
FrontendPageRoute(path='/dms/trash', component='@/pages/DmsTrash', protected=True),
|
||||
],
|
||||
detail_tabs=[
|
||||
FrontendDetailTab(entity_type='contact', label_key='tabs.files', label='Dateien', component='@/components/contact/ContactFilesTab', icon='FolderOpen', order=40, permission='dms:read'),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendDetailTab
|
||||
|
||||
|
||||
class EntityLinksPlugin(BasePlugin):
|
||||
@@ -37,6 +37,9 @@ class EntityLinksPlugin(BasePlugin):
|
||||
"entity_links:delete",
|
||||
],
|
||||
is_core=True,
|
||||
detail_tabs=[
|
||||
FrontendDetailTab(entity_type='contact', label_key='tabs.links', label='Verknüpfungen', component='@/components/contact/ContactLinksTab', icon='Link', order=60, permission='entity_links:read'),
|
||||
],
|
||||
)
|
||||
|
||||
async def on_contact_deleted(self, payload: dict[str, Any]) -> None:
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -49,6 +49,12 @@ class KommunikationPlugin(BasePlugin):
|
||||
"comm:delete",
|
||||
],
|
||||
is_core=True,
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.communication', label='Communication', path='/communication', icon='MessageSquare', order=80),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/communication', component='@/pages/Communication', protected=True),
|
||||
],
|
||||
)
|
||||
|
||||
async def on_activate(self, db, service_container, event_bus) -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendDetailTab, FrontendSettingsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -56,6 +56,20 @@ class MailPlugin(BasePlugin):
|
||||
events=[],
|
||||
migrations=["0001_initial.sql", "0006_flag_type.sql", "0007_sync_queue.sql", "0008_sync_queue_deleted_at.sql", "0009_remove_mail_soft_delete.sql"],
|
||||
permissions=["mail:read", "mail:send", "mail:config", "mail:share", "mail:write", "mail:delete"],
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.email', label='Mail', path='/mail', icon='Mail', order=30),
|
||||
FrontendMenuItem(label_key='nav.emailSettings', label='Mail Settings', path='/mail/settings', icon='Settings', group='nav.email', order=31),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/mail', component='@/pages/Mail', protected=True),
|
||||
FrontendPageRoute(path='/mail/settings', component='@/pages/MailSettings', protected=True),
|
||||
],
|
||||
settings_pages=[
|
||||
FrontendSettingsPage(path='mail', label_key='settings.mail', label='Mail', component='@/pages/MailSettings', icon='Mail', order=50),
|
||||
],
|
||||
detail_tabs=[
|
||||
FrontendDetailTab(entity_type='contact', label_key='tabs.email', label='E-Mails', component='@/components/contact/ContactMailTab', icon='Mail', order=20, permission='mail:read'),
|
||||
],
|
||||
)
|
||||
|
||||
async def on_activate(
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendSettingsPage
|
||||
|
||||
|
||||
class PermissionsPlugin(BasePlugin):
|
||||
@@ -31,4 +31,9 @@ class PermissionsPlugin(BasePlugin):
|
||||
migrations=["0001_initial.sql"],
|
||||
permissions=[],
|
||||
is_core=True,
|
||||
settings_pages=[
|
||||
FrontendSettingsPage(path='roles', label_key='settings.roles', label='Roles', component='@/pages/SettingsRoles', icon='Shield', order=10, permission='permissions:read'),
|
||||
FrontendSettingsPage(path='users', label_key='settings.users', label='Users', component='@/pages/SettingsUsers', icon='Users', order=11, permission='permissions:read'),
|
||||
FrontendSettingsPage(path='groups', label_key='settings.groups', label='Groups', component='@/pages/SettingsGroups', icon='UsersRound', order=12, permission='permissions:read'),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute
|
||||
|
||||
|
||||
class ReportGeneratorPlugin(BasePlugin):
|
||||
@@ -26,4 +26,10 @@ class ReportGeneratorPlugin(BasePlugin):
|
||||
events=["report.requested", "report.generated"],
|
||||
migrations=["0001_initial.sql"],
|
||||
permissions=["reports.read", "reports.generate", "reports.manage_templates"],
|
||||
menu_items=[
|
||||
FrontendMenuItem(label_key='nav.reports', label='Reports', path='/reports', icon='BarChart3', order=70),
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/reports', component='@/pages/Reports', protected=True),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest
|
||||
from app.plugins.manifest import PluginManifest, FrontendSettingsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -38,6 +38,9 @@ class SystemNotifPlugin(BasePlugin):
|
||||
migrations=[],
|
||||
permissions=["system_notif:read"],
|
||||
is_core=False,
|
||||
settings_pages=[
|
||||
FrontendSettingsPage(path='notifications', label_key='settings.notifications', label='Notifications', component='@/pages/SettingsNotifications', icon='Bell', order=40),
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendDetailTab
|
||||
|
||||
|
||||
class TagsPlugin(BasePlugin):
|
||||
@@ -31,4 +31,7 @@ class TagsPlugin(BasePlugin):
|
||||
"tags:admin",
|
||||
],
|
||||
is_core=True,
|
||||
detail_tabs=[
|
||||
FrontendDetailTab(entity_type='contact', label_key='tabs.tags', label='Tags', component='@/components/contact/ContactTagsTab', icon='Tag', order=50, permission='tags:read'),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendPageRoute
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,6 +40,9 @@ class UnifiedSearchPlugin(BasePlugin):
|
||||
migrations=["0001_initial.sql", "0002_embeddings.sql"],
|
||||
permissions=["search:read", "search:admin"],
|
||||
is_core=False,
|
||||
page_routes=[
|
||||
FrontendPageRoute(path='/search', component='@/pages/GlobalSearchResults', protected=True),
|
||||
],
|
||||
)
|
||||
|
||||
async def on_activate(self, db, service_container, event_bus) -> None:
|
||||
|
||||
@@ -24,6 +24,74 @@ class FieldDefinition(BaseModel):
|
||||
sensitivity: str = Field(default="normal", description="normal|sensitive|critical")
|
||||
|
||||
|
||||
# ── Frontend UI definition models (Phase 3) ──────────────────────────────────
|
||||
|
||||
|
||||
class FrontendMenuItem(BaseModel):
|
||||
"""A sidebar navigation item contributed by a plugin."""
|
||||
|
||||
label_key: str = Field(..., description="i18n key for the menu label")
|
||||
label: str = Field(default="", description="Fallback label if i18n key is missing")
|
||||
path: str = Field(..., description="Frontend route path, e.g. /mail")
|
||||
icon: str = Field(default="FileText", description="lucide-react icon name")
|
||||
group: str = Field(default="", description="Optional group label_key for tree-style nesting")
|
||||
order: int = Field(default=100, description="Sort order within the sidebar")
|
||||
badge_key: str = Field(default="", description="Optional store key for badge count")
|
||||
|
||||
|
||||
class FrontendPageRoute(BaseModel):
|
||||
"""A frontend page route contributed by a plugin."""
|
||||
|
||||
path: str = Field(..., description="Frontend route path, e.g. /mail or /mail/settings")
|
||||
component: str = Field(
|
||||
..., description="Dotted path to the React component, e.g. @/pages/Mail"
|
||||
)
|
||||
parent: str = Field(
|
||||
default="",
|
||||
description="Parent route path for nested routes (e.g. /settings for a settings sub-page)",
|
||||
)
|
||||
protected: bool = Field(default=True, description="Whether the route requires authentication")
|
||||
order: int = Field(default=100, description="Sort order")
|
||||
|
||||
|
||||
class FrontendDetailTab(BaseModel):
|
||||
"""A detail tab contributed by a plugin for entity detail views."""
|
||||
|
||||
entity_type: str = Field(..., description="Entity type this tab applies to, e.g. 'contact'")
|
||||
label_key: str = Field(..., description="i18n key for the tab label")
|
||||
label: str = Field(default="", description="Fallback label")
|
||||
component: str = Field(..., description="Dotted path to the React component")
|
||||
icon: str = Field(default="FileText", description="lucide-react icon name")
|
||||
order: int = Field(default=100, description="Sort order within the detail view")
|
||||
permission: str = Field(default="", description="Optional permission required to see this tab")
|
||||
|
||||
|
||||
class FrontendSettingsPage(BaseModel):
|
||||
"""A settings sub-page contributed by a plugin."""
|
||||
|
||||
path: str = Field(..., description="Settings sub-route path, e.g. mail or notifications")
|
||||
label_key: str = Field(..., description="i18n key for the settings nav label")
|
||||
label: str = Field(default="", description="Fallback label")
|
||||
component: str = Field(..., description="Dotted path to the React component")
|
||||
icon: str = Field(default="Settings", description="lucide-react icon name")
|
||||
order: int = Field(default=100, description="Sort order within settings nav")
|
||||
permission: str = Field(default="", description="Optional permission required")
|
||||
|
||||
|
||||
class FrontendDashboardWidget(BaseModel):
|
||||
"""A dashboard widget contributed by a plugin."""
|
||||
|
||||
id: str = Field(..., description="Unique widget identifier")
|
||||
label_key: str = Field(..., description="i18n key for the widget title")
|
||||
label: str = Field(default="", description="Fallback label")
|
||||
component: str = Field(..., description="Dotted path to the React component")
|
||||
icon: str = Field(default="LayoutDashboard", description="lucide-react icon name")
|
||||
order: int = Field(default=100, description="Sort order on the dashboard")
|
||||
col_span: int = Field(default=1, description="Grid column span (1-4)")
|
||||
row_span: int = Field(default=1, description="Grid row span")
|
||||
permission: str = Field(default="", description="Optional permission required")
|
||||
|
||||
|
||||
class PluginManifest(BaseModel):
|
||||
"""Manifest describing a plugin's metadata, dependencies, and capabilities."""
|
||||
|
||||
@@ -58,6 +126,22 @@ class PluginManifest(BaseModel):
|
||||
default_factory=list,
|
||||
description="AI agent capabilities this plugin provides (e.g. 'contact_search', 'email_draft')",
|
||||
)
|
||||
# ── Frontend UI contributions (Phase 3) ──
|
||||
menu_items: list[FrontendMenuItem] = Field(
|
||||
default_factory=list, description="Sidebar navigation items contributed by this plugin"
|
||||
)
|
||||
page_routes: list[FrontendPageRoute] = Field(
|
||||
default_factory=list, description="Frontend page routes contributed by this plugin"
|
||||
)
|
||||
detail_tabs: list[FrontendDetailTab] = Field(
|
||||
default_factory=list, description="Entity detail tabs contributed by this plugin"
|
||||
)
|
||||
settings_pages: list[FrontendSettingsPage] = Field(
|
||||
default_factory=list, description="Settings sub-pages contributed by this plugin"
|
||||
)
|
||||
dashboard_widgets: list[FrontendDashboardWidget] = Field(
|
||||
default_factory=list, description="Dashboard widgets contributed by this plugin"
|
||||
)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
@@ -120,6 +204,31 @@ MANIFEST_SCHEMA_DOC = ManifestSchemaResponse(
|
||||
"required": "false",
|
||||
"description": "Required permissions",
|
||||
},
|
||||
"menu_items": {
|
||||
"type": "list[FrontendMenuItem]",
|
||||
"required": "false",
|
||||
"description": "Sidebar navigation items (label_key, path, icon, group, order)",
|
||||
},
|
||||
"page_routes": {
|
||||
"type": "list[FrontendPageRoute]",
|
||||
"required": "false",
|
||||
"description": "Frontend page routes (path, component, parent, protected)",
|
||||
},
|
||||
"detail_tabs": {
|
||||
"type": "list[FrontendDetailTab]",
|
||||
"required": "false",
|
||||
"description": "Entity detail tabs (entity_type, label_key, component, icon, permission)",
|
||||
},
|
||||
"settings_pages": {
|
||||
"type": "list[FrontendSettingsPage]",
|
||||
"required": "false",
|
||||
"description": "Settings sub-pages (path, label_key, component, icon, permission)",
|
||||
},
|
||||
"dashboard_widgets": {
|
||||
"type": "list[FrontendDashboardWidget]",
|
||||
"required": "false",
|
||||
"description": "Dashboard widgets (id, label_key, component, col_span, permission)",
|
||||
},
|
||||
},
|
||||
example=PluginManifest(
|
||||
name="example_plugin",
|
||||
@@ -131,5 +240,21 @@ MANIFEST_SCHEMA_DOC = ManifestSchemaResponse(
|
||||
events=["contact.created"],
|
||||
migrations=["0001_initial.sql"],
|
||||
permissions=["contacts.read"],
|
||||
menu_items=[
|
||||
FrontendMenuItem(
|
||||
label_key="nav.examplePlugin",
|
||||
label="Example",
|
||||
path="/example",
|
||||
icon="Sparkles",
|
||||
order=50,
|
||||
)
|
||||
],
|
||||
page_routes=[
|
||||
FrontendPageRoute(
|
||||
path="/example",
|
||||
component="@/pages/Example",
|
||||
protected=True,
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
@@ -671,6 +671,37 @@ class PluginRegistry:
|
||||
|
||||
return plugins_list
|
||||
|
||||
# ── Active UI Manifests (Phase 3) ──
|
||||
|
||||
async def get_active_manifests(self, db: AsyncSession) -> list[dict[str, Any]]:
|
||||
"""Return UI manifests for all active plugins.
|
||||
|
||||
Each entry contains the plugin name and its frontend UI contributions
|
||||
(menu_items, page_routes, detail_tabs, settings_pages, dashboard_widgets).
|
||||
"""
|
||||
result = await db.execute(select(PluginModel).where(PluginModel.active.is_(True)))
|
||||
active_records = {row.name: row for row in result.scalars().all()}
|
||||
|
||||
manifests: list[dict[str, Any]] = []
|
||||
for name, plugin in self._plugins.items():
|
||||
if name not in active_records:
|
||||
continue
|
||||
m = plugin.manifest
|
||||
manifests.append(
|
||||
{
|
||||
"name": m.name,
|
||||
"display_name": m.display_name,
|
||||
"version": m.version,
|
||||
"is_core": m.is_core,
|
||||
"menu_items": [item.model_dump() for item in m.menu_items],
|
||||
"page_routes": [route.model_dump() for route in m.page_routes],
|
||||
"detail_tabs": [tab.model_dump() for tab in m.detail_tabs],
|
||||
"settings_pages": [page.model_dump() for page in m.settings_pages],
|
||||
"dashboard_widgets": [widget.model_dump() for widget in m.dashboard_widgets],
|
||||
}
|
||||
)
|
||||
return manifests
|
||||
|
||||
# ── Internal Helpers ──
|
||||
|
||||
async def _get_plugin_record(self, db: AsyncSession, name: str) -> PluginModel | None:
|
||||
|
||||
+448
-4
@@ -1,16 +1,31 @@
|
||||
"""Plugin routes — list, install, activate, deactivate, uninstall, manifest schema, config."""
|
||||
"""Plugin routes — list, install, activate, deactivate, uninstall, manifest schema, config, upload, install-url."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.db import get_db
|
||||
from app.deps import require_permission
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest
|
||||
from app.plugins.migration_runner import MigrationValidationError
|
||||
from app.services.plugin_service import get_plugin_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/plugins", tags=["plugins"])
|
||||
|
||||
|
||||
@@ -19,6 +34,14 @@ class PluginConfigUpdate(BaseModel):
|
||||
config: dict
|
||||
|
||||
|
||||
class PluginUrlInstall(BaseModel):
|
||||
"""Request body for installing a plugin from a URL."""
|
||||
url: str
|
||||
|
||||
|
||||
MAX_UPLOAD_SIZE = 10 * 1024 * 1024 # 10 MB
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_plugins(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -39,6 +62,23 @@ async def get_manifest_schema(
|
||||
return service.get_manifest_schema()
|
||||
|
||||
|
||||
@router.get("/active-manifests")
|
||||
async def get_active_manifests(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict = Depends(require_permission("plugins:read")),
|
||||
):
|
||||
"""Get UI manifests for all active plugins.
|
||||
|
||||
Returns menu_items, page_routes, detail_tabs, settings_pages, and
|
||||
dashboard_widgets contributed by each active plugin. Used by the
|
||||
frontend PluginRegistry to dynamically register routes, sidebar items,
|
||||
settings pages, and detail tabs.
|
||||
"""
|
||||
service = get_plugin_service()
|
||||
manifests = await service.get_active_manifests(db)
|
||||
return {"plugins": manifests, "total": len(manifests)}
|
||||
|
||||
|
||||
@router.get("/{name}/config")
|
||||
async def get_plugin_config(
|
||||
name: str,
|
||||
@@ -190,9 +230,9 @@ async def uninstall_plugin(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict = Depends(require_permission("plugins:configure")),
|
||||
):
|
||||
"""Uninstall a plugin. Optionally drop plugin-created tables with remove_data=true.
|
||||
"""Uninstall a plugin by name. Deactivates, drops tables, removes DB record.
|
||||
|
||||
Returns 200 with uninstalled status. Idempotent for already-uninstalled plugins.
|
||||
Idempotent: returns 200 if already uninstalled.
|
||||
"""
|
||||
import uuid as uuid_mod
|
||||
|
||||
@@ -212,3 +252,407 @@ async def uninstall_plugin(
|
||||
404, detail={"detail": str(exc), "code": "plugin_not_found"}
|
||||
) from None
|
||||
raise HTTPException(400, detail={"detail": str(exc), "code": "plugin_error"}) from None
|
||||
|
||||
|
||||
# ── Plugin Upload / URL Install ──────────────────────────────────────────────
|
||||
|
||||
|
||||
def _validate_manifest_name(name: str) -> str:
|
||||
"""Validate plugin name is alphanumeric with underscores only."""
|
||||
if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", name):
|
||||
raise ValueError(
|
||||
f"Invalid plugin name '{name}': must start with a letter and contain only "
|
||||
f"alphanumeric characters and underscores"
|
||||
)
|
||||
return name
|
||||
|
||||
|
||||
def _check_dangerous_imports(source_code: str) -> list[str]:
|
||||
"""Check plugin source for dangerous imports/patterns.
|
||||
|
||||
Returns a list of dangerous patterns found (empty if safe).
|
||||
"""
|
||||
dangerous_patterns = [
|
||||
(r"\bos\.system\b", "os.system call"),
|
||||
(r"\bsubprocess\.", "subprocess module"),
|
||||
(r"\beval\s*\(", "eval() call"),
|
||||
(r"\bexec\s*\(", "exec() call"),
|
||||
(r"\b__import__\s*\(", "__import__() call"),
|
||||
(r"\bcompile\s*\(", "compile() call"),
|
||||
]
|
||||
found: list[str] = []
|
||||
for pattern, description in dangerous_patterns:
|
||||
if re.search(pattern, source_code):
|
||||
found.append(description)
|
||||
return found
|
||||
|
||||
|
||||
def _check_migration_sql(sql_content: str) -> list[str]:
|
||||
"""Basic SQL validation for migration files.
|
||||
|
||||
Returns a list of issues found (empty if OK).
|
||||
"""
|
||||
issues: list[str] = []
|
||||
# Check for basic SQL syntax issues
|
||||
lines = sql_content.strip().split("\n")
|
||||
for i, line in enumerate(lines, 1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("--"):
|
||||
continue
|
||||
# Check for unclosed parentheses
|
||||
if stripped.count("(") != stripped.count(")"):
|
||||
issues.append(f"Line {i}: unbalanced parentheses")
|
||||
# Check for DROP TABLE (dangerous in migrations)
|
||||
if re.search(r"\bDROP\s+TABLE\b", stripped, re.IGNORECASE):
|
||||
issues.append(f"Line {i}: DROP TABLE is not allowed in plugin migrations")
|
||||
return issues
|
||||
|
||||
|
||||
def _find_plugin_class_in_module(module: Any) -> type[BasePlugin] | None:
|
||||
"""Find a BasePlugin subclass in a module."""
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
if (
|
||||
isinstance(attr, type)
|
||||
and issubclass(attr, BasePlugin)
|
||||
and attr is not BasePlugin
|
||||
):
|
||||
return attr
|
||||
return None
|
||||
|
||||
|
||||
def _extract_plugin_from_zip(zip_path: str) -> tuple[Path, str, type[BasePlugin]]:
|
||||
"""Extract a ZIP file and find the plugin class.
|
||||
|
||||
Returns (extract_dir, plugin_name, plugin_class).
|
||||
"""
|
||||
extract_dir = Path(tempfile.mkdtemp(prefix="plugin_upload_"))
|
||||
try:
|
||||
with zipfile.ZipFile(zip_path, "r") as zf:
|
||||
# Validate ZIP
|
||||
bad_files = [f for f in zf.namelist() if f.startswith("..") or f.startswith("/")]
|
||||
if bad_files:
|
||||
raise ValueError(f"ZIP contains files with unsafe paths: {bad_files}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
# Find plugin.py in the extracted contents
|
||||
plugin_py_path: Path | None = None
|
||||
for fpath in extract_dir.rglob("plugin.py"):
|
||||
plugin_py_path = fpath
|
||||
break
|
||||
|
||||
if plugin_py_path is None:
|
||||
raise ValueError("ZIP does not contain a plugin.py file")
|
||||
|
||||
# Import the module dynamically
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"uploaded_plugin", plugin_py_path
|
||||
)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ValueError("Could not load plugin.py module")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# Find BasePlugin subclass
|
||||
plugin_class = _find_plugin_class_in_module(module)
|
||||
if plugin_class is None:
|
||||
raise ValueError(
|
||||
"plugin.py does not contain a BasePlugin subclass"
|
||||
)
|
||||
|
||||
plugin_instance = plugin_class()
|
||||
plugin_name = plugin_instance.name
|
||||
|
||||
# Validate manifest
|
||||
manifest = plugin_instance.manifest
|
||||
if not manifest.name or not manifest.version or not manifest.display_name:
|
||||
raise ValueError(
|
||||
"Plugin manifest must include name, version, and display_name"
|
||||
)
|
||||
|
||||
# Validate plugin name
|
||||
_validate_manifest_name(manifest.name)
|
||||
|
||||
# Check for dangerous imports in plugin.py
|
||||
source_code = plugin_py_path.read_text(encoding="utf-8")
|
||||
dangerous = _check_dangerous_imports(source_code)
|
||||
if dangerous:
|
||||
raise ValueError(
|
||||
f"Plugin contains dangerous patterns: {', '.join(dangerous)}"
|
||||
)
|
||||
|
||||
# Check migration SQL files
|
||||
migrations_dir = plugin_py_path.parent / "migrations"
|
||||
if migrations_dir.exists():
|
||||
for sql_file in sorted(migrations_dir.glob("*.sql")):
|
||||
sql_content = sql_file.read_text(encoding="utf-8")
|
||||
issues = _check_migration_sql(sql_content)
|
||||
if issues:
|
||||
raise ValueError(
|
||||
f"Migration file {sql_file.name} has issues: {'; '.join(issues)}"
|
||||
)
|
||||
|
||||
return extract_dir, plugin_name, plugin_class
|
||||
|
||||
except Exception:
|
||||
# Clean up on failure
|
||||
shutil.rmtree(extract_dir, ignore_errors=True)
|
||||
raise
|
||||
|
||||
|
||||
def _install_plugin_from_dir(
|
||||
extract_dir: Path,
|
||||
plugin_name: str,
|
||||
plugin_class: type[BasePlugin],
|
||||
) -> None:
|
||||
"""Copy plugin directory to builtins and register it.
|
||||
|
||||
Copies the extracted plugin directory to app/plugins/builtins/{plugin_name}/.
|
||||
"""
|
||||
builtins_dir = Path(__file__).parent.parent / "plugins" / "builtins" / plugin_name
|
||||
builtins_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Copy all files from extract_dir to builtins_dir
|
||||
for item in extract_dir.iterdir():
|
||||
dest = builtins_dir / item.name
|
||||
if item.is_dir():
|
||||
if dest.exists():
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(item, dest)
|
||||
else:
|
||||
shutil.copy2(item, dest)
|
||||
|
||||
# Register the plugin in the registry
|
||||
registry = get_plugin_service().registry
|
||||
instance = plugin_class()
|
||||
registry.register_plugin(instance)
|
||||
|
||||
logger.info(
|
||||
"Installed plugin '%s' from uploaded ZIP to %s",
|
||||
plugin_name,
|
||||
builtins_dir,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_plugin(
|
||||
file: UploadFile = File(...),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict = Depends(require_permission("plugins:configure")),
|
||||
):
|
||||
"""Upload and install a plugin from a ZIP file.
|
||||
|
||||
The ZIP must contain a plugin directory with a plugin.py that defines a BasePlugin subclass.
|
||||
Validates the manifest, checks for conflicts, runs migrations, and installs the plugin.
|
||||
"""
|
||||
import uuid as uuid_mod
|
||||
|
||||
# Validate file is a ZIP
|
||||
if not file.filename or not file.filename.endswith(".zip"):
|
||||
raise HTTPException(400, detail={"detail": "File must be a .zip archive", "code": "invalid_file"})
|
||||
|
||||
# Check file size
|
||||
contents = await file.read()
|
||||
if len(contents) > MAX_UPLOAD_SIZE:
|
||||
raise HTTPException(
|
||||
413,
|
||||
detail={
|
||||
"detail": f"File too large. Maximum size is {MAX_UPLOAD_SIZE // (1024*1024)} MB",
|
||||
"code": "file_too_large",
|
||||
},
|
||||
)
|
||||
|
||||
# Write to temp file
|
||||
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
||||
try:
|
||||
tmp_zip.write(contents)
|
||||
tmp_zip.close()
|
||||
|
||||
# Extract and validate
|
||||
extract_dir, plugin_name, plugin_class = _extract_plugin_from_zip(tmp_zip.name)
|
||||
|
||||
# Check for name conflicts with existing plugins
|
||||
service = get_plugin_service()
|
||||
existing_plugins = await service.list_plugins(db)
|
||||
existing_names = {p["name"] for p in existing_plugins}
|
||||
|
||||
if plugin_name in existing_names:
|
||||
# Check if version is higher
|
||||
existing_plugin = next(
|
||||
(p for p in existing_plugins if p["name"] == plugin_name), None
|
||||
)
|
||||
if existing_plugin:
|
||||
raise HTTPException(
|
||||
409,
|
||||
detail={
|
||||
"detail": f"Plugin '{plugin_name}' already exists (version {existing_plugin.get('version', 'unknown')}). "
|
||||
f"Uninstall the existing plugin first or upload a higher version.",
|
||||
"code": "plugin_exists",
|
||||
},
|
||||
)
|
||||
|
||||
# Install the plugin directory
|
||||
_install_plugin_from_dir(extract_dir, plugin_name, plugin_class)
|
||||
|
||||
# Run migrations and install via service
|
||||
result = await service.install_plugin(
|
||||
db,
|
||||
plugin_name,
|
||||
tenant_id=uuid_mod.UUID(current_user["tenant_id"]),
|
||||
user_id=uuid_mod.UUID(current_user["user_id"]),
|
||||
)
|
||||
|
||||
# Log audit
|
||||
from app.core.audit import log_audit
|
||||
await log_audit(
|
||||
db,
|
||||
uuid_mod.UUID(current_user["tenant_id"]),
|
||||
uuid_mod.UUID(current_user["user_id"]),
|
||||
action="plugin.upload",
|
||||
entity_type="plugin",
|
||||
changes={"name": plugin_name, "version": result.get("version"), "method": "upload"},
|
||||
)
|
||||
|
||||
return {
|
||||
**result,
|
||||
"message": f"Plugin '{plugin_name}' uploaded and installed successfully",
|
||||
}
|
||||
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail={"detail": str(exc), "code": "plugin_validation_error"}) from None
|
||||
except MigrationValidationError as exc:
|
||||
raise HTTPException(
|
||||
422, detail={"detail": str(exc), "code": "migration_validation_error"}
|
||||
) from None
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to upload plugin")
|
||||
raise HTTPException(
|
||||
500, detail={"detail": f"Failed to install plugin: {str(exc)}", "code": "install_error"}
|
||||
) from None
|
||||
finally:
|
||||
# Clean up temp files
|
||||
try:
|
||||
os.unlink(tmp_zip.name)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if "extract_dir" in dir():
|
||||
shutil.rmtree(extract_dir, ignore_errors=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@router.post("/install-url")
|
||||
async def install_plugin_from_url(
|
||||
body: PluginUrlInstall,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict = Depends(require_permission("plugins:configure")),
|
||||
):
|
||||
"""Install a plugin from a URL (downloads ZIP and installs)."""
|
||||
import uuid as uuid_mod
|
||||
|
||||
if not body.url:
|
||||
raise HTTPException(400, detail={"detail": "URL is required", "code": "missing_url"})
|
||||
|
||||
# Download ZIP from URL
|
||||
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
response = await client.get(body.url, follow_redirects=True)
|
||||
response.raise_for_status()
|
||||
|
||||
content = response.content
|
||||
if len(content) > MAX_UPLOAD_SIZE:
|
||||
raise HTTPException(
|
||||
413,
|
||||
detail={
|
||||
"detail": f"Downloaded file too large. Maximum size is {MAX_UPLOAD_SIZE // (1024*1024)} MB",
|
||||
"code": "file_too_large",
|
||||
},
|
||||
)
|
||||
|
||||
tmp_zip.write(content)
|
||||
tmp_zip.close()
|
||||
|
||||
# Extract and validate
|
||||
extract_dir, plugin_name, plugin_class = _extract_plugin_from_zip(tmp_zip.name)
|
||||
|
||||
# Check for name conflicts
|
||||
service = get_plugin_service()
|
||||
existing_plugins = await service.list_plugins(db)
|
||||
existing_names = {p["name"] for p in existing_plugins}
|
||||
|
||||
if plugin_name in existing_names:
|
||||
raise HTTPException(
|
||||
409,
|
||||
detail={
|
||||
"detail": f"Plugin '{plugin_name}' already exists. Uninstall the existing plugin first.",
|
||||
"code": "plugin_exists",
|
||||
},
|
||||
)
|
||||
|
||||
# Install the plugin directory
|
||||
_install_plugin_from_dir(extract_dir, plugin_name, plugin_class)
|
||||
|
||||
# Run migrations and install via service
|
||||
result = await service.install_plugin(
|
||||
db,
|
||||
plugin_name,
|
||||
tenant_id=uuid_mod.UUID(current_user["tenant_id"]),
|
||||
user_id=uuid_mod.UUID(current_user["user_id"]),
|
||||
)
|
||||
|
||||
# Log audit
|
||||
from app.core.audit import log_audit
|
||||
await log_audit(
|
||||
db,
|
||||
uuid_mod.UUID(current_user["tenant_id"]),
|
||||
uuid_mod.UUID(current_user["user_id"]),
|
||||
action="plugin.install_url",
|
||||
entity_type="plugin",
|
||||
changes={"name": plugin_name, "version": result.get("version"), "url": body.url},
|
||||
)
|
||||
|
||||
return {
|
||||
**result,
|
||||
"message": f"Plugin '{plugin_name}' downloaded and installed successfully",
|
||||
}
|
||||
|
||||
except httpx.HTTPStatusError as exc:
|
||||
raise HTTPException(
|
||||
400,
|
||||
detail={
|
||||
"detail": f"Failed to download plugin from URL: HTTP {exc.response.status_code}",
|
||||
"code": "download_error",
|
||||
},
|
||||
) from None
|
||||
except httpx.RequestError as exc:
|
||||
raise HTTPException(
|
||||
400,
|
||||
detail={
|
||||
"detail": f"Failed to download plugin from URL: {str(exc)}",
|
||||
"code": "download_error",
|
||||
},
|
||||
) from None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail={"detail": str(exc), "code": "plugin_validation_error"}) from None
|
||||
except MigrationValidationError as exc:
|
||||
raise HTTPException(
|
||||
422, detail={"detail": str(exc), "code": "migration_validation_error"}
|
||||
) from None
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to install plugin from URL")
|
||||
raise HTTPException(
|
||||
500, detail={"detail": f"Failed to install plugin: {str(exc)}", "code": "install_error"}
|
||||
) from None
|
||||
finally:
|
||||
# Clean up temp files
|
||||
try:
|
||||
os.unlink(tmp_zip.name)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if "extract_dir" in dir():
|
||||
shutil.rmtree(extract_dir, ignore_errors=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -261,6 +261,10 @@ class PluginService:
|
||||
|
||||
return MANIFEST_SCHEMA_DOC.model_dump()
|
||||
|
||||
async def get_active_manifests(self, db: AsyncSession) -> list[dict[str, Any]]:
|
||||
"""Return UI manifests for all active plugins."""
|
||||
return await self._registry.get_active_manifests(db)
|
||||
|
||||
|
||||
# Global service instance
|
||||
_service: PluginService | None = None
|
||||
|
||||
Reference in New Issue
Block a user