GeezerVison is showing github.com — feat(server): pty websocket auth tickets (#25660) · cavanaug/opencode@7bc26da
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/app/src/components/terminal.tsx +24-1Lines changed: 24 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -479,6 +479,21 @@ export const Terminal = (props: TerminalProps) => { | 479 | 479 | return false | 480 | 480 | }) | 481 | 481 |
| | 482 | + const connectToken = async () => { | | 483 | + const result = await client.pty.connectToken( | | 484 | + { ptyID: id }, | | 485 | + { | | 486 | + throwOnError: false, | | 487 | + headers: { "x-opencode-ticket": "1" }, | | 488 | + }, | | 489 | + ) | | 490 | + if (result.response.status === 200 && result.data?.ticket) return result.data.ticket | | 491 | + if ((result.response.status === 404 || result.response.status === 405) && password) return | | 492 | + if (result.response.status === 403) | | 493 | + throw new Error("PTY connect ticket rejected by origin or CSRF checks. Check the server CORS config.") | | 494 | + throw new Error(`PTY connect ticket failed with ${result.response.status}`) | | 495 | + } | | 496 | + | 482 | 497 | const retry = (err: unknown) => { | 483 | 498 | if (disposed) return | 484 | 499 | if (reconn !== undefined) return | @@ -498,16 +513,24 @@ export const Terminal = (props: TerminalProps) => { | 498 | 513 | }, ms) | 499 | 514 | } | 500 | 515 |
| 501 | | - const open = () => { | | 516 | + const open = async () => { | 502 | 517 | if (disposed) return | 503 | 518 | drop?.() | 504 | 519 |
| | 520 | + const ticket = await connectToken().catch((err) => { | | 521 | + fail(err) | | 522 | + return undefined | | 523 | + }) | | 524 | + if (once.value) return | | 525 | + if (disposed) return | | 526 | + | 505 | 527 | const socket = new WebSocket( | 506 | 528 | terminalWebSocketURL({ | 507 | 529 | url, | 508 | 530 | id, | 509 | 531 | directory, | 510 | 532 | cursor: seek, | | 533 | + ticket, | 511 | 534 | sameOrigin, | 512 | 535 | username, | 513 | 536 | password, | |
Collapse file Copy file name to clipboardExpand all lines: packages/app/src/utils/terminal-websocket-url.ts +7-2Lines changed: 7 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5,15 +5,20 @@ export function terminalWebSocketURL(input: { | 5 | 5 | id: string | 6 | 6 | directory: string | 7 | 7 | cursor: number | 8 | | - sameOrigin: boolean | 9 | | - username: string | | 8 | + ticket?: string | | 9 | + sameOrigin?: boolean | | 10 | + username?: string | 10 | 11 | password?: string | 11 | 12 | authToken?: boolean | 12 | 13 | }) { | 13 | 14 | const next = new URL(`${input.url}/pty/${input.id}/connect`) | 14 | 15 | next.searchParams.set("directory", input.directory) | 15 | 16 | next.searchParams.set("cursor", String(input.cursor)) | 16 | 17 | next.protocol = next.protocol === "https:" ? "wss:" : "ws:" | | 18 | + if (input.ticket) { | | 19 | + next.searchParams.set("ticket", input.ticket) | | 20 | + return next | | 21 | + } | 17 | 22 | if (input.password && (!input.sameOrigin || input.authToken)) | 18 | 23 | next.searchParams.set( | 19 | 24 | "auth_token", | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/effect/app-runtime.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -46,6 +46,7 @@ import { Vcs } from "@/project/vcs" | 46 | 46 | import { Workspace } from "@/control-plane/workspace" | 47 | 47 | import { Worktree } from "@/worktree" | 48 | 48 | import { Pty } from "@/pty" | | 49 | +import { PtyTicket } from "@/pty/ticket" | 49 | 50 | import { Installation } from "@/installation" | 50 | 51 | import { ShareNext } from "@/share/share-next" | 51 | 52 | import { SessionShare } from "@/share/session" | @@ -98,6 +99,7 @@ export const AppLayer = Layer.mergeAll( | 98 | 99 | Workspace.defaultLayer, | 99 | 100 | Worktree.appLayer, | 100 | 101 | Pty.defaultLayer, | | 102 | + PtyTicket.defaultLayer, | 101 | 103 | Installation.defaultLayer, | 102 | 104 | ShareNext.defaultLayer, | 103 | 105 | SessionShare.defaultLayer, | |
Collapse file Copy file name to clipboard +66Lines changed: 66 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +export * as PtyTicket from "./ticket" | | 2 | + | | 3 | +import { WorkspaceID } from "@/control-plane/schema" | | 4 | +import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" | | 5 | +import { PtyID } from "@/pty/schema" | | 6 | +import { PositiveInt } from "@/util/schema" | | 7 | +import { Cache, Context, Duration, Effect, Layer, Schema } from "effect" | | 8 | + | | 9 | +const DEFAULT_TTL = Duration.seconds(60) | | 10 | +const CAPACITY = 10_000 | | 11 | + | | 12 | +export const ConnectToken = Schema.Struct({ | | 13 | + ticket: Schema.String, | | 14 | + expires_in: PositiveInt, | | 15 | +}) | | 16 | + | | 17 | +export type Scope = { | | 18 | + readonly ptyID: PtyID | | 19 | + readonly directory?: string | | 20 | + readonly workspaceID?: WorkspaceID | | 21 | +} | | 22 | + | | 23 | +export interface Interface { | | 24 | + issue(input: Scope): Effect.Effect<typeof ConnectToken.Type> | | 25 | + consume(input: Scope & { readonly ticket: string }): Effect.Effect<boolean> | | 26 | +} | | 27 | + | | 28 | +export class Service extends Context.Service<Service, Interface>()("@opencode/PtyTicket") {} | | 29 | + | | 30 | +function matches(record: Scope, input: Scope) { | | 31 | + return record.ptyID === input.ptyID && record.directory === input.directory && record.workspaceID === input.workspaceID | | 32 | +} | | 33 | + | | 34 | +// Tickets are inserted via Cache.set and removed atomically via invalidateWhen. The lookup is | | 35 | +// never invoked; it dies if it ever is, which would signal a misuse of the Service interface. | | 36 | +const noLookup = () => Effect.die("PtyTicket cache must be used via set/invalidateWhen, never get") | | 37 | + | | 38 | +// Visible for tests so the TTL can be shortened. Production uses `layer` with the default TTL. | | 39 | +export const make = (ttl: Duration.Input = DEFAULT_TTL) => | | 40 | + Effect.gen(function* () { | | 41 | + const cache = yield* Cache.make<string, Scope>({ capacity: CAPACITY, lookup: noLookup, timeToLive: ttl }) | | 42 | + const expiresIn = Math.max(1, Math.round(Duration.toSeconds(Duration.fromInputUnsafe(ttl)))) | | 43 | + return Service.of({ | | 44 | + issue: Effect.fn("PtyTicket.issue")(function* (input) { | | 45 | + const ticket = crypto.randomUUID() | | 46 | + yield* Cache.set(cache, ticket, input) | | 47 | + return { ticket, expires_in: expiresIn } | | 48 | + }), | | 49 | + consume: Effect.fn("PtyTicket.consume")(function* (input) { | | 50 | + return yield* Cache.invalidateWhen(cache, input.ticket, (stored) => matches(stored, input)) | | 51 | + }), | | 52 | + }) | | 53 | + }) | | 54 | + | | 55 | +export const layer = Layer.effect(Service, make()) | | 56 | + | | 57 | +export const defaultLayer = layer | | 58 | + | | 59 | +export const scope = Effect.gen(function* () { | | 60 | + const instance = yield* InstanceRef | | 61 | + const workspaceID = yield* WorkspaceRef | | 62 | + return { | | 63 | + directory: instance?.directory, | | 64 | + workspaceID, | | 65 | + } | | 66 | +}) |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/cors.ts +20Lines changed: 20 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { Context } from "effect" | | 2 | + | 1 | 3 | const opencodeOrigin = /^https:\/\/([a-z0-9-]+\.)*opencode\.ai$/ | 2 | 4 |
| 3 | 5 | export type CorsOptions = { readonly cors?: ReadonlyArray<string> } | 4 | 6 |
| | 7 | +export const CorsConfig = Context.Reference<CorsOptions | undefined>("@opencode/ServerCorsConfig", { | | 8 | + defaultValue: () => undefined, | | 9 | +}) | | 10 | + | 5 | 11 | export function isAllowedCorsOrigin(input: string | undefined, opts?: CorsOptions) { | 6 | 12 | if (!input) return true | 7 | 13 | if (input.startsWith("http://localhost:")) return true | @@ -12,3 +18,17 @@ export function isAllowedCorsOrigin(input: string | undefined, opts?: CorsOption | 12 | 18 | if (opencodeOrigin.test(input)) return true | 13 | 19 | return opts?.cors?.includes(input) ?? false | 14 | 20 | } | | 21 | + | | 22 | +export function isAllowedRequestOrigin(input: string | undefined, host: string | undefined, opts?: CorsOptions) { | | 23 | + if (!input) return true | | 24 | + if (host && sameHost(input, host)) return true | | 25 | + return isAllowedCorsOrigin(input, opts) | | 26 | +} | | 27 | + | | 28 | +function sameHost(origin: string, host: string) { | | 29 | + try { | | 30 | + return new URL(origin).host === host | | 31 | + } catch { | | 32 | + return false | | 33 | + } | | 34 | +} |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/error.ts +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,6 +21,9 @@ export const ERRORS = { | 21 | 21 | }, | 22 | 22 | }, | 23 | 23 | }, | | 24 | + 403: { | | 25 | + description: "Forbidden", | | 26 | + }, | 24 | 27 | 404: { | 25 | 28 | description: "Not found", | 26 | 29 | content: { | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/middleware.ts +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -12,6 +12,7 @@ import { cors } from "hono/cors" | 12 | 12 | import { compress } from "hono/compress" | 13 | 13 | import * as ServerBackend from "./backend" | 14 | 14 | import { isAllowedCorsOrigin, type CorsOptions } from "./cors" | | 15 | +import { isPtyConnectPath, PTY_CONNECT_TICKET_QUERY } from "./shared/pty-ticket" | 15 | 16 |
| 16 | 17 | const log = Log.create({ service: "server" }) | 17 | 18 |
| @@ -44,6 +45,7 @@ export const AuthMiddleware: MiddlewareHandler = (c, next) => { | 44 | 45 | if (c.req.method === "OPTIONS") return next() | 45 | 46 | const password = Flag.OPENCODE_SERVER_PASSWORD | 46 | 47 | if (!password) return next() | | 48 | + if (isPtyConnectPath(c.req.path) && c.req.query(PTY_CONNECT_TICKET_QUERY)) return next() | 47 | 49 | const username = Flag.OPENCODE_SERVER_USERNAME ?? "opencode" | 48 | 50 |
| 49 | 51 | if (c.req.query("auth_token")) c.req.raw.headers.set("authorization", `Basic ${c.req.query("auth_token")}`) | @@ -58,6 +60,7 @@ export function LoggerMiddleware(backendAttributes: ServerBackend.Attributes): M | 58 | 60 | const attributes = { | 59 | 61 | method: c.req.method, | 60 | 62 | path: c.req.path, | | 63 | + // If this logger grows full-URL fields, redact auth_token and ticket query params. | 61 | 64 | ...backendAttributes, | 62 | 65 | } | 63 | 66 | log.info("request", attributes) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/routes/instance/httpapi/groups/pty.ts +14-1Lines changed: 14 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { Pty } from "@/pty" | | 2 | +import { PtyTicket } from "@/pty/ticket" | 2 | 3 | import { PtyID } from "@/pty/schema" | 3 | 4 | import { Schema } from "effect" | 4 | 5 | import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" | @@ -23,6 +24,7 @@ export const PtyPaths = { | 23 | 24 | get: `${root}/:ptyID`, | 24 | 25 | update: `${root}/:ptyID`, | 25 | 26 | remove: `${root}/:ptyID`, | | 27 | + connectToken: `${root}/:ptyID/connect-token`, | 26 | 28 | connect: `${root}/:ptyID/connect`, | 27 | 29 | } as const | 28 | 30 |
| @@ -93,6 +95,17 @@ export const PtyApi = HttpApi.make("pty") | 93 | 95 | description: "Remove and terminate a specific pseudo-terminal (PTY) session.", | 94 | 96 | }), | 95 | 97 | ), | | 98 | + HttpApiEndpoint.post("connectToken", PtyPaths.connectToken, { | | 99 | + params: { ptyID: PtyID }, | | 100 | + success: described(PtyTicket.ConnectToken, "WebSocket connect token"), | | 101 | + error: [HttpApiError.Forbidden, HttpApiError.NotFound], | | 102 | + }).annotateMerge( | | 103 | + OpenApi.annotations({ | | 104 | + identifier: "pty.connectToken", | | 105 | + summary: "Create PTY WebSocket token", | | 106 | + description: "Create a short-lived ticket for opening a PTY WebSocket connection.", | | 107 | + }), | | 108 | + ), | 96 | 109 | ) | 97 | 110 | .annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental HttpApi PTY routes." })) | 98 | 111 | .middleware(InstanceContextMiddleware) | @@ -113,7 +126,7 @@ export const PtyConnectApi = HttpApi.make("pty-connect").add( | 113 | 126 | HttpApiEndpoint.get("connect", PtyPaths.connect, { | 114 | 127 | params: Params, | 115 | 128 | success: described(Schema.Boolean, "Connected session"), | 116 | | - error: HttpApiError.NotFound, | | 129 | + error: [HttpApiError.Forbidden, HttpApiError.NotFound], | 117 | 130 | }).annotateMerge( | 118 | 131 | OpenApi.annotations({ | 119 | 132 | identifier: "pty.connect", | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts +33-1Lines changed: 33 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { Pty } from "@/pty" | 2 | 2 | import { PtyID } from "@/pty/schema" | | 3 | +import { PtyTicket } from "@/pty/ticket" | 3 | 4 | import { handlePtyInput } from "@/pty/input" | 4 | 5 | import { Shell } from "@/shell/shell" | 5 | 6 | import { EffectBridge } from "@/effect/bridge" | | 7 | +import { CorsConfig, isAllowedRequestOrigin, type CorsOptions } from "@/server/cors" | | 8 | +import { | | 9 | + PTY_CONNECT_TICKET_QUERY, | | 10 | + PTY_CONNECT_TOKEN_HEADER, | | 11 | + PTY_CONNECT_TOKEN_HEADER_VALUE, | | 12 | +} from "@/server/shared/pty-ticket" | 6 | 13 | import { Effect } from "effect" | 7 | 14 | import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" | 8 | 15 | import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" | @@ -11,9 +18,15 @@ import { InstanceHttpApi } from "../api" | 11 | 18 | import { CursorQuery, Params, PtyPaths } from "../groups/pty" | 12 | 19 | import { WebSocketTracker } from "../websocket-tracker" | 13 | 20 |
| | 21 | +function validOrigin(request: HttpServerRequest.HttpServerRequest, opts: CorsOptions | undefined) { | | 22 | + return isAllowedRequestOrigin(request.headers.origin, request.headers.host, opts) | | 23 | +} | | 24 | + | 14 | 25 | export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handlers) => | 15 | 26 | Effect.gen(function* () { | 16 | 27 | const pty = yield* Pty.Service | | 28 | + const tickets = yield* PtyTicket.Service | | 29 | + const cors = yield* CorsConfig | 17 | 30 |
| 18 | 31 | const shells = Effect.fn("PtyHttpApi.shells")(function* () { | 19 | 32 | return yield* Effect.promise(() => Shell.list()) | @@ -54,19 +67,30 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler | 54 | 67 | return true | 55 | 68 | }) | 56 | 69 |
| | 70 | + const connectToken = Effect.fn("PtyHttpApi.connectToken")(function* (ctx: { params: { ptyID: PtyID } }) { | | 71 | + const request = yield* HttpServerRequest.HttpServerRequest | | 72 | + if (request.headers[PTY_CONNECT_TOKEN_HEADER] !== PTY_CONNECT_TOKEN_HEADER_VALUE || !validOrigin(request, cors)) | | 73 | + return yield* new HttpApiError.Forbidden({}) | | 74 | + if (!(yield* pty.get(ctx.params.ptyID))) return yield* new HttpApiError.NotFound({}) | | 75 | + return yield* tickets.issue({ ptyID: ctx.params.ptyID, ...(yield* PtyTicket.scope) }) | | 76 | + }) | | 77 | + | 57 | 78 | return handlers | 58 | 79 | .handle("shells", shells) | 59 | 80 | .handle("list", list) | 60 | 81 | .handle("create", create) | 61 | 82 | .handle("get", get) | 62 | 83 | .handle("update", update) | 63 | 84 | .handle("remove", remove) | | 85 | + .handle("connectToken", connectToken) | 64 | 86 | }), | 65 | 87 | ) | 66 | 88 |
| 67 | 89 | export const ptyConnectRoute = HttpRouter.use((router) => | 68 | 90 | Effect.gen(function* () { | 69 | 91 | const pty = yield* Pty.Service | | 92 | + const tickets = yield* PtyTicket.Service | | 93 | + const cors = yield* CorsConfig | 70 | 94 | yield* router.add( | 71 | 95 | "GET", | 72 | 96 | PtyPaths.connect, | @@ -75,12 +99,20 @@ export const ptyConnectRoute = HttpRouter.use((router) => | 75 | 99 | if (!(yield* pty.get(params.ptyID))) return HttpServerResponse.empty({ status: 404 }) | 76 | 100 |
| 77 | 101 | const query = yield* HttpServerRequest.schemaSearchParams(CursorQuery) | | 102 | + const request = yield* HttpServerRequest.HttpServerRequest | | 103 | + const ticket = new URL(request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY) | | 104 | + if (ticket) { | | 105 | + const valid = validOrigin(request, cors) | | 106 | + ? yield* tickets.consume({ ticket, ptyID: params.ptyID, ...(yield* PtyTicket.scope) }) | | 107 | + : false | | 108 | + if (!valid) return HttpServerResponse.empty({ status: 403 }) | | 109 | + } | 78 | 110 | const parsedCursor = query.cursor === undefined ? undefined : Number(query.cursor) | 79 | 111 | const cursor = | 80 | 112 | parsedCursor !== undefined && Number.isSafeInteger(parsedCursor) && parsedCursor >= -1 | 81 | 113 | ? parsedCursor | 82 | 114 | : undefined | 83 | | - const socket = yield* Effect.orDie((yield* HttpServerRequest.HttpServerRequest).upgrade) | | 115 | + const socket = yield* Effect.orDie(request.upgrade) | 84 | 116 | const write = yield* socket.writer | 85 | 117 | const closeAccepted = (event: Socket.CloseEvent) => | 86 | 118 | socket | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts +9-2Lines changed: 9 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,7 @@ import { ServerAuth } from "@/server/auth" | 2 | 2 | import { Effect, Encoding, Layer, Redacted } from "effect" | 3 | 3 | import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" | 4 | 4 | import { HttpApiError, HttpApiMiddleware } from "effect/unstable/httpapi" | | 5 | +import { hasPtyConnectTicketURL } from "@/server/shared/pty-ticket" | 5 | 6 |
| 6 | 7 | const AUTH_TOKEN_QUERY = "auth_token" | 7 | 8 | const UNAUTHORIZED = 401 | @@ -55,7 +56,11 @@ function decodeCredential(input: string) { | 55 | 56 | } | 56 | 57 |
| 57 | 58 | function credentialFromRequest(request: HttpServerRequest.HttpServerRequest) { | 58 | | - const token = new URL(request.url, "http://localhost").searchParams.get(AUTH_TOKEN_QUERY) | | 59 | + return credentialFromURL(new URL(request.url, "http://localhost"), request) | | 60 | +} | | 61 | + | | 62 | +function credentialFromURL(url: URL, request: HttpServerRequest.HttpServerRequest) { | | 63 | + const token = url.searchParams.get(AUTH_TOKEN_QUERY) | 59 | 64 | if (token) return decodeCredential(token) | 60 | 65 | const match = /^Basic\s+(.+)$/i.exec(request.headers.authorization ?? "") | 61 | 66 | if (match) return decodeCredential(match[1]) | @@ -86,7 +91,9 @@ export const authorizationRouterMiddleware = HttpRouter.middleware()( | 86 | 91 | return (effect) => | 87 | 92 | Effect.gen(function* () { | 88 | 93 | const request = yield* HttpServerRequest.HttpServerRequest | 89 | | - return yield* credentialFromRequest(request).pipe( | | 94 | + const url = new URL(request.url, "http://localhost") | | 95 | + if (hasPtyConnectTicketURL(url)) return yield* effect | | 96 | + return yield* credentialFromURL(url, request).pipe( | 90 | 97 | Effect.flatMap((credential) => validateRawCredential(effect, credential, config)), | 91 | 98 | ) | 92 | 99 | }) | |
|