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 collide after sanitizing
zszz3e2e1105addde
diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rsindex 28e6f6c6f..99a378f7b 100644--- a/crates/host-core/src/plugins/manifest.rs+++ b/crates/host-core/src/plugins/manifest.rs@@ -57,6 +57,7 @@ impl PluginManager {if manifest.id.trim().is_empty() || manifest.main.trim().is_empty() {bail!("PLUGIN_INVALID: id/main required");}+ validate_plugin_id(&manifest.id)?;if manifest.name.trim().is_empty() || manifest.version.trim().is_empty() {bail!("PLUGIN_INVALID: name/version required");}@@ -78,6 +79,21 @@ impl PluginManager {}}+/// A plugin id names the plugin's install directory, data directory, log+/// file, and browser session partition. Each of those maps characters+/// 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.+fn validate_plugin_id(id: &str) -> Result<()> {+ let allowed = id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));+ if !allowed || id == "." || id == ".." {+ bail!("PLUGIN_INVALID: id may only contain letters, digits, '.', '-' and '_'");+ }+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -120,4 +136,55 @@ mod tests {fs::write(dir.path().join("ui/index.html"), "<!doctype html>").unwrap();assert!(PluginManager::read_manifest(dir.path()).is_ok());}++ fn read_with_id(id: &str) -> Result<PluginManifest> {+ let dir = tempdir().unwrap();+ let mut manifest = base();+ manifest["id"] = json!(id);+ write_manifest(dir.path(), manifest);+ fs::write(dir.path().join("main.js"), "export function onLoad() {}").unwrap();+ PluginManager::read_manifest(dir.path())+ }++ #[test]+ fn ids_that_would_share_a_directory_or_partition_are_rejected() {+ for id in ["foo!bar", "foo/bar", "foo bar", "插件", "..", "."] {+ let error = read_with_id(id).unwrap_err();+ assert_eq!(+ error.to_string(),+ "PLUGIN_INVALID: id may only contain letters, digits, '.', '-' and '_'",+ "{id}"+ );+ }+ for id in [+ "foo_bar",+ "pi.browser",+ "io.github.b1eight.pi-desktop-claude-theme",+ "a..b",+ ] {+ assert_eq!(read_with_id(id).unwrap().id, id);+ }+ }++ #[test]+ fn every_accepted_id_keeps_its_own_install_and_data_directory() {+ let dir = tempdir().unwrap();+ let manager = PluginManager::new(dir.path(), MarketChannel::Official, None);+ let accepted: Vec<String> = ["foo_bar", "foo!bar", "foo/bar", "foo-bar", "foo.bar"]+ .into_iter()+ .filter_map(|id| read_with_id(id).ok().map(|m| m.id))+ .collect();+ assert_eq!(accepted, ["foo_bar", "foo-bar", "foo.bar"]);+ let installed: std::collections::HashSet<_> = accepted+ .iter()+ .map(|id| manager.installed_dir(id))+ .collect();+ let data: std::collections::HashSet<_> =+ accepted.iter().map(|id| manager.data_dir_for(id)).collect();+ assert_eq!(installed.len(), accepted.len());+ assert_eq!(data.len(), accepted.len());+ for path in installed {+ assert!(path.starts_with(dir.path().join("plugins/installed")));+ }+ }}diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 1d4aceb69..c3cb2d27a 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4209,6 +4209,14 @@ this does not claim an installed full-app settings journey.- **Milestone**: M4- **Status**: Automated (protocol smoke: plugins.loadDev)+#### 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).+- **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`+#### E2E-022A: Create a plugin from a template- **Preconditions**: App running; an empty folder available.diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex a781e2466..d165cad25 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -632,7 +632,12 @@ 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+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 §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 a8b5aca7a..5f7a5ceb5 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,7 +576,10 @@ OAuth 贡献使用宿主管理的服务商账号界面。`onProviderOAuth` 处## 7. 验证规则1. `schemaVersion` 必填且必须是数字。当前格式为 `1`,但不会校验具体取值-2. 需要 `id` / `name` / `version` / `main`+2. 需要 `id` / `name` / `version` / `main`。安装和加载时,`id` 含+ `[A-Za-z0-9._-]` 以外的字符或等于 `.` / `..` 会被拒绝: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/package.json b/package.jsonindex 3fb3e1852..31b6ee9f4 100644--- a/package.json+++ b/package.json@@ -104,6 +104,7 @@"test:e2e:plugin-fetch-redirect": "node --test apps/desktop/test/plugin-fetch-redirect.test.mjs","test:e2e:plugin-command-ownership": "node --test --test-timeout=60000 apps/desktop/test/plugin-command-ownership.test.mjs","test:e2e:plugin-projects": "node scripts/e2e-plugin-projects.mjs",+ "test:e2e:plugin-id-collision": "node scripts/e2e-plugin-id-collision.mjs","test:e2e:plugin-import-deps": "node scripts/e2e-plugin-import-deps.mjs","test:e2e:trusted-extensions": "node scripts/e2e-trusted-extensions.mjs","test:e2e:plugin-ui-slots": "node scripts/e2e-plugin-ui-slots.mjs",diff --git a/packages/plugin-devkit/src/check.ts b/packages/plugin-devkit/src/check.tsindex 070b6a60f..0253dedc1 100644--- a/packages/plugin-devkit/src/check.ts+++ b/packages/plugin-devkit/src/check.ts@@ -159,6 +159,10 @@ async function fileExists(path: string): Promise<boolean> {}}+function invalidIdMessage(id: string): string {+ return `manifest.id "${id}" must be a lowercase dotted id such as "acme.notes" (${PLUGIN_ID_PATTERN.source})`;+}+/*** Validate a plugin directory against every rule host-core enforces at install* time, so a clean `check` means `install` will not reject the package.@@ -195,6 +199,12 @@ 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.+ 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));+ }return fail("manifest.invalid", validated.error ?? "manifest is invalid");}const manifest = validated.manifest;@@ -202,7 +212,7 @@ export async function check(dirInput: string): Promise<CheckResult> {if (!PLUGIN_ID_PATTERN.test(manifest.id)) {errors.push({code: "manifest.invalid-id",- message: `manifest.id "${manifest.id}" must be a lowercase dotted id such as "acme.notes" (${PLUGIN_ID_PATTERN.source})`,+ message: invalidIdMessage(manifest.id),});}diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex 309ed8be8..c7980eef1 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -85,6 +85,18 @@ describe("validateManifest", () => {expect(result.ok).toBe(true);});+ it("rejects ids that would share another plugin's directory or partition", () => {+ for (const id of ["foo!bar", "foo/bar", "foo bar", "插件", ".", ".."]) {+ expect(validateManifest({ ...base, id })).toEqual({+ ok: false,+ 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 }).ok).toBe(true);+ }+ });+it("accepts enabledByDefault as a boolean", () => {expect(validateManifest({ ...base, enabledByDefault: false }).ok).toBe(true);expect(validateManifest({ ...base, enabledByDefault: "no" }).error).toMatch(diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex bcd527426..88300cb5b 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -1756,6 +1756,15 @@ export function validateManifest(raw: unknown): {if (typeof m.id !== "string" || !m.id) {return { ok: false, error: "manifest.id is required" };}+ // The id names the plugin's install and data directories and its browser+ // session partition, which map any other character to `_`; only these+ // characters keep two plugins apart (the host enforces the same rule).+ if (!/^[A-Za-z0-9._-]+$/.test(m.id) || m.id === "." || m.id === "..") {+ return {+ ok: false,+ error: "manifest.id may only contain letters, digits, '.', '-' and '_'",+ };+ }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.mjsnew file mode 100644index 000000000..32504825c--- /dev/null+++ b/scripts/e2e-plugin-id-collision.mjs@@ -0,0 +1,71 @@+#!/usr/bin/env node+/**+ * E2E-PLUGIN-id-cannot-collide — two plugins whose ids differ only in+ * characters the host maps to `_` must not share an install directory, data+ * 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.+ */+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++const hostBinary = resolveHostBinary();+const scratch = await realpath(await mkdtemp(join(tmpdir(), "pi-plugin-id-collision-")));+const dataDir = join(scratch, "data");++async function writePlugin(dir, id, marker) {+ await mkdir(dir, { recursive: true });+ await writeFile(+ join(dir, "manifest.json"),+ JSON.stringify({ schemaVersion: 1, id, name: marker, version: "1.0.0", main: "main.js" }),+ );+ await writeFile(join(dir, "main.js"), `// ${marker}\nexport function onLoad() {}\n`);+}++const host = new Host(hostBinary, dataDir, { quiet: true });+try {+ await host.start();++ const first = join(scratch, "src-first");+ await writePlugin(first, "e2e.foo_bar", "first plugin");+ await host.call("plugins.installFromPath", { path: first, enable: true });+ const installedMain = join(dataDir, "plugins/installed/e2e.foo_bar/main.js");+ const dataMarker = join(dataDir, "plugins/data/e2e.foo_bar/owner.txt");+ 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 }],+ ]) {+ 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`,+ );+ }++ assert.match(await readFile(installedMain, "utf8"), /first plugin/, "first plugin's files stay its own");+ assert.equal(await readFile(dataMarker, "utf8"), "first plugin data", "first plugin's data stays its own");+ assert.deepEqual(await readdir(join(dataDir, "plugins/installed")), ["e2e.foo_bar"]);+ const { plugins } = await host.call("plugins.list", {});+ 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");+} finally {+ await host.stop().catch(() => {});+ await rm(scratch, { recursive: true, force: true });+}