diff --git a/packages/core/src/persistent-pty/index.ts b/packages/core/src/persistent-pty/index.ts index 780880fb252..90c0014de64 100644 --- a/packages/core/src/persistent-pty/index.ts +++ b/packages/core/src/persistent-pty/index.ts @@ -1,5 +1,6 @@ export * as PersistentPty from "./index.js" +import { stat } from "node:fs/promises" import path from "node:path" import { Context, Effect, Layer, Schema } from "effect" import { makeGlobalNode } from "@opencode/util/effect/app-node" @@ -57,6 +58,11 @@ export class NotFoundError extends Schema.TaggedError()("Persiste ptyID: Pty.ID, }) {} +export class InvalidCwdError extends Schema.TaggedError()("PersistentPty.InvalidCwdError", { + cwd: Schema.String, + message: Schema.String, +}) {} + export interface Interface { readonly list: (sessionID?: Session.ID) => Effect.Effect readonly get: (id: Pty.ID) => Effect.Effect @@ -71,7 +77,7 @@ export interface Interface { readonly cols?: number readonly rows?: number }, - ) => Effect.Effect + ) => Effect.Effect readonly write: ( id: Pty.ID, data: string, @@ -158,13 +164,22 @@ const makeLayer = (options: Options = {}) => sessionID: Session.ID, input: Parameters[1], ) { + const cwd = path.resolve(input.cwd ?? "/") + // opencode-pty's PTY library silently falls back to $HOME when the cwd is not a directory. + const directory = yield* Effect.promise(() => + stat(cwd).then( + (info) => info.isDirectory(), + () => false, + ), + ) + if (!directory) return yield* new InvalidCwdError({ cwd, message: `cwd is not a directory: ${cwd}` }) const response = yield* request( daemon, { op: "create", program: input.command ?? ShellSelect.environment(global.bin), args: input.args, - cwd: input.cwd ?? path.resolve("/"), + cwd, title: input.title, group_id: sessionID, env: input.env, diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index 0b40b2cd013..b3a2d0802b0 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -1,6 +1,11 @@ import { PersistentPty } from "@opencode/core/persistent-pty" import { PtyTicket } from "@opencode/core/pty/ticket" -import { ForbiddenError, PtyNotFoundError, ServiceUnavailableError } from "@opencode/protocol/errors" +import { + ForbiddenError, + InvalidRequestError, + PtyNotFoundError, + ServiceUnavailableError, +} from "@opencode/protocol/errors" import { PTY_CONNECT_TICKET_QUERY, PTY_CONNECT_TOKEN_HEADER, @@ -58,7 +63,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment cols: ctx.payload.size?.cols, rows: ctx.payload.size?.rows, }) - .pipe(Effect.catchTag("PersistentPty.UnavailableError", unavailable)), + .pipe( + Effect.catchTags({ + "PersistentPty.InvalidCwdError": (error) => + new InvalidRequestError({ message: error.message, kind: "invalid_cwd", field: "cwd" }), + "PersistentPty.UnavailableError": unavailable, + }), + ), } }), ) diff --git a/packages/server/test/persistent-pty.test.ts b/packages/server/test/persistent-pty.test.ts index 1f8b31ae9a8..0ecfe5c2d07 100644 --- a/packages/server/test/persistent-pty.test.ts +++ b/packages/server/test/persistent-pty.test.ts @@ -141,6 +141,55 @@ async function waitForRead(client: ReturnType, sessionID: throw new Error(`Terminal ${ptyID} did not become current for ${sessionID}`) } +smoke( + "rejects a cwd that is missing or not a directory without starting a shell", + () => + Effect.gen(function* () { + const fixture = yield* testDirectory() + const server = yield* ServerProcess.start({ + hostname: "127.0.0.1", + port: 0, + password: "secret", + app: { version: "test-version" }, + database: { path: fixture.database }, + pty: { root: fixture.directory }, + fs: { filewatcher: false }, + }) + const base = HttpServer.formatAddress(server.address) + const createPath = "/api/experimental/session/ses_invalid_cwd/terminal" + const file = path.join(fixture.root, "file.txt") + yield* Effect.promise(() => fs.writeFile(file, "")) + for (const cwd of [path.join(fixture.root, "missing"), file]) { + const response = yield* Effect.promise(async () => { + const response = await fetch(new URL(createPath, base), { + method: "POST", + headers: { authorization: `Basic ${btoa("opencode:secret")}`, "content-type": "application/json" }, + body: JSON.stringify({ command: "/bin/sh", args: [], cwd, title: "invalid", env: {} }), + }) + return { status: response.status, body: await response.json() } + }) + expect(response).toEqual({ + status: 400, + body: { + _tag: "InvalidRequestError", + message: `cwd is not a directory: ${cwd}`, + kind: "invalid_cwd", + field: "cwd", + }, + }) + } + // The daemon is never started, so no shell can have been spawned. + expect(existsSync(fixture.directory)).toBeFalse() + expect((yield* request(base, "GET", createPath)).data).toEqual([]) + const valid = { command: "/bin/sh", args: [], cwd: fixture.root, title: "valid", env: {} } + const created = yield* request(base, "POST", createPath, valid) + const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(created.data) + expect(terminal.cwd).toBe(fixture.root) + yield* request(base, "POST", "/api/experimental/persistent-pty/shutdown") + }), + 20_000, +) + smoke( "creates two persistent terminals for one session through the client API", () =>