fix(core): reject persistent terminals with a missing cwd (#60300)

This commit is contained in:
James Long 2026-10-29 13:09:36 -04:00 • committed by GitHub
parent ccd406b00f
commit 756f832902
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 79 additions and 4 deletions

View file

@ -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<NotFoundError>()("Persiste
ptyID: Pty.ID,
}) {}
export class InvalidCwdError extends Schema.TaggedError<InvalidCwdError>()("PersistentPty.InvalidCwdError", {
cwd: Schema.String,
message: Schema.String,
}) {}
export interface Interface {
readonly list: (sessionID?: Session.ID) => Effect.Effect<Info[], UnavailableError>
readonly get: (id: Pty.ID) => Effect.Effect<Info, NotFoundError | UnavailableError>
@ -71,7 +77,7 @@ export interface Interface {
readonly cols?: number
readonly rows?: number
},
) => Effect.Effect<Info, UnavailableError>
) => Effect.Effect<Info, InvalidCwdError | UnavailableError>
readonly write: (
id: Pty.ID,
data: string,
@ -158,13 +164,22 @@ const makeLayer = (options: Options = {}) =>
sessionID: Session.ID,
input: Parameters<Interface["create"]>[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,

View file

@ -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,
}),
),
}
}),
)

View file

@ -141,6 +141,55 @@ async function waitForRead(client: ReturnType<typeof OpenCode.make>, 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<never, never>({
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",
() =>