Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): validate session id path segment and dispose session creds on unexpected exit
Chrisf88c51ae0606
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRequest.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRequest.test.tsindex cc7d2f0afa..cb65081e0d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionRequest.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRequest.test.ts@@ -111,6 +111,33 @@ describe('session IPC request parsing', () => {expect(allocateDialogueWorkspace).not.toHaveBeenCalled();});+ it('rejects path-traversal ids for project sessions with an explicit workingDir (codex review)', () => {+ // 项目会话此前直接用 body.id 未校验;device-link 传 `../../..` 会经下游 path.join+ // 逃出 runtimeDir(如 Pi perm-<id>.json)覆盖任意文件。边界统一按安全单段值拒绝。+ for (const id of ['../../../../tmp/x', '..', 'a/b', 'a\\b', '.', 'foo/../bar']) {+ expect(() =>+ readCreateSessionOpts({+ agentKind: 'pi',+ workspaceKind: 'project',+ model: 'claude-sonnet-4-6',+ workingDir: '/repo',+ id,+ }),+ ).toThrow('[INVALID_PARAMS]');+ }+ });++ it('accepts a safe cuid-style id for a project session', () => {+ const opts = readCreateSessionOpts({+ agentKind: 'pi',+ workspaceKind: 'project',+ model: 'claude-sonnet-4-6',+ workingDir: '/repo',+ id: 'clh1a2b3c0000abcd1234wxyz',+ });+ expect(opts.id).toBe('clh1a2b3c0000abcd1234wxyz');+ });+it('still rejects project sessions without an explicit workingDir', () => {expect(() =>readCreateSessionOpts({diff --git a/apps/desktop/src/main/maker-ipc/sessionRequest.ts b/apps/desktop/src/main/maker-ipc/sessionRequest.tsindex 502ed488cc..c81e5de33f 100644--- a/apps/desktop/src/main/maker-ipc/sessionRequest.ts+++ b/apps/desktop/src/main/maker-ipc/sessionRequest.ts@@ -117,6 +117,12 @@ export function readCreateSessionOpts(const id = needsDialogueWorkspace? readDialogueSessionId(body.id, deps.createSessionId): body.id;+ // 外部(含 device-link)可控的 session id 会被下游拼进磁盘路径(如 Pi 权限档+ // perm-<id>.json)。未校验的 `../../..` 之类 id 经 path.join 逃出 runtimeDir,writeFile+ // 可覆盖任意可写文件(codex review)。在边界统一限制为安全单段值;缺省(自动生成)放行。+ if (typeof id === 'string' && id.length > 0 && !isSafePathSegment(id)) {+ throwIpcError('INVALID_PARAMS', 'session id must be a safe path segment');+ }const workingDir = needsDialogueWorkspace? deps.allocateDialogueWorkspace!(id as string,diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex c1dab0882d..266de99942 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -18,12 +18,19 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// hoisted 控制旋钮:vi.mock 工厂被提升到 import 之上,不能闭包引用普通 let。-const knobs = vi.hoisted(() => ({ ctorThrows: false, getStateRejects: false, closeCount: 0 }));+const knobs = vi.hoisted(() => ({+ ctorThrows: false,+ getStateRejects: false,+ closeCount: 0,+ onExit: null as null | ((info: { code: number | null; signal: string | null }) => void),+}));vi.mock('../rpc-client.js', () => ({PiRpcProcess: class {isClosed = false;- constructor(_opts: unknown) {+ constructor(opts: unknown) {+ // 捕获 onExit 以便单测模拟进程异常退出(crash)。+ knobs.onExit = (opts as { onExit?: typeof knobs.onExit } | undefined)?.onExit ?? null;if (knobs.ctorThrows) throw new Error('spawn failed (mock)');}async request(cmd: { type: string }): Promise<{ success: boolean; data?: unknown; error?: string }> {@@ -62,6 +69,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {knobs.ctorThrows = false;knobs.getStateRejects = false;knobs.closeCount = 0;+ knobs.onExit = null;disposed = 0;proxyDisposed = 0;agentHome = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-home-'));@@ -129,4 +137,34 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {expect(disposed).toBe(1); // close() 才注销expect(proxyDisposed).toBe(1);});++ it('disposes proxy token + MCP ctx when the pi process exits unexpectedly (crash), idempotent with close()', async () => {+ // codex review:崩溃时 onExit 只 end 队列、上层短路 close(),proxy token / MCP ctx+ // 会滞留内存被本地进程盗用。onExit 必须幂等注销这些注册。+ const agent = new PiAgent(buildDeps());+ const handle = await agent.startSession(opts());+ expect(disposed).toBe(0);+ expect(proxyDisposed).toBe(0);+ expect(knobs.onExit).toBeTypeOf('function');++ knobs.onExit!({ code: 1, signal: null }); // 模拟进程异常退出+ expect(disposed).toBe(1);+ expect(proxyDisposed).toBe(1);++ // 上层随后仍可能调用 close() —— 幂等,不得二次注销。+ await handle.close();+ expect(disposed).toBe(1);+ expect(proxyDisposed).toBe(1);+ });++ it('rejects a sessionId that would escape the runtime dir via the permission file path', async () => {+ // codex review:sessionId 拼进 perm-<id>.json;`../../..` 经 path.join 逃出 runtimeDir。+ const agent = new PiAgent(buildDeps());+ await expect(+ agent.startSession({ sessionId: '../../../../tmp/evil', workingDir: cwd, model: 'm' }),+ ).rejects.toThrow(/unsafe sessionId/);+ // 未注册任何东西 → 无泄漏。+ expect(disposed).toBe(0);+ expect(proxyDisposed).toBe(0);+ });});diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 0471f9f277..61b846ee31 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -476,9 +476,16 @@ export class PiAgent extends BaseAgent {// 权限档文件:extension 每次 tool_call 现读(热切换);读不到按 ask fail-closed。const runtimeDir = path.join(agentHome, 'runtime');await fs.mkdir(runtimeDir, { recursive: true });+ // 防御:sessionId 会拼进文件名,不能含路径分隔符 / 上级引用 —— 否则可逃出 runtimeDir+ // 覆盖任意文件(codex review)。IPC 边界已统一校验,这里对所有 startSession 调用方+ // (scheduler / orca / resume 等)再兜一层 fail-closed,与安全底线一致。+ const sid = opts.sessionId;+ if (sid !== undefined && (sid === '.' || sid === '..' || /[\\/\0]/.test(sid))) {+ throw new Error(`pi: unsafe sessionId for runtime path: ${JSON.stringify(sid)}`);+ }const permissionFile = path.join(runtimeDir,- `perm-${opts.sessionId ?? `anon-${process.pid}-${Date.now()}`}.json`,+ `perm-${sid ?? `anon-${process.pid}-${Date.now()}`}.json`,);// auto 保留(Cindy 侧 dispatcher 用);bridge 只特判 bypassPermissions,auto 在// 桥内行为同 ask(非只读全部冒泡)。其余档(default/acceptEdits/plan)归 ask 最严。@@ -625,7 +632,12 @@ export class PiAgent extends BaseAgent {let proc: PiRpcProcess;const proxySessionToken = randomBytes(32).toString('base64url');let disposeProxySession: (() => void) | undefined;+ // 幂等:onExit(进程异常退出)与 close()(用户结束)可能都调用它;首次注销后置位,+ // 后续调用直接返回,避免二次注销(codex review:crash 时须由 onExit 立即释放)。+ let sessionRegistrationsDisposed = false;const disposeSessionRegistrations = (): void => {+ if (sessionRegistrationsDisposed) return;+ sessionRegistrationsDisposed = true;let firstError: unknown;for (const dispose of [disposeProxySession, disposeSessionCtx]) {try {@@ -709,6 +721,16 @@ export class PiAgent extends BaseAgent {data: { message: `pi process exited unexpectedly (code=${code}, signal=${signal})`, isTerminal: true },source: 'pi',});+ // 崩溃/被杀:上层见迭代器结束即把 session 标 closed,close() 随后短路,+ // proxy token 与 MCP session ctx 会滞留 Main 内存直到重启 —— 期间任何本地+ // 进程仍可拿旧 token 经 loopback 代理盗用宿主凭证(codex review)。在此幂等注销。+ try {+ disposeSessionRegistrations();+ } catch (err) {+ this.deps.logger.warn('pi dispose on unexpected exit failed (non-fatal)', {+ message: err instanceof Error ? err.message : String(err),+ });+ }}queue.end();},