diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts
index ff993fb1e7ce6..b0884a967c306 100644
--- a/packages/app/src/runtime/i18n/en.ts
+++ b/packages/app/src/runtime/i18n/en.ts
@@ -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",
diff --git a/packages/app/src/runtime/server/api.test.ts b/packages/app/src/runtime/server/api.test.ts
index cb2364cd2fa98..bccdf253c16d6 100644
--- a/packages/app/src/runtime/server/api.test.ts
+++ b/packages/app/src/runtime/server/api.test.ts
@@ -6,6 +6,7 @@ import {
fileStreamUrl,
machineFileStreamUrl,
serverRelativeUrl,
+ serverRequestHeaders,
} from "./api"
test.each([
@@ -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",
)
@@ -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 }> = []
diff --git a/packages/app/src/runtime/server/api.ts b/packages/app/src/runtime/server/api.ts
index bc13412e5cc2d..57af5b65bbea7 100644
--- a/packages/app/src/runtime/server/api.ts
+++ b/packages/app/src/runtime/server/api.ts
@@ -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}`)
@@ -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) {
+ const headers: Record = 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("/")}`,
@@ -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)
}
diff --git a/packages/app/src/runtime/server/client.test.ts b/packages/app/src/runtime/server/client.test.ts
index 6312ba577bc43..610b29d8c6baa 100644
--- a/packages/app/src/runtime/server/client.test.ts
+++ b/packages/app/src/runtime/server/client.test.ts
@@ -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")
+})
diff --git a/packages/app/src/runtime/server/client.tsx b/packages/app/src/runtime/server/client.tsx
index 6a24438c178a8..d7279d3846d23 100644
--- a/packages/app/src/runtime/server/client.tsx
+++ b/packages/app/src/runtime/server/client.tsx
@@ -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)
@@ -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. */
@@ -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 }) }
}
diff --git a/packages/app/src/runtime/server/headers.test.ts b/packages/app/src/runtime/server/headers.test.ts
new file mode 100644
index 0000000000000..c0687d6e9cf0f
--- /dev/null
+++ b/packages/app/src/runtime/server/headers.test.ts
@@ -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"]])
+ })
+})
diff --git a/packages/app/src/runtime/server/headers.ts b/packages/app/src/runtime/server/headers.ts
new file mode 100644
index 0000000000000..68e3f80214540
--- /dev/null
+++ b/packages/app/src/runtime/server/headers.ts
@@ -0,0 +1,94 @@
+/**
+ * Rules for the custom headers a connection saves. The form applies them to explain a row, and the request path applies
+ * them so a stored or plugin-written entry can never make `fetch` throw or quietly behave differently per surface.
+ *
+ * Browsers silently drop several request headers (and throw on some values) while a native client may send them, so both
+ * are rejected here instead of letting one saved connection act differently on the web and in the desktop app.
+ */
+
+export type RequestHeader = { readonly name: string; readonly value: string }
+
+export type HeaderProblem = "name-missing" | "name-invalid" | "name-forbidden" | "value-invalid" | "duplicate"
+
+// RFC 9110 field-name: one or more tchar.
+const namePattern = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
+
+// Field values are visible ASCII, HTAB and obs-text; anything else is a control character or needs encoding.
+const valuePattern = /^[\t\x20-\x7e\x80-\xff]*$/
+
+// The Fetch standard's forbidden request-header names, which a browser refuses to send.
+const forbidden = new Set([
+ "accept-charset",
+ "accept-encoding",
+ "access-control-request-headers",
+ "access-control-request-method",
+ "connection",
+ "content-length",
+ "cookie",
+ "cookie2",
+ "date",
+ "dnt",
+ "expect",
+ "host",
+ "keep-alive",
+ "origin",
+ "referer",
+ "set-cookie",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ "via",
+])
+
+/** One problem per header row, aligned with the input. `undefined` means the row is valid or blank. */
+export function headerProblems(headers: readonly RequestHeader[]): (HeaderProblem | undefined)[] {
+ const seen = new Set()
+
+ return headers.map((header) => {
+ const name = header.name.trim()
+
+ // A row with neither part is just an unused input; one with a value and no name cannot be sent.
+ if (!name) return header.value.trim() ? "name-missing" : undefined
+
+ if (!namePattern.test(name)) return "name-invalid"
+
+ if (isForbiddenName(name)) return "name-forbidden"
+
+ if (!valuePattern.test(header.value.trim())) return "value-invalid"
+
+ const key = name.toLowerCase()
+
+ if (seen.has(key)) return "duplicate"
+
+ seen.add(key)
+
+ return undefined
+ })
+}
+
+/**
+ * The headers a request can actually send: trimmed, without blank or unsendable rows, and deduplicated
+ * case-insensitively (the last entry wins). Plain entries, because `new Headers` merges object keys that differ only in
+ * case instead of replacing one.
+ */
+export function requestHeaders(headers: readonly RequestHeader[] | undefined): [string, string][] {
+ const entries = new Map()
+
+ for (const header of headers ?? []) {
+ const name = header.name.trim()
+ const value = header.value.trim()
+
+ if (!name || !namePattern.test(name) || isForbiddenName(name) || !valuePattern.test(value)) continue
+
+ entries.set(name.toLowerCase(), [name, value])
+ }
+
+ return [...entries.values()]
+}
+
+function isForbiddenName(name: string) {
+ const lower = name.toLowerCase()
+
+ return forbidden.has(lower) || lower.startsWith("proxy-") || lower.startsWith("sec-")
+}
diff --git a/packages/app/src/runtime/server/health.test.ts b/packages/app/src/runtime/server/health.test.ts
index a7861f3412c79..07c74abf29fbf 100644
--- a/packages/app/src/runtime/server/health.test.ts
+++ b/packages/app/src/runtime/server/health.test.ts
@@ -46,6 +46,21 @@ describe("checkServerHealth", () => {
])
})
+ test("sends the connection's saved headers with the health check", async () => {
+ const requests: Headers[] = []
+
+ const fetch = fakeFetch(async (_input, init) => {
+ requests.push(new Headers(init?.headers))
+
+ return info()
+ })
+
+ const result = await checkServerHealth({ ...server, headers: [{ name: "X-Api-Key", value: "key" }] }, fetch)
+
+ expect(result).toMatchObject({ type: "healthy" })
+ expect(requests[0].get("x-api-key")).toBe("key")
+ })
+
test("reports rejected credentials without retrying", async () => {
let calls = 0
diff --git a/packages/app/src/runtime/server/health.ts b/packages/app/src/runtime/server/health.ts
index 751c71da64cbf..93d999414ff89 100644
--- a/packages/app/src/runtime/server/health.ts
+++ b/packages/app/src/runtime/server/health.ts
@@ -1,6 +1,6 @@
import { usePlatform } from "@/runtime/platform/platform"
import { ServerConnection } from "@/runtime/server/registry"
-import { authTokenFromCredentials } from "./api"
+import { serverRequestHeaders } from "./api"
import {
createServerHealthState,
selectServerHealthRecord,
@@ -104,11 +104,7 @@ export async function checkServerHealth(
const retryCount = opts?.retryCount ?? defaultRetryCount
const retryDelayMs = opts?.retryDelayMs ?? defaultRetryDelayMs
- const headers = server.password
- ? {
- Authorization: `Basic ${authTokenFromCredentials({ password: server.password })}`,
- }
- : undefined
+ const headers = serverRequestHeaders(server)
const next = (count: number, retry: boolean): Promise => {
if (count >= retryCount || !retry) return Promise.resolve(unreachable)
@@ -228,7 +224,12 @@ function healthInput(conn: ServerConnection.Any): ServerHealthInput {
const key = ServerConnection.key(conn)
if (conn.type !== "plugin")
- return { type: "endpoint", key, http: { url: conn.http.url, password: conn.http.password }, managed: false }
+ return {
+ type: "endpoint",
+ key,
+ http: { url: conn.http.url, password: conn.http.password, headers: conn.http.headers },
+ managed: false,
+ }
if (conn.status.type === "ready") return { type: "endpoint", key, http: conn.status.http, managed: conn.managed }
diff --git a/packages/app/src/runtime/server/machine.ts b/packages/app/src/runtime/server/machine.ts
index eeb7170f77681..3b29b86a5917f 100644
--- a/packages/app/src/runtime/server/machine.ts
+++ b/packages/app/src/runtime/server/machine.ts
@@ -90,7 +90,9 @@ type ServerEffect =
type ServerTransition = { readonly state: ServerControllerState; readonly effects: readonly ServerEffect[] }
export function endpointCredentials(http: ServerConnection.HttpBase) {
- return `${http.url}\n${http.password ?? ""}`
+ const headers = http.headers?.length ? `\n${JSON.stringify(http.headers)}` : ""
+
+ return `${http.url}\n${http.password ?? ""}${headers}`
}
export function serverCredentials(conn: ServerConnection.Any): ServerCredentials {
diff --git a/packages/app/src/runtime/server/persistence.test.ts b/packages/app/src/runtime/server/persistence.test.ts
index 10ed3af86e6d2..841267dd6dd1f 100644
--- a/packages/app/src/runtime/server/persistence.test.ts
+++ b/packages/app/src/runtime/server/persistence.test.ts
@@ -56,6 +56,25 @@ describe("server persistence schema", () => {
expect(Schema.decodeUnknownSync(schema)(encoded)).toEqual(state)
})
+ test("keeps a connection's custom headers through decode and encode", () => {
+ const schema = serverSchema()
+
+ const list = [
+ {
+ type: "http" as const,
+ http: {
+ url: "https://proxy.example",
+ headers: [{ name: "CF-Access-Client-Id", value: "id" }],
+ },
+ },
+ ]
+
+ const state = Schema.decodeUnknownSync(schema)({ list })
+
+ expect(state.list).toEqual(list)
+ expect(Schema.encodeSync(schema)(state)).toEqual(state)
+ })
+
test("defaults missing or malformed fields and drops invalid entries independently", () => {
const decode = Schema.decodeUnknownSync(serverSchema())
expect(decode({})).toEqual(initial)
diff --git a/packages/app/src/runtime/server/persistence.ts b/packages/app/src/runtime/server/persistence.ts
index ef15fadfcca1c..f49a19e1dbd04 100644
--- a/packages/app/src/runtime/server/persistence.ts
+++ b/packages/app/src/runtime/server/persistence.ts
@@ -6,6 +6,7 @@ export const ServerKey = Schema.String.pipe(Schema.brand("ServerConnection.Key")
export const ServerHttpBase = Persistence.struct({
url: Schema.String,
password: Schema.optional(Schema.String),
+ headers: Persistence.optional(Persistence.array(Persistence.struct({ name: Schema.String, value: Schema.String }))),
})
export const ServerHttp = Persistence.struct({
@@ -16,16 +17,28 @@ export const ServerHttp = Persistence.struct({
label: Schema.optional(Schema.String),
})
-const StoredServer = Schema.Union([ServerHttp, ServerHttpBase, Schema.String]).pipe(
+const StoredServerInput = Schema.Union([ServerHttp, ServerHttpBase, Schema.String])
+
+const StoredServer = StoredServerInput.pipe(
Schema.decodeTo(ServerHttp, {
- decode: SchemaGetter.transform((value) => {
+ // Stored values predate headers, so the encoded array shape differs from the decoded one; this is the same
+ // untyped storage boundary `withInitial` handles, and the loaded value is decoded with `ServerHttp` after it.
+ decode: SchemaGetter.transform((value): typeof ServerHttp.Type => {
if (Predicate.isString(value)) return { type: "http", http: { url: value } }
- if ("http" in value) return value
+ if ("http" in value) {
+ // SAFETY: the `http` branch carries the stored server shape, which `withInitial` decodes with ServerHttp.
+ return value as typeof ServerHttp.Type
+ }
- return { type: "http", http: value }
+ // SAFETY: the flat branch is the stored form of `ServerHttp["http"]`, decoded through this same schema.
+ return { type: "http", http: value as (typeof ServerHttp.Type)["http"] }
}),
- encode: SchemaGetter.transform((value) => value),
+ encode: SchemaGetter.transform(
+ (value: typeof StoredServerInput.Encoded): typeof StoredServerInput.Type =>
+ // SAFETY: the stored and current shapes differ only in array variance, so encoding passes the value through.
+ value as typeof StoredServerInput.Type,
+ ),
}),
)
diff --git a/packages/app/src/runtime/server/plugin-machine.ts b/packages/app/src/runtime/server/plugin-machine.ts
index 3c9c3a48a9de0..2d7a0a249dab4 100644
--- a/packages/app/src/runtime/server/plugin-machine.ts
+++ b/packages/app/src/runtime/server/plugin-machine.ts
@@ -158,11 +158,15 @@ function target(
if (!entry.http) return { status: "failed" }
- return { status: "ready", http: { url: entry.http.url, password: entry.http.password } }
+ return { status: "ready", http: { url: entry.http.url, password: entry.http.password, headers: entry.http.headers } }
}
function same(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 ?? [])
+ )
}
function unchanged(state: PluginServerState): PluginServerTransition {
diff --git a/packages/app/src/runtime/server/server-sync/endpoint-machine.ts b/packages/app/src/runtime/server/server-sync/endpoint-machine.ts
index c1d92151273f2..b28336574ead0 100644
--- a/packages/app/src/runtime/server/server-sync/endpoint-machine.ts
+++ b/packages/app/src/runtime/server/server-sync/endpoint-machine.ts
@@ -26,7 +26,7 @@ export type EndpointSyncTransition = {
}
export function createEndpointSyncState(http: ServerConnection.HttpBase): EndpointSyncState {
- return { type: "idle", http: { url: http.url, password: http.password }, attempt: 0 }
+ return { type: "idle", http: { url: http.url, password: http.password, headers: http.headers }, attempt: 0 }
}
export function transitionEndpointSync(state: EndpointSyncState, event: EndpointSyncEvent): EndpointSyncTransition {
@@ -39,7 +39,7 @@ export function transitionEndpointSync(state: EndpointSyncState, event: Endpoint
if (event.type === "endpoint.reported") {
if (sameEndpoint(state.http, event.http)) return { state, effects: [] }
- const http = { url: event.http.url, password: event.http.password }
+ const http = { url: event.http.url, password: event.http.password, headers: event.http.headers }
// A resolution still running is now stale: its result arrives in `idle` and is ignored.
return {
@@ -52,11 +52,15 @@ export function transitionEndpointSync(state: EndpointSyncState, event: Endpoint
if (event.type === "resolve.failed" || sameEndpoint(state.http, event.http))
return { state: { type: "idle", http: state.http, attempt: state.attempt }, effects: [] }
- const http = { url: event.http.url, password: event.http.password }
+ const http = { url: event.http.url, password: event.http.password, headers: event.http.headers }
return { state: { type: "idle", http, attempt: state.attempt }, effects: [{ type: "transport.update", http }] }
}
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 ?? [])
+ )
}
diff --git a/packages/app/src/servers/connect/connect.fixture.tsx b/packages/app/src/servers/connect/connect.fixture.tsx
index c76e131f087d2..0f5c72ef18f52 100644
--- a/packages/app/src/servers/connect/connect.fixture.tsx
+++ b/packages/app/src/servers/connect/connect.fixture.tsx
@@ -22,7 +22,10 @@ type CameraScene = "ready" | "opening" | "denied" | "invalid" | "decode" | "expi
type Preset = {
camera?: ServerCameraSupport | "probing"
- events?: Extract[]
+ events?: Extract<
+ ServerConnectEvent,
+ { type: "field.changed" | "method.changed" | "submitted" | "header.added" | "header.removed" | "header.changed" }
+ >[]
scanner?: CameraScene
exchange?: "expired" | "unreachable"
check?: "unreachable" | "pending"
diff --git a/packages/app/src/servers/connect/dialog.lab.tsx b/packages/app/src/servers/connect/dialog.lab.tsx
index 10bd188880d9a..31e77d58e1940 100644
--- a/packages/app/src/servers/connect/dialog.lab.tsx
+++ b/packages/app/src/servers/connect/dialog.lab.tsx
@@ -3,9 +3,12 @@ import type { ServerConnectTarget } from "./machine"
const edit = {
kind: "edit",
- original: { url: address, displayName: "Build cluster", password: undefined, unauthorized: false },
+ original: { url: address, displayName: "Build cluster", password: undefined, headers: [], unauthorized: false },
} satisfies ServerConnectTarget
+const header = (index: number, part: "name" | "value", value: string) =>
+ ({ type: "header.changed", index, part, value }) as const
+
export default {
title: "App/Dialogs/Add Server",
id: "app-dialog-add-server",
@@ -15,6 +18,20 @@ export const PairingLink = serverLab()
export const Password = serverLab({ events: [password] })
+export const Headers = serverLab({
+ events: [
+ password,
+ { type: "header.added" },
+ header(0, "name", "X-Api-Key"),
+ header(0, "value", "secret"),
+ { type: "header.added" },
+ ],
+})
+
+export const HeadersInvalid = serverLab({
+ events: [password, { type: "header.added" }, header(0, "name", "Cookie"), header(0, "value", "secret")],
+})
+
export const ReadyToPair = serverLab({ events: [field("link", link), field("name", "Build cluster")] })
export const InvalidLink = serverLab({ events: [field("link", "incomplete"), submit] })
diff --git a/packages/app/src/servers/connect/dialog.tsx b/packages/app/src/servers/connect/dialog.tsx
index 1d662f31ccee4..a910272c6e159 100644
--- a/packages/app/src/servers/connect/dialog.tsx
+++ b/packages/app/src/servers/connect/dialog.tsx
@@ -2,9 +2,10 @@ import { Button } from "@opencode/ui/button"
import { Dialog, DialogBody, DialogFooter, DialogHeader, DialogTitle } from "@opencode/ui/dialog"
import { Divider } from "@opencode/ui/divider"
import { Icon } from "@opencode/ui/icon"
+import { IconButton } from "@opencode/ui/icon-button"
import { TextInput } from "@opencode/ui/text-input"
import { useDialog } from "@opencode/ui/context/dialog"
-import { type Component, type ComponentProps, Show, Suspense, createMemo, lazy, untrack } from "solid-js"
+import { type Component, type ComponentProps, Index, Show, Suspense, createMemo, lazy, untrack } from "solid-js"
import { useGlobal } from "@/runtime/server/runtime"
import { useLanguage } from "@/runtime/i18n/language"
import { ServerConnection, useServers } from "@/runtime/server/registry"
@@ -52,6 +53,9 @@ export function DialogServer(props: {
const submit = () => form.dispatch({ type: "submitted" })
const change = (field: ServerConnectField, value: string) => form.dispatch({ type: "field.changed", field, value })
+ const changeHeader = (index: number, part: "name" | "value", value: string) =>
+ form.dispatch({ type: "header.changed", index, part, value })
+
const keyDown = (event: KeyboardEvent) => {
if (event.key !== "Enter" || event.isComposing) return
event.preventDefault()
@@ -190,6 +194,79 @@ export function DialogServer(props: {
+
+
+
{language.t("server.connect.headers.title")}
+
+ {(header, index) => (
+
+
+ changeHeader(index, "name", event.currentTarget.value)}
+ onKeyDown={keyDown}
+ />
+ changeHeader(index, "value", event.currentTarget.value)}
+ onKeyDown={keyDown}
+ />
+ }
+ aria-label={language.t("server.connect.headers.remove")}
+ disabled={view().disabled}
+ onClick={() => form.dispatch({ type: "header.removed", index })}
+ />
+
+
+ {(error) => (
+
+ )}
+
+
+ )}
+
+
+
{language.t("server.connect.headers.hint")}
+
+
+