diff --git a/packages/app/src/servers/connect/pairing.test.ts b/packages/app/src/servers/connect/pairing.test.ts index f4318640120..60a776df2e2 100644 --- a/packages/app/src/servers/connect/pairing.test.ts +++ b/packages/app/src/servers/connect/pairing.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { bareServerAddress, legacyPairingLink, pairingLink } from "./pairing" +import { bareServerAddress, legacyPairingLink, pairingLink, redeemPairingLink } from "./pairing" describe("pairing link", () => { test("reads the server address and code from opencode pair links", () => { @@ -55,3 +55,35 @@ describe("pairing link", () => { expect(legacyPairingLink("http://192.168.1.2:49374/auth/connect/abc")).toBe(false) }) }) + +test("redeems codes on servers that predate POST redemption", async () => { + const methods: string[] = [] + const reply = (status: string, body = "") => + `HTTP/1.1 ${status}\r\ncontent-type: application/json\r\ncontent-length: ${body.length}\r\naccess-control-allow-origin: *\r\naccess-control-allow-methods: GET, POST\r\nconnection: close\r\n\r\n${body}` + // Servers before POST redemption have no POST route for pairing links and redeem the code on GET. + const server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(socket, chunk) { + const method = String(chunk).split(" ")[0] ?? "" + methods.push(method) + if (method === "OPTIONS") return void socket.end(reply("204 No Content")) + if (method !== "GET") return void socket.end(reply("404 Not Found")) + socket.end(reply("200 OK", JSON.stringify({ token: "session-token" }))) + }, + }, + }) + const url = `http://127.0.0.1:${server.port}` + + try { + expect(await redeemPairingLink({ urls: [url], code: "abc" })).toEqual({ + type: "paired", + pairing: { url, password: "session-token" }, + }) + // happy-dom's fetch may add CORS preflights; only the POST and the GET reach the pairing route. + expect(methods.filter((method) => method !== "OPTIONS")).toEqual(["POST", "GET"]) + } finally { + server.stop(true) + } +}) diff --git a/packages/app/src/servers/connect/pairing.ts b/packages/app/src/servers/connect/pairing.ts index 25bc974e60d..0da35bd6116 100644 --- a/packages/app/src/servers/connect/pairing.ts +++ b/packages/app/src/servers/connect/pairing.ts @@ -2,6 +2,7 @@ import { isUnauthorizedError, OpenCode } from "@opencode/client/promise" import { Option, Schema } from "effect" import { checkServerHealth } from "@/runtime/server/health" import { normalizeServerUrl } from "@/runtime/server/registry" +import { errorStatus } from "@/shell/errors/description" export function serverAddress(value: string) { if (value.includes("://") && !/^https?:\/\//.test(value.trim())) return @@ -84,9 +85,7 @@ export type Redeemed = // Every address may reach the same server, but the code is single-use, so at most one attempt succeeds. export function redeemPairingLink(link: { urls: ReadonlyArray; code: string }) { const attempts = link.urls.map((url) => - OpenCode.make({ baseUrl: url }) - .server.connect({ code: link.code }, { signal: AbortSignal.timeout(5_000) }) - .then((session): Pairing => ({ url, password: session.token })), + redeem(url, link.code).then((session): Pairing => ({ url, password: session.token })), ) // Whether the first address answered at all: a 401 there means another address spent the code first. @@ -107,6 +106,22 @@ export function redeemPairingLink(link: { urls: ReadonlyArray; code: str ) } +// Servers before POST redemption answer it with 404 and redeem the code on GET instead. +function redeem(url: string, code: string) { + const signal = AbortSignal.timeout(5_000) + return OpenCode.make({ baseUrl: url }) + .server.connect({ code }, { signal }) + .catch((error) => { + if (errorStatus(error) !== 404) throw error + const fetch = Object.assign( + (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, { ...init, method: "GET" }), + // Bun's fetch type carries preconnect; the browser never calls it. + { preconnect: () => {} }, + ) + return OpenCode.make({ baseUrl: url, fetch }).server.connect({ code }, { signal }) + }) +} + // The token works on every address of the server, so keep the first one (the address the user chose in Pairing) when it // answers, even if a nearer address answered sooner: a local network address stops working away from that network. An // address that has not answered within a second, such as a local one seen from elsewhere, is not waited for. diff --git a/packages/cli/test/web-ui.test.ts b/packages/cli/test/web-ui.test.ts index 14aa95b0059..17396f9ea33 100644 --- a/packages/cli/test/web-ui.test.ts +++ b/packages/cli/test/web-ui.test.ts @@ -78,6 +78,7 @@ describe("web UI", () => { ) const redirect = yield* Effect.promise(() => fetch(new URL(`/auth/connect/${pairing.code}`, origin), { + method: "POST", redirect: "manual", headers: { accept: "text/html" }, }), diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index cb1725def15..dd7dbfa947e 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -487,7 +487,7 @@ export function make(options: ClientOptions) { connect: (input: ServerConnectInput, requestOptions?: RequestOptions) => request( { - method: "GET", + method: "POST", path: `/auth/connect/${encodeURIComponent(input.code)}`, successStatus: 200, declaredStatuses: [400, 401], diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 797d2807508..9f107a0a74f 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -91,7 +91,7 @@ } }, "/auth/connect/{code}": { - "get": { + "post": { "tags": ["server"], "operationId": "server.connect", "parameters": [ @@ -137,8 +137,57 @@ } } }, - "description": "Redeem a pairing code. Browsers receive a session cookie and a redirect to the web app; requests that accept JSON receive a session token to use as the password.", + "description": "Redeem a pairing code. Browsers submitting the pairing page receive a session cookie and a redirect to the web app; other clients receive a session token to use as the password.", "summary": "Redeem pairing code" + }, + "get": { + "tags": ["server"], + "operationId": "server.connectPage", + "parameters": [ + { + "name": "code", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "PairingSession", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PairingSession" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Show browsers a page that redeems the pairing code when the user confirms; the code stays valid until then. Deprecated: a GET that does not ask for HTML still redeems the code for a session token, for clients built before POST. Removed in the next minor.", + "summary": "Open pairing link" } }, "/api/location": { diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index b46ff3d9056..e6f9e78836e 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -75,12 +75,14 @@ export const clientNamespace = (endpoint: { readonly path: string }) => endpoint.path === "/api/experimental" || endpoint.path.startsWith("/api/experimental/") ? "experimental" : undefined export const promiseOmitEndpoints = new Set([ + "server.connectPage", "pty.connect", "persistentPty.connect", "mcp.client", "generate.textLegacy", ]) export const effectOmitEndpoints = new Set([ + "server.connectPage", "fs.read", "fs.write", "media.get", diff --git a/packages/protocol/src/groups/server.ts b/packages/protocol/src/groups/server.ts index d78813bfc8b..48745cda4e2 100644 --- a/packages/protocol/src/groups/server.ts +++ b/packages/protocol/src/groups/server.ts @@ -64,7 +64,7 @@ export const ServerGroup = HttpApiGroup.make("server.server") ), ) .add( - HttpApiEndpoint.get("server.connect", PAIRING_CONNECT_PATH, { + HttpApiEndpoint.post("server.connect", PAIRING_CONNECT_PATH, { params: { code: Schema.String }, success: PairingSession, error: UnauthorizedError, @@ -73,7 +73,23 @@ export const ServerGroup = HttpApiGroup.make("server.server") identifier: "server.connect", summary: "Redeem pairing code", description: - "Redeem a pairing code. Browsers receive a session cookie and a redirect to the web app; requests that accept JSON receive a session token to use as the password.", + "Redeem a pairing code. Browsers submitting the pairing page receive a session cookie and a redirect to the web app; other clients receive a session token to use as the password.", + }), + ), + ) + // Opening a link must not spend its code: link checkers, chat previews and HEAD probes fetch it before the user does. + // Omitted from generated clients. + .add( + HttpApiEndpoint.get("server.connectPage", PAIRING_CONNECT_PATH, { + params: { code: Schema.String }, + success: PairingSession, + error: UnauthorizedError, + }).annotateMerge( + OpenApi.annotations({ + identifier: "server.connectPage", + summary: "Open pairing link", + description: + "Show browsers a page that redeems the pairing code when the user confirms; the code stays valid until then. Deprecated: a GET that does not ask for HTML still redeems the code for a session token, for clients built before POST. Removed in the next minor.", }), ), ) diff --git a/packages/server/src/handlers/server.ts b/packages/server/src/handlers/server.ts index 7487581e70d..55517ad3ade 100644 --- a/packages/server/src/handlers/server.ts +++ b/packages/server/src/handlers/server.ts @@ -14,6 +14,28 @@ export const ServerHandler = HttpApiBuilder.group(Api, "server.server", (handler const pairing = yield* ServerPairing.Service const auth = yield* ServerAuth.Config + const redeem = Effect.fnUntraced(function* (code: string, request: HttpServerRequest.HttpServerRequest) { + // Browsers ask for HTML; everything else is an API client that wants the token. + const browser = request.headers.accept?.includes("text/html") === true + const token = (yield* pairing.consume(code)) ? ServerAuth.issueSession(auth) : undefined + if (token === undefined) { + if (!browser) return yield* new UnauthorizedError({ message: "Pairing link expired or already used" }) + return HttpServerResponse.text( + "This pairing link expired or was already used. Run `opencode pair` to get a new one.", + { status: 401 }, + ) + } + if (!browser) return { token } + return HttpServerResponse.redirect("/").pipe( + HttpServerResponse.setCookieUnsafe(ServerAuth.sessionCookieName(request.headers.host), token, { + path: "/", + httpOnly: true, + sameSite: "lax", + maxAge: Duration.seconds(ServerAuth.SESSION_TTL_SECONDS), + }), + ) + }) + return handlers .handle("server.info", () => Effect.gen(function* () { @@ -31,28 +53,56 @@ export const ServerHandler = HttpApiBuilder.group(Api, "server.server", (handler .handle("server.pair", () => pairing.issue()) .handle( "server.connect", + Effect.fn(function* (ctx) { + return yield* redeem(ctx.params.code, yield* HttpServerRequest.HttpServerRequest) + }), + ) + .handle( + "server.connectPage", Effect.fn(function* (ctx) { const request = yield* HttpServerRequest.HttpServerRequest - // Browser navigations ask for HTML; everything else is an API client that wants the token. - const browser = request.headers.accept?.includes("text/html") === true - const token = (yield* pairing.consume(ctx.params.code)) ? ServerAuth.issueSession(auth) : undefined - if (token === undefined) { - if (!browser) return yield* new UnauthorizedError({ message: "Pairing link expired or already used" }) - return HttpServerResponse.text( - "This pairing link expired or was already used. Run `opencode pair` to get a new one.", - { status: 401 }, - ) - } - if (!browser) return { token } - return HttpServerResponse.redirect("/").pipe( - HttpServerResponse.setCookieUnsafe(ServerAuth.sessionCookieName(request.headers.host), token, { - path: "/", - httpOnly: true, - sameSite: "lax", - maxAge: Duration.seconds(ServerAuth.SESSION_TTL_SECONDS), - }), - ) + // HEAD probes (wslview, link checkers) and page loads (browsers, chat previews) must not spend the code. + // The page's form POSTs back to this URL, which redeems it. + if (request.method === "HEAD" || request.headers.accept?.includes("text/html")) + return HttpServerResponse.text(CONNECT_PAGE, { + contentType: "text/html; charset=utf-8", + headers: { + "cache-control": "no-store", + "referrer-policy": "no-referrer", + "content-security-policy": + "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'", + }, + }) + // Deprecated: clients built before POST redeem with a plain GET. Removed in the next minor. + return yield* redeem(ctx.params.code, request) }), ) }), ) + +// Static, so nothing from the URL reaches the markup. The form has no action and posts back to the link itself. +const CONNECT_PAGE = ` + + + + + +Connect to OpenCode + + + +
+

Connect to OpenCode

+

Sign this browser in to the OpenCode server that created this pairing link.

+
+
+ + +` diff --git a/packages/server/test/process.test.ts b/packages/server/test/process.test.ts index 20ada8bae07..29c256c4baa 100644 --- a/packages/server/test/process.test.ts +++ b/packages/server/test/process.test.ts @@ -198,7 +198,21 @@ it.live("pairing links sign in browsers with a cookie and API clients with a tok const browser = yield* pair expect(browser.expires_in).toBe(300) - const redirect = yield* request(`/auth/connect/${browser.code}`, { headers: { accept: "text/html" } }) + // Link checkers (wslview's `curl --head`), chat previews and the browser's own page load must not spend the code. + for (const init of [{ method: "HEAD" }, { headers: { accept: "text/html" } }]) { + const page = yield* request(`/auth/connect/${browser.code}`, init) + expect(page.status).toBe(200) + expect(page.headers.get("content-type")).toContain("text/html") + expect(page.headers.get("set-cookie")).toBeNull() + yield* Effect.promise(() => page.arrayBuffer()) + } + const page = yield* request(`/auth/connect/${browser.code}`, { headers: { accept: "text/html" } }) + expect(yield* Effect.promise(() => page.text())).toContain('
') + const redirect = yield* request(`/auth/connect/${browser.code}`, { + method: "POST", + headers: { accept: "text/html", "content-type": "application/x-www-form-urlencoded" }, + body: "", + }) expect(redirect.status).toBe(302) expect(redirect.headers.get("location")).toBe("/") const setCookie = redirect.headers.get("set-cookie") ?? "" @@ -207,7 +221,7 @@ it.live("pairing links sign in browsers with a cookie and API clients with a tok expect(setCookie).toContain("SameSite=Lax") const cookie = setCookie.split(";")[0] - const reused = yield* request(`/auth/connect/${browser.code}`, { headers: { accept: "text/html" } }) + const reused = yield* request(`/auth/connect/${browser.code}`, { method: "POST", headers: { accept: "text/html" } }) expect(reused.status).toBe(401) expect(yield* Effect.promise(() => reused.text())).toContain("opencode pair") @@ -217,15 +231,22 @@ it.live("pairing links sign in browsers with a cookie and API clients with a tok expect((yield* request("/api/info", { headers: { cookie: `${cookie}x` } })).status).toBe(401) const client = yield* pair - const redeemed = yield* request(`/auth/connect/${client.code}`) + const redeemed = yield* request(`/auth/connect/${client.code}`, { method: "POST" }) expect(redeemed.status).toBe(200) const session = (yield* Effect.promise(() => redeemed.json())) as { token: string } expect( (yield* request("/api/info", { headers: { authorization: `Basic ${btoa(`opencode:${session.token}`)}` } })) .status, ).toBe(200) - expect((yield* request(`/auth/connect/${client.code}`)).status).toBe(401) - expect((yield* request("/auth/connect/unknown")).status).toBe(401) + expect((yield* request(`/auth/connect/${client.code}`, { method: "POST" })).status).toBe(401) + expect((yield* request("/auth/connect/unknown", { method: "POST" })).status).toBe(401) + + // Clients built before POST redeem with a plain GET. + const legacy = yield* pair + const legacyRedeemed = yield* request(`/auth/connect/${legacy.code}`) + expect(legacyRedeemed.status).toBe(200) + expect(yield* Effect.promise(() => legacyRedeemed.json())).toHaveProperty("token") + expect((yield* request(`/auth/connect/${legacy.code}`)).status).toBe(401) }), ) diff --git a/packages/server/test/request-site.test.ts b/packages/server/test/request-site.test.ts index f81abdb9836..f7977121b76 100644 --- a/packages/server/test/request-site.test.ts +++ b/packages/server/test/request-site.test.ts @@ -58,7 +58,7 @@ it.live("rejects API navigations and calls from other sites while other clients ).toBe(200) // Pairing links and artifact pages are opened from elsewhere on purpose. - expect(yield* status("/auth/connect/expired", { ...navigate("cross-site"), accept: "text/html" })).toBe(401) + expect(yield* status("/auth/connect/expired", { ...navigate("cross-site"), accept: "text/html" })).toBe(200) const artifact = new URL("/api/experimental/artifacts/art_missing/view/", server.base) artifact.searchParams.set("location[directory]", tmp.path) const opened = yield* Effect.promise(() =>