Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/app/src/runtime/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,19 @@ export const dict = {
"server.connect.password.prompt": "No pairing link?",
"server.connect.password.use": "Use password",
"server.connect.password.hint": "To see it, run opencode service get password on the server's computer.",
"server.connect.headers.title": "Headers",
"server.connect.headers.add": "Add header",
"server.connect.headers.name": "Header name",
"server.connect.headers.value": "Header value",
"server.connect.headers.remove": "Remove header",
"server.connect.headers.hint":
"Sent with every request, for a proxy in front of the server such as Cloudflare Access.",
"server.connect.headers.invalid": "Fix the highlighted header rows before connecting.",
"server.connect.headers.error.name": "Enter a header name, or remove this row.",
"server.connect.headers.error.invalid": "Use only letters, digits, and !#$%&'*+-.^_`|~ in a header name.",
"server.connect.headers.error.forbidden": "The browser cannot send this header.",
"server.connect.headers.error.value": "A header value cannot contain line breaks or control characters.",
"server.connect.headers.error.duplicate": "This header is already listed.",
"server.connect.link.prompt": "Have a pairing link?",
"server.connect.link.use": "Use pairing link",
"server.connect.button": "Connect",
Expand Down
50 changes: 50 additions & 0 deletions packages/app/src/runtime/server/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
fileStreamUrl,
machineFileStreamUrl,
serverRelativeUrl,
serverRequestHeaders,
} from "./api"

test.each([
Expand All @@ -26,12 +27,21 @@ test("authTokenFromCredentials ignores usernames in legacy saved credentials", (
test("fileStreamUrl never puts a credential in a media URL", () => {
const input = { path: "clips/final cut.mp4", directory: "/work/app" }
expect(fileStreamUrl({ url: "http://127.0.0.1:4096", password: "secret" }, input)).toBeUndefined()
expect(
fileStreamUrl({ url: "http://127.0.0.1:4096", headers: [{ name: "X-Api-Key", value: "key" }] }, input),
).toBeUndefined()
expect(fileStreamUrl({ url: "http://127.0.0.1:4096", headers: [{ name: "", value: "" }] }, input)).toBe(
"http://127.0.0.1:4096/api/fs/read/clips/final%20cut.mp4?location%5Bdirectory%5D=%2Fwork%2Fapp",
)
expect(fileStreamUrl({ url: "http://127.0.0.1:4096" }, input)).toBe(
"http://127.0.0.1:4096/api/fs/read/clips/final%20cut.mp4?location%5Bdirectory%5D=%2Fwork%2Fapp",
)

const path = "win:C:/clips/final cut.mp4"
expect(machineFileStreamUrl({ url: "http://127.0.0.1:4096", password: "secret" }, path)).toBeUndefined()
expect(
machineFileStreamUrl({ url: "http://127.0.0.1:4096", headers: [{ name: "X-Api-Key", value: "key" }] }, path),
).toBeUndefined()
expect(machineFileStreamUrl({ url: "http://127.0.0.1:4096" }, path)).toBe(
"http://127.0.0.1:4096/api/experimental/machine/file/read?path=win%3AC%3A%2Fclips%2Ffinal+cut.mp4",
)
Expand All @@ -47,6 +57,46 @@ test("serverRelativeUrl keeps the server's base path for a ticketed read", () =>
)
})

test("a saved header replaces Basic auth regardless of case, and unsendable rows are dropped", () => {
expect(
serverRequestHeaders({
password: "secret",
headers: [
{ name: "authorization", value: "Bearer token" },
{ name: "Cookie", value: "secret" },
{ name: "X-Api-Key", value: "first" },
{ name: "x-api-key", value: "last" },
],
}),
).toEqual({ authorization: "Bearer token", "x-api-key": "last" })
})

test("saved headers are sent, and an explicit Authorization wins over the password", async () => {
const requests: Headers[] = []

const api = createApiForServer({
server: {
url: "https://server.example:4096",
password: "secret",
headers: [
{ name: "X-Api-Key", value: "key" },
{ name: "Authorization", value: "Bearer token" },
],
},
// SAFETY: the API client only calls fetch with a URL and init, which this stub accepts.
fetch: (async (input: string | URL | Request, init?: RequestInit) => {
requests.push(new Headers(init?.headers))

return Response.json({ data: [], cursor: {} })
}) as typeof fetch,
})

await api.session.list()

expect(requests[0].get("x-api-key")).toBe("key")
expect(requests[0].get("authorization")).toBe("Bearer token")
})

test("only message and inbox reads ask for media refs, so other cross-origin requests stay unpreflighted", async () => {
const requests: Array<{ path: string; headers: Headers }> = []

Expand Down
47 changes: 33 additions & 14 deletions packages/app/src/runtime/server/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { OpenCode, withMediaRefs, type MediaRequestOptions } from "@opencode/cli
import type { ServerConnection } from "@/runtime/server/registry"
import { decode64 } from "@/runtime/persistence/base64"
import { machineFileURL } from "@opencode/util/path"
import { requestHeaders } from "./headers"

export function authTokenFromCredentials(input: { password: string }) {
return btoa(`opencode:${input.password}`)
Expand All @@ -23,29 +24,46 @@ export function authFromToken(token: string | null) {
/** `mediaRefs: false` reads stored media as inline bytes, for callers such as export that need self-contained messages. */
export type ServerRequestOptions = MediaRequestOptions

/** Request headers for a server: the generated Basic auth first, then the saved headers, which win on a clash. */
export function serverRequestHeaders(server: Pick<ServerConnection.HttpBase, "password" | "headers">) {
const headers: Record<string, string> = server.password
? {
Authorization: `Basic ${authTokenFromCredentials({
password: server.password,
})}`,
}
: {}

// A saved header wins even when it differs only in case, so `authorization` replaces the Basic one instead of being
// sent beside it.
for (const [name, value] of requestHeaders(server.headers)) {
for (const existing of Object.keys(headers)) {
if (existing.toLowerCase() === name.toLowerCase()) delete headers[existing]
}

headers[name] = value
}

return headers
}

export function createApiForServer(input: { server: ServerConnection.HttpBase; fetch?: typeof globalThis.fetch }) {
return withMediaRefs(
OpenCode.make({
baseUrl: input.server.url,
fetch: input.fetch,
headers: input.server.password
? {
Authorization: `Basic ${authTokenFromCredentials({
password: input.server.password,
})}`,
}
: undefined,
headers: serverRequestHeaders(input.server),
}),
)
}

/**
* The server's ranged read of one file, for media elements. They cannot send the Authorization header, and a credential
* never goes in a DOM URL, so a server that needs a password has none: its media downloads through the API instead.
* A machine file has a ticketed URL for that (see `machineFileStreamUrl`).
* The server's ranged read of one file, for media elements. They cannot send request headers, and a credential never
* goes in a DOM URL, so a server that needs a password or custom headers has none: its media downloads through the API
* instead. A machine file has a ticketed URL for that (see `machineFileStreamUrl`).
*/
export function fileStreamUrl(server: ServerConnection.HttpBase, input: { path: string; directory: string }) {
if (server.password) return
if (server.password || server.headers?.some((header) => header.name.trim())) return

const url = new URL(
`api/fs/read/${input.path.split("/").map(encodeURIComponent).join("/")}`,
Expand All @@ -58,11 +76,12 @@ export function fileStreamUrl(server: ServerConnection.HttpBase, input: { path:
}

/**
* The ranged read of a file on a paired machine, for media elements; none with a password, as `fileStreamUrl`. A
* server with a password issues a URL carrying a ticket for that one path instead (`machine.file.ticket`).
* The ranged read of a file on a paired machine, for media elements; none with a password or custom headers, as
* `fileStreamUrl`. A server with a password issues a URL carrying a ticket for that one path instead
* (`machine.file.ticket`).
*/
export function machineFileStreamUrl(server: ServerConnection.HttpBase, path: string) {
if (server.password) return
if (server.password || server.headers?.some((header) => header.name.trim())) return

return machineFileURL(server.url, path)
}
Expand Down
32 changes: 32 additions & 0 deletions packages/app/src/runtime/server/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,35 @@ test("rotates the HTTP client with the endpoint", async () => {
},
])
})

test("rebuilds the client when only the saved headers change", async () => {
const requests: Headers[] = []

// SAFETY: the transport only calls fetch with a request and init; `preconnect` and other statics are never read.
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input, init)
requests.push(request.headers)

return Response.json({
version: "2.0.0-test",
pid: 1,
urls: [request.url],
paths: { tmp: "/tmp/opencode" },
})
}) as typeof globalThis.fetch

const transport = createServerTransport({ http: { url: "http://127.0.0.1:4100" }, fetch })

await transport.api.server.info()

const replacement = transport.update({
url: "http://127.0.0.1:4100",
headers: [{ name: "X-Api-Key", value: "key" }],
})

await transport.api.server.info()

expect(replacement).toBe(transport.api)
expect(requests[0].get("x-api-key")).toBeNull()
expect(requests[1].get("x-api-key")).toBe("key")
})
10 changes: 7 additions & 3 deletions packages/app/src/runtime/server/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
() => {
const http = ServerConnection.http(server)

return http && `${http.url}\0${http.password ?? ""}`
return http && `${http.url}\0${http.password ?? ""}\0${JSON.stringify(http.headers ?? [])}`
},
() => {
const http = ServerConnection.http(server)
Expand Down Expand Up @@ -219,7 +219,11 @@ function resolveEndpoint(
}

function sameEndpoint(a: ServerConnection.HttpBase, b: ServerConnection.HttpBase) {
return a.url === b.url && a.password === b.password
return (
a.url === b.url &&
a.password === b.password &&
JSON.stringify(a.headers ?? []) === JSON.stringify(b.headers ?? [])
)
}

/** A server's HTTP client, rebuilt when its endpoint changes. */
Expand Down Expand Up @@ -248,7 +252,7 @@ export function createServerTransport(input: {
// Keeps the endpoint as plain values: a plugin's endpoint can be a store proxy that already reads the next password,
// and the client built here keeps the one it started with.
const build = (input: ServerConnection.HttpBase) => {
const http = { url: input.url, password: input.password }
const http = { url: input.url, password: input.password, headers: input.headers }

return { http, api: createApiForServer({ server: http, fetch: queue.fetch }) }
}
Expand Down
62 changes: 62 additions & 0 deletions packages/app/src/runtime/server/headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { describe, expect, test } from "bun:test"
import { headerProblems, requestHeaders } from "./headers"

describe("headerProblems", () => {
test("accepts ordinary and proxy headers", () => {
expect(
headerProblems([
{ name: "X-Api-Key", value: "key" },
{ name: "CF-Access-Client-Id", value: "id" },
{ name: "authorization", value: "Bearer token" },
]),
).toEqual([undefined, undefined, undefined])
})

test("a blank row is not a problem, but a value without a name is", () => {
expect(headerProblems([{ name: "", value: "" }])).toEqual([undefined])
expect(headerProblems([{ name: " ", value: "orphan" }])).toEqual(["name-missing"])
})

test("rejects names that are not HTTP tokens", () => {
expect(headerProblems([{ name: "X Api Key", value: "key" }])).toEqual(["name-invalid"])
expect(headerProblems([{ name: "X-Api-Key:", value: "key" }])).toEqual(["name-invalid"])
expect(headerProblems([{ name: "X-Api-Key\r\nX-Evil", value: "key" }])).toEqual(["name-invalid"])
})

test("rejects the headers a browser refuses to send", () => {
expect(headerProblems([{ name: "Cookie", value: "secret" }])).toEqual(["name-forbidden"])
expect(headerProblems([{ name: "content-length", value: "1" }])).toEqual(["name-forbidden"])
expect(headerProblems([{ name: "Proxy-Authorization", value: "secret" }])).toEqual(["name-forbidden"])
expect(headerProblems([{ name: "Sec-Fetch-Site", value: "none" }])).toEqual(["name-forbidden"])
})

test("rejects control characters in values but allows HTAB and obs-text", () => {
expect(headerProblems([{ name: "X-Api-Key", value: "a\nb" }])).toEqual(["value-invalid"])
expect(headerProblems([{ name: "X-Api-Key", value: "a\u0000b" }])).toEqual(["value-invalid"])
expect(headerProblems([{ name: "X-Api-Key", value: "a\tb" }])).toEqual([undefined])
expect(headerProblems([{ name: "X-Api-Key", value: "café" }])).toEqual([undefined])
})

test("flags a later duplicate regardless of case", () => {
expect(
headerProblems([
{ name: "X-Api-Key", value: "first" },
{ name: "x-api-key", value: "second" },
]),
).toEqual([undefined, "duplicate"])
})
})

describe("requestHeaders", () => {
test("trims, drops unsendable rows, and keeps the last duplicate", () => {
expect(
requestHeaders([
{ name: " X-Api-Key ", value: " key " },
{ name: "Cookie", value: "secret" },
{ name: "", value: "orphan" },
{ name: "", value: "" },
{ name: "x-api-key", value: "last" },
]),
).toEqual([["x-api-key", "last"]])
})
})
Loading
Loading