From dda032a9368f49ae680b839648493487a8b352ac Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:43:05 +0800 Subject: [PATCH] fix(gateway): list dormant plugins in full after a core upgrade With no plugin enabled, Plugins::build does not compile disabled plugins and shows each one with the manifest remembered in plugins/.manifests.json. That cache is keyed on the core version, so every upgrade discards it, and with every plugin disabled nothing ever compiles to rebuild it. The bundled default plugins ship disabled, so after any upgrade a default install listed each plugin as a bare id: no name, description, permissions, request kinds, scope or settings (empty permissions, which the desktop app reads as "manifest unknown"). A dormant plugin with neither a compiled nor a cached manifest now gets a display-only manifest read from its approved bytes without starting the sandbox. The manifest is plain data, so tw_plugin::declared_manifest finds the literal and checks it with the same code that checks a compiled one: manifest::parse is split into fields() (every field except hooks) and finish() (hooks against permissions when hooks are known, then requests against permissions), and both paths go through them, in the same order, so they cannot drift. Hooks cannot be known without running the module, so they are left empty and the hook/permission pairing is not checked; a dormant plugin never runs, and enabling one makes the next build compile every plugin. A dormant plugin whose file changed shows its approved copy the same way, as the awake path does by compiling it. A manifest that is not plain data, or breaks a rule, still leaves only the id (with on_error and scope as declared, as before). The static manifest is never written to .manifests.json, which keeps holding compiled manifests only. Nothing security-relevant uses it: enabling a plugin, changing code, approving a changed file and trials all compile first (compiled_manifest() refuses a dormant host), and a test pins that with an engine whose compiled manifest asks for more than the file declares. .manifests.json is still invalidated on every core version. A compiled manifest depends on tw-plugin's rules, bridge.js and the gateway's conversion, none of which feed GUEST_WASM_SHA256 (it hashes the wasm before the snapshot), so dropping the core version would rely on someone remembering to bump FORMAT. With the static fallback an invalidated cache no longer changes what the list shows. Tests: the bundled defaults (as shipped and after the user edits their data) read statically to exactly what the real sandbox compiles, field by field except hooks; field-rule violations give the same LoadError both ways; dormant plugins with an absent or stale cache list name, description, permissions, requests, scope, on_error and settings (order, labels, values) without compiling and without writing the cache; a non-literal manifest falls back to the id; enabling a plugin compiles every plugin. No new messages. Co-Authored-By: Claude Opus 5.5 --- crates/tw-control/src/plugins.rs | 10 +- crates/tw-control/tests/plugin_defaults.rs | 167 +++++++++++- crates/tw-gateway/src/plugin/defaults/mod.rs | 67 +++++ crates/tw-gateway/src/plugin/host.rs | 5 +- crates/tw-gateway/src/plugin/load.rs | 270 +++++++++++++++---- crates/tw-gateway/src/plugin/manifests.rs | 18 +- crates/tw-gateway/src/plugin/mod.rs | 3 +- crates/tw-gateway/src/plugin/sandbox.rs | 4 +- crates/tw-gateway/src/plugin/set.rs | 7 +- crates/tw-gateway/src/plugin/source.rs | 16 ++ crates/tw-plugin/src/lib.rs | 32 ++- crates/tw-plugin/src/manifest.rs | 47 +++- crates/tw-plugin/tests/loading.rs | 173 ++++++++++++ 13 files changed, 735 insertions(+), 84 deletions(-) diff --git a/crates/tw-control/src/plugins.rs b/crates/tw-control/src/plugins.rs index a603f235..8cb9e1ae 100644 --- a/crates/tw-control/src/plugins.rs +++ b/crates/tw-control/src/plugins.rs @@ -32,8 +32,8 @@ //! 别的都不用点头:只改数据(哪怕是工具调用插件的)、停用、删、排顺序,装、打开、改、批准 //! 不碰工具调用的插件。 //! -//! **判断只认真的编出来的 manifest**,不认显示用的缓存(它是用户目录里的一个文件,被人改了 -//! 只是显示不对);**读不出旧的那一份要什么权限的按改得了算**:它此刻跑不了,可一旦又跑得 +//! **判断只认真的编出来的 manifest**,不认休眠的插件手里显示用的那一份(缓存是用户目录里的 +//! 一个文件,被人改了只是显示不对;照源码读的那一份说不出钩子,也不保证编得过);**读不出旧的那一份要什么权限的按改得了算**:它此刻跑不了,可一旦又跑得 //! 了(运行时恢复了),网页替它做的事就生效了。所以这里也不假设调用方看过什么:源码在这里 //! 再编一遍,批准时磁盘上的文件得正好是调用方看过的那一份(哈希核对)。 @@ -601,7 +601,7 @@ fn plugins_in(text: &str) -> Option> { } /// 批准的那一份改不改得了回答里的工具调用。改得了、**或者读不出来**(批准的那份字节没了、 -/// 编不成)就是 `Some(名字)` —— 读不出来按改得了算。真的编一遍,不认显示用的缓存 +/// 编不成)就是 `Some(名字)` —— 读不出来按改得了算。真的编一遍,不认显示用的那一份 async fn approved_steers(s: &ControlState, id: &str, sha256: &str) -> Option { match compiled_manifest(s, id, sha256).await { Some(m) if !steers(&m) => None, @@ -756,8 +756,8 @@ async fn store( } /// 这个插件**真的编出来**的 manifest。开着的插件手里就有;休眠的(停用着、运行时没起)、 -/// 加载出错的,把批准的那份字节编一遍。**安全上的判断只认它**,不认显示用的缓存。读不到 -/// 批准的那份字节、编不成是 None +/// 加载出错的,把批准的那份字节编一遍。**安全上的判断只认它**,不认休眠的插件手里显示用的 +/// 那一份(缓存里的、照源码读的)。读不到批准的那份字节、编不成是 None async fn compiled_manifest(s: &ControlState, id: &str, sha256: &str) -> Option { let held = s .gateway diff --git a/crates/tw-control/tests/plugin_defaults.rs b/crates/tw-control/tests/plugin_defaults.rs index ec04226c..d9b1edef 100644 --- a/crates/tw-control/tests/plugin_defaults.rs +++ b/crates/tw-control/tests/plugin_defaults.rs @@ -753,6 +753,58 @@ async fn the_shipped_defaults_go_in_turned_off_without_starting_the_sandbox() { assert_eq!(engine.count(), 0); } +/// core 升级之后(显示用的缓存是上一版写的,整份作废;或者缓存没了):随 core 发的那几个 +/// 停用着,列表照样说得全它们是什么 —— 照文件里写着的读,**不起运行时**,也不把读出来的写进 +/// 缓存。说得全:名字、说明、权限、处理哪几种请求、范围、出错时怎么办、设置 +#[tokio::test] +async fn after_an_upgrade_the_shipped_defaults_still_list_in_full_without_the_sandbox() { + let b = bed_with("real", Counting::new(real())); + Seeder::shipped().seed(&b.mgr).await; + let stored = std::fs::read_to_string(cache_file(&b)).unwrap(); + let version = tw_gateway::plugin::manifests::version(); + assert!(stored.contains(&version), "{stored}"); + for stale in [Some(stored.replace(&version, "0.63.0/old/3")), None] { + match &stale { + Some(text) => std::fs::write(cache_file(&b), text).unwrap(), + None => std::fs::remove_file(cache_file(&b)).unwrap(), + } + let engine = Counting::new(real()); + let again = b.restart(engine.clone()); + assert_eq!(Seeder::shipped().seed(&again.mgr).await, Seeded::default()); + for (id, _) in tw_gateway::plugin::defaults::ALL { + let m = tw_gateway::plugin::defaults::manifest(id).unwrap(); + let v = again.plugin(id).await; + assert_eq!(v["status"], json!({"kind": "disabled"}), "{id}: {v}"); + assert_eq!(v["name"], m.name.as_str(), "{id}: {v}"); + assert_eq!(v["description"], json!(m.description), "{id}: {v}"); + assert_eq!(v["permissions"], json!(m.permissions), "{id}: {v}"); + assert_eq!(v["requests"], json!(m.requests), "{id}: {v}"); + assert_eq!(v["on_error"], json!(m.on_error), "{id}: {v}"); + assert_eq!(v["reply_mode"], json!(m.reply_mode), "{id}: {v}"); + assert_eq!( + v["scope"], + json!({"clients": m.scope.clients, "models": m.scope.models, + "upstreams": m.scope.upstreams}), + "{id}: {v}" + ); + let schema: Vec = m + .settings + .iter() + .map(|s| json!({"key": s.key, "kind": s.kind, "label": s.label, "value": s.value})) + .collect(); + assert_eq!(v["settings_schema"], json!(schema), "{id}: {v}"); + let a = again.gw.runtime().plugins.get(id).unwrap().clone(); + assert!(a.ready().unwrap().dormant(), "{id}"); + } + assert_eq!(engine.count(), 0, "listing started the sandbox"); + assert_eq!( + std::fs::read_to_string(cache_file(&b)).ok(), + stale, + "the manifests read from the files went into the cache" + ); + } +} + /// 打开一个默认插件:这时才真的编(起运行时),编出来就能跑 #[tokio::test] async fn enabling_a_default_compiles_it_and_then_it_runs() { @@ -905,15 +957,18 @@ async fn a_tampered_manifest_cache_cannot_hide_tool_calls_from_the_confirmation( ); } -/// 缓存对不上(版本不对、是别的字节的):不认,插件只按 id 和状态列出来,也不为此编 +/// 缓存对不上(版本不对、是别的字节的、写坏了,或者干脆没有):不认,也不为此编 —— 列表 +/// 照插件文件里写着的显示,不是缓存里那一条说的。照文件读的那一份不写回缓存 #[tokio::test] async fn a_cache_entry_that_does_not_match_is_ignored() { let b = bed(); let src = install_calls(&b).await; - let stored: Value = + let mut stored: Value = serde_json::from_str(&std::fs::read_to_string(cache_file(&b)).unwrap()).unwrap(); let sha_now = sha(&src); assert!(stored["manifests"][&sha_now].is_object(), "{stored}"); + // 缓存里那一条要是被用上了,列表上就是这个名字 + stored["manifests"][&sha_now]["name"] = json!("缓存里的"); let mut old_version = stored.clone(); old_version["version"] = json!("0.0.0/old/1"); @@ -921,19 +976,115 @@ async fn a_cache_entry_that_does_not_match_is_ignored() { let entry = other_bytes["manifests"][&sha_now].clone(); other_bytes["manifests"] = json!({ sha_now.replace(|c: char| c != '0', "0"): entry }); for (what, file) in [ - ("another version", old_version.to_string()), - ("other bytes", other_bytes.to_string()), - ("a broken file", "{ not json".to_string()), + ("another version", Some(old_version.to_string())), + ("other bytes", Some(other_bytes.to_string())), + ("a broken file", Some("{ not json".to_string())), + ("no file", None), ] { - std::fs::write(cache_file(&b), file).unwrap(); + match &file { + Some(text) => std::fs::write(cache_file(&b), text).unwrap(), + None => std::fs::remove_file(cache_file(&b)).unwrap(), + } let engine = Counting::new(Arc::new(FakeEngine)); let again = b.restart(engine.clone()); let v = again.plugin("calls").await; - assert_eq!(v["name"], "calls", "{what}: {v}"); - assert_eq!(v["permissions"], json!([]), "{what}: {v}"); + assert_eq!(v["name"], "改工具调用", "{what}: {v}"); + assert_eq!(v["permissions"], json!(["reply_tool_calls"]), "{what}: {v}"); + assert_eq!(v["requests"], json!(["conversation"]), "{what}: {v}"); + assert_eq!(v["settings_schema"][0]["label"], "方式", "{what}: {v}"); + assert_eq!(v["settings_schema"][0]["value"], "a", "{what}: {v}"); assert_eq!(v["status"], json!({"kind": "disabled"}), "{what}: {v}"); assert_eq!(engine.count(), 0, "{what}"); + // 照文件读的那一份没有写进去:缓存原样(别的字节的那一条照旧清掉) + let after = std::fs::read_to_string(cache_file(&b)).ok(); + if what == "other bytes" { + let after: Value = serde_json::from_str(after.as_deref().unwrap()).unwrap(); + assert_eq!(after["manifests"], json!({}), "{what}: {after}"); + } else { + assert_eq!(after, file, "{what}: the cache was written"); + } + } +} + +/// 编出来的说它改得了工具调用,照文件读的那一份说它只改系统提示(模块代码在运行时多要了 +/// 权限 —— 真的沙箱不收这种插件,这里用一个这么「编」的引擎) +struct Steering; + +struct Steered { + manifest: tw_gateway::plugin::Manifest, + sha256: [u8; 32], +} + +impl PluginHost for Steered { + fn manifest(&self) -> &tw_gateway::plugin::Manifest { + &self.manifest + } + fn sha256(&self) -> [u8; 32] { + self.sha256 + } +} + +impl Engine for Steering { + fn load(&self, source: &[u8]) -> Result, LoadError> { + let host = FakeEngine.load(source)?; + let mut manifest = host.manifest().clone(); + manifest + .permissions + .push(tw_api::Permission::ReplyToolCalls); + manifest.hooks.tool_call = true; + Ok(Arc::new(Steered { + manifest, + sha256: host.sha256(), + })) + } +} + +/// 缓存作废之后,休眠的插件列表上是照文件读的那一份;**判断不认它**:网页那条路打开它、改它的 +/// 代码,照样先真的编一遍、按编出来的权限要点头 +#[tokio::test] +async fn a_manifest_read_without_compiling_is_not_what_the_confirmation_trusts() { + let b = bed(); + let src = source( + json!({"name": "只改系统提示", "api": 1, "permissions": ["system"]}), + &["onRequest"], + ); + let (st, v) = call( + &b.app, + "POST", + "/plugins", + Some(json!({"source": src, "id": "quiet", "enabled": false})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + std::fs::remove_file(cache_file(&b)).unwrap(); + + let engine = Counting::new(Arc::new(Steering)); + let again = b.restart(engine.clone()); + let v = again.plugin("quiet").await; + assert_eq!(v["name"], "只改系统提示", "{v}"); + assert_eq!(v["permissions"], json!(["system"]), "{v}"); + assert_eq!(engine.count(), 0); + for (what, source) in [ + ("turning it on", src.clone()), + ("a code change", format!("{src}// 多一行\n")), + ] { + let (st, v) = call( + &again.app, + "PUT", + "/plugins/quiet", + Some(json!({"source": source, "enabled": what == "turning it on", + "base_version": again.version().await})), + ) + .await; + assert_eq!(st, StatusCode::FORBIDDEN, "{what}: {v}"); + assert_eq!(v["code"], "control.plugin.needs_confirmation", "{what}"); } + assert!( + engine.count() > 0, + "the decision was not made on a compiled manifest" + ); + assert!(!again.entry("quiet").unwrap().enabled); + assert_eq!(again.read(again.file("quiet")), src); } /// `wsl-paths` 改得了回答里的工具调用:网页那条路打不开它,确认过的那条打得开;改它的 diff --git a/crates/tw-gateway/src/plugin/defaults/mod.rs b/crates/tw-gateway/src/plugin/defaults/mod.rs index 429e82d0..a45e7a0c 100644 --- a/crates/tw-gateway/src/plugin/defaults/mod.rs +++ b/crates/tw-gateway/src/plugin/defaults/mod.rs @@ -168,6 +168,73 @@ mod tests { assert!(changed[0].1.contains("value: \"English\""), "{changed:?}"); } + /// 不编、照源码读出来的(休眠时列表上显示的那一份,[`crate::plugin::source::display_manifest`]) + /// 和真的沙箱编出来的一个字段一个字段都一样,只差钩子(说不出来,空着)。用户在界面上改过 + /// 出错时怎么办、范围和设置的值之后也一样 + #[test] + fn every_default_reads_without_compiling_as_the_sandbox_compiles_it() { + let engine = crate::plugin::default_engine(); + for (id, source) in ALL { + let shipped = source.to_string(); + let settings: std::collections::BTreeMap<_, _> = engine + .load(source.as_bytes()) + .unwrap_or_else(|e| panic!("{id} does not load: {}", e.msg())) + .manifest() + .settings + .iter() + .map(|s| { + let v = match s.kind { + tw_api::SettingKind::String => tw_api::SettingValue::String("改过".into()), + tw_api::SettingKind::Number => tw_api::SettingValue::Number(7.5), + tw_api::SettingKind::Boolean => { + tw_api::SettingValue::Bool(s.value != serde_json::json!(true)) + } + }; + (s.key.clone(), v) + }) + .collect(); + let edited = crate::plugin::source::rewrite( + source, + tw_api::OnError::Skip, + &tw_api::PluginScope { + clients: vec!["codex".into()], + models: vec!["claude-*".into(), "gpt-*".into()], + upstreams: vec!["relay".into()], + }, + &settings, + ) + .unwrap_or_else(|e| panic!("{id}: {e:?}")); + for (what, src) in [("shipped", shipped), ("edited", edited)] { + let compiled = engine.load(src.as_bytes()).unwrap().manifest().clone(); + let shown = crate::plugin::source::display_manifest(src.as_bytes()) + .unwrap_or_else(|| panic!("{id} ({what}) does not read without compiling")); + assert_eq!(shown.name, compiled.name, "{id} ({what})"); + assert_eq!(shown.api, compiled.api, "{id} ({what})"); + assert_eq!(shown.description, compiled.description, "{id} ({what})"); + assert_eq!(shown.permissions, compiled.permissions, "{id} ({what})"); + assert_eq!(shown.requests, compiled.requests, "{id} ({what})"); + assert_eq!(shown.scope, compiled.scope, "{id} ({what})"); + assert_eq!(shown.on_error, compiled.on_error, "{id} ({what})"); + assert_eq!(shown.reply_mode, compiled.reply_mode, "{id} ({what})"); + assert_eq!(shown.settings, compiled.settings, "{id} ({what})"); + assert_eq!( + shown.hooks, + crate::plugin::Hooks::default(), + "{id} ({what})" + ); + // 上面一条一条比过了;这一条兜住以后加的字段 + assert_eq!( + crate::plugin::Manifest { + hooks: compiled.hooks, + ..shown + }, + compiled, + "{id} ({what})" + ); + } + } + } + /// 每一个都在真的沙箱里编得成:装不上的默认插件只会在日志里留一行 #[test] fn every_default_compiles_in_the_real_sandbox() { diff --git a/crates/tw-gateway/src/plugin/host.rs b/crates/tw-gateway/src/plugin/host.rs index ec785b82..fd750266 100644 --- a/crates/tw-gateway/src/plugin/host.rs +++ b/crates/tw-gateway/src/plugin/host.rs @@ -19,8 +19,9 @@ pub trait PluginHost: Send + Sync { fn sha256(&self) -> [u8; 32]; /// **休眠的插件**:停用着、运行时没起,还没真的编过(见 [`crate::plugin::load`])。 - /// 它跑不了任何钩子,`manifest()` 是缓存里的那一份(或者只有名字的占位),**只拿来 - /// 显示** —— 要跑它(试跑)、要按它的权限做判断,先真的编一遍 + /// 它跑不了任何钩子,`manifest()` 是缓存里的那一份、照源码读的那一份(钩子是空的), + /// 或者只有名字的占位,**只拿来显示** —— 要跑它(试跑)、要按它的权限做判断,先真的 + /// 编一遍 fn dormant(&self) -> bool { false } diff --git a/crates/tw-gateway/src/plugin/load.rs b/crates/tw-gateway/src/plugin/load.rs index 565bc252..919a5be9 100644 --- a/crates/tw-gateway/src/plugin/load.rs +++ b/crates/tw-gateway/src/plugin/load.rs @@ -14,8 +14,10 @@ //! **一个插件都没打开时不起运行时**:沙箱一起来就是几 MB 常驻内存,而 core 自带的默认 //! 插件装上时都停用着 —— 一个插件都没打开的用户不该为它付这个钱。这时停用的插件照样读 //! 文件、算哈希,但不编:它们是「休眠」的([`PluginHost::dormant`],跑不了任何钩子), -//! 列表上显示的 manifest 来自缓存([`super::manifests`],只拿来显示),缓存里没有就只有 -//! id。有一个插件开着,运行时反正要起,所有插件照常编,缓存跟着补齐。 +//! 列表上显示的 manifest 来自缓存([`super::manifests`],编过的那一份);缓存里没有(core +//! 升级了、缓存整份作废)就照批准的那份字节里写着的读([`super::source::display_manifest`], +//! 不编:除了导出了哪些钩子,和编出来的一样);连那也读不出来才只有 id。这两份都**只拿来 +//! 显示**。有一个插件开着,运行时反正要起,所有插件照常编,缓存跟着补齐。 //! //! **出错时怎么办、范围、设置的值都在插件文件里**(契约附录四),配置里只有 id、文件、 //! 哈希和开关。所以它们跟着 manifest 走:编得出来就是编出来的那一份;编不出来(运行时 @@ -300,7 +302,8 @@ impl Plugins { /// 停用着、运行时没起的一个插件:**不编**。文件照样读、哈希照样比(「文件变了」照样 /// 查得出来);这个进程里编过的直接拿来用,没编过的是休眠的,显示用的 manifest 从缓存 - /// 里拿,缓存里没有就只有 id(出错时怎么办和范围照文件里写着的) + /// 里拿,缓存里没有就照批准的那份字节里写着的读(不编),再读不出来就只有 id(出错时 + /// 怎么办和范围照文件里写着的) fn dormant_one( &self, dir: &Path, @@ -331,10 +334,12 @@ impl Plugins { let bytes = match read_capped(&path) { Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - return Loaded::shown(Broken::Changed, shown); + return dormant_broken(dir, p, Broken::Changed, shown); } Err(e) => { - return Loaded::shown( + return dormant_broken( + dir, + p, Broken::Error(msg!( "gw.plugin.unreadable", file = &p.file, detail = e => "The plugin file {file} cannot be read: {detail}" @@ -345,7 +350,7 @@ impl Plugins { }; let sha: [u8; 32] = Sha256::digest(&bytes).into(); if hex(&sha) != p.sha256 { - return Loaded::shown(Broken::Changed, shown); + return dormant_broken(dir, p, Broken::Changed, shown); } if let Some((_, host)) = compiled { return Loaded { @@ -354,7 +359,10 @@ impl Plugins { declared: None, }; } - let declared = shown.is_none().then(|| source::declared(&bytes)).flatten(); + let (shown, declared) = match shown { + Some(m) => (Some(m), None), + None => written(&bytes), + }; let host = Dormant { manifest: shown.clone().unwrap_or_else(|| placeholder(&p.id)), sha256: sha, @@ -378,10 +386,7 @@ impl Plugins { why: Broken, ) -> Loaded { let state = State::Broken(why); - let Some(bytes) = read_capped(&tw_config::plugins::approved_path(dir, &p.id)) - .ok() - .filter(|b| sha256_hex(b) == p.sha256) - else { + let Some(bytes) = approved_copy(dir, p) else { return Loaded { state, manifest: None, @@ -417,7 +422,7 @@ impl Plugins { /// 一个插件读下来的样子([`Plugins::build`] 用) struct Loaded { state: State, - /// 编出来的(或者缓存里的)manifest + /// 编出来的 manifest;休眠的插件是显示用的那一份(缓存里的,或者照源码读的) manifest: Option, /// 读不出 manifest 时,批准的那份字节里写着的出错时怎么办和范围 declared: Option<(tw_api::OnError, Scope)>, @@ -431,16 +436,43 @@ impl Loaded { declared: None, } } +} - fn shown(why: Broken, manifest: Option) -> Self { - Self { - state: State::Broken(why), - manifest, - declared: None, - } +/// 休眠的插件跑不了(文件变了、读不了):显示批准过的那一份。缓存里有就是缓存里的,没有就照 +/// 底稿里写着的读(不编,和醒着时 [`Plugins::approved`] 编底稿是同一个意思) +fn dormant_broken( + dir: &Path, + p: &tw_config::Plugin, + why: Broken, + shown: Option, +) -> Loaded { + let (manifest, declared) = match shown { + Some(m) => (Some(m), None), + None => approved_copy(dir, p).map_or((None, None), |b| written(&b)), + }; + Loaded { + state: State::Broken(why), + manifest, + declared, + } +} + +/// 照一份字节里写着的读(不编):读得出整份 manifest 就是它(**只拿来显示**,见 +/// [`source::display_manifest`]);读不出就只有出错时怎么办和范围,再读不出是两个 None +fn written(bytes: &[u8]) -> (Option, Option<(tw_api::OnError, Scope)>) { + match source::display_manifest(bytes) { + Some(m) => (Some(m), None), + None => (None, source::declared(bytes)), } } +/// 底稿(`plugins/.approved/.js`),**只在它就是批准的那一份时**:被人动过的不拿来冒充 +fn approved_copy(dir: &Path, p: &tw_config::Plugin) -> Option> { + read_capped(&tw_config::plugins::approved_path(dir, &p.id)) + .ok() + .filter(|b| sha256_hex(b) == p.sha256) +} + /// 交给插件的设置:manifest 里每个设置此刻的值 pub fn values_of(m: &Manifest) -> serde_json::Map { m.settings @@ -451,7 +483,7 @@ pub fn values_of(m: &Manifest) -> serde_json::Map { /// 停用着、这个进程里还没编过的插件(见 [`Plugins::build`])。**跑不了任何钩子**( /// [`PluginHost`] 的默认实现一律报错):要它跑之前,调用方先真的编一遍。手里的 manifest -/// 是缓存里的那一份或者只有名字的占位,**只拿来显示** +/// 是缓存里的那一份、照源码读的那一份(钩子是空的),或者只有名字的占位,**只拿来显示** struct Dormant { manifest: Manifest, sha256: [u8; 32], @@ -469,7 +501,7 @@ impl PluginHost for Dormant { } } -/// 缓存里没有它的 manifest 时的占位:名字就是 id,什么权限、钩子都没有 +/// 缓存里没有、照源码也读不出它的 manifest 时的占位:名字就是 id,什么权限、钩子都没有 fn placeholder(id: &str) -> Manifest { Manifest { name: id.to_string(), @@ -885,7 +917,7 @@ mod tests { p } - /// 一个插件都没开:停用的不编(不起运行时),休眠着;缓存里没有就只有 id + /// 一个插件都没开:停用的不编(不起运行时),休眠着,跑不了 #[test] fn with_nothing_enabled_a_disabled_plugin_is_not_compiled() { let bed = Bed::new(); @@ -896,12 +928,124 @@ mod tests { let a = set.get("add-date").unwrap(); let host = a.ready().expect("a dormant plugin is not broken"); assert!(host.dormant()); - assert_eq!(a.name, "add-date"); - assert!(a.manifest.is_none() && a.permissions.is_empty()); // 跑不了:钩子一律报错 assert!(host.on_request(json!({}), json!({})).result.is_err()); } + /// 休眠的插件、缓存里没有(core 升级了,缓存整份作废;或者从来没编过):不编,照文件里 + /// 写着的显示 —— 名字、说明、权限、处理哪几种请求、范围、出错时怎么办、设置(先后、标签、 + /// 值),除了钩子(说不出来,空着)和编出来的一样。**它不写进缓存**:缓存里只放编出来的 + #[test] + fn a_dormant_plugin_without_a_usable_cache_shows_what_its_file_declares() { + // 手写:设置项的先后不按字母(`json!` 会把键排好序) + let src = r#"export const manifest = { + name: "附加日期", + api: 1, + description: "在系统提示里写上今天的日期", + permissions: ["messages", "system"], + requests: ["embeddings", "conversation"], + match: { clients: ["codex"], models: ["claude-*"] }, + on_error: "skip", + reply: "block", + settings: { + note: { type: "string", label: "附加内容", value: "今天" }, + days: { type: "number", label: "天数", value: 2.5 }, + loud: { type: "boolean" }, + }, +}; +export function onRequest(x, ctx) {} +"#; + let compiled = FakeEngine.load(src.as_bytes()).unwrap().manifest().clone(); + for invalid_cache in [false, true] { + let bed = Bed::new(); + let p = off(bed.install("add-date", src)); + let cache = manifests::path_in(bed.dir.path()); + if invalid_cache { + // 上一版 core 编过、记下的:版本对不上,整份不认 + bed.plugins.remember(&p.sha256, &add_date_manifest()); + let text = std::fs::read_to_string(&cache).unwrap(); + std::fs::write(&cache, text.replace(&manifests::version(), "0.69.0/old/3")) + .unwrap(); + } + // 下一个进程 + let engine = Arc::new(Counting(Default::default())); + let next = Plugins::new(engine.clone()); + next.set_dir(bed.dir.path().to_path_buf()); + let before = std::fs::read(&cache).ok(); + let set = next.build(&tw_config::Config { + plugins: vec![p.clone()], + ..Default::default() + }); + assert_eq!(engine.count(), 0, "invalid cache: {invalid_cache}"); + let a = set.get("add-date").unwrap(); + assert!(a.ready().unwrap().dormant()); + let shown = a.manifest.clone().expect("nothing was read from the file"); + assert_eq!( + Manifest { + hooks: compiled.hooks, + ..shown.clone() + }, + compiled, + "invalid cache: {invalid_cache}" + ); + assert_eq!(shown.hooks, crate::plugin::Hooks::default()); + assert_eq!(a.name, "附加日期"); + assert_eq!( + a.permissions, + [tw_api::Permission::System, tw_api::Permission::Messages] + ); + assert_eq!( + a.requests, + [ + tw_api::RequestKind::Conversation, + tw_api::RequestKind::Embeddings + ] + ); + assert_eq!(a.on_error, tw_api::OnError::Skip); + assert_eq!(a.scope.clients, ["codex"]); + assert_eq!(a.scope.models, ["claude-*"]); + let keys: Vec<_> = shown.settings.iter().map(|s| s.key.as_str()).collect(); + assert_eq!(keys, ["note", "days", "loud"]); + assert_eq!(shown.settings[2].label, "loud"); + assert_eq!(a.settings["days"], json!(2.5)); + assert_eq!(a.settings["loud"], json!(false)); + // 照源码读的不进缓存 + assert_eq!(std::fs::read(&cache).ok(), before); + } + } + + /// 照源码也读不出来:manifest 不是纯数据就只有 id(出错时怎么办、范围也说不出来);是纯数据 + /// 但不合规矩,只有 id,出错时怎么办和范围照文件里写着的 + #[test] + fn a_dormant_plugin_whose_manifest_cannot_be_read_is_listed_by_its_id() { + let bed = Bed::new(); + let engine = Arc::new(Counting(Default::default())); + bed.plugins.set_engine(engine.clone()); + let not_data = "const NAME = \"x\";\nexport const manifest = { name: NAME, api: 1, \ + permissions: [\"system\"], on_error: \"skip\" };\n\ + export function onRequest(x, ctx) {}\n"; + let against_the_rules = source( + json!({"name": "x", "api": 1, "permissions": ["network"], + "match": {"models": ["gpt-*"]}, "on_error": "skip"}), + &["onRequest"], + ); + let set = bed.build(vec![ + off(bed.install("not-data", not_data)), + off(bed.install("against-the-rules", &against_the_rules)), + ]); + assert_eq!(engine.count(), 0); + let a = set.get("not-data").unwrap(); + assert!(a.ready().unwrap().dormant()); + assert_eq!(a.name, "not-data"); + assert!(a.manifest.is_none() && a.permissions.is_empty()); + assert_eq!(a.on_error, tw_api::OnError::Reject); + let a = set.get("against-the-rules").unwrap(); + assert_eq!(a.name, "against-the-rules"); + assert!(a.manifest.is_none() && a.permissions.is_empty()); + assert_eq!(a.on_error, tw_api::OnError::Skip); + assert_eq!(a.scope.models, ["gpt-*"]); + } + /// 编过一次的记在缓存里:下一个进程里它停用着,列表照样说得出它是什么,而且不编 #[test] fn a_dormant_plugin_shows_the_manifest_remembered_from_an_earlier_compile() { @@ -921,41 +1065,32 @@ mod tests { assert_eq!(a.settings["note"], json!("今天")); } - /// 休眠的插件、缓存里没有:只有 id,可出错时怎么办和范围照文件里写着的说得出来 - #[test] - fn a_dormant_plugin_without_a_cached_manifest_still_shows_its_on_error_and_scope() { - let bed = Bed::new(); - let src = source( - json!({"name": "x", "api": 1, "permissions": ["system"], - "match": {"clients": ["codex"]}, "on_error": "skip"}), - &["onRequest"], - ); - let engine = Arc::new(Counting(Default::default())); - bed.plugins.set_engine(engine.clone()); - let set = bed.build(vec![off(bed.install("x", &src))]); - assert_eq!(engine.count(), 0); - let a = set.get("x").unwrap(); - assert!(a.ready().unwrap().dormant()); - assert!(a.manifest.is_none()); - assert_eq!(a.on_error, tw_api::OnError::Skip); - assert_eq!(a.scope.clients, ["codex"]); - } - - /// 有一个开着,运行时反正要起:全都编,停用的也编(缓存跟着补齐) + /// 有一个开着,运行时反正要起:全都编,停用的也编(缓存跟着补齐)。之前照源码显示的 + /// 休眠插件也一样编,手里换成编出来的那一份(钩子有了) #[test] fn once_one_plugin_is_enabled_every_plugin_is_compiled() { let bed = Bed::new(); let engine = Arc::new(Counting(Default::default())); bed.plugins.set_engine(engine.clone()); let other = add_date().replace("附加日期", "另一个"); - let set = bed.build(vec![ - off(bed.install("add-date", &add_date())), - bed.install("other", &other), - ]); + let a = off(bed.install("add-date", &add_date())); + let o = bed.install("other", &other); + let dormant = bed.build(vec![a.clone(), off(o.clone())]); + assert_eq!(engine.count(), 0); + assert_eq!(dormant.get("add-date").unwrap().name, "附加日期"); + assert!(!dormant.get("add-date").unwrap().hooks.request); + let set = bed.build(vec![a.clone(), o]); assert_eq!(engine.count(), 2); let a = set.get("add-date").unwrap(); assert!(!a.ready().unwrap().dormant()); assert_eq!(a.name, "附加日期"); + assert!(a.hooks.request); + assert!(set.get("other").unwrap().hooks.request); + // 缓存里记的是编出来的那一份 + let cached = manifests::Cache::default() + .get(bed.dir.path(), &sha256_hex(add_date().as_bytes())) + .unwrap(); + assert!(cached.hooks.request); } /// 休眠的插件文件变了:照样是「变了」(只算哈希,不编),显示的是缓存里批准的那一份 @@ -978,7 +1113,7 @@ mod tests { assert_eq!(engine.count(), 0); } - /// 缓存里是另一份字节的(插件换过源码):不拿来冒充 + /// 缓存里是另一份字节的(插件换过源码):不拿来冒充,显示的是这一份文件里写着的 #[test] fn a_cached_manifest_of_other_bytes_is_not_used() { let bed = Bed::new(); @@ -988,8 +1123,45 @@ mod tests { let p = bed.install("add-date", &newer); let set = bed.build(vec![off(p)]); let a = set.get("add-date").unwrap(); + assert_eq!(a.name, "新的一版"); + assert_eq!(a.manifest.as_ref().unwrap().name, "新的一版"); + } + + /// 休眠的插件文件变了、缓存里也没有:照底稿(批准的那一份)里写着的显示,照样不编。 + /// 底稿也对不上就只有 id + #[test] + fn a_dormant_plugin_whose_file_changed_shows_its_approved_copy_without_compiling() { + let bed = Bed::new(); + let src = source( + json!({"name": "附加日期", "api": 1, "permissions": ["system"], + "match": {"models": ["gpt-*"]}, "on_error": "skip"}), + &["onRequest"], + ); + let p = off(bed.install("add-date", &src)); + let engine = Arc::new(Counting(Default::default())); + bed.plugins.set_engine(engine.clone()); + let file = tw_config::plugins::file_path(bed.dir.path(), "add-date"); + std::fs::write(&file, src.replace("附加日期", "改过的")).unwrap(); + let set = bed.build(vec![p.clone()]); + let a = set.get("add-date").unwrap(); + assert_eq!(a.broken(), Some(&Broken::Changed)); + assert_eq!(a.name, "附加日期"); + assert_eq!(a.permissions, [tw_api::Permission::System]); + assert_eq!(a.on_error, tw_api::OnError::Skip); + assert_eq!(a.scope.models, ["gpt-*"]); + assert_eq!(engine.count(), 0); + + std::fs::write( + tw_config::plugins::approved_path(bed.dir.path(), "add-date"), + src.replace("附加日期", "也改过"), + ) + .unwrap(); + let set = bed.build(vec![p]); + let a = set.get("add-date").unwrap(); + assert_eq!(a.broken(), Some(&Broken::Changed)); assert_eq!(a.name, "add-date"); assert!(a.manifest.is_none()); + assert_eq!(a.on_error, tw_api::OnError::Reject); } fn add_date_manifest() -> Manifest { diff --git a/crates/tw-gateway/src/plugin/manifests.rs b/crates/tw-gateway/src/plugin/manifests.rs index edbc7aa8..996c68d6 100644 --- a/crates/tw-gateway/src/plugin/manifests.rs +++ b/crates/tw-gateway/src/plugin/manifests.rs @@ -6,12 +6,13 @@ //! //! - **键是批准的那份字节的 SHA-256**;整份文件带着运行时和这份格式的版本([`version`]), //! 版本对不上(core 升级、沙箱换了)就整份不认,等下一次运行时起来时重建;读不出来、 -//! 写坏了也一样当作没有。没有可用的那一条时,插件只按 id 和状态列出来,**不为了列个 -//! 名字去起运行时**。 +//! 写坏了也一样当作没有。没有可用的那一条时,照批准的那份字节里写着的读(不编, +//! [`super::source::display_manifest`]),读不出来才只按 id 和状态列出来 —— **不为了列个 +//! 名字去起运行时**。照源码读的那一份不写进这里:这里只放编出来的。 //! - 只有 core 写它,和插件文件一样只给自己(0600)。 -//! - **安全上的判断一律不用它**:打开插件、改改得了工具调用的插件的代码、批准它改过的文件、 -//! 试跑之前,都先真的编一遍、看编出来的 manifest。它是用户目录里的一个文件,被人改了只是 -//! 显示不对。 +//! - **安全上的判断一律不用它**(照源码读的那一份也一样):打开插件、改改得了工具调用的插件 +//! 的代码、批准它改过的文件、试跑之前,都先真的编一遍、看编出来的 manifest。它是用户目录里 +//! 的一个文件,被人改了只是显示不对。 use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; @@ -28,7 +29,12 @@ pub const FILE: &str = ".manifests.json"; /// 3:多了 `on_error`,设置的 `default` 换成了 `value`) const FORMAT: u32 = 3; -/// 缓存认的版本:core 的版本、沙箱的哈希、这份格式的版本,三样有一样不同就不认 +/// 缓存认的版本:core 的版本、沙箱的哈希、这份格式的版本,三样有一样不同就不认。 +/// +/// **core 的版本留着**:编出来的 manifest 取决于 `tw_plugin` 的核对规矩、沙箱里的桥 +/// (`bridge.js`)和网关这边的换法,这几样改了都不会变沙箱的哈希(它是快照之前那份 wasm +/// 的),去掉 core 的版本就得指望每次都记得加 [`FORMAT`]。作废了也不碍事:列表照批准的那份 +/// 字节里写着的读([`super::source::display_manifest`]),除了不显示的钩子,和编出来的一样 pub fn version() -> String { format!( "{}/{}/{FORMAT}", diff --git a/crates/tw-gateway/src/plugin/mod.rs b/crates/tw-gateway/src/plugin/mod.rs index 0f5ac474..8501ef80 100644 --- a/crates/tw-gateway/src/plugin/mod.rs +++ b/crates/tw-gateway/src/plugin/mod.rs @@ -36,7 +36,8 @@ //! - [`trial`]:对着存下来的请求和回答试跑一个插件。 //! //! [`defaults`] 是随 core 一起发的那几个插件(清单和源码);[`manifests`] 是编过的插件的 -//! manifest 缓存,一个插件都没开时拿它显示停用的插件,不为此起运行时(见 [`load`])。 +//! manifest 缓存,一个插件都没开时拿它显示停用的插件,不为此起运行时;缓存里没有的照源码 +//! 读([`source::display_manifest`],不编)(见 [`load`])。 pub mod bridge; pub mod defaults; diff --git a/crates/tw-gateway/src/plugin/sandbox.rs b/crates/tw-gateway/src/plugin/sandbox.rs index 3592de8c..b5db5f49 100644 --- a/crates/tw-gateway/src/plugin/sandbox.rs +++ b/crates/tw-gateway/src/plugin/sandbox.rs @@ -195,7 +195,9 @@ pub(crate) fn on_error(o: tw_plugin::OnError) -> tw_api::OnError { } } -fn manifest(m: &tw_plugin::Manifest) -> Manifest { +/// 换成网关那一份。编出来的和照源码读出来的([`crate::plugin::source::display_manifest`]) +/// 都走这里 +pub(crate) fn manifest(m: &tw_plugin::Manifest) -> Manifest { let granted: Vec = m.permissions.iter().copied().map(permission).collect(); let handled: Vec = m.requests.iter().copied().map(request_kind).collect(); Manifest { diff --git a/crates/tw-gateway/src/plugin/set.rs b/crates/tw-gateway/src/plugin/set.rs index 25258e7d..02a5287b 100644 --- a/crates/tw-gateway/src/plugin/set.rs +++ b/crates/tw-gateway/src/plugin/set.rs @@ -98,12 +98,15 @@ pub struct Active { /// `requests` 的插件对待 —— 它拦的是对话,嵌入、补全照常过去 pub requests: Vec, pub reply_mode: ReplyMode, + /// 导出了哪些钩子。**休眠的插件说不准**:缓存里的那一份有,照源码读的那一份没有(空的) + /// —— 休眠的插件都停用着,不跑,用不着它 pub hooks: Hooks, /// 交给插件的设置:manifest 里每个设置此刻的值(`value`),加载时核对过类型。读不出 /// manifest 时是空的 pub settings: serde_json::Map, - /// 读出来的 manifest。文件变了时是批准过的那一份的(只拿来显示,不跑); - /// 哪一份都读不出来时是 None + /// 读出来的 manifest。文件变了时是批准过的那一份的(只拿来显示,不跑);休眠的插件 + /// ([`PluginHost::dormant`])是显示用的那一份:缓存里编过的,或者照源码读的(不编, + /// 钩子是空的,见 [`crate::plugin::source::display_manifest`])。哪一份都读不出来时是 None pub manifest: Option, pub state: State, pub stats: Arc, diff --git a/crates/tw-gateway/src/plugin/source.rs b/crates/tw-gateway/src/plugin/source.rs index c6326e04..56e2dc77 100644 --- a/crates/tw-gateway/src/plugin/source.rs +++ b/crates/tw-gateway/src/plugin/source.rs @@ -106,6 +106,22 @@ pub fn declared(bytes: &[u8]) -> Option<(OnError, Scope)> { )) } +/// 文件里写着的整份 manifest,**不编译、不起沙箱**([`tw_plugin::declared_manifest`]): +/// 和编出来的同一套规矩,只是说不出导出了哪些钩子 —— `hooks` 一律是空的。 +/// +/// **只拿来显示**:一个插件都没打开时,停用的插件不编(见 [`crate::plugin::load`]),缓存里 +/// 又没有它编过的那一份(core 升级过、缓存没了),列表就照这一份说它是什么。它跑不了,也不 +/// 写进缓存(缓存里只放编出来的);要跑它、按它的权限做判断,先真的编一遍。 +/// +/// 读不出来(不是纯数据、不合规矩、太大)是 None +pub fn display_manifest(bytes: &[u8]) -> Option { + if bytes.len() > MAX_SOURCE { + return None; + } + let m = tw_plugin::declared_manifest(bytes).ok()?; + Some(crate::plugin::sandbox::manifest(&m)) +} + /// 把 `from` 里**写明了的**那几样搬到 `into` 上:出错时怎么办(`on_error`)、范围(`match`), /// 以及 `into` 还声明着、类型也没变的设置的值(`value`)。默认插件换成新版时用:用户设过的 /// 留着,新版新加的设置取新版写的值。 diff --git a/crates/tw-plugin/src/lib.rs b/crates/tw-plugin/src/lib.rs index fe302a64..8a364086 100644 --- a/crates/tw-plugin/src/lib.rs +++ b/crates/tw-plugin/src/lib.rs @@ -515,6 +515,23 @@ impl Runtime { } } +/// 照源码里写着的读出 manifest,**不编译、不起沙箱**:manifest 是纯数据([`literal`]),照着 +/// 源码就读得出来,核对的规矩和 [`Runtime::load`] 一条一条完全一样(同一个函数)。 +/// +/// **钩子说不出来**:导出了哪些函数要执行模块才看得到,所以返回的 `hooks` 一律是空的,钩子和 +/// 权限对不对得上也没核对。也就是说,编得过的插件,这里读出来的除了钩子和编出来的一模一样; +/// 反过来不成立 —— 这里读得出来的未必编得过(模块别处有语法错、钩子和权限对不上、模块代码改了 +/// manifest)。 +/// +/// **只拿来显示**一个还没编过的插件(停用着、为它起沙箱不值得)。要跑它、按它的权限做判断, +/// 先 [`Runtime::load`]。大小由调用方管([`Limits::max_source`]) +pub fn declared_manifest(source: &[u8]) -> Result { + let text = std::str::from_utf8(source).map_err(|e| not_utf8(source, e.valid_up_to()))?; + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let lit = literal::find(text).map_err(not_data)?; + manifest::declared(&lit) +} + // ── 插件 ───────────────────────────────────────────────────────── /// 一个加载好的插件。克隆很便宜,可以跨线程共享 @@ -891,11 +908,7 @@ pub fn js_equal(a: &Value, b: &Value) -> bool { /// manifest 得是源码里写着的那一段纯数据,沙箱求值出来的也得正好是它:模块顶层改了 /// manifest(加一个权限、换一个值)的不认 —— 界面改的是写着的那一份,跑起来的就得是它 fn same_as_written(text: &str, evaluated: &Value) -> Result<(), LoadError> { - let lit = literal::find(text).map_err(|e| LoadError::NotData { - message: e.message, - line: e.line, - column: e.column, - })?; + let lit = literal::find(text).map_err(not_data)?; if !js_equal(&lit.data.to_json(), evaluated) { return Err(LoadError::NotData { message: "the module's code changes the manifest after declaring it; the manifest \ @@ -908,6 +921,15 @@ fn same_as_written(text: &str, evaluated: &Value) -> Result<(), LoadError> { Ok(()) } +/// 源码里找不到 manifest,或者它不是纯数据 +fn not_data(e: literal::NotData) -> LoadError { + LoadError::NotData { + message: e.message, + line: e.line, + column: e.column, + } +} + fn to_json(v: &Value) -> Vec { // serde_json::Value 的键都是字符串,序列化不会失败 serde_json::to_vec(v).unwrap_or_else(|_| b"null".to_vec()) diff --git a/crates/tw-plugin/src/manifest.rs b/crates/tw-plugin/src/manifest.rs index 35bfd291..161eddec 100644 --- a/crates/tw-plugin/src/manifest.rs +++ b/crates/tw-plugin/src/manifest.rs @@ -5,6 +5,11 @@ //! //! 核对之前先对一遍源码:manifest 得是纯数据,沙箱求值出来的得正好是源码里写的那一份 //! ([`crate::literal`],由调用方给的 `literal` 做)。 +//! +//! **同一套规矩有两个入口**:编译时读沙箱交来的那份([`parse`]),不编译时照源码里写着的 +//! 读([`declared`],[`crate::declared_manifest`])。钩子以外的字段都由 [`fields`] 读、 +//! [`finish`] 收尾 —— 两条路认的规矩没法各改各的。只有钩子是编了才知道的:导出了哪些函数 +//! 要执行模块才看得到,所以「钩子和权限一一对应」只在编译时核对。 use std::collections::BTreeSet; @@ -92,7 +97,31 @@ pub(crate) fn parse( let Value::Object(m) = info.manifest else { return Err(err("the manifest must be an object")); }; + let m = fields(&m, info.settings_order.as_deref())?; + finish(m, Some(hooks)) +} +/// 照源码里写着的读一份 manifest,**不编译**([`crate::declared_manifest`]):钩子说不出来, +/// 一律是空的,钩子和权限对不对得上也不核对;别的和 [`parse`] 一条一条完全一样。 +/// +/// 设置项的先后就是字面量里写的先后。沙箱那边是 `Object.keys` 的先后,只在整数样子的键上 +/// 不同(它们排在最前面),而那样的键本来就不合规矩(不能以数字开头) +pub(crate) fn declared(lit: &crate::literal::Literal) -> Result { + let Value::Object(m) = lit.data.to_json() else { + return Err(err("the manifest must be an object")); + }; + let order: Option> = match lit.data.get("settings") { + Some(crate::literal::Data::Object(s)) => Some(s.iter().map(|(k, _)| k.clone()).collect()), + _ => None, + }; + finish(fields(&m, order.as_deref())?, None) +} + +/// 钩子以外的每个字段,逐项核对。`hooks` 先空着,由 [`finish`] 填 +fn fields( + m: &Map, + settings_order: Option<&[String]>, +) -> Result { // api 先看:将来的 api 2 可能有这里不认识的字段,那时该说的是「版本不支持」 let api = match m.get("api") { None | Some(Value::Null) => return Err(err("the manifest needs `api: 1`")), @@ -174,10 +203,7 @@ pub(crate) fn parse( Some(Value::String(s)) if s == "stream" => ReplyMode::Stream, Some(_) => return Err(err("`reply` must be \"block\" or \"stream\"")), }; - let settings = settings(m.get("settings"), info.settings_order.as_deref())?; - - check_hooks(&hooks, &permissions, reply_mode)?; - check_requests(&requests, &permissions)?; + let settings = settings(m.get("settings"), settings_order)?; Ok(Manifest { name, @@ -189,10 +215,21 @@ pub(crate) fn parse( on_error, reply_mode, settings, - hooks, + hooks: Hooks::default(), }) } +/// 字段之间的约束。`hooks` 是编出来的那一份时,先核对钩子和权限一一对应、再填上;`None` +/// 是说不出来([`declared`]),钩子空着 +fn finish(mut m: Manifest, hooks: Option) -> Result { + if let Some(hooks) = hooks { + check_hooks(&hooks, &m.permissions, m.reply_mode)?; + m.hooks = hooks; + } + check_requests(&m.requests, &m.permissions)?; + Ok(m) +} + fn permissions(v: Option<&Value>) -> Result, LoadError> { let list = match v { Some(Value::Array(a)) => a, diff --git a/crates/tw-plugin/tests/loading.rs b/crates/tw-plugin/tests/loading.rs index 8d9ac6ae..f55476ed 100644 --- a/crates/tw-plugin/tests/loading.rs +++ b/crates/tw-plugin/tests/loading.rs @@ -442,6 +442,179 @@ fn requests_that_break_the_rules_are_load_errors() { } } +// ── 不编译、照源码读(`declared_manifest`)────────────────────────── + +/// 照源码读 manifest(停用的插件显示用的那一份)和编译认的是同一套规矩:编得过的,读出来 +/// 除了钩子一模一样;字段不合规矩的,两边报同一个错。只有编了才看得出来的(钩子和权限对不上、 +/// 模块别处的语法错、模块代码改了 manifest)照源码读得出来 —— 那一份只拿来显示 +#[test] +fn reading_the_manifest_without_compiling_follows_the_same_rules() { + let reply_end = "export function onReplyTextEnd() { return \"\"; }"; + let loads = [ + plugin( + r#"{ name: "合法", api: 1, permissions: ["system", "params"] }"#, + ON_REQUEST, + ), + plugin( + r#"{ + // 注释、多行、结尾的逗号 + name: " 全的 ", + api: 1, + description: "说明", + permissions: ["reply.text", "system", "messages"], + requests: ["embeddings", "conversation"], + match: { clients: ["codex"], models: ["claude-*"], upstreams: [] }, + on_error: "skip", + reply: "stream", + settings: { + zeta: { type: "string", label: " Z ", value: "今天" }, + alpha: { type: "number", value: 2.5 }, + mid: { type: "boolean", label: "", value: true }, + none: { type: "number", label: null, value: null }, + }, +}"#, + &format!("{ON_REQUEST}\n{ON_TEXT}\n{reply_end}"), + ), + format!( + "\u{feff}{}", + plugin( + r#"{ name: "x", api: 1, permissions: ["messages"], requests: ["completions"] }"#, + ON_REQUEST, + ) + ), + ]; + for src in &loads { + let compiled = load_source(src).manifest().clone(); + let read = tw_plugin::declared_manifest(src.as_bytes()) + .unwrap_or_else(|e| panic!("{src}\n=> {e:?}")); + assert_eq!(read.hooks, tw_plugin::Hooks::default(), "{src}"); + assert_eq!( + tw_plugin::Manifest { + hooks: compiled.hooks, + ..read + }, + compiled, + "{src}" + ); + } + + // 字段不合规矩:同一个错 + let fields_break: Vec = [ + r#"{ name: "x", api: 1, permissions: [] }"#.to_string(), + r#"{ name: "x", api: 1, permissions: ["system", "network"] }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system", "system"] }"#.into(), + r#"{ api: 1, permissions: ["system"] }"#.into(), + r#"{ name: " ", api: 1, permissions: ["system"] }"#.into(), + format!(r#"{{ name: "{}", api: 1, permissions: ["system"] }}"#, "名".repeat(65)), + format!( + r#"{{ name: "x", api: 1, description: "{}", permissions: ["system"] }}"#, + "述".repeat(501) + ), + r#"{ name: "x", api: 2, permissions: ["system"] }"#.into(), + r#"{ name: "x", api: "1", permissions: ["system"] }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], colour: "red" }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], on_error: "retry" }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], reply: "batch" }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], match: { models: "claude-*" } }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], match: { models: [" "] } }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], match: { hosts: [] } }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], settings: { a: { type: "file" } } }"# + .into(), + r#"{ name: "x", api: 1, permissions: ["system"], settings: { a: { type: "number", value: "八" } } }"# + .into(), + r#"{ name: "x", api: 1, permissions: ["system"], settings: { "1a": { type: "string" } } }"# + .into(), + r#"{ name: "x", api: 1, permissions: ["system"], settings: { a: { type: "string", hint: "h" } } }"# + .into(), + format!( + r#"{{ name: "x", api: 1, permissions: ["system"], settings: {{ {} }} }}"#, + (0..21) + .map(|i| format!(r#"s{i}: {{ type: "string" }}"#)) + .collect::>() + .join(", ") + ), + r#"{ name: "x", api: 1, permissions: ["messages"], requests: [] }"#.into(), + r#"{ name: "x", api: 1, permissions: ["messages"], requests: ["images"] }"#.into(), + r#"{ name: "x", api: 1, permissions: ["system"], requests: ["conversation", "embeddings"] }"# + .into(), + r#"{ name: "x", api: 1, permissions: ["system", "messages"], requests: ["completions"] }"# + .into(), + ] + .into(); + let mut cases: Vec> = fields_break + .iter() + .map(|m| plugin(m, ON_REQUEST).into_bytes()) + .collect(); + // 回答钩子只在对话上跑:钩子和权限对得上,错在 `requests` + cases.push( + plugin( + r#"{ name: "x", api: 1, permissions: ["messages", "reply.text"], requests: ["embeddings"] }"#, + &format!("{ON_REQUEST}\n{ON_TEXT}"), + ) + .into_bytes(), + ); + // 不是纯数据:说得出同一个位置 + cases.push( + format!( + "export const manifest = {{\n name: \"x\" + \"y\",\n api: 1,\n permissions: [\"system\"],\n}};\n{ON_REQUEST}\n" + ) + .into_bytes(), + ); + // 不是 UTF-8 + let mut not_utf8 = plugin( + r#"{ name: "x", api: 1, permissions: ["system"] }"#, + ON_REQUEST, + ) + .into_bytes(); + not_utf8.extend_from_slice(b"// \xff\xfe\n"); + cases.push(not_utf8); + for src in &cases { + let shown = String::from_utf8_lossy(src); + assert_eq!( + tw_plugin::declared_manifest(src), + Err(load_err(src)), + "{shown}" + ); + } + + // 只有编了才看得出来的:照源码读得出来 + let compile_only = [ + plugin(r#"{ name: "x", api: 1, permissions: ["system"] }"#, ""), + plugin(r#"{ name: "x", api: 1, permissions: ["system"] }"#, ON_TEXT), + plugin( + r#"{ name: "x", api: 1, permissions: ["system", "reply.text"] }"#, + ON_REQUEST, + ), + plugin( + r#"{ name: "x", api: 1, permissions: ["system"] }"#, + "export const onRequest = 42;", + ), + plugin( + r#"{ name: "x", api: 1, permissions: ["system"] }"#, + "export function onRequest(req) { return req +; }", + ), + plugin( + r#"{ name: "x", api: 1, permissions: ["system"] }"#, + &format!("manifest.permissions.push(\"params\");\n{ON_REQUEST}"), + ), + ]; + for src in &compile_only { + load_err(src.as_bytes()); + let read = tw_plugin::declared_manifest(src.as_bytes()) + .unwrap_or_else(|e| panic!("{src}\n=> {e:?}")); + assert_eq!(read.name, "x"); + assert_eq!( + read.permissions.len(), + src.matches("\"reply.text\"").count() + 1 + ); + } + + // 没有 manifest:两边都读不出来(说法不同:沙箱看得到导出了什么) + assert!(tw_plugin::declared_manifest(ON_REQUEST.as_bytes()).is_err()); + load_err(ON_REQUEST.as_bytes()); + still_fine(); +} + #[test] fn an_unsupported_api_version_is_named() { let e = load_err(