feat(plugins): plugin pages, per-user config, capabilities gate, mobile/telegram refactors
- Plugin HTTP routes + web pages (plugin-page-host, plugin-catalog, plugin-detail) - Plugin access grants + per-user config (DB tables + API + frontend forms) - Capabilities-based guard (caps.rs) replacing role-id checks - Mobile connector: message routing, payload types, router refactor - Telegram bot: auth flow, event handling improvements - Honcho plugin: substantial rework - Sidebar: plugin pages integration, role-driven visibility - i18n: new strings for plugins, connectors, capabilities - Remove unused mascot asset
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
// here would make the core depend on every plugin — and, through
|
||||
// `plugin-transcribe-whisper-local`, on a C build — for no gain: the consumer
|
||||
// constructs the plugin list and passes it to `Skald::new`.
|
||||
pub use core_api::plugin::{Plugin, PluginContext, RouterFactory};
|
||||
pub use core_api::plugin::{Plugin, PluginContext, PluginPage, RouterFactory};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
@@ -12,6 +12,7 @@ const PLUGIN_START_TIMEOUT_SECS: u64 = 30;
|
||||
const PLUGIN_STOP_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::SqlitePool;
|
||||
@@ -19,21 +20,78 @@ use tokio::sync::Mutex;
|
||||
use tokio::time::timeout;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::db::plugins as db;
|
||||
use crate::db::{plugin_access, plugin_user_configs, plugins as db};
|
||||
use crate::skald::Skald;
|
||||
|
||||
// ── Public plugin info (returned by list_items tool and REST API) ─────────────
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PluginInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub enabled: bool,
|
||||
pub running: bool,
|
||||
pub config: Value,
|
||||
pub config_schema: Value,
|
||||
pub runtime_status: Option<Value>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub enabled: bool,
|
||||
pub running: bool,
|
||||
pub config: Value,
|
||||
pub config_schema: Value,
|
||||
pub user_config_schema: Value,
|
||||
/// Whether the plugin contributes an `http_router()` — its routes are
|
||||
/// mounted at boot and gated at runtime, so they serve as soon as the
|
||||
/// plugin is enabled (no restart).
|
||||
pub has_router: bool,
|
||||
/// Whether the plugin gates access through its own binding lifecycle — the
|
||||
/// admin UI hides the "User access" checklist when true (see the trait).
|
||||
pub manages_own_access: bool,
|
||||
pub runtime_status: Option<Value>,
|
||||
}
|
||||
|
||||
/// One user's view of a plugin they may use — served by `GET /api/plugins/mine`.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserPluginView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub user_config_schema: Value,
|
||||
pub user_config: Value,
|
||||
}
|
||||
|
||||
/// A plugin-contributed web page as seen by one user — served by
|
||||
/// `GET /api/plugins/pages`. `entry_url` is already resolved against the
|
||||
/// plugin's router mount, so the frontend can `import()` it directly.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PluginPageInfo {
|
||||
pub plugin_id: String,
|
||||
pub page_id: String,
|
||||
pub title: String,
|
||||
pub icon: String,
|
||||
pub priority: i32,
|
||||
pub entry_url: String,
|
||||
/// Fragment-contract version the host speaks. Always 1 for now — bump when
|
||||
/// the contract changes so old hosts can refuse new fragments cleanly.
|
||||
pub api_version: u32,
|
||||
}
|
||||
|
||||
// ── Per-user config store (the PluginUserConfigApi injected into PluginContext) ─
|
||||
|
||||
/// `PluginUserConfigApi` over the system pool. Admin-readable by design —
|
||||
/// see `db::plugin_user_configs`.
|
||||
struct UserConfigStore {
|
||||
db: Arc<SqlitePool>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl core_api::user_plugin_config::PluginUserConfigApi for UserConfigStore {
|
||||
async fn get(&self, plugin_id: &str, user_id: &str) -> Result<Option<Value>> {
|
||||
plugin_user_configs::get(&self.db, plugin_id, user_id).await
|
||||
}
|
||||
|
||||
async fn set(&self, plugin_id: &str, user_id: &str, config: Value) -> Result<()> {
|
||||
plugin_user_configs::set(&self.db, plugin_id, user_id, &config).await
|
||||
}
|
||||
|
||||
async fn delete(&self, plugin_id: &str, user_id: &str) -> Result<()> {
|
||||
plugin_user_configs::delete(&self.db, plugin_id, user_id).await
|
||||
}
|
||||
}
|
||||
|
||||
// ── PluginManager ─────────────────────────────────────────────────────────────
|
||||
@@ -41,6 +99,7 @@ pub struct PluginInfo {
|
||||
pub struct PluginManager {
|
||||
plugins: Vec<Arc<dyn Plugin>>,
|
||||
db: Arc<SqlitePool>,
|
||||
user_config: Arc<UserConfigStore>,
|
||||
skald: OnceLock<Arc<Skald>>,
|
||||
/// Provided by WebFrontend before start_enabled() is called.
|
||||
router_factory: OnceLock<RouterFactory>,
|
||||
@@ -54,6 +113,7 @@ impl PluginManager {
|
||||
pub fn new(db: Arc<SqlitePool>) -> Self {
|
||||
Self {
|
||||
plugins: Vec::new(),
|
||||
user_config: Arc::new(UserConfigStore { db: Arc::clone(&db) }),
|
||||
db,
|
||||
skald: OnceLock::new(),
|
||||
router_factory: OnceLock::new(),
|
||||
@@ -109,30 +169,25 @@ impl PluginManager {
|
||||
location: Arc::clone(skald.location_manager()) as _,
|
||||
system_bus: Arc::clone(skald.system_bus()),
|
||||
user_channel: self.skald()? as Arc<dyn core_api::user_channel::UserChannelApi>,
|
||||
user_config: Arc::clone(&self.user_config) as _,
|
||||
web_port,
|
||||
remote_slot: Arc::clone(skald.remote()),
|
||||
router_factory,
|
||||
})
|
||||
}
|
||||
|
||||
/// Collects the HTTP routers contributed by enabled plugins (plugin.md §12.3).
|
||||
/// Returns `(plugin_id, router)` pairs; the caller (`WebFrontend::start`)
|
||||
/// nests each under `/api/plugin/<id>/`. Only plugins with `enabled=true` in
|
||||
/// the DB and a non-`None` `http_router()` are included.
|
||||
/// Collects the HTTP routers contributed by **every** registered plugin —
|
||||
/// enabled or not. Returns `(plugin_id, router)` pairs; the caller
|
||||
/// (`WebFrontend::start`) nests each under `/api/plugin/<id>/` behind the
|
||||
/// auth + enabled gates, so a disabled plugin's routes answer 404 and
|
||||
/// enabling one at runtime serves them immediately (no restart).
|
||||
///
|
||||
/// Call this AFTER `start_enabled()` so a plugin's router can close over state
|
||||
/// initialised during `reload`/`start`.
|
||||
/// Call this AFTER `start_enabled()` so a started plugin's router can close
|
||||
/// over state initialised during `reload`/`start`. The router must still be
|
||||
/// safe to build for a plugin that never started (see `Plugin::http_router`).
|
||||
pub async fn collect_plugin_routers(&self) -> Vec<(String, axum::Router)> {
|
||||
let mut out = Vec::new();
|
||||
for plugin in &self.plugins {
|
||||
match db::get(&self.db, plugin.id()).await {
|
||||
Ok(Some(row)) if row.enabled => {}
|
||||
Ok(_) => continue,
|
||||
Err(e) => {
|
||||
warn!(plugin = plugin.id(), error = %e, "collect_plugin_routers: DB read failed; skipping");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(router) = plugin.http_router() {
|
||||
info!(plugin = plugin.id(), "plugin contributed an HTTP router → /api/plugin/{}", plugin.id());
|
||||
out.push((plugin.id().to_string(), router));
|
||||
@@ -314,14 +369,17 @@ impl PluginManager {
|
||||
.map(|r| (r.enabled, r.config))
|
||||
.unwrap_or((false, "{}".to_string()));
|
||||
out.push(PluginInfo {
|
||||
id: plugin.id().to_string(),
|
||||
name: plugin.name().to_string(),
|
||||
description: plugin.description().to_string(),
|
||||
id: plugin.id().to_string(),
|
||||
name: plugin.name().to_string(),
|
||||
description: plugin.description().to_string(),
|
||||
enabled,
|
||||
running: plugin.is_running(),
|
||||
config: serde_json::from_str(&config_json).unwrap_or(json!({})),
|
||||
config_schema: plugin.config_schema(),
|
||||
runtime_status: plugin.runtime_status(),
|
||||
running: plugin.is_running(),
|
||||
config: serde_json::from_str(&config_json).unwrap_or(json!({})),
|
||||
config_schema: plugin.config_schema(),
|
||||
user_config_schema: plugin.user_config_schema(),
|
||||
has_router: plugin.http_router().is_some(),
|
||||
manages_own_access: plugin.manages_own_access(),
|
||||
runtime_status: plugin.runtime_status(),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
@@ -334,6 +392,125 @@ impl PluginManager {
|
||||
&self.plugins
|
||||
}
|
||||
|
||||
// ── Per-user access & configuration ───────────────────────────────────────
|
||||
|
||||
/// The plugins a user sees in their UI: **enabled** and granted in
|
||||
/// `plugin_access` (admins see every enabled plugin). Each entry carries
|
||||
/// the user's current config blob for the schema-driven form.
|
||||
pub async fn list_accessible(&self, user_id: &str, is_admin: bool) -> Result<Vec<UserPluginView>> {
|
||||
let granted: std::collections::HashSet<String> = if is_admin {
|
||||
std::collections::HashSet::new()
|
||||
} else {
|
||||
plugin_access::plugin_ids_for_user(&self.db, user_id).await?.into_iter().collect()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for plugin in &self.plugins {
|
||||
// Binding-managed plugins (e.g. mobile-connector) aren't configured
|
||||
// from the "My plugins" view — they own their own pairing UI.
|
||||
if plugin.manages_own_access() {
|
||||
continue;
|
||||
}
|
||||
let enabled = db::get(&self.db, plugin.id()).await?
|
||||
.map(|r| r.enabled)
|
||||
.unwrap_or(false);
|
||||
if !enabled || (!is_admin && !granted.contains(plugin.id())) {
|
||||
continue;
|
||||
}
|
||||
let user_config = plugin_user_configs::get(&self.db, plugin.id(), user_id)
|
||||
.await?
|
||||
.unwrap_or(json!({}));
|
||||
out.push(UserPluginView {
|
||||
id: plugin.id().to_string(),
|
||||
name: plugin.name().to_string(),
|
||||
description: plugin.description().to_string(),
|
||||
user_config_schema: plugin.user_config_schema(),
|
||||
user_config,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub async fn has_access(&self, id: &str, user_id: &str) -> Result<bool> {
|
||||
plugin_access::has_access(&self.db, id, user_id).await
|
||||
}
|
||||
|
||||
/// The web pages a user sees in the frontend menu: every `web_pages()`
|
||||
/// entry of every **enabled** plugin, filtered by audience — `admin_only`
|
||||
/// pages go to the admin role only; the others require the `plugin_access`
|
||||
/// grant (admins see all). Binding-managed plugins (`manages_own_access`)
|
||||
/// keep their pages admin-only unless the page says otherwise, mirroring
|
||||
/// `list_accessible`.
|
||||
pub async fn web_pages_for(&self, user_id: &str, is_admin: bool) -> Result<Vec<PluginPageInfo>> {
|
||||
let granted: std::collections::HashSet<String> = if is_admin {
|
||||
std::collections::HashSet::new()
|
||||
} else {
|
||||
plugin_access::plugin_ids_for_user(&self.db, user_id).await?.into_iter().collect()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for plugin in &self.plugins {
|
||||
let pages = plugin.web_pages();
|
||||
if pages.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !self.is_enabled(plugin.id()).await? {
|
||||
continue;
|
||||
}
|
||||
let owns_access = plugin.manages_own_access();
|
||||
for page in pages {
|
||||
let visible = if is_admin {
|
||||
true
|
||||
} else if page.admin_only || owns_access {
|
||||
false
|
||||
} else {
|
||||
granted.contains(plugin.id())
|
||||
};
|
||||
if visible {
|
||||
out.push(PluginPageInfo {
|
||||
plugin_id: plugin.id().to_string(),
|
||||
page_id: page.page_id.to_string(),
|
||||
title: page.title,
|
||||
icon: page.icon.to_string(),
|
||||
priority: page.priority,
|
||||
entry_url: format!("/api/plugin/{}/{}", plugin.id(), page.entry),
|
||||
api_version: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|p| p.priority);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub async fn is_enabled(&self, id: &str) -> Result<bool> {
|
||||
Ok(db::get(&self.db, id).await?.map(|r| r.enabled).unwrap_or(false))
|
||||
}
|
||||
|
||||
/// The user ids granted access to a plugin (admin UI checklist).
|
||||
pub async fn list_grants(&self, id: &str) -> Result<Vec<String>> {
|
||||
self.find(id)?;
|
||||
plugin_access::users_for_plugin(&self.db, id).await
|
||||
}
|
||||
|
||||
pub async fn set_grants(&self, id: &str, user_ids: &[String]) -> Result<()> {
|
||||
self.find(id)?;
|
||||
plugin_access::set_access(&self.db, id, user_ids).await
|
||||
}
|
||||
|
||||
/// Applies a user's per-plugin config submission. The plugin must be
|
||||
/// enabled, declare a non-empty `user_config_schema`, and the caller must
|
||||
/// hold access (enforced by the API layer).
|
||||
pub async fn update_user_config(&self, id: &str, user_id: &str, config: Value) -> Result<()> {
|
||||
let plugin = self.find(id)?;
|
||||
if !self.is_enabled(id).await? {
|
||||
anyhow::bail!("plugin is not enabled: {id}");
|
||||
}
|
||||
if plugin.user_config_schema().as_object().is_none_or(|s| s.is_empty()) {
|
||||
anyhow::bail!("plugin has no per-user configuration: {id}");
|
||||
}
|
||||
let skald = self.skald()?;
|
||||
plugin.update_user_config(user_id, config, &self.build_context(&skald)?).await
|
||||
}
|
||||
|
||||
pub fn get_plugin_typed<T: Plugin + 'static>(&self, id: &str) -> Option<Arc<T>> {
|
||||
self.plugins.iter()
|
||||
.find(|p| p.id() == id)
|
||||
@@ -347,3 +524,105 @@ impl PluginManager {
|
||||
.ok_or_else(|| anyhow::anyhow!("plugin not found: {id}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_api::plugin::PluginPage;
|
||||
|
||||
struct FakePlugin {
|
||||
id: &'static str,
|
||||
pages: Vec<PluginPage>,
|
||||
owns_access: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Plugin for FakePlugin {
|
||||
fn id(&self) -> &str { self.id }
|
||||
fn name(&self) -> &str { self.id }
|
||||
fn description(&self) -> &str { "" }
|
||||
fn is_running(&self) -> bool { false }
|
||||
fn manages_own_access(&self) -> bool { self.owns_access }
|
||||
fn web_pages(&self) -> Vec<PluginPage> { self.pages.clone() }
|
||||
async fn reload(&self, _enabled: bool, _config: Value, _ctx: PluginContext) -> Result<()> { Ok(()) }
|
||||
async fn start(&self, _ctx: PluginContext) -> Result<()> { Ok(()) }
|
||||
async fn stop(&self) -> Result<()> { Ok(()) }
|
||||
fn as_any(&self) -> &dyn std::any::Any { self }
|
||||
fn as_arc_any(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync> { self }
|
||||
}
|
||||
|
||||
fn page(page_id: &'static str, admin_only: bool, priority: i32) -> PluginPage {
|
||||
PluginPage {
|
||||
page_id,
|
||||
title: page_id.to_string(),
|
||||
icon: "puzzle",
|
||||
entry: format!("web/{page_id}.js"),
|
||||
admin_only,
|
||||
priority,
|
||||
}
|
||||
}
|
||||
|
||||
async fn test_manager(tag: &str) -> PluginManager {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("skald-plugin-test-{tag}-{}-{nanos}", std::process::id()))
|
||||
.join("system.db");
|
||||
let pool = crate::db::init_system_pool(path.to_str().unwrap()).await.unwrap();
|
||||
PluginManager::new(Arc::new(pool))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn web_pages_for_filters_by_enabled_audience_and_access() {
|
||||
let mut mgr = test_manager("pages-filter").await;
|
||||
mgr.register_arc(Arc::new(FakePlugin {
|
||||
id: "alpha",
|
||||
pages: vec![page("admin-console", true, 10), page("user-dash", false, 20)],
|
||||
owns_access: false,
|
||||
}));
|
||||
mgr.register_arc(Arc::new(FakePlugin {
|
||||
id: "beta",
|
||||
pages: vec![page("off-page", false, 5)],
|
||||
owns_access: false,
|
||||
}));
|
||||
mgr.register_arc(Arc::new(FakePlugin {
|
||||
id: "gamma",
|
||||
pages: vec![page("pairing", false, 15)],
|
||||
owns_access: true,
|
||||
}));
|
||||
// alpha + gamma enabled, beta disabled; user u1 holds grants on both.
|
||||
db::upsert(&mgr.db, "alpha", true, "{}").await.unwrap();
|
||||
db::upsert(&mgr.db, "beta", false, "{}").await.unwrap();
|
||||
db::upsert(&mgr.db, "gamma", true, "{}").await.unwrap();
|
||||
for (id, username) in [("u1", "user-one"), ("u2", "user-two")] {
|
||||
sqlx::query("INSERT INTO users (id, username, role_id, encrypted) VALUES (?, ?, 'admin', 0)")
|
||||
.bind(id).bind(username).execute(&*mgr.db).await.unwrap();
|
||||
}
|
||||
plugin_access::grant(&mgr.db, "alpha", "u1").await.unwrap();
|
||||
plugin_access::grant(&mgr.db, "gamma", "u1").await.unwrap();
|
||||
|
||||
// Admin: everything enabled, priority-ascending.
|
||||
let admin = mgr.web_pages_for("admin-user", true).await.unwrap();
|
||||
let got: Vec<(&str, &str)> = admin.iter()
|
||||
.map(|p| (p.plugin_id.as_str(), p.page_id.as_str())).collect();
|
||||
assert_eq!(got, vec![
|
||||
("alpha", "admin-console"),
|
||||
("gamma", "pairing"),
|
||||
("alpha", "user-dash"),
|
||||
]);
|
||||
assert_eq!(admin[0].entry_url, "/api/plugin/alpha/web/admin-console.js");
|
||||
assert_eq!(admin[0].api_version, 1);
|
||||
|
||||
// Non-admin: only the non-admin_only page of a granted, enabled,
|
||||
// non-binding-managed plugin — beta is disabled, gamma manages its own
|
||||
// access, alpha's admin console is admin_only.
|
||||
let user = mgr.web_pages_for("u1", false).await.unwrap();
|
||||
let got: Vec<(&str, &str)> = user.iter()
|
||||
.map(|p| (p.plugin_id.as_str(), p.page_id.as_str())).collect();
|
||||
assert_eq!(got, vec![("alpha", "user-dash")]);
|
||||
|
||||
// A user with no grants sees nothing.
|
||||
let stranger = mgr.web_pages_for("u2", false).await.unwrap();
|
||||
assert!(stranger.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user