From 21b1681474f51d5c76f714255aea5fe143dcaaf2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 10 Feb 2026 11:52:08 +0000 Subject: [PATCH] Validate critical renderer RPC payloads before resolving responses Co-authored-by: Theo Browne --- apps/renderer/src/wsNativeApi.test.ts | 103 +++++++++++++ apps/renderer/src/wsNativeApi.ts | 209 +++++++++++++++++++------- packages/contracts/src/ipc.test.ts | 67 +++++++++ packages/contracts/src/ipc.ts | 34 +++-- packages/contracts/src/provider.ts | 2 + 5 files changed, 343 insertions(+), 72 deletions(-) create mode 100644 packages/contracts/src/ipc.test.ts diff --git a/apps/renderer/src/wsNativeApi.test.ts b/apps/renderer/src/wsNativeApi.test.ts index d2932e2ad5..9486ef93bd 100644 --- a/apps/renderer/src/wsNativeApi.test.ts +++ b/apps/renderer/src/wsNativeApi.test.ts @@ -431,6 +431,34 @@ describe("wsNativeApi", () => { }); }); + it("rejects app.health responses with invalid payload shape", async () => { + setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4521"); + const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); + const api = getOrCreateWsNativeApi(); + + const request = api.app.health(); + const socket = MockWebSocket.instances[0]; + await waitForCondition(() => (socket?.sentMessages.length ?? 0) > 0); + const requestEnvelope = JSON.parse(socket?.sentMessages[0] ?? "{}") as { id: string }; + socket?.emitMessage( + JSON.stringify({ + type: "response", + id: requestEnvelope.id, + ok: true, + result: { + status: "ok", + launchCwd: "/workspace", + sessionCount: -1, + activeClientConnected: true, + }, + }), + ); + + await expect(request).rejects.toThrow( + "Runtime method 'app.health' returned invalid response payload.", + ); + }); + it("sends app.bootstrap requests and returns payload", async () => { setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4412"); const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); @@ -1605,6 +1633,29 @@ describe("wsNativeApi", () => { await expect(request).resolves.toBe("/workspace"); }); + it("rejects dialogs.pickFolder responses with invalid payload shape", async () => { + setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4522"); + const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); + const api = getOrCreateWsNativeApi(); + + const request = api.dialogs.pickFolder(); + const socket = MockWebSocket.instances[0]; + await waitForCondition(() => (socket?.sentMessages.length ?? 0) > 0); + const requestEnvelope = JSON.parse(socket?.sentMessages[0] ?? "{}") as { id: string }; + socket?.emitMessage( + JSON.stringify({ + type: "response", + id: requestEnvelope.id, + ok: true, + result: 123, + }), + ); + + await expect(request).rejects.toThrow( + "Runtime method 'dialogs.pickFolder' returned invalid response payload.", + ); + }); + it("sends providers.listSessions requests and resolves payload", async () => { setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4415"); const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); @@ -1646,6 +1697,33 @@ describe("wsNativeApi", () => { ]); }); + it("rejects providers.listSessions responses with invalid payload shape", async () => { + setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4523"); + const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); + const api = getOrCreateWsNativeApi(); + + const request = api.providers.listSessions(); + const socket = MockWebSocket.instances[0]; + await waitForCondition(() => (socket?.sentMessages.length ?? 0) > 0); + const requestEnvelope = JSON.parse(socket?.sentMessages[0] ?? "{}") as { id: string }; + socket?.emitMessage( + JSON.stringify({ + type: "response", + id: requestEnvelope.id, + ok: true, + result: [ + { + sessionId: "", + }, + ], + }), + ); + + await expect(request).rejects.toThrow( + "Runtime method 'providers.listSessions' returned invalid response payload.", + ); + }); + it("sends provider turn-control requests with expected payloads", async () => { setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4419"); const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); @@ -1977,6 +2055,31 @@ describe("wsNativeApi", () => { await expect(killRequest).resolves.toBeUndefined(); }); + it("rejects void method responses that do not return null", async () => { + setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4524"); + const { getOrCreateWsNativeApi } = await import("./wsNativeApi"); + const api = getOrCreateWsNativeApi(); + + const request = api.agent.kill("agent-session-1"); + const socket = await waitForSocket(); + await waitForCondition(() => (socket?.sentMessages.length ?? 0) > 0); + const requestEnvelope = JSON.parse(socket?.sentMessages[0] ?? "{}") as { id: string }; + socket?.emitMessage( + JSON.stringify({ + type: "response", + id: requestEnvelope.id, + ok: true, + result: { + unexpected: true, + }, + }), + ); + + await expect(request).rejects.toThrow( + "Runtime method 'agent.kill' returned invalid response payload.", + ); + }); + it("rejects requests when websocket connection fails", async () => { setWindowSearch("?ws=ws%3A%2F%2F127.0.0.1%3A4405"); MockWebSocket.failOpen = true; diff --git a/apps/renderer/src/wsNativeApi.ts b/apps/renderer/src/wsNativeApi.ts index 6a35074581..0ab755e22e 100644 --- a/apps/renderer/src/wsNativeApi.ts +++ b/apps/renderer/src/wsNativeApi.ts @@ -1,21 +1,26 @@ import type { AppBootstrapResult, AppHealthResult, + AgentExit, NativeApi, + OutputChunk, ProviderEvent, WsClientMessage, WsEventMessage, WsResponseMessage, - OutputChunk, - AgentExit, } from "@acme/contracts"; import { WS_CLOSE_CODES, WS_CLOSE_REASONS, WS_EVENT_CHANNELS, + agentSessionIdSchema, agentExitSchema, outputChunkSchema, + providerSessionSchema, + providerTurnStartResultSchema, providerEventSchema, + terminalCommandResultSchema, + todoListSchema, wsServerMessageSchema, } from "@acme/contracts"; @@ -26,6 +31,10 @@ type PendingRequest = { }; type SubscriptionSet = Set<(value: TValue) => void>; +type SafeParseResult = { success: true; data: TValue } | { success: false }; +type SchemaLike = { + safeParse: (value: unknown) => SafeParseResult; +}; const REQUEST_TIMEOUT_MS = 30_000; const MAX_NESTED_ERROR_EXTRACTION_DEPTH = 8; const textDecoder = new TextDecoder(); @@ -162,6 +171,10 @@ function normalizeCloseCode(value: unknown) { return value; } +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + class WsNativeApiClient { private socket: WebSocket | null = null; private connectPromise: Promise | null = null; @@ -328,6 +341,119 @@ class WsNativeApiClient { return requestPromise; } + private async requestParsed( + method: string, + schema: SchemaLike, + params?: unknown, + ): Promise { + const value = await this.request(method, params); + const parsed = schema.safeParse(value); + if (!parsed.success) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + return parsed.data; + } + + private async requestNullResult(method: string, params?: unknown): Promise { + const value = await this.request(method, params); + if (value !== null) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + } + + private parseAppHealthResult(method: string, value: unknown): AppHealthResult { + if (!isRecord(value)) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + const launchCwd = value.launchCwd; + const sessionCount = value.sessionCount; + const activeClientConnected = value.activeClientConnected; + if ( + value.status !== "ok" || + typeof launchCwd !== "string" || + launchCwd.length === 0 || + typeof sessionCount !== "number" || + !Number.isInteger(sessionCount) || + sessionCount < 0 || + typeof activeClientConnected !== "boolean" + ) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + const normalizedSessionCount = sessionCount as number; + + return { + status: "ok", + launchCwd, + sessionCount: normalizedSessionCount, + activeClientConnected, + }; + } + + private parseAppBootstrapResult(method: string, value: unknown): AppBootstrapResult { + if (!isRecord(value)) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + + const launchCwd = value.launchCwd; + const projectName = value.projectName; + const provider = value.provider; + const model = value.model; + const bootstrapError = value.bootstrapError; + const parsedSession = providerSessionSchema.safeParse(value.session); + if ( + !parsedSession.success || + typeof launchCwd !== "string" || + launchCwd.length === 0 || + typeof projectName !== "string" || + projectName.length === 0 || + typeof model !== "string" || + model.length === 0 || + (bootstrapError !== undefined && + (typeof bootstrapError !== "string" || bootstrapError.length === 0)) + ) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + if (provider !== "codex" && provider !== "claudeCode") { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + const normalizedProvider = provider as AppBootstrapResult["provider"]; + + const baseResult = { + launchCwd, + projectName, + provider: normalizedProvider, + model, + session: parsedSession.data, + }; + if (bootstrapError !== undefined) { + return { + ...baseResult, + bootstrapError, + }; + } + + return baseResult; + } + + private parseProviderSessionList( + method: string, + value: unknown, + ): Awaited> { + if (!Array.isArray(value)) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + + const parsedSessions: Awaited> = []; + for (const session of value) { + const parsedSession = providerSessionSchema.safeParse(session); + if (!parsedSession.success) { + throw new Error(`Runtime method '${method}' returned invalid response payload.`); + } + parsedSessions.push(parsedSession.data); + } + return parsedSessions; + } + private handleResponse(message: WsResponseMessage) { const pending = this.pending.get(message.id); if (!pending) { @@ -434,48 +560,31 @@ class WsNativeApiClient { asNativeApi(): NativeApi { return { app: { - bootstrap: async () => - this.request("app.bootstrap").then((value) => value as AppBootstrapResult), - health: async () => - this.request("app.health").then((value) => value as AppHealthResult), + bootstrap: async () => this.parseAppBootstrapResult("app.bootstrap", await this.request("app.bootstrap")), + health: async () => this.parseAppHealthResult("app.health", await this.request("app.health")), }, todos: { - list: async () => - this.request("todos.list").then( - (value) => value as Awaited>, - ), - add: async (input) => - this.request("todos.add", input).then( - (value) => value as Awaited>, - ), - toggle: async (id) => - this.request("todos.toggle", id).then( - (value) => value as Awaited>, - ), - remove: async (id) => - this.request("todos.remove", id).then( - (value) => value as Awaited>, - ), + list: async () => this.requestParsed("todos.list", todoListSchema), + add: async (input) => this.requestParsed("todos.add", todoListSchema, input), + toggle: async (id) => this.requestParsed("todos.toggle", todoListSchema, id), + remove: async (id) => this.requestParsed("todos.remove", todoListSchema, id), }, dialogs: { - pickFolder: async () => - this.request("dialogs.pickFolder").then((value) => value as string | null), + pickFolder: async () => { + const value = await this.request("dialogs.pickFolder"); + if (value === null || typeof value === "string") { + return value; + } + throw new Error("Runtime method 'dialogs.pickFolder' returned invalid response payload."); + }, }, terminal: { - run: async (input) => - this.request("terminal.run", input).then( - (value) => value as Awaited>, - ), + run: async (input) => this.requestParsed("terminal.run", terminalCommandResultSchema, input), }, agent: { - spawn: async (config) => - this.request("agent.spawn", config).then((value) => value as string), - kill: async (sessionId) => { - await this.request("agent.kill", sessionId); - }, - write: async (sessionId, data) => { - await this.request("agent.write", { sessionId, data }); - }, + spawn: async (config) => this.requestParsed("agent.spawn", agentSessionIdSchema, config), + kill: async (sessionId) => this.requestNullResult("agent.kill", sessionId), + write: async (sessionId, data) => this.requestNullResult("agent.write", { sessionId, data }), onOutput: (callback) => { this.agentOutputListeners.add(callback); return () => { @@ -491,26 +600,14 @@ class WsNativeApiClient { }, providers: { startSession: async (input) => - this.request("providers.startSession", input).then( - (value) => value as Awaited>, - ), + this.requestParsed("providers.startSession", providerSessionSchema, input), sendTurn: async (input) => - this.request("providers.sendTurn", input).then( - (value) => value as Awaited>, - ), - interruptTurn: async (input) => { - await this.request("providers.interruptTurn", input); - }, - respondToRequest: async (input) => { - await this.request("providers.respondToRequest", input); - }, - stopSession: async (input) => { - await this.request("providers.stopSession", input); - }, + this.requestParsed("providers.sendTurn", providerTurnStartResultSchema, input), + interruptTurn: async (input) => this.requestNullResult("providers.interruptTurn", input), + respondToRequest: async (input) => this.requestNullResult("providers.respondToRequest", input), + stopSession: async (input) => this.requestNullResult("providers.stopSession", input), listSessions: async () => - this.request("providers.listSessions").then( - (value) => value as Awaited>, - ), + this.parseProviderSessionList("providers.listSessions", await this.request("providers.listSessions")), onEvent: (callback) => { this.providerEventListeners.add(callback); return () => { @@ -519,9 +616,7 @@ class WsNativeApiClient { }, }, shell: { - openInEditor: async (cwd, editor) => { - await this.request("shell.openInEditor", { cwd, editor }); - }, + openInEditor: async (cwd, editor) => this.requestNullResult("shell.openInEditor", { cwd, editor }), }, }; } diff --git a/packages/contracts/src/ipc.test.ts b/packages/contracts/src/ipc.test.ts new file mode 100644 index 0000000000..0dd1fe28a6 --- /dev/null +++ b/packages/contracts/src/ipc.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; + +import { appBootstrapResultSchema, appHealthResultSchema } from "./ipc"; + +describe("appBootstrapResultSchema", () => { + it("accepts valid bootstrap payloads", () => { + const parsed = appBootstrapResultSchema.parse({ + launchCwd: "/workspace", + projectName: "workspace", + provider: "codex", + model: "gpt-5-codex", + session: { + sessionId: "sess-1", + provider: "codex", + status: "ready", + cwd: "/workspace", + model: "gpt-5-codex", + createdAt: "2026-02-01T00:00:00.000Z", + updatedAt: "2026-02-01T00:00:00.000Z", + }, + }); + + expect(parsed.provider).toBe("codex"); + }); + + it("rejects invalid bootstrap payloads", () => { + expect(() => + appBootstrapResultSchema.parse({ + launchCwd: "/workspace", + projectName: "", + provider: "codex", + model: "gpt-5-codex", + session: { + sessionId: "sess-1", + provider: "codex", + status: "ready", + createdAt: "2026-02-01T00:00:00.000Z", + updatedAt: "2026-02-01T00:00:00.000Z", + }, + }), + ).toThrow(); + }); +}); + +describe("appHealthResultSchema", () => { + it("accepts valid health payloads", () => { + const parsed = appHealthResultSchema.parse({ + status: "ok", + launchCwd: "/workspace", + sessionCount: 2, + activeClientConnected: true, + }); + + expect(parsed.status).toBe("ok"); + }); + + it("rejects invalid health payloads", () => { + expect(() => + appHealthResultSchema.parse({ + status: "ok", + launchCwd: "/workspace", + sessionCount: -1, + activeClientConnected: true, + }), + ).toThrow(); + }); +}); diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 5b1b75def0..ae115971a2 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1,7 +1,8 @@ +import { z } from "zod"; import type { AgentConfig, AgentExit, OutputChunk } from "./agent"; +import { providerKindSchema, providerSessionSchema } from "./provider"; import type { ProviderEvent, - ProviderKind, ProviderInterruptTurnInput, ProviderRespondToRequestInput, ProviderSendTurnInput, @@ -20,21 +21,24 @@ export const EDITORS = [ export type EditorId = (typeof EDITORS)[number]["id"]; -export interface AppBootstrapResult { - launchCwd: string; - projectName: string; - provider: ProviderKind; - model: string; - session: ProviderSession; - bootstrapError?: string; -} +export const appBootstrapResultSchema = z.object({ + launchCwd: z.string().min(1), + projectName: z.string().min(1), + provider: providerKindSchema, + model: z.string().min(1), + session: providerSessionSchema, + bootstrapError: z.string().min(1).optional(), +}); -export interface AppHealthResult { - status: "ok"; - launchCwd: string; - sessionCount: number; - activeClientConnected: boolean; -} +export const appHealthResultSchema = z.object({ + status: z.literal("ok"), + launchCwd: z.string().min(1), + sessionCount: z.number().int().min(0), + activeClientConnected: z.boolean(), +}); + +export type AppBootstrapResult = z.infer; +export type AppHealthResult = z.infer; export interface NativeApi { app: { diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index b31e8f04e5..f8e31fd59e 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -45,6 +45,8 @@ export const providerSessionSchema = z.object({ lastError: z.string().min(1).optional(), }); +export const providerSessionListSchema = z.array(providerSessionSchema); + export const providerSessionStartInputSchema = z.object({ provider: providerKindSchema.default("codex"), cwd: z.string().min(1).optional(),