Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(plugins): refuse plugin ids that alias another plugin's directory
zszz3c01177006d14
diff --git a/crates/host-core/src/plugins/install.rs b/crates/host-core/src/plugins/install.rsindex 3587ddc88..c758388aa 100644--- a/crates/host-core/src/plugins/install.rs+++ b/crates/host-core/src/plugins/install.rs@@ -40,6 +40,7 @@ impl PluginManager {};let manifest = Self::read_manifest(&extracted_root)?;+ self.ensure_storage_identity_free(&manifest.id)?;let existing = self.get(&manifest.id);let upgraded = existing.as_ref()diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rsindex 99a378f7b..f27d9cfaa 100644--- a/crates/host-core/src/plugins/manifest.rs+++ b/crates/host-core/src/plugins/manifest.rs@@ -84,6 +84,10 @@ impl PluginManager {/// outside `[A-Za-z0-9._-]` to `_`, so only ids already made of those/// characters keep distinct plugins in distinct places, and `.` / `..`/// would name a parent or current directory instead of the plugin's own.+/// Windows also drops a trailing `.` from a path segment and resolves+/// device names (`con`, `nul.x`, ...) to devices, so those ids could not+/// name a directory of their own either. Ids that differ only in letter+/// case are a registry-level conflict, see `ensure_storage_identity_free`.fn validate_plugin_id(id: &str) -> Result<()> {let allowed = id.chars()@@ -91,6 +95,17 @@ fn validate_plugin_id(id: &str) -> Result<()> {if !allowed || id == "." || id == ".." {bail!("PLUGIN_INVALID: id may only contain letters, digits, '.', '-' and '_'");}+ if id.ends_with('.') {+ bail!("PLUGIN_INVALID: id must not end with '.'");+ }+ let stem = id.split('.').next().unwrap_or(id).to_ascii_lowercase();+ let reserved = matches!(stem.as_str(), "con" | "prn" | "aux" | "nul")+ || ((stem.starts_with("com") || stem.starts_with("lpt"))+ && stem.len() == 4+ && matches!(stem.as_bytes()[3], b'1'..=b'9'));+ if reserved {+ bail!("PLUGIN_INVALID: id must not start with a Windows device name");+ }Ok(())}@@ -156,11 +171,31 @@ mod tests {"{id}");}+ for (id, message) in [+ ("e2e.foo.", "PLUGIN_INVALID: id must not end with '.'"),+ (+ "con",+ "PLUGIN_INVALID: id must not start with a Windows device name",+ ),+ (+ "NUL.plugin",+ "PLUGIN_INVALID: id must not start with a Windows device name",+ ),+ (+ "com1.x",+ "PLUGIN_INVALID: id must not start with a Windows device name",+ ),+ ] {+ assert_eq!(read_with_id(id).unwrap_err().to_string(), message, "{id}");+ }for id in ["foo_bar","pi.browser","io.github.b1eight.pi-desktop-claude-theme","a..b",+ "console.tools",+ "com.example.x",+ "com10.x",] {assert_eq!(read_with_id(id).unwrap().id, id);}diff --git a/crates/host-core/src/plugins/registry.rs b/crates/host-core/src/plugins/registry.rsindex 6e9e7598a..0b2566caf 100644--- a/crates/host-core/src/plugins/registry.rs+++ b/crates/host-core/src/plugins/registry.rs@@ -224,6 +224,25 @@ impl PluginManager {.collect()}+ /// Refuses an id that differs from a registered plugin's id only in+ /// letter case. Case-insensitive file systems (macOS and Windows+ /// defaults) resolve both to the same install and data directory, so the+ /// newcomer would overwrite the other plugin's files. Existing rows and+ /// directories keep their names; only the new id is refused.+ pub(crate) fn ensure_storage_identity_free(&self, id: &str) -> Result<()> {+ if let Some(other) = self+ .runtime+ .iter()+ .find(|p| p.id != id && p.id.eq_ignore_ascii_case(id))+ {+ bail!(+ "PLUGIN_INVALID: id {id} differs from installed plugin {} only in letter case",+ other.id+ );+ }+ Ok(())+ }+pub fn get(&self, id: &str) -> Option<PluginSummary> {self.runtime.iter()@@ -300,6 +319,7 @@ impl PluginManager {pub fn load_dev(&mut self, plugin_path: &str) -> Result<PluginSummary> {let path = PathBuf::from(plugin_path);let manifest = Self::read_manifest(&path)?;+ self.ensure_storage_identity_free(&manifest.id)?;let now = Utc::now().to_rfc3339();let summary = PluginSummary {id: manifest.id.clone(),diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rsindex 2e76cfbfe..27d7f357a 100644--- a/crates/host-core/src/plugins/tests.rs+++ b/crates/host-core/src/plugins/tests.rs@@ -2584,3 +2584,67 @@ fn plugin_ui_meta_parses_the_floating_widget_placement() {assert!(panel.always_on_top.is_none());assert!(panel.resizable.is_none());}++fn write_id_plugin(root: &Path, id: &str, marker: &str) {+ fs::create_dir_all(root).unwrap();+ fs::write(+ root.join("manifest.json"),+ json!({ "schemaVersion": 1, "id": id, "name": marker, "version": "1.0.0", "main": "main.js" })+ .to_string(),+ )+ .unwrap();+ fs::write(root.join("main.js"), format!("// {marker}\n")).unwrap();+}++fn local_install(source: &str) -> InstallOptions {+ InstallOptions {+ source: source.into(),+ enable: true,+ marketplace: None,+ expected_shasum: None,+ auto_update: false,+ granted_permissions: None,+ }+}++#[test]+fn an_id_differing_only_in_case_cannot_take_over_an_installed_plugin() {+ let dir = tempdir().unwrap();+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);+ let first = dir.path().join("src-first");+ write_id_plugin(&first, "e2e.foo", "first");+ mgr.install_from_path(first.to_str().unwrap(), local_install("installed"))+ .unwrap();+ let installed_main = mgr.installed_dir("e2e.foo").join("main.js");+ fs::write(mgr.data_dir_for("e2e.foo").join("owner.txt"), "first data").unwrap();++ let second = dir.path().join("src-second");+ write_id_plugin(&second, "e2e.Foo", "second");+ let install = mgr+ .install_from_path(second.to_str().unwrap(), local_install("installed"))+ .unwrap_err();+ let dev = mgr.load_dev(second.to_str().unwrap()).unwrap_err();+ for error in [install, dev] {+ assert_eq!(+ error.to_string(),+ "PLUGIN_INVALID: id e2e.Foo differs from installed plugin e2e.foo only in letter case"+ );+ }++ assert_eq!(fs::read_to_string(installed_main).unwrap(), "// first\n");+ assert_eq!(+ fs::read_to_string(mgr.data_dir_for("e2e.foo").join("owner.txt")).unwrap(),+ "first data"+ );+ let ids: Vec<_> = mgr+ .list()+ .into_iter()+ .map(|plugin| plugin.id)+ .filter(|id| id.starts_with("e2e."))+ .collect();+ assert_eq!(ids, ["e2e.foo"]);++ // Reinstalling the same id is still an ordinary upgrade.+ mgr.install_from_path(first.to_str().unwrap(), local_install("installed"))+ .unwrap();+}diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c3cb2d27a..f1d02c6ff 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4212,8 +4212,8 @@ this does not claim an installed full-app settings journey.#### E2E-PLUGIN-id-cannot-collide: Plugins with look-alike ids never share storage- **Preconditions**: Real host-core binary on a scratch data directory.-- **Steps**: 1) Install a plugin with id `e2e.foo_bar` from a local folder and write a file into its data directory. 2) Try to install, then to load as a development plugin, a second plugin with id `e2e.foo!bar`.-- **Expected**: Both attempts fail with `PLUGIN_INVALID` (ids may only use `[A-Za-z0-9._-]`, and not `.` / `..`). The first plugin's installed files, data directory, and registry row are unchanged, and no second install directory appears, so the two can never share a directory or browser session partition (issue #2297).+- **Steps**: 1) Install a plugin with id `e2e.foo_bar` from a local folder and write a file into its data directory. 2) For each look-alike id `e2e.foo!bar` (character replacement), `e2e.Foo_Bar` (letter case on case-insensitive file systems) and `e2e.foo_bar.` (Windows trailing dot), try to install it, then to load it as a development plugin.+- **Expected**: Every attempt fails with `PLUGIN_INVALID` naming the reason. The first plugin's installed files, data directory, and registry row are unchanged, and no second install directory appears, so two plugins can never share a directory or browser session partition (issue #2297).- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md` §7- **Status**: Automated (`pnpm test:e2e:plugin-id-collision`, `scripts/e2e-plugin-id-collision.mjs`); unit coverage in `crates/host-core/src/plugins/manifest.rs` and `packages/plugin-sdk/src/index.test.ts`diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex d165cad25..cfa7e51c9 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -632,12 +632,16 @@ the oldest host you claim. Export `onLoad` / `onUnload` from `main`; there is no1. `schemaVersion` is required and must be a number. The current format is `1`;the value itself is not checked-2. `id` / `name` / `version` / `main` are required. The installer and loader- reject an `id` with characters outside `[A-Za-z0-9._-]` or equal to `.` /- `..`: the id names the plugin's install and data directories and its- browser session partition, and each of those maps every other character to- `_`, so such ids could share another plugin's files, storage, and network- policy. `pi-plugin check` still asks for the stricter shape in §1+2. `id` / `name` / `version` / `main` are required. The id names the+ plugin's install and data directories and its browser session partition,+ so the installer and loader refuse ids that could resolve to another+ plugin's directory and share its files, storage, and network policy:+ characters outside `[A-Za-z0-9._-]` (each of those locations maps them to+ `_`), `.` / `..`, a trailing `.` or a leading Windows device name (`con`,+ `nul.x`, ...), and an id that differs from an installed or development+ plugin's id only in letter case (case-insensitive file systems resolve both+ to one directory). Existing plugins keep their ids and directories.+ `pi-plugin check` still asks for the stricter shape in §13. Opening `ui.panel` requires the explicit declared and granted `ui.panel`permission; a panel path does not implicitly grant it4. If `agentTools` are present, `agent.tool.register` must be declared.diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.mdindex 5f7a5ceb5..3510d2291 100644--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md@@ -576,10 +576,12 @@ OAuth 贡献使用宿主管理的服务商账号界面。`onProviderOAuth` 处## 7. 验证规则1. `schemaVersion` 必填且必须是数字。当前格式为 `1`,但不会校验具体取值-2. 需要 `id` / `name` / `version` / `main`。安装和加载时,`id` 含- `[A-Za-z0-9._-]` 以外的字符或等于 `.` / `..` 会被拒绝:id 决定插件的安装目录、- 数据目录和浏览器会话分区,这些位置都会把其他字符替换为 `_`,这样的 id 可能与另一个- 插件共用文件、存储和网络策略。`pi-plugin check` 仍要求 §1 中更严格的格式+2. 需要 `id` / `name` / `version` / `main`。id 决定插件的安装目录、数据目录和浏览器+ 会话分区,因此安装和加载时会拒绝可能落到另一个插件目录、与其共用文件、存储和网络策略+ 的 id:含 `[A-Za-z0-9._-]` 以外的字符(这些位置都会把它们替换为 `_`)、等于 `.` /+ `..`、以 `.` 结尾或以 Windows 设备名开头(`con`、`nul.x` 等),以及与已安装或开发中+ 插件的 id 仅大小写不同(不区分大小写的文件系统会把两者解析到同一目录)。已有插件的+ id 和目录保持不变。`pi-plugin check` 仍要求 §1 中更严格的格式3. 打开 `ui.panel` 需要显式声明和用户授予 `ui.panel`,路径不会隐式授权4. 如果存在 `agentTools`,则必须声明 `agent.tool.register`。缺少该权限时`pi-plugin check` 报错(`permission.tools-missing`),安装器不会拒绝,diff --git a/packages/plugin-devkit/src/check.test.ts b/packages/plugin-devkit/src/check.test.tsindex 33303ac64..8e76dccbf 100644--- a/packages/plugin-devkit/src/check.test.ts+++ b/packages/plugin-devkit/src/check.test.ts@@ -100,6 +100,19 @@ describe("check", () => {expect(result.errors.map((e) => e.code)).toContain("manifest.invalid-id");});+ it("rejects a dotted id the installer refuses, with the installer's reason", async () => {+ const dir = join(await tempDir(), "deviceid");+ await scaffold({ dir, template: "panel-basic" });+ await editManifest(dir, (m) => {+ m.id = "nul.plugin";+ });+ const result = await check(dir);+ expect(result.ok).toBe(false);+ expect(result.errors).toEqual([+ { code: "manifest.invalid-id", message: "manifest.id must not start with a Windows device name" },+ ]);+ });+it("fails a manifest.renderer entry that does not exist, as the installer does (#1464)", async () => {const dir = join(await tempDir(), "renderer-entry");await scaffold({ dir, template: "panel-basic" });diff --git a/packages/plugin-devkit/src/check.ts b/packages/plugin-devkit/src/check.tsindex 0253dedc1..e72600929 100644--- a/packages/plugin-devkit/src/check.ts+++ b/packages/plugin-devkit/src/check.ts@@ -199,11 +199,14 @@ export async function check(dirInput: string): Promise<CheckResult> {const validated = validateManifest(parsed);if (!validated.ok || !validated.manifest) {- // An id the installer refuses also breaks the schema shape; keep the- // devkit's own code and hint for it.+ // Report an id the installer refuses under the devkit's own code, with+ // the schema-shape hint when the id breaks that shape too.const id = (parsed as { id?: unknown } | null)?.id;- if (validated.error?.startsWith("manifest.id may only") && typeof id === "string") {- return fail("manifest.invalid-id", invalidIdMessage(id));+ if (validated.error?.startsWith("manifest.id ") && typeof id === "string" && id) {+ return fail(+ "manifest.invalid-id",+ PLUGIN_ID_PATTERN.test(id) ? validated.error : invalidIdMessage(id),+ );}return fail("manifest.invalid", validated.error ?? "manifest is invalid");}diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex c7980eef1..15e3aae4b 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -92,7 +92,21 @@ describe("validateManifest", () => {error: "manifest.id may only contain letters, digits, '.', '-' and '_'",});}- for (const id of ["foo_bar", "pi.browser", "io.github.b1eight.pi-desktop-claude-theme", "a..b"]) {+ expect(validateManifest({ ...base, id: "e2e.foo." }).error).toBe("manifest.id must not end with '.'");+ for (const id of ["con", "NUL.plugin", "com1.x"]) {+ expect(validateManifest({ ...base, id }).error).toBe(+ "manifest.id must not start with a Windows device name",+ );+ }+ for (const id of [+ "foo_bar",+ "pi.browser",+ "io.github.b1eight.pi-desktop-claude-theme",+ "a..b",+ "console.tools",+ "com.example.x",+ "com10.x",+ ]) {expect(validateManifest({ ...base, id }).ok).toBe(true);}});diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex 88300cb5b..00614c4d1 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -1765,6 +1765,14 @@ export function validateManifest(raw: unknown): {error: "manifest.id may only contain letters, digits, '.', '-' and '_'",};}+ // Windows drops a trailing `.` and maps device names to devices, so such+ // ids cannot name a directory of their own.+ if (m.id.endsWith(".")) {+ return { ok: false, error: "manifest.id must not end with '.'" };+ }+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(m.id)) {+ return { ok: false, error: "manifest.id must not start with a Windows device name" };+ }if (typeof m.name !== "string" || !m.name) {return { ok: false, error: "manifest.name is required" };}diff --git a/scripts/e2e-plugin-id-collision.mjs b/scripts/e2e-plugin-id-collision.mjsindex 32504825c..8fa5959b3 100644--- a/scripts/e2e-plugin-id-collision.mjs+++ b/scripts/e2e-plugin-id-collision.mjs@@ -5,10 +5,10 @@* directory, or browser session partition (issue #2297).** Runs the real host-core binary against a scratch data directory: installs- * `e2e.foo_bar`, then tries to install `e2e.foo!bar` and to load it as a- * development plugin. The second plugin must be refused with PLUGIN_INVALID,- * and the first plugin's installed files, data directory, and registry row- * must be untouched.+ * `e2e.foo_bar`, then tries to install and to load as a development plugin+ * `e2e.foo!bar`, `e2e.Foo_Bar` and `e2e.foo_bar.`. Each must be refused with+ * PLUGIN_INVALID, and the first plugin's installed files, data directory,+ * and registry row must be untouched.*/import assert from "node:assert/strict";import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";@@ -29,6 +29,7 @@ async function writePlugin(dir, id, marker) {await writeFile(join(dir, "main.js"), `// ${marker}\nexport function onLoad() {}\n`);}+const attempts = [];const host = new Host(hostBinary, dataDir, { quiet: true });try {await host.start();@@ -41,20 +42,30 @@ try {assert.match(await readFile(installedMain, "utf8"), /first plugin/);await writeFile(dataMarker, "first plugin data");- const second = join(scratch, "src-second");- await writePlugin(second, "e2e.foo!bar", "second plugin");- for (const [method, params] of [- ["plugins.installFromPath", { path: second, enable: true }],- ["plugins.loadDev", { path: second }],+ // Each look-alike id would resolve to the first plugin's directory: by+ // character replacement, by letter case on case-insensitive file systems+ // (macOS / Windows defaults), or by Windows dropping a trailing dot.+ for (const [lookAlike, reason] of [+ ["e2e.foo!bar", /PLUGIN_INVALID: id may only contain/],+ ["e2e.Foo_Bar", /PLUGIN_INVALID: id e2e\.Foo_Bar differs from installed plugin e2e\.foo_bar only in letter case/],+ ["e2e.foo_bar.", /PLUGIN_INVALID: id must not end with '\.'/],]) {- await assert.rejects(- host.call(method, params),- (error) => {- assert.match(String(error.message), /PLUGIN_INVALID: id may only contain/);- return true;- },- `${method} must refuse an id that maps onto another plugin's directory`,- );+ const second = join(scratch, `src-${attempts.length}`);+ attempts.push(lookAlike);+ await writePlugin(second, lookAlike, "second plugin");+ for (const [method, params] of [+ ["plugins.installFromPath", { path: second, enable: true }],+ ["plugins.loadDev", { path: second }],+ ]) {+ await assert.rejects(+ host.call(method, params),+ (error) => {+ assert.match(String(error.message), reason);+ return true;+ },+ `${method} must refuse ${lookAlike}, which maps onto another plugin's directory`,+ );+ }}assert.match(await readFile(installedMain, "utf8"), /first plugin/, "first plugin's files stay its own");@@ -64,7 +75,7 @@ try {const ids = plugins.map((plugin) => plugin.id).filter((id) => id.startsWith("e2e."));assert.deepEqual(ids, ["e2e.foo_bar"]);- console.log("PASS: a plugin id that maps onto another plugin's directory is refused");+ console.log("PASS: plugin ids that map onto another plugin's directory are refused");} finally {await host.stop().catch(() => {});await rm(scratch, { recursive: true, force: true });