From 4b7d9b984e8dae9a05c9821cc2d730d938b7e0e6 Mon Sep 17 00:00:00 2001
From: bigcookie <5748299+biggestcookie@users.noreply.github.com>
Date: Tue, 1 Dec 2026 16:43:29 -0500
Subject: [PATCH 1/3] feat(app): custom request headers for server connections
Add request headers to the Add Server dialog and connect screen. In
password mode a Headers section lists name/value rows with a remove
action and a small Add header button, matching the mobile client.
Saved headers are sent on every request to the server (API client,
health checks, uploads), and an explicit Authorization header takes
precedence over the Basic auth generated from the password.
Refs #64673
---
packages/app/src/runtime/i18n/en.ts | 7 ++
packages/app/src/runtime/server/api.test.ts | 26 ++++++
packages/app/src/runtime/server/api.ts | 30 +++++--
packages/app/src/runtime/server/client.tsx | 10 ++-
.../app/src/runtime/server/health.test.ts | 15 ++++
packages/app/src/runtime/server/health.ts | 15 ++--
packages/app/src/runtime/server/machine.ts | 4 +-
.../app/src/runtime/server/persistence.ts | 23 +++--
.../app/src/runtime/server/plugin-machine.ts | 8 +-
.../server/server-sync/endpoint-machine.ts | 12 ++-
.../src/servers/connect/connect.fixture.tsx | 5 +-
packages/app/src/servers/connect/dialog.tsx | 61 +++++++++++++-
.../app/src/servers/connect/machine.test.ts | 79 +++++++++++++++++
packages/app/src/servers/connect/machine.ts | 84 +++++++++++++++++--
packages/app/src/servers/connect/screen.css | 38 +++++++++
packages/app/src/servers/connect/screen.tsx | 66 ++++++++++++++-
16 files changed, 446 insertions(+), 37 deletions(-)
diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts
index ff993fb1e7ce6..e50b6f630c4a6 100644
--- a/packages/app/src/runtime/i18n/en.ts
+++ b/packages/app/src/runtime/i18n/en.ts
@@ -542,6 +542,13 @@ 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.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..62566f082a16b 100644
--- a/packages/app/src/runtime/server/api.test.ts
+++ b/packages/app/src/runtime/server/api.test.ts
@@ -47,6 +47,32 @@ test("serverRelativeUrl keeps the server's base path for a ticketed read", () =>
)
})
+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..251f808d8d432 100644
--- a/packages/app/src/runtime/server/api.ts
+++ b/packages/app/src/runtime/server/api.ts
@@ -23,18 +23,34 @@ 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) {
+ return {
+ ...(server.password
+ ? {
+ Authorization: `Basic ${authTokenFromCredentials({
+ password: server.password,
+ })}`,
+ }
+ : {}),
+ ...Object.fromEntries(
+ (server.headers ?? []).flatMap((header) => {
+ const name = header.name.trim()
+
+ if (!name) return []
+
+ return [[name, header.value] as [string, string]]
+ }),
+ ),
+ }
+}
+
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),
}),
)
}
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/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.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.tsx b/packages/app/src/servers/connect/dialog.tsx
index 1d662f31ccee4..9a2e130d1f43d 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,60 @@ 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 })}
+ />
+
+ )}
+
+
+
{language.t("server.connect.headers.hint")}
+
+
+
From 084d20b3660f41930d3221acf74697991db5ac74 Mon Sep 17 00:00:00 2001
From: biggestcookie <5748299+biggestcookie@users.noreply.github.com>
Date: Tue, 1 Dec 2026 23:52:26 -0500
Subject: [PATCH 2/3] fix(app): validate custom server headers
Reject header rows a browser cannot send: non-token names, the Fetch forbidden list, control characters in values, and case-insensitive duplicates. Each row explains the problem and blocks submit; the request path trims, deduplicates and drops unsendable rows so a stored or plugin-written entry cannot throw or vanish silently.
A saved authorization now replaces the generated Basic header regardless of case, and media falls back to the API download when the connection has custom headers.
---
packages/app/src/runtime/i18n/en.ts | 6 +
packages/app/src/runtime/server/api.test.ts | 24 ++++
packages/app/src/runtime/server/api.ts | 51 +++++----
.../app/src/runtime/server/client.test.ts | 32 ++++++
.../app/src/runtime/server/headers.test.ts | 62 +++++++++++
packages/app/src/runtime/server/headers.ts | 94 ++++++++++++++++
.../src/runtime/server/persistence.test.ts | 19 ++++
packages/app/src/servers/connect/dialog.tsx | 87 +++++++++------
.../app/src/servers/connect/machine.test.ts | 33 ++++++
packages/app/src/servers/connect/machine.ts | 27 ++++-
packages/app/src/servers/connect/screen.tsx | 105 +++++++++++-------
11 files changed, 438 insertions(+), 102 deletions(-)
create mode 100644 packages/app/src/runtime/server/headers.test.ts
create mode 100644 packages/app/src/runtime/server/headers.ts
diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts
index e50b6f630c4a6..b0884a967c306 100644
--- a/packages/app/src/runtime/i18n/en.ts
+++ b/packages/app/src/runtime/i18n/en.ts
@@ -549,6 +549,12 @@ export const dict = {
"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 62566f082a16b..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,20 @@ 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[] = []
diff --git a/packages/app/src/runtime/server/api.ts b/packages/app/src/runtime/server/api.ts
index 251f808d8d432..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}`)
@@ -25,24 +26,25 @@ 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) {
- return {
- ...(server.password
- ? {
- Authorization: `Basic ${authTokenFromCredentials({
- password: server.password,
- })}`,
- }
- : {}),
- ...Object.fromEntries(
- (server.headers ?? []).flatMap((header) => {
- const name = header.name.trim()
-
- if (!name) return []
-
- return [[name, header.value] as [string, string]]
- }),
- ),
+ 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 }) {
@@ -56,12 +58,12 @@ export function createApiForServer(input: { server: ServerConnection.HttpBase; f
}
/**
- * 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("/")}`,
@@ -74,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/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/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/servers/connect/dialog.tsx b/packages/app/src/servers/connect/dialog.tsx
index 9a2e130d1f43d..a910272c6e159 100644
--- a/packages/app/src/servers/connect/dialog.tsx
+++ b/packages/app/src/servers/connect/dialog.tsx
@@ -199,39 +199,58 @@ 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 })}
- />
+
+
+ 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) => (
+
+ )}
+
)}
@@ -245,7 +264,7 @@ export function DialogServer(props: {
>
{language.t("server.connect.headers.add")}
- {language.t("server.connect.headers.hint")}
+ {language.t("server.connect.headers.hint")}
diff --git a/packages/app/src/servers/connect/machine.test.ts b/packages/app/src/servers/connect/machine.test.ts
index b0ffb2ca10666..2b44a6231c44e 100644
--- a/packages/app/src/servers/connect/machine.test.ts
+++ b/packages/app/src/servers/connect/machine.test.ts
@@ -390,6 +390,39 @@ describe("server connect form", () => {
})
})
+ test("an unsendable header row is explained and blocks submit", () => {
+ const result = replay({ kind: "add" }, [
+ password,
+ field("url", "new:4096"),
+ { type: "header.added" },
+ header(0, "name", "Cookie"),
+ header(0, "value", "secret"),
+ ])
+
+ const view = selectServerConnectView(result.state, context)
+ expect(view.headerErrors).toEqual(["server.connect.headers.error.forbidden"])
+ expect(view.canSubmit).toBe(false)
+
+ const submit = transitionServerConnect(result.state, submitted)
+ expect(submit.state).toMatchObject({ status: "editing", error: { type: "headers-invalid" } })
+ expect(submit.effects).toEqual([])
+ })
+
+ test("a header repeated with different casing is flagged", () => {
+ const result = replay({ kind: "add" }, [
+ password,
+ { type: "header.added" },
+ header(0, "name", "X-Api-Key"),
+ { type: "header.added" },
+ header(1, "name", "x-api-key"),
+ ])
+
+ expect(selectServerConnectView(result.state, context).headerErrors).toEqual([
+ undefined,
+ "server.connect.headers.error.duplicate",
+ ])
+ })
+
test("an unchanged edit of a signed-out server checks the credentials again", () => {
const result = replay(edit({ password: "secret", unauthorized: true }), [password, submitted])
diff --git a/packages/app/src/servers/connect/machine.ts b/packages/app/src/servers/connect/machine.ts
index 725ad3025be1b..de946ac562d01 100644
--- a/packages/app/src/servers/connect/machine.ts
+++ b/packages/app/src/servers/connect/machine.ts
@@ -1,4 +1,5 @@
import type { ServerConnection } from "@/runtime/server/registry"
+import { headerProblems, type HeaderProblem } from "@/runtime/server/headers"
import { isMixedContent } from "./browser"
import type { ConnectMethod } from "./method"
import { bareServerAddress, legacyPairingLink, pairingLink, serverAddress } from "./pairing"
@@ -57,6 +58,7 @@ export type ServerConnectError =
| { readonly type: "link-invalid" }
| { readonly type: "link-legacy" }
| { readonly type: "address-invalid" }
+ | { readonly type: "headers-invalid" }
/** Already localized by `useRedeemPairing`. */
| { readonly type: "redeem"; readonly message: string }
| { readonly type: "connection-failed"; readonly url: string }
@@ -265,6 +267,7 @@ export type ServerConnectErrorKey =
| "server.connect.link.invalid"
| "server.connect.link.legacy"
| "server.connect.address.invalid"
+ | "server.connect.headers.invalid"
| "server.connect.mixedContent"
| "server.connect.failed"
| "dialog.server.add.error"
@@ -273,6 +276,11 @@ export type ServerConnectViewKey =
| ServerConnectErrorKey
| "server.connect.camera.unavailable"
| "server.connect.camera.native"
+ | "server.connect.headers.error.name"
+ | "server.connect.headers.error.invalid"
+ | "server.connect.headers.error.forbidden"
+ | "server.connect.headers.error.value"
+ | "server.connect.headers.error.duplicate"
export type ServerConnectErrorContext = {
readonly surface: "screen" | "dialog"
@@ -290,6 +298,8 @@ export function formatServerConnectError(error: ServerConnectError, context: Ser
if (error.type === "address-invalid") return context.t("server.connect.address.invalid")
+ if (error.type === "headers-invalid") return context.t("server.connect.headers.invalid")
+
if (context.pageHref && isMixedContent(context.pageHref, error.url)) return context.t("server.connect.mixedContent")
return context.t(context.surface === "screen" ? "server.connect.failed" : "dialog.server.add.error")
@@ -299,8 +309,11 @@ export function selectServerConnectView(state: ServerConnectState, context: Serv
const link = state.draft.method === "link"
const primary = link ? state.draft.link : state.draft.url
const camera = state.camera.status
+ const headers = headerProblems(state.draft.headers)
return {
+ /** One localized message per header row, aligned with the draft; undefined for a valid or blank row. */
+ headerErrors: headers.map((problem) => (problem ? context.t(headerProblemKeys[problem]) : undefined)),
// Shown, disabled, while the camera check runs, so the hint does not flash in first.
showScan: link && (camera === "available" || camera === "probing"),
canScan: state.status === "editing" && link && camera === "available",
@@ -308,7 +321,7 @@ export function selectServerConnectView(state: ServerConnectState, context: Serv
scanning: state.status === "scanning",
busy: state.status === "submitting",
disabled: state.status !== "editing",
- canSubmit: state.status === "editing" && primary.trim().length > 0,
+ canSubmit: state.status === "editing" && primary.trim().length > 0 && !headers.some(Boolean),
signedOut: state.target.kind === "edit" && state.target.original.unauthorized,
draft: state.draft,
error: state.status === "editing" && state.error ? formatServerConnectError(state.error, context) : undefined,
@@ -326,6 +339,14 @@ function cameraHint(camera: ServerCameraState["status"], context: ServerConnectE
return undefined
}
+const headerProblemKeys: Record = {
+ "name-missing": "server.connect.headers.error.name",
+ "name-invalid": "server.connect.headers.error.invalid",
+ "name-forbidden": "server.connect.headers.error.forbidden",
+ "value-invalid": "server.connect.headers.error.value",
+ duplicate: "server.connect.headers.error.duplicate",
+}
+
const stop = { type: "timer.stop" } as const
function probe(attempt: number): ServerConnectEffect {
@@ -378,6 +399,10 @@ function editing(state: Form, draft: ServerConnectDraft, error?: ServerConnectEr
// Where the form points: a pasted or scanned pairing link wins, in either field; else the address and password.
function submit(state: Form, draft: ServerConnectDraft): ServerConnectTransition {
+ // Headers are saved whichever method reaches the server, so an invalid row blocks both paths.
+ if (headerProblems(draft.headers).some(Boolean))
+ return { state: editing(state, draft, { type: "headers-invalid" }), effects: [] }
+
const value = draft.method === "link" ? draft.link : draft.url
const link = pairingLink(value)
const attempt = state.attempt + 1
diff --git a/packages/app/src/servers/connect/screen.tsx b/packages/app/src/servers/connect/screen.tsx
index 7bfd3e59e469c..e678f7fe590c8 100644
--- a/packages/app/src/servers/connect/screen.tsx
+++ b/packages/app/src/servers/connect/screen.tsx
@@ -131,49 +131,68 @@ export function ConnectServerForm(props: {
{(header, index) => (
-