Skip to content

Commit 756f832

Browse files
authored
fix(core): reject persistent terminals with a missing cwd (#60300)
1 parent ccd406b commit 756f832

3 files changed

Lines changed: 79 additions & 4 deletions

File tree

‎packages/core/src/persistent-pty/index.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export * as PersistentPty from "./index.js"
22

3+
import { stat } from "node:fs/promises"
34
import path from "node:path"
45
import { Context, Effect, Layer, Schema } from "effect"
56
import { makeGlobalNode } from "@opencode/util/effect/app-node"
@@ -57,6 +58,11 @@ export class NotFoundError extends Schema.TaggedError<NotFoundError>()("Persiste
5758
ptyID: Pty.ID,
5859
}) {}
5960

61+
export class InvalidCwdError extends Schema.TaggedError<InvalidCwdError>()("PersistentPty.InvalidCwdError", {
62+
cwd: Schema.String,
63+
message: Schema.String,
64+
}) {}
65+
6066
export interface Interface {
6167
readonly list: (sessionID?: Session.ID) => Effect.Effect<Info[], UnavailableError>
6268
readonly get: (id: Pty.ID) => Effect.Effect<Info, NotFoundError | UnavailableError>
@@ -71,7 +77,7 @@ export interface Interface {
7177
readonly cols?: number
7278
readonly rows?: number
7379
},
74-
) => Effect.Effect<Info, UnavailableError>
80+
) => Effect.Effect<Info, InvalidCwdError | UnavailableError>
7581
readonly write: (
7682
id: Pty.ID,
7783
data: string,
@@ -158,13 +164,22 @@ const makeLayer = (options: Options = {}) =>
158164
sessionID: Session.ID,
159165
input: Parameters<Interface["create"]>[1],
160166
) {
167+
const cwd = path.resolve(input.cwd ?? "/")
168+
// opencode-pty's PTY library silently falls back to $HOME when the cwd is not a directory.
169+
const directory = yield* Effect.promise(() =>
170+
stat(cwd).then(
171+
(info) => info.isDirectory(),
172+
() => false,
173+
),
174+
)
175+
if (!directory) return yield* new InvalidCwdError({ cwd, message: `cwd is not a directory: ${cwd}` })
161176
const response = yield* request(
162177
daemon,
163178
{
164179
op: "create",
165180
program: input.command ?? ShellSelect.environment(global.bin),
166181
args: input.args,
167-
cwd: input.cwd ?? path.resolve("/"),
182+
cwd,
168183
title: input.title,
169184
group_id: sessionID,
170185
env: input.env,

‎packages/server/src/handlers/persistent-pty.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { PersistentPty } from "@opencode/core/persistent-pty"
22
import { PtyTicket } from "@opencode/core/pty/ticket"
3-
import { ForbiddenError, PtyNotFoundError, ServiceUnavailableError } from "@opencode/protocol/errors"
3+
import {
4+
ForbiddenError,
5+
InvalidRequestError,
6+
PtyNotFoundError,
7+
ServiceUnavailableError,
8+
} from "@opencode/protocol/errors"
49
import {
510
PTY_CONNECT_TICKET_QUERY,
611
PTY_CONNECT_TOKEN_HEADER,
@@ -58,7 +63,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment
5863
cols: ctx.payload.size?.cols,
5964
rows: ctx.payload.size?.rows,
6065
})
61-
.pipe(Effect.catchTag("PersistentPty.UnavailableError", unavailable)),
66+
.pipe(
67+
Effect.catchTags({
68+
"PersistentPty.InvalidCwdError": (error) =>
69+
new InvalidRequestError({ message: error.message, kind: "invalid_cwd", field: "cwd" }),
70+
"PersistentPty.UnavailableError": unavailable,
71+
}),
72+
),
6273
}
6374
}),
6475
)

‎packages/server/test/persistent-pty.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,55 @@ async function waitForRead(client: ReturnType<typeof OpenCode.make>, sessionID:
141141
throw new Error(`Terminal ${ptyID} did not become current for ${sessionID}`)
142142
}
143143

144+
smoke(
145+
"rejects a cwd that is missing or not a directory without starting a shell",
146+
() =>
147+
Effect.gen(function* () {
148+
const fixture = yield* testDirectory()
149+
const server = yield* ServerProcess.start<never, never>({
150+
hostname: "127.0.0.1",
151+
port: 0,
152+
password: "secret",
153+
app: { version: "test-version" },
154+
database: { path: fixture.database },
155+
pty: { root: fixture.directory },
156+
fs: { filewatcher: false },
157+
})
158+
const base = HttpServer.formatAddress(server.address)
159+
const createPath = "/api/experimental/session/ses_invalid_cwd/terminal"
160+
const file = path.join(fixture.root, "file.txt")
161+
yield* Effect.promise(() => fs.writeFile(file, ""))
162+
for (const cwd of [path.join(fixture.root, "missing"), file]) {
163+
const response = yield* Effect.promise(async () => {
164+
const response = await fetch(new URL(createPath, base), {
165+
method: "POST",
166+
headers: { authorization: `Basic ${btoa("opencode:secret")}`, "content-type": "application/json" },
167+
body: JSON.stringify({ command: "/bin/sh", args: [], cwd, title: "invalid", env: {} }),
168+
})
169+
return { status: response.status, body: await response.json() }
170+
})
171+
expect(response).toEqual({
172+
status: 400,
173+
body: {
174+
_tag: "InvalidRequestError",
175+
message: `cwd is not a directory: ${cwd}`,
176+
kind: "invalid_cwd",
177+
field: "cwd",
178+
},
179+
})
180+
}
181+
// The daemon is never started, so no shell can have been spawned.
182+
expect(existsSync(fixture.directory)).toBeFalse()
183+
expect((yield* request(base, "GET", createPath)).data).toEqual([])
184+
const valid = { command: "/bin/sh", args: [], cwd: fixture.root, title: "valid", env: {} }
185+
const created = yield* request(base, "POST", createPath, valid)
186+
const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(created.data)
187+
expect(terminal.cwd).toBe(fixture.root)
188+
yield* request(base, "POST", "/api/experimental/persistent-pty/shutdown")
189+
}),
190+
20_000,
191+
)
192+
144193
smoke(
145194
"creates two persistent terminals for one session through the client API",
146195
() =>

0 commit comments

Comments
 (0)