diff --git a/packages/protocol/src/api.ts b/packages/protocol/src/api.ts index e837cff1165..0691ad4fb24 100644 --- a/packages/protocol/src/api.ts +++ b/packages/protocol/src/api.ts @@ -18,7 +18,7 @@ import { AgentGroup } from "./groups/agent.js" import { PluginGroup } from "./groups/plugin.js" import { ServerGroup } from "./groups/server.js" import { DebugGroup } from "./groups/debug.js" -import { PtyGroup } from "./groups/pty.js" +import { makePtyGroup } from "./groups/pty.js" import { PersistentPtyGroup } from "./groups/persistent-pty.js" import { ShellGroup } from "./groups/shell.js" import { ReferenceGroup } from "./groups/reference.js" @@ -47,12 +47,15 @@ type LocationGroups = | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware - | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware +type PtyGroups = ReturnType< + typeof makePtyGroup +> + type SessionGroups< SessionLocationId extends HttpApiMiddleware.AnyId, SessionLocationService, @@ -95,6 +98,7 @@ type ApiGroups< | typeof CredentialGroup | LocationGroups | LocationGroup + | PtyGroups | FormGroups | SessionGroups | MixedMiddlewareGroups @@ -173,7 +177,7 @@ const makeApiFromGroup = < .add(SkillGroup.middleware(locationMiddleware)) .add(RpcGroup.middleware(locationMiddleware)) .add(eventGroup) - .add(PtyGroup.middleware(locationMiddleware)) + .add(makePtyGroup(locationMiddleware)) .add(PersistentPtyGroup) .add(ShellGroup.middleware(locationMiddleware)) .add(ReferenceGroup.middleware(locationMiddleware)) diff --git a/packages/protocol/src/groups/pty.ts b/packages/protocol/src/groups/pty.ts index 00efe91a939..f86677ba4b2 100644 --- a/packages/protocol/src/groups/pty.ts +++ b/packages/protocol/src/groups/pty.ts @@ -1,9 +1,9 @@ import { Pty } from "@opencode/schema/pty" import { PtyTicket } from "@opencode/schema/pty-ticket" import { Location } from "@opencode/schema/location" -import { Schema } from "effect" -import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" -import { ForbiddenError, PtyNotFoundError } from "../errors.js" +import { Context, Schema } from "effect" +import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" +import { ForbiddenError, LocationNotFoundError, PtyNotFoundError } from "../errors.js" import { LocationQuery, locationQueryOpenApi } from "./location.js" export const PTY_CONNECT_TICKET_QUERY = "ticket" @@ -18,127 +18,130 @@ export function hasPtyConnectTicketURL(url: URL) { return PTY_CONNECT_PATH.test(url.pathname) && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY) } -export const PtyGroup = HttpApiGroup.make("server.pty") - .add( - HttpApiEndpoint.get("pty.list", "/api/pty", { - query: LocationQuery, - success: Location.response(Schema.Array(Pty.Info)), - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( +export const makePtyGroup = ( + locationMiddleware: Context.Key, +) => + HttpApiGroup.make("server.pty") + .add( + HttpApiEndpoint.get("pty.list", "/api/pty", { + query: LocationQuery, + success: Location.response(Schema.Array(Pty.Info)), + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.list", + summary: "List PTY sessions", + description: "List PTY sessions for a location, including exited sessions retained until removal.", + }), + ), + ) + .add( + HttpApiEndpoint.post("pty.create", "/api/pty", { + query: LocationQuery, + payload: Pty.CreateInput, + success: Location.response(Pty.Info), + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.create", + summary: "Create PTY session", + description: "Create a pseudo-terminal session for a location.", + }), + ), + ) + .add( + HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", { + params: { ptyID: Pty.ID }, + query: LocationQuery, + success: Location.response(Pty.Info), + error: PtyNotFoundError, + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.get", + summary: "Get PTY session", + description: "Get one PTY session, including its exit code once exited.", + }), + ), + ) + .add( + HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", { + params: { ptyID: Pty.ID }, + query: LocationQuery, + payload: Pty.UpdateInput, + success: Location.response(Pty.Info), + error: PtyNotFoundError, + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.update", + summary: "Update PTY session", + description: "Update the title or viewport size of one PTY session.", + }), + ), + ) + .add( + HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", { + params: { ptyID: Pty.ID }, + query: LocationQuery, + success: HttpApiSchema.NoContent, + error: PtyNotFoundError, + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.remove", + summary: "Remove PTY session", + description: "Terminate and remove one PTY session.", + }), + ), + ) + .add( + HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", { + params: { ptyID: Pty.ID }, + query: LocationQuery, + headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }), + success: Location.response(PtyTicket.ConnectToken), + error: [ForbiddenError, PtyNotFoundError], + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "pty.connect.token", + summary: "Create PTY WebSocket token", + description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.", + }), + ), + ) + .middleware(locationMiddleware) + .add( + // Query fields are decoded in the raw handler before upgrade work. + HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", { + params: { ptyID: Pty.ID }, + success: Schema.Boolean, + error: [ForbiddenError, PtyNotFoundError, LocationNotFoundError], + }).annotateMerge( OpenApi.annotations({ - identifier: "pty.list", - summary: "List PTY sessions", - description: "List PTY sessions for a location, including exited sessions retained until removal.", + identifier: "pty.connect", + summary: "Connect to PTY session", + description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.", + transform: (operation) => ({ + ...operation, + "x-websocket": true, + parameters: [ + ...(operation.parameters ?? []), + ...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({ + in: "query", + name, + schema: { type: "string" }, + })), + ], + }), }), ), - ) - .add( - HttpApiEndpoint.post("pty.create", "/api/pty", { - query: LocationQuery, - payload: Pty.CreateInput, - success: Location.response(Pty.Info), - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( - OpenApi.annotations({ - identifier: "pty.create", - summary: "Create PTY session", - description: "Create a pseudo-terminal session for a location.", - }), - ), - ) - .add( - HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", { - params: { ptyID: Pty.ID }, - query: LocationQuery, - success: Location.response(Pty.Info), - error: PtyNotFoundError, - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( - OpenApi.annotations({ - identifier: "pty.get", - summary: "Get PTY session", - description: "Get one PTY session, including its exit code once exited.", - }), - ), - ) - .add( - HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", { - params: { ptyID: Pty.ID }, - query: LocationQuery, - payload: Pty.UpdateInput, - success: Location.response(Pty.Info), - error: PtyNotFoundError, - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( - OpenApi.annotations({ - identifier: "pty.update", - summary: "Update PTY session", - description: "Update the title or viewport size of one PTY session.", - }), - ), - ) - .add( - HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", { - params: { ptyID: Pty.ID }, - query: LocationQuery, - success: HttpApiSchema.NoContent, - error: PtyNotFoundError, - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( - OpenApi.annotations({ - identifier: "pty.remove", - summary: "Remove PTY session", - description: "Terminate and remove one PTY session.", - }), - ), - ) - .add( - HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", { - params: { ptyID: Pty.ID }, - query: LocationQuery, - headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }), - success: Location.response(PtyTicket.ConnectToken), - error: [ForbiddenError, PtyNotFoundError], - }) - .annotateMerge(locationQueryOpenApi) - .annotateMerge( - OpenApi.annotations({ - identifier: "pty.connect.token", - summary: "Create PTY WebSocket token", - description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.", - }), - ), - ) - .add( - // Query fields are decoded in the raw handler after the existence check so a missing - // session responds with an empty 404 before any upgrade work. - HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", { - params: { ptyID: Pty.ID }, - success: Schema.Boolean, - error: [ForbiddenError, PtyNotFoundError], - }).annotateMerge( - OpenApi.annotations({ - identifier: "pty.connect", - summary: "Connect to PTY session", - description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.", - transform: (operation) => ({ - ...operation, - "x-websocket": true, - parameters: [ - ...(operation.parameters ?? []), - ...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({ - in: "query", - name, - schema: { type: "string" }, - })), - ], - }), - }), - ), - ) - .annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." })) + ) + .annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." })) diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index 76aa3a025bf..748b86e42f3 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -108,14 +108,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment .handleRaw( "persistentPty.connect", Effect.fn("PersistentPtyHandler.connect")(function* (ctx) { + if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)) + return HttpServerResponse.empty({ status: 403 }) + const url = new URL(ctx.request.url, "http://localhost") const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY) - if (ticket) { - const valid = isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors) - ? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID }) - : false - if (!valid) return HttpServerResponse.empty({ status: 403 }) - } + if (ticket && !(yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID }))) + return HttpServerResponse.empty({ status: 403 }) const cursor = Number(url.searchParams.get("cursor") ?? "0") const role = url.searchParams.get("role") === "observer" ? "observer" : "controller" diff --git a/packages/server/src/handlers/pty.ts b/packages/server/src/handlers/pty.ts index 4e8f922edbb..3de69057550 100644 --- a/packages/server/src/handlers/pty.ts +++ b/packages/server/src/handlers/pty.ts @@ -2,6 +2,7 @@ import { Pty } from "@opencode/core/pty" import { PtyProtocol } from "@opencode/core/pty/protocol" import { PtyTicket } from "@opencode/core/pty/ticket" import { Location } from "@opencode/core/location" +import { LocationServiceMap } from "@opencode/core/location-service-map" import { Effect, Queue } from "effect" import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi" @@ -14,7 +15,7 @@ import { PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE, } from "@opencode/protocol/groups/pty" -import { response } from "../location" +import { locationErrors, requestRef, response } from "../location" import { PtyEnvironment } from "../pty-environment" import { runPtySocket } from "./pty-socket" @@ -25,6 +26,7 @@ const ticketScope = Effect.gen(function* () { export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) => Effect.gen(function* () { + const locations = yield* LocationServiceMap.Service const tickets = yield* PtyTicket.Service const cors = yield* CorsConfig const environment = yield* PtyEnvironment.Service @@ -142,83 +144,93 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) => .handleRaw( "pty.connect", Effect.fn("PtyHandler.connect")(function* (ctx) { - const pty = yield* Pty.Service - const exists = yield* pty.get(ctx.params.ptyID).pipe( - Effect.as(true), - Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)), - ) - if (!exists) return HttpServerResponse.empty({ status: 404 }) + if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)) + return HttpServerResponse.empty({ status: 403 }) + const ref = LocationServiceMap.canonical(requestRef(ctx.request)) const url = new URL(ctx.request.url, "http://localhost") const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY) - if (ticket) { - const valid = isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors) - ? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) }) - : false - if (!valid) return HttpServerResponse.empty({ status: 403 }) - } - const parsedCursor = url.searchParams.get("cursor") - const cursorNumber = parsedCursor === null ? undefined : Number(parsedCursor) - const cursor = - cursorNumber !== undefined && Number.isSafeInteger(cursorNumber) && cursorNumber >= -1 - ? cursorNumber - : undefined - - const socket = yield* Effect.orDie(ctx.request.upgrade) - const write = yield* socket.writer - const closeAccepted = (event: Socket.CloseEvent) => - socket - .runRaw(() => Effect.void, { onOpen: write(event).pipe(Effect.catch(() => Effect.void)) }) - .pipe( - Effect.timeout("1 second"), - Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void), - Effect.catch(() => Effect.void), - ) - - // Outbound frames flow through one queue drained by a single writer so replay, live - // output, and the close frame keep their order. - // TODO: Integrate graceful-shutdown socket tracking before clients migrate to this route. - const outbox = yield* Queue.unbounded() - const attachment = yield* pty - .attach(ctx.params.ptyID, { - cursor, - onData: (chunk) => Queue.offerUnsafe(outbox, chunk), - onEnd: () => Queue.offerUnsafe(outbox, new Socket.CloseEvent(1000)), - }) - .pipe( - Effect.catchTags({ - "Pty.NotFoundError": () => - closeAccepted(new Socket.CloseEvent(4404, "session not found")).pipe(Effect.as(undefined)), - "Pty.ExitedError": () => - closeAccepted(new Socket.CloseEvent(4404, "session exited")).pipe(Effect.as(undefined)), - }), - ) - if (!attachment) return HttpServerResponse.empty() - - for (const chunk of PtyProtocol.chunks(attachment.replay)) Queue.offerUnsafe(outbox, chunk) - Queue.offerUnsafe(outbox, PtyProtocol.metaFrame(attachment.cursor)) - attachment.activate() - - const drain = Effect.gen(function* () { - while (true) { - const item = yield* Queue.take(outbox) - yield* write(item) - if (item instanceof Socket.CloseEvent) return - } - }) - - yield* runPtySocket( - drain, - socket.runRaw((message) => { - const decoded = PtyProtocol.decodeInput(message) - if (decoded !== undefined) attachment.write(decoded) - }), - attachment.detach, - ).pipe( - Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void), - Effect.orDie, + if ( + ticket && + !(yield* tickets.consume({ + ticket, + ptyID: ctx.params.ptyID, + directory: ref.directory, + workspaceID: ref.workspaceID, + })) ) - return HttpServerResponse.empty() + return HttpServerResponse.empty({ status: 403 }) + + return yield* Effect.gen(function* () { + const pty = yield* Pty.Service + const exists = yield* pty.get(ctx.params.ptyID).pipe( + Effect.as(true), + Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)), + ) + if (!exists) return HttpServerResponse.empty({ status: 404 }) + const parsedCursor = url.searchParams.get("cursor") + const cursorNumber = parsedCursor === null ? undefined : Number(parsedCursor) + const cursor = + cursorNumber !== undefined && Number.isSafeInteger(cursorNumber) && cursorNumber >= -1 + ? cursorNumber + : undefined + + const socket = yield* Effect.orDie(ctx.request.upgrade) + const write = yield* socket.writer + const closeAccepted = (event: Socket.CloseEvent) => + socket + .runRaw(() => Effect.void, { onOpen: write(event).pipe(Effect.catch(() => Effect.void)) }) + .pipe( + Effect.timeout("1 second"), + Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void), + Effect.catch(() => Effect.void), + ) + + // Outbound frames flow through one queue drained by a single writer so replay, live + // output, and the close frame keep their order. + // TODO: Integrate graceful-shutdown socket tracking before clients migrate to this route. + const outbox = yield* Queue.unbounded() + const attachment = yield* pty + .attach(ctx.params.ptyID, { + cursor, + onData: (chunk) => Queue.offerUnsafe(outbox, chunk), + onEnd: () => Queue.offerUnsafe(outbox, new Socket.CloseEvent(1000)), + }) + .pipe( + Effect.catchTags({ + "Pty.NotFoundError": () => + closeAccepted(new Socket.CloseEvent(4404, "session not found")).pipe(Effect.as(undefined)), + "Pty.ExitedError": () => + closeAccepted(new Socket.CloseEvent(4404, "session exited")).pipe(Effect.as(undefined)), + }), + ) + if (!attachment) return HttpServerResponse.empty() + + for (const chunk of PtyProtocol.chunks(attachment.replay)) Queue.offerUnsafe(outbox, chunk) + Queue.offerUnsafe(outbox, PtyProtocol.metaFrame(attachment.cursor)) + attachment.activate() + + const drain = Effect.gen(function* () { + while (true) { + const item = yield* Queue.take(outbox) + yield* write(item) + if (item instanceof Socket.CloseEvent) return + } + }) + + yield* runPtySocket( + drain, + socket.runRaw((message) => { + const decoded = PtyProtocol.decodeInput(message) + if (decoded !== undefined) attachment.write(decoded) + }), + attachment.detach, + ).pipe( + Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void), + Effect.orDie, + ) + return HttpServerResponse.empty() + }).pipe(Effect.provide(locations.get(ref)), locationErrors) }), ) }), diff --git a/packages/server/test/fetch.test.ts b/packages/server/test/fetch.test.ts index bbe5510ff83..952a89aca0a 100644 --- a/packages/server/test/fetch.test.ts +++ b/packages/server/test/fetch.test.ts @@ -249,8 +249,86 @@ it.live("applies custom CORS origins to HTTP responses and PTY ticket checks", ( ) // Allowed origins pass the ticket guard and reach the missing-terminal lookup. expect(ticket.status).toBe(allowed ? 404 : 403) + + const invalidTicket = yield* Effect.promise(() => + handler( + new Request("http://opencode.local/api/pty/pty_missing/connect?ticket=invalid&location[directory]=/tmp", { + headers: { origin }, + }), + ), + ) + expect(invalidTicket.status).toBe(403) + + const connect = yield* Effect.promise(() => + handler( + new Request("http://opencode.local/api/pty/pty_missing/connect", { + headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` }, + }), + ), + ) + expect(connect.status).toBe(allowed ? 404 : 403) + + const persistentConnect = yield* Effect.promise(() => + handler( + new Request("http://opencode.local/api/experimental/persistent-pty/pty_missing/connect?cursor=-1", { + headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` }, + }), + ), + ) + expect(persistentConnect.status).toBe(allowed ? 400 : 403) }), ) + + const loaded = yield* Effect.promise(() => + handler( + new Request("http://opencode.local/api/debug/location", { + headers: { authorization: `Basic ${btoa("opencode:secret")}` }, + }), + ).then((response) => response.json()), + ) + expect(loaded).toEqual([{ directory: process.cwd() }]) + + const created = (yield* Effect.promise(() => + handler( + new Request("http://opencode.local/api/pty", { + method: "POST", + headers: { + authorization: `Basic ${btoa("opencode:secret")}`, + "content-type": "application/json", + }, + body: JSON.stringify({ command: process.execPath, args: ["-e", "setInterval(() => {}, 1000)"] }), + }), + ).then((response) => response.json()), + )) as { data: { id: string } } + const issued = (yield* Effect.promise(() => + handler( + new Request(`http://opencode.local/api/pty/${created.data.id}/connect-token`, { + method: "POST", + headers: { + authorization: `Basic ${btoa("opencode:secret")}`, + "x-opencode-ticket": "1", + }, + }), + ).then((response) => response.json()), + )) as { data: { ticket: string } } + yield* Effect.promise(() => + handler( + new Request(`http://opencode.local/api/pty/${created.data.id}`, { + method: "DELETE", + headers: { authorization: `Basic ${btoa("opencode:secret")}` }, + }), + ), + ) + + const consumed = yield* Effect.promise(() => + handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)), + ) + expect(consumed.status).toBe(404) + + const replayed = yield* Effect.promise(() => + handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)), + ) + expect(replayed.status).toBe(403) }).pipe(Effect.scoped), )