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): pass HOME/USER into plugin child processes
vastsa21621a35d00c
diff --git a/apps/desktop/electron/main/child-process-env.ts b/apps/desktop/electron/main/child-process-env.tsnew file mode 100644index 000000000..c91d69577--- /dev/null+++ b/apps/desktop/electron/main/child-process-env.ts@@ -0,0 +1,64 @@+/**+ * The environment a restricted child process is allowed to inherit.+ *+ * Not the host's `process.env`: that carries provider keys and shell secrets a+ * plugin has no business reading (ADR 0008, `07-plugins/04-plugin-security.md`+ * §11.7). The list below is closed on purpose, and every entry has to earn its+ * place.+ *+ * `HOME` / `USER` / `USERPROFILE` earn theirs because the consumer is not only+ * the plugin: a plugin that spawns a third-party binary hands this environment+ * to code we do not own, and that code resolves `~` through `$HOME` rather than+ * calling `os.homedir()` (issue #717). Without an identity variable it falls+ * back to `TMPDIR`, looks for its state somewhere that never exists, and fails+ * as `runtime exited (1)` — an error the user cannot act on. Forwarding the+ * value crosses no boundary the plugin cannot already cross itself: it can read+ * the same path from `os.homedir()` (the `getpwuid` fallback), so this only+ * stops plugin authors from having to restore it by hand in every plugin.+ *+ * `USERPROFILE` is the Windows counterpart, and is what shipped plugins already+ * probe for.+ */++/**+ * `PATH` is here so a bare command name stays findable. A caller that needs the+ * login-shell PATH instead (ADR 0045) overrides it after the fact.+ */+const INHERITED_ENV_KEYS = [+ "PATH",+ "SystemRoot",+ "windir",+ "TEMP",+ "TMP",+ "TMPDIR",+ "LANG",+ "HOME",+ "USER",+ "USERPROFILE",+] as const;++/**+ * The host variables that may cross into a plugin-owned child process.+ *+ * A variable the host does not have stays absent rather than being written as+ * an empty string: `HOME=""` is worse than no `HOME` at all, because a binary+ * that would otherwise fall back to `getpwuid` resolves `~` against the working+ * directory instead.+ */+export function minimalChildEnv(): Record<string, string> {+ const env: Record<string, string> = {};+ for (const key of INHERITED_ENV_KEYS) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** The environment of a plugin's own utility process: minimal, plus its identity. */+export function pluginChildEnv(pluginId: string): Record<string, string> {+ return {+ ...minimalChildEnv(),+ PI_PLUGIN_ID: pluginId,+ NODE_ENV: process.env.NODE_ENV ?? "production",+ };+}diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.tsindex c4c3615f3..c622190ed 100644--- a/apps/desktop/electron/main/plugin-mcp.ts+++ b/apps/desktop/electron/main/plugin-mcp.ts@@ -1,6 +1,7 @@import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";import { isAbsolute, resolve, sep } from "node:path";import type { PluginMcpServerContrib } from "@pi-desktop/plugin-sdk";+import { minimalChildEnv } from "./child-process-env.ts";import { userLookupPath } from "./user-login-path.ts";/** MCP revision we advertise during the handshake. */@@ -71,7 +72,9 @@ function mcpError(code: string, message: string): McpError {* plugin identity to announce.** PATH is the login-shell PATH (ADR 0045 / D600), not the Finder/Dock GUI- * PATH, so a market-installed `uvx`/`npx` server can spawn (issue #571).+ * PATH, so a market-installed `uvx`/`npx` server can spawn (issue #571). The+ * identity variables cross for the same reason the toolchain ones do: the child+ * is third-party code that resolves `~` through `$HOME` (issue #717).*/export function mcpProcessEnv(pluginId: string | undefined,@@ -80,11 +83,8 @@ export function mcpProcessEnv(const env: Record<string, string> = {...(pluginId ? { PI_PLUGIN_ID: pluginId } : {}),NODE_ENV: process.env.NODE_ENV ?? "production",+ ...minimalChildEnv(),};- for (const key of ["SystemRoot", "windir", "TEMP", "TMP", "TMPDIR", "LANG"]) {- const value = process.env[key];- if (value) env[key] = value;- }const path = userLookupPath(process.env.PATH ?? "");if (path) env.PATH = path;return { ...env, ...values };diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 2861a6460..a84f30d7e 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -77,6 +77,7 @@ import {resolveRealPathWithinRoot,resolveWithinRoot,} from "@pi-desktop/host-runtime";+import { pluginChildEnv } from "./child-process-env";import { desktopDataDir } from "./data-paths";import { McpServerClient, type McpServerClientOptions } from "./plugin-mcp";import { PluginToolInvocations, type PluginToolInvocation } from "./plugin-tool-invocations";@@ -1154,29 +1155,13 @@ function resolveWindowBackground(return result.light || result.dark ? result : undefined;}-/**- * Minimal environment for a plugin process: the host's own env may carry- * provider keys and shell secrets, and plugins have no business seeing them.- */-function pluginProcessEnv(pluginId: string): Record<string, string> {- const env: Record<string, string> = {- PI_PLUGIN_ID: pluginId,- NODE_ENV: process.env.NODE_ENV ?? "production",- };- for (const key of ["PATH", "SystemRoot", "windir", "TEMP", "TMP", "TMPDIR", "LANG"]) {- const value = process.env[key];- if (value) env[key] = value;- }- return env;-}-/** Default spawner: an Electron utilityProcess per plugin. */const spawnUtilityProcess: PluginProcessSpawner = async ({ pluginId, entry }) => {const { utilityProcess } = await import("electron");const child = utilityProcess.fork(entry, [], {serviceName: `pi-plugin-${pluginId.replace(/[^a-zA-Z0-9._-]/g, "_")}`,stdio: "pipe",- env: pluginProcessEnv(pluginId),+ env: pluginChildEnv(pluginId),});return {postMessage: (message) => child.postMessage(message),diff --git a/apps/desktop/test/plugin-child-env.test.mjs b/apps/desktop/test/plugin-child-env.test.mjsnew file mode 100644index 000000000..131ed647f--- /dev/null+++ b/apps/desktop/test/plugin-child-env.test.mjs@@ -0,0 +1,94 @@+import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { minimalChildEnv, pluginChildEnv } from "../electron/main/child-process-env.ts";+import { mcpProcessEnv } from "../electron/main/plugin-mcp.ts";++const here = dirname(fileURLToPath(import.meta.url));+const desktopRoot = join(here, "..");++/** Run `fn` with `patch` applied to `process.env`, restoring the host's values after. */+function withHostEnv(patch, fn) {+ const saved = new Map();+ for (const [key, value] of Object.entries(patch)) {+ saved.set(key, process.env[key]);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ try {+ return fn();+ } finally {+ for (const [key, value] of saved) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+}++test("a plugin process carries the identity a spawned binary resolves ~ with", () => {+ withHostEnv({ HOME: "/tmp/pi-home", USER: "pi-user", USERPROFILE: "/tmp/pi-home" }, () => {+ const env = pluginChildEnv("com.example.plugin");+ assert.equal(env.HOME, "/tmp/pi-home");+ assert.equal(env.USER, "pi-user");+ assert.equal(env.USERPROFILE, "/tmp/pi-home");+ assert.equal(env.PI_PLUGIN_ID, "com.example.plugin");+ // PATH still crosses, or a bare command name could never be found.+ assert.ok(typeof env.PATH === "string" && env.PATH.length > 0);+ });+});++test("a variable the host does not have stays absent instead of empty", () => {+ withHostEnv({ HOME: undefined, USER: undefined, USERPROFILE: undefined }, () => {+ const env = pluginChildEnv("com.example.plugin");+ // `HOME=""` is worse than no HOME: a binary that would fall back to getpwuid+ // resolves `~` against the working directory instead.+ assert.equal("HOME" in env, false);+ assert.equal("USER" in env, false);+ assert.equal("USERPROFILE" in env, false);+ });+ withHostEnv({ HOME: "" }, () => {+ assert.equal("HOME" in minimalChildEnv(), false);+ });+});++test("the child environment stays closed to host secrets", () => {+ withHostEnv({ PI_TEST_SECRET: "must-not-cross", OPENAI_API_KEY: "sk-must-not-cross" }, () => {+ const envs = [+ pluginChildEnv("com.example.plugin"),+ mcpProcessEnv("com.example.plugin", {}),+ ];+ for (const env of envs) {+ assert.equal(env.PI_TEST_SECRET, undefined);+ assert.equal(env.OPENAI_API_KEY, undefined);+ }+ });+});++test("a stdio MCP server gets the same identity, and declared values still win", () => {+ withHostEnv({ HOME: "/tmp/pi-home" }, () => {+ const env = mcpProcessEnv("com.example.plugin", { TOKEN: "t0ken" });+ assert.equal(env.HOME, "/tmp/pi-home");+ assert.equal(env.TOKEN, "t0ken");+ assert.equal(env.PI_PLUGIN_ID, "com.example.plugin");+ });+ // A plugin-declared value is the caller's explicit choice (D018), so it wins.+ withHostEnv({ HOME: "/tmp/pi-home" }, () => {+ assert.equal(mcpProcessEnv("com.example.plugin", { HOME: "/tmp/declared" }).HOME, "/tmp/declared");+ });+});++test("both plugin child environments are built from the one allowlist", () => {+ const runtimeSrc = readFileSync(join(desktopRoot, "electron/main/plugin-runtime.ts"), "utf8");+ const mcpSrc = readFileSync(join(desktopRoot, "electron/main/plugin-mcp.ts"), "utf8");+ const envSrc = readFileSync(join(desktopRoot, "electron/main/child-process-env.ts"), "utf8");+ assert.match(runtimeSrc, /env: pluginChildEnv\(pluginId\)/);+ assert.match(mcpSrc, /\.\.\.minimalChildEnv\(\)/);+ // A second private allowlist is how the identity variables went missing once.+ assert.doesNotMatch(runtimeSrc, /pluginProcessEnv/);+ assert.doesNotMatch(mcpSrc, /for \(const key of \["SystemRoot"/);+ assert.doesNotMatch(runtimeSrc, /for \(const key of \["PATH"/);+ assert.match(envSrc, /"HOME",\s*\n\s*"USER",\s*\n\s*"USERPROFILE",/);+});diff --git a/docs/adr/0008-plugin-runtime-isolation-target.md b/docs/adr/0008-plugin-runtime-isolation-target.mdindex f466a1828..0ba60e4a4 100644--- a/docs/adr/0008-plugin-runtime-isolation-target.md+++ b/docs/adr/0008-plugin-runtime-isolation-target.md@@ -40,8 +40,10 @@ The target architecture shipped; no transitional in-main runtime remains.- `apps/desktop/electron/main/plugin-host-process.mjs` is the per-plugin entry,forked with `utilityProcess.fork` (one process per plugin, bundled to- `out/main/plugin-host-process.js`). It receives a minimal environment, so the- host's shell env and provider keys never reach plugin code.+ `out/main/plugin-host-process.js`). It receives a minimal environment from+ `pluginChildEnv` (`child-process-env.ts`): `PATH`, toolchain dirs, `HOME` /+ `USER` / `USERPROFILE`, plus `PI_PLUGIN_ID` and `NODE_ENV`. The host's other+ shell env and provider keys never reach plugin code (issue #717).- `apps/desktop/electron/main/plugin-runtime.ts` became the broker: it keeps theregistry of commands/tools, and every `pi.*` call arrives as RPC, passes`HOST_API_ALLOWLIST`, then `assertPermission`, then the host service, then thediff --git a/docs/diagrams/plugin-architecture.html b/docs/diagrams/plugin-architecture.htmlindex d1afc7a78..2bfa92444 100644--- a/docs/diagrams/plugin-architecture.html+++ b/docs/diagrams/plugin-architecture.html@@ -372,8 +372,8 @@</button><button class="node" style="--tint: var(--child)" data-node="env"><span class="node-name">最小环境</span>- <span class="node-desc">只透传 PATH/TEMP/LANG 等;宿主 env 里的 provider key 与 shell 密钥不进插件</span>- <span class="node-meta">pluginProcessEnv()</span>+ <span class="node-desc">透传 PATH/TEMP/LANG/HOME/USER/USERPROFILE;宿主 env 里的 provider key 与 shell 密钥不进插件</span>+ <span class="node-meta">pluginChildEnv()</span></button></div></section>@@ -748,8 +748,8 @@ const DETAILS = {"子进程持 run/execute 函数,宿主只持描述符 + 一个回打过去的代理","宿主注册失败时子进程回滚本地 Map,两侧不会不一致","工具名在宿主侧改成 plugin_<id>_<tool>,插件内部仍用原名"]],- "env": ["最小环境", "pluginProcessEnv()", [- "只注入 PI_PLUGIN_ID、NODE_ENV,以及 PATH / SystemRoot / windir / TEMP / TMP / TMPDIR / LANG",+ "env": ["最小环境", "pluginChildEnv()", [+ "只注入 PI_PLUGIN_ID、NODE_ENV,以及 PATH / SystemRoot / windir / TEMP / TMP / TMPDIR / LANG / HOME / USER / USERPROFILE","宿主 env 里可能带 provider key 与 shell 密钥,插件没有理由看到","serviceName 形如 pi-plugin-<sanitized-id>,便于在活动监视器里定位"]],"tools-expose": ["工具暴露", "pluginToolName() · D015", [diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.mdindex 23a28de4d..254122ee9 100644--- a/docs/spec/07-plugins/04-plugin-security.md+++ b/docs/spec/07-plugins/04-plugin-security.md@@ -347,8 +347,13 @@ manifest did not name:- `transport: "stdio"` spawns a local executable (`mcp.server.local`). The`command` must be a bare PATH name or a plugin-relative path; absolute paths- are refused at validation time. The child gets a minimal environment — only- the declared `env` entries plus what the host needs to run a process.+ are refused at validation time. The child gets a minimal environment — the+ declared `env` entries plus one shared allowlist (`child-process-env.ts`):+ `PATH`, `SystemRoot`, `windir`, `TEMP`, `TMP`, `TMPDIR`, `LANG`, `HOME`,+ `USER`, `USERPROFILE`. The identity variables are there because the child is+ third-party code that resolves `~` through `$HOME` rather than calling+ `os.homedir()` (issue #717); provider keys and other host state still never+ cross.- `transport: "http"` reaches a remote endpoint (`mcp.server.remote`). The `url`may use `http` or `https`; non-loopback HTTP is unencrypted and should only beused on a trusted network. Plugin endpoints must also be covered by@@ -473,8 +478,10 @@ Current enforcement:5. Marketplace/package install requires explicit permission acceptance in UI6. Auto-update refuses silent permission expansion7. Plugin main runs in a dedicated `utilityProcess` per plugin (ADR 0008) with a- minimal environment; all `pi.*` calls cross an allowlist + permission gateway- in the host, and a plugin crash only tears down that plugin+ minimal environment from the shared `child-process-env.ts` allowlist (PATH,+ toolchain dirs, `HOME` / `USER` / `USERPROFILE`; no provider keys); all+ `pi.*` calls cross an allowlist + permission gateway in the host, and a+ plugin crash only tears down that plugin8. Contributed theme CSS is sanitized in the main process before it reaches therenderer (§3.1)9. Bus routing is host-owned with declared topics and hard caps (§5.1)diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.mdindex 98b6fda66..b137d01a6 100644--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md@@ -270,8 +270,11 @@ MCP 服务器是 `net.fetch` 旁边的第二个出口路径,因此它是声明- `transport: "stdio"` 生成本地可执行文件 (`mcp.server.local`)。的`command` 必须是裸路径名称或插件相对路径;绝对路径- 在验证时被拒绝。孩子得到的环境是最小的——只有- 声明的 `env` 条目加上主机运行进程所需的内容。+ 在验证时被拒绝。子进程拿到的是最小环境——声明的 `env` 条目,加上共享+ 白名单(`child-process-env.ts`):`PATH`、`SystemRoot`、`windir`、`TEMP`、+ `TMP`、`TMPDIR`、`LANG`、`HOME`、`USER`、`USERPROFILE`。身份变量要透传,+ 是因为子进程是第三方代码,用 `$HOME` 解析 `~` 而不是调用 `os.homedir()`+ (issue #717);provider key 和其它宿主状态仍然不会穿越。- `transport: "http"` 到达远程端点 (`mcp.server.remote`)。`url` 可以使用`http` 或 `https`;非回环 HTTP 不加密,只应在可信网络中使用。插件端点还必须被 `manifest.net.domains` 覆盖。工具参数会离开机器,这就是为什么权限@@ -377,8 +380,9 @@ PI-Desktop 自己当前占用(默认是 `Alt+Space` 与 `Alt+Shift+W`;用户4. 插件仍然无法访问 Secrets/host DB5. Marketplace/package 安装需要在 UI 中明确接受权限6.自动更新拒绝静默权限扩展-7. 插件主程序在每个插件专用的 `utilityProcess` (ADR 0008) 中运行,并带有- 最小环境;所有 `pi.*` 调用都跨越白名单 + 权限网关+7. 插件主程序在每个插件专用的 `utilityProcess` (ADR 0008) 中运行,环境来自+ 共享白名单 `child-process-env.ts`(PATH、工具链目录、`HOME` / `USER` /+ `USERPROFILE`,不含 provider key);所有 `pi.*` 调用都跨越白名单 + 权限网关在主机中,插件崩溃只会破坏该插件8. 贡献的主题 CSS 在到达主进程之前会在主进程中进行清理渲染器(§3.1)