diff --git a/packages/app/src/app.tsx b/packages/app/src/app.tsx index 11fdb574329..350c03833f9 100644 --- a/packages/app/src/app.tsx +++ b/packages/app/src/app.tsx @@ -43,7 +43,7 @@ function UiI18nBridge(props: ParentProps) { declare global { interface Window { - __OPENCODE__?: { updaterEnabled?: boolean; serverPassword?: string; deepLinks?: string[] } + __OPENCODE__?: { updaterEnabled?: boolean; serverPassword?: string; deepLinks?: string[]; rootPath?: string } } } @@ -102,7 +102,18 @@ export function AppInterface(props: { defaultUrl?: string }) { if (import.meta.env.DEV) return `http://${import.meta.env.VITE_OPENCODE_SERVER_HOST ?? "localhost"}:${import.meta.env.VITE_OPENCODE_SERVER_PORT ?? "4096"}` - return window.location.origin + const rootPath = document.getElementById("root")?.dataset.rootPath || window.__OPENCODE__?.rootPath || "" + + // Properly normalize URL to avoid duplicate slashes + if (!rootPath) return window.location.origin + + try { + const normalized = new URL(rootPath, window.location.origin).toString() + // Remove trailing slash + return normalized.replace(/\/+$/, "") + } catch { + return (window.location.origin + rootPath).replace(/\/+$/, "") + } } return ( @@ -111,6 +122,7 @@ export function AppInterface(props: { defaultUrl?: string }) { ( diff --git a/packages/app/src/pages/directory-layout.tsx b/packages/app/src/pages/directory-layout.tsx index 037b08c723a..140286a8a69 100644 --- a/packages/app/src/pages/directory-layout.tsx +++ b/packages/app/src/pages/directory-layout.tsx @@ -25,7 +25,7 @@ export default function Layout(props: ParentProps) { showToast({ variant: "error", title: language.t("common.requestFailed"), - description: "Invalid directory in URL.", + description: `Invalid directory in URL (${params.dir}).`, }) navigate("/") }) diff --git a/packages/opencode/src/cli/cmd/serve.ts b/packages/opencode/src/cli/cmd/serve.ts index bee2c8f711f..654150d8fa5 100644 --- a/packages/opencode/src/cli/cmd/serve.ts +++ b/packages/opencode/src/cli/cmd/serve.ts @@ -13,7 +13,8 @@ export const ServeCommand = cmd({ } const opts = await resolveNetworkOptions(args) const server = Server.listen(opts) - console.log(`opencode server listening on http://${server.hostname}:${server.port}`) + const displayUrl = opts.rootPath ? new URL(opts.rootPath, `http://${server.hostname}:${server.port}`).toString() : `http://${server.hostname}:${server.port}` + console.log(`opencode server listening on ${displayUrl}`) await new Promise(() => {}) await server.stop() }, diff --git a/packages/opencode/src/cli/cmd/web.ts b/packages/opencode/src/cli/cmd/web.ts index 5fa2bb42640..7215369cce8 100644 --- a/packages/opencode/src/cli/cmd/web.ts +++ b/packages/opencode/src/cli/cmd/web.ts @@ -37,24 +37,25 @@ export const WebCommand = cmd({ UI.println(UI.Style.TEXT_WARNING_BOLD + "! " + "OPENCODE_SERVER_PASSWORD is not set; server is unsecured.") } const opts = await resolveNetworkOptions(args) - const server = Server.listen(opts) + const server = await Server.listen(opts) UI.empty() UI.println(UI.logo(" ")) UI.empty() if (opts.hostname === "0.0.0.0") { // Show localhost for local access - const localhostUrl = `http://localhost:${server.port}` - UI.println(UI.Style.TEXT_INFO_BOLD + " Local access: ", UI.Style.TEXT_NORMAL, localhostUrl) + const baseUrl = opts.rootPath ? new URL(opts.rootPath, `http://localhost:${server.port}`).toString() : `http://localhost:${server.port}` + UI.println(UI.Style.TEXT_INFO_BOLD + " Local access: ", UI.Style.TEXT_NORMAL, baseUrl) // Show network IPs for remote access const networkIPs = getNetworkIPs() if (networkIPs.length > 0) { for (const ip of networkIPs) { + const networkUrl = opts.rootPath ? new URL(opts.rootPath, `http://${ip}:${server.port}`).toString() : `http://${ip}:${server.port}` UI.println( UI.Style.TEXT_INFO_BOLD + " Network access: ", UI.Style.TEXT_NORMAL, - `http://${ip}:${server.port}`, + networkUrl, ) } } @@ -68,14 +69,17 @@ export const WebCommand = cmd({ } // Open localhost in browser - open(localhostUrl.toString()).catch(() => {}) + open(baseUrl.toString()).catch(() => { }) } else { - const displayUrl = server.url.toString() + let displayUrl = server.url.toString() + if (opts.rootPath) { + displayUrl = new URL(opts.rootPath, server.url).toString() + } UI.println(UI.Style.TEXT_INFO_BOLD + " Web interface: ", UI.Style.TEXT_NORMAL, displayUrl) - open(displayUrl).catch(() => {}) + open(displayUrl).catch(() => { }) } - await new Promise(() => {}) + await new Promise(() => { }) await server.stop() }, }) diff --git a/packages/opencode/src/cli/network.ts b/packages/opencode/src/cli/network.ts index fe5731d0713..507848571e8 100644 --- a/packages/opencode/src/cli/network.ts +++ b/packages/opencode/src/cli/network.ts @@ -23,6 +23,11 @@ const options = { describe: "additional domains to allow for CORS", default: [] as string[], }, + rootPath: { + type: "string" as const, + describe: "base path for reverse proxy", + default: "", + }, } export type NetworkOptions = InferredOptionTypes @@ -37,6 +42,7 @@ export async function resolveNetworkOptions(args: NetworkOptions) { const hostnameExplicitlySet = process.argv.includes("--hostname") const mdnsExplicitlySet = process.argv.includes("--mdns") const corsExplicitlySet = process.argv.includes("--cors") + const rootPathExplicitlySet = process.argv.includes("--root-path") const mdns = mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns) const port = portExplicitlySet ? args.port : (config?.server?.port ?? args.port) @@ -48,6 +54,14 @@ export async function resolveNetworkOptions(args: NetworkOptions) { const configCors = config?.server?.cors ?? [] const argsCors = Array.isArray(args.cors) ? args.cors : args.cors ? [args.cors] : [] const cors = [...configCors, ...argsCors] + const rootPath = rootPathExplicitlySet ? args.rootPath : (config?.server?.rootPath ?? args.rootPath) + + if (rootPath && !rootPath.startsWith("/")) { + throw new Error( + `Invalid rootPath: must start with '/' (got: '${rootPath}')\n` + + `Example: --root-path /jupyter/proxy/opencode` + ) + } - return { hostname, port, mdns, cors } + return { hostname, port, mdns, cors, rootPath } } diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 98970ba392d..472799c0204 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -854,6 +854,7 @@ export namespace Config { hostname: z.string().optional().describe("Hostname to listen on"), mdns: z.boolean().optional().describe("Enable mDNS service discovery"), cors: z.array(z.string()).optional().describe("Additional domains to allow for CORS"), + rootPath: z.string().optional().describe("Base path for reverse proxy"), }) .strict() .meta({ diff --git a/packages/opencode/src/server/html-utils.ts b/packages/opencode/src/server/html-utils.ts new file mode 100644 index 00000000000..cd962905bc0 --- /dev/null +++ b/packages/opencode/src/server/html-utils.ts @@ -0,0 +1,106 @@ +/** + * Utilities for safely modifying HTML with rootPath injection + */ + +import { Log } from "../util/log" + +const log = Log.create({ service: "html-utils" }) + +/** + * Escapes special characters for safe use in HTML attributes + */ +function escapeHtmlAttribute(value: string): string { + return value + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(/'/g, "'") + .replace(//g, ">") +} + +/** + * Safely injects rootPath configuration into index.html + * + * Security measures: + * - HTML attribute escaping prevents XSS via DOM attributes + * - JSON.stringify prevents XSS via script injection + * - Duplicate tag detection prevents configuration conflicts + * + * @param html - Original HTML content + * @param rootPath - Base path to inject (e.g., "/proxy") + * @returns Modified HTML with rootPath configuration, or original HTML on error + * + * @example + * const html = await Bun.file("index.html").text() + * const modified = injectRootPath(html, "/jupyter/proxy") + */ +export function injectRootPath(html: string, rootPath: string): string { + if (!rootPath) return html + + try { + let modifiedHtml = html + + // Check if base tag already exists + const hasBaseTag = /` + modifiedHtml = modifiedHtml.replace(/(]*>)/i, `$1\n ${baseTag}`) + } + + // Add script tag with safely escaped rootPath + const scriptTag = `` + modifiedHtml = modifiedHtml.replace(/(]*>)/i, `$1\n ${scriptTag}`) + + // Add data-root-path to root div if not already present + if (!/]*id="root"[^>]*data-root-path=/i.test(modifiedHtml)) { + modifiedHtml = modifiedHtml.replace( + /(]*id="root")/i, + `$1 data-root-path="${escapeHtmlAttribute(rootPath)}"` + ) + } + + return modifiedHtml + } catch (error) { + log.error("Failed to inject rootPath into HTML", { error }) + return html // Return original HTML on error + } +} + +/** + * Normalizes URL by removing duplicate slashes (except in protocol) + */ +export function normalizeUrl(baseUrl: string, path?: string): string { + if (!path) return baseUrl + + try { + // Normalize path - remove leading extra slashes but keep one + const normalizedPath = path.replace(/^\/+/, "/") + const url = new URL(normalizedPath, baseUrl).toString() + // Replace multiple slashes with single slash, but preserve protocol:// + return url.replace(/([^:]\/)\/+/g, "$1") + } catch (error) { + log.error("Failed to normalize URL", { error }) + return baseUrl + } +} + +/** + * Content Security Policy header value for serving HTML + */ +export const HTML_CSP_HEADER = + "default-src 'self'; " + + "script-src 'self' 'wasm-unsafe-eval'; " + + "style-src 'self' 'unsafe-inline'; " + + "img-src 'self' data: https:; " + + "font-src 'self' data:; " + + "media-src 'self' data:; " + + "connect-src 'self' data:" diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index f6dd0d122f8..ab3d5a94926 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -33,13 +33,14 @@ import { lazy } from "../util/lazy" import { InstanceBootstrap } from "../project/bootstrap" import { Storage } from "../storage/storage" import type { ContentfulStatusCode } from "hono/utils/http-status" -import { websocket } from "hono/bun" +import { websocket, serveStatic } from "hono/bun" import { HTTPException } from "hono/http-exception" import { errors } from "./error" import { QuestionRoutes } from "./routes/question" import { PermissionRoutes } from "./routes/permission" import { GlobalRoutes } from "./routes/global" import { MDNS } from "./mdns" +import { injectRootPath, normalizeUrl, HTML_CSP_HEADER } from "./html-utils" // @ts-ignore This global is needed to prevent ai-sdk from logging warnings to stdout https://github.com/vercel/ai/blob/2dc67e0ef538307f21368db32d5a12345d98831b/packages/ai/src/logger/log-warnings.ts#L85 globalThis.AI_SDK_LOG_WARNINGS = false @@ -47,8 +48,14 @@ globalThis.AI_SDK_LOG_WARNINGS = false export namespace Server { const log = Log.create({ service: "server" }) + // Constants for paths and URLs + const APP_DIST_PATH = "../app/dist" + const APP_INDEX_PATH = `${APP_DIST_PATH}/index.html` + const REMOTE_PROXY_URL = "https://app.opencode.ai" + let _url: URL | undefined let _corsWhitelist: string[] = [] + let _rootPath: string = "" export function url(): URL { return _url ?? new URL("http://localhost:4096") @@ -530,22 +537,7 @@ export namespace Server { }) }, ) - .all("/*", async (c) => { - const path = c.req.path - - const response = await proxy(`https://app.opencode.ai${path}`, { - ...c.req, - headers: { - ...c.req.raw.headers, - host: "app.opencode.ai", - }, - }) - response.headers.set( - "Content-Security-Policy", - "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:", - ) - return response - }) as unknown as Hono, + .use("/*", serveStatic({ root: APP_DIST_PATH })) as unknown as Hono, ) export async function openapi() { @@ -563,13 +555,146 @@ export namespace Server { return result } - export function listen(opts: { port: number; hostname: string; mdns?: boolean; cors?: string[] }) { + /** + * Creates a handler that serves static files locally if available, + * otherwise falls back to remote proxy + */ + async function createStaticOrProxyHandler() { + const indexFile = Bun.file(APP_INDEX_PATH) + const localAppExists = await indexFile.exists() + + if (localAppExists) { + log.info("πŸ“¦ Serving app from local build (../app/dist)") + return { + type: "local" as const, + handler: serveStatic({ root: APP_DIST_PATH }) + } + } else { + log.warn("🌐 Local app build not found, falling back to remote proxy (https://app.opencode.ai)") + log.warn(" For better performance, build the app: cd packages/app && bun run build") + + return { + type: "proxy" as const, + handler: async (c: any) => { + const path = c.req.path + const response = await proxy(`${REMOTE_PROXY_URL}${path}`, { + ...c.req, + headers: { + ...c.req.raw.headers, + host: "app.opencode.ai", + }, + }) + response.headers.set("Content-Security-Policy", HTML_CSP_HEADER) + return response + } + } + } + } + + /** + * Creates a handler that serves index.html with rootPath injection + * Centralizes HTML serving logic to avoid duplication + */ + function createIndexHandler(rootPath: string) { + return async (c: any) => { + try { + const indexFile = Bun.file(APP_INDEX_PATH) + if (!(await indexFile.exists())) { + log.warn("index.html not found at ../app/dist/index.html") + return c.text("Not Found", 404) + } + + const html = await indexFile.text() + const modifiedHtml = injectRootPath(html, rootPath) + + return c.html(modifiedHtml, 200, { + "Content-Security-Policy": HTML_CSP_HEADER, + }) + } catch (error) { + log.error("Error serving index.html", { error }) + return c.text("Internal Server Error", 500) + } + } + } + + /** + * Creates app with common routes to avoid duplication + */ + function createAppWithRoutes( + indexHandler: (c: any) => Promise, + staticHandler: any, + apiApp: Hono + ): Hono { + return new Hono() + .route("/", apiApp) + .get("/", indexHandler) + .get("/index.html", indexHandler) + .use("/*", staticHandler) + .all("/*", indexHandler) as unknown as Hono + } + + /** + * Starts the OpenCode HTTP server + * + * @param opts.rootPath - Base path for reverse proxy deployment (e.g., "/jupyter/proxy/opencode") + * When provided, requires local app build. Without it, falls back to remote proxy. + * + * @example + * // Standard mode (auto fallback) + * listen({ port: 4096, hostname: "localhost" }) + * + * @example + * // Reverse proxy mode (requires local build) + * listen({ port: 4096, hostname: "0.0.0.0", rootPath: "/proxy" }) + * + * @throws {Error} If rootPath is provided but local app build is missing + */ + export async function listen(opts: { port: number; hostname: string; mdns?: boolean; cors?: string[]; rootPath?: string }) { _corsWhitelist = opts.cors ?? [] + _rootPath = opts.rootPath ?? "" + + // rootPath requires local build for reliable routing + if (opts.rootPath) { + const localAppExists = await Bun.file(APP_INDEX_PATH).exists() + if (!localAppExists) { + throw new Error( + "rootPath requires local app build.\n" + + "Build the app first: cd packages/app && bun run build\n" + + "Or run without --root-path to use remote proxy." + ) + } + } + + const { type: serveType, handler: staticHandler } = await createStaticOrProxyHandler() + + // Create single index handler (no duplication!) + const indexHandler = createIndexHandler(_rootPath) + const apiApp = App() + + // Setup routing based on whether rootPath is provided + let baseApp: Hono + + if (opts.rootPath) { + // When behind reverse proxy: mount app at rootPath + // This ensures all routes including WebSocket work correctly + const rootedApp = new Hono() + .basePath(opts.rootPath) + .route("/", createAppWithRoutes(indexHandler, staticHandler, apiApp)) + + // Root app to handle both rooted and global asset paths + baseApp = new Hono() + .route("/", rootedApp) + // Serve static assets that may use absolute paths (e.g., /assets/...) + .use("/*", staticHandler) + } else { + // Standard setup without rootPath + baseApp = createAppWithRoutes(indexHandler, staticHandler, apiApp) + } const args = { hostname: opts.hostname, idleTimeout: 0, - fetch: App().fetch, + fetch: baseApp.fetch, websocket: websocket, } as const const tryServe = (port: number) => { @@ -582,7 +707,7 @@ export namespace Server { const server = opts.port === 0 ? (tryServe(4096) ?? tryServe(0)) : tryServe(opts.port) if (!server) throw new Error(`Failed to start server on port ${opts.port}`) - _url = server.url + _url = opts.rootPath ? new URL(normalizeUrl(server.url.toString(), opts.rootPath)) : server.url const shouldPublishMDNS = opts.mdns && diff --git a/packages/opencode/test/server/rootpath.test.ts b/packages/opencode/test/server/rootpath.test.ts new file mode 100644 index 00000000000..be1de3b72e3 --- /dev/null +++ b/packages/opencode/test/server/rootpath.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, test } from "bun:test" +import { injectRootPath, normalizeUrl } from "../../src/server/html-utils" + +describe("rootPath HTML injection", () => { + test("injects rootPath into clean HTML", () => { + const html = '
' + const result = injectRootPath(html, "/proxy") + + expect(result).toContain('') + expect(result).toContain('window.__OPENCODE__.rootPath = "/proxy"') + expect(result).toContain('data-root-path="/proxy"') + }) + + test("prevents XSS via malicious rootPath", () => { + const maliciousPath = '/test"onerror="alert(1)"' + const html = '
' + const result = injectRootPath(html, maliciousPath) + + // Should not contain unescaped quotes that could break out + expect(result).not.toContain('onerror="alert(1)"') + // Should contain escaped version + expect(result).toContain(""") + + // JSON.stringify should handle the script tag + expect(result).toContain(JSON.stringify(maliciousPath)) + }) + + test("prevents XSS via script tag injection", () => { + const maliciousPath = "/test" + const html = '
' + const result = injectRootPath(html, maliciousPath) + + // The value should be assigned via JSON string literal + // This makes it safe because it's never parsed as HTML within the script context + expect(result).toContain("window.__OPENCODE__.rootPath = ") + + // Verify the base tag has properly escaped HTML attributes + expect(result).toContain(" { + const html = '' + const result = injectRootPath(html, "/new") + + const baseTagCount = (result.match(/ { + const html = + '
' + const result = injectRootPath(html, "/new") + + const attrCount = (result.match(/data-root-path=/gi) || []).length + expect(attrCount).toBe(1) + expect(result).toContain('data-root-path="/existing"') + }) + + test("handles empty rootPath gracefully", () => { + const html = '
' + const result = injectRootPath(html, "") + + expect(result).toBe(html) + }) + + test("handles HTML with attributes on head tag", () => { + const html = '
' + const result = injectRootPath(html, "/proxy") + + expect(result).toContain('') + expect(result).toContain("__OPENCODE__") + }) + + test("handles multiline HTML", () => { + const html = ` + + + Test + + +
+ +` + const result = injectRootPath(html, "/proxy") + + expect(result).toContain('') + expect(result).toContain('data-root-path="/proxy"') + }) +}) + +describe("URL normalization", () => { + test("normalizes URLs with duplicate slashes", () => { + expect(normalizeUrl("http://localhost:4096", "//proxy//path/")).toBe( + "http://localhost:4096/proxy/path/" + ) + }) + + test("preserves protocol slashes", () => { + const result = normalizeUrl("http://localhost:4096", "/proxy") + expect(result).toContain("http://") + expect(result).not.toContain("http:/localhost") + }) + + test("handles empty path", () => { + expect(normalizeUrl("http://localhost:4096", "")).toBe("http://localhost:4096") + }) + + test("handles undefined path", () => { + expect(normalizeUrl("http://localhost:4096")).toBe("http://localhost:4096") + }) + + test("handles complex paths", () => { + expect(normalizeUrl("http://localhost:4096", "/jupyter/proxy/opencode/")).toBe( + "http://localhost:4096/jupyter/proxy/opencode/" + ) + }) + + test("handles trailing slashes correctly", () => { + const result = normalizeUrl("http://localhost:4096/", "/proxy") + expect(result).toBe("http://localhost:4096/proxy") + }) +}) + +describe("rootPath validation", () => { + test("rootPath must start with /", () => { + const invalidPaths = ["proxy", "test/path", "no-slash"] + const validPaths = ["/proxy", "/test/path", "/jupyter/proxy/opencode"] + + for (const path of invalidPaths) { + expect(path.startsWith("/")).toBe(false) + } + + for (const path of validPaths) { + expect(path.startsWith("/")).toBe(true) + } + }) +}) + +describe("server URL with rootPath", () => { + test("constructs URL correctly with rootPath", () => { + const serverUrl = new URL("http://localhost:4096") + const rootPath = "/proxy" + const finalUrl = new URL(normalizeUrl(serverUrl.toString(), rootPath)) + + expect(finalUrl.toString()).toBe("http://localhost:4096/proxy") + }) + + test("constructs URL correctly without rootPath", () => { + const serverUrl = new URL("http://localhost:4096") + const finalUrl = normalizeUrl(serverUrl.toString()) + + expect(finalUrl).toBe("http://localhost:4096/") + }) +}) + +describe("Special character handling", () => { + test("handles URL encoded characters", () => { + const html = '
' + const result = injectRootPath(html, "/ν•œκΈ€/경둜") + + // Should properly escape in HTML attributes + expect(result).toContain('data-root-path=') + // Should safely encode in JavaScript + expect(result).toContain('window.__OPENCODE__.rootPath') + }) + + test("handles spaces and special chars in rootPath", () => { + const html = '
' + const paths = ["/path with space", "/path-with-dash", "/path_with_underscore", "/path.with.dot"] + + for (const path of paths) { + const result = injectRootPath(html, path) + expect(result).toContain(JSON.stringify(path)) + } + }) + + test("handles paths with query-like characters", () => { + const maliciousPath = "/proxy?token=abc&key=xyz" + const html = '
' + const result = injectRootPath(html, maliciousPath) + + // Should be safely escaped + expect(result).toContain(JSON.stringify(maliciousPath)) + }) +}) + +describe("URL normalization edge cases", () => { + test("handles multiple consecutive slashes", () => { + expect(normalizeUrl("http://localhost:4096", "///proxy///path///")).toBe( + "http://localhost:4096/proxy/path/" + ) + }) + + test("handles mixed slash patterns", () => { + expect(normalizeUrl("http://localhost:4096/", "//proxy/path")).toBe( + "http://localhost:4096/proxy/path" + ) + }) + + test("preserves trailing slash when explicitly provided", () => { + const result = normalizeUrl("http://localhost:4096", "/proxy/") + expect(result.endsWith("/")).toBe(true) + }) +}) + +describe("WebSocket compatibility", () => { + test("WebSocket URL construction with rootPath", () => { + const serverUrl = "http://localhost:4096" + const rootPath = "/jupyter/proxy/opencode" + + // WebSocket should use same base path + const wsUrl = new URL(rootPath, serverUrl) + wsUrl.protocol = "ws:" + + expect(wsUrl.toString()).toBe("ws://localhost:4096/jupyter/proxy/opencode") + }) + + test("WebSocket URL without rootPath", () => { + const serverUrl = "http://localhost:4096" + const wsUrl = new URL(serverUrl) + wsUrl.protocol = "ws:" + + expect(wsUrl.toString()).toBe("ws://localhost:4096/") + }) +}) + +describe("Fallback strategy", () => { + test("validates fallback behavior when local build missing", () => { + // This test documents expected behavior + const scenarios = [ + { hasLocalBuild: true, hasRootPath: false, expected: "local" }, + { hasLocalBuild: false, hasRootPath: false, expected: "proxy" }, + { hasLocalBuild: true, hasRootPath: true, expected: "local" }, + { hasLocalBuild: false, hasRootPath: true, expected: "error" }, + ] + + for (const scenario of scenarios) { + // Expected behavior documented + expect(scenario.expected).toBeDefined() + } + }) +}) diff --git a/packages/web/src/content/docs/cli.mdx b/packages/web/src/content/docs/cli.mdx index 7fb948f5054..96786d3f6a6 100644 --- a/packages/web/src/content/docs/cli.mdx +++ b/packages/web/src/content/docs/cli.mdx @@ -368,6 +368,7 @@ This starts an HTTP server that provides API access to opencode functionality wi | `--hostname` | Hostname to listen on | | `--mdns` | Enable mDNS discovery | | `--cors` | Additional browser origin(s) to allow CORS | +| `--root-path` | Base path for reverse proxy | --- @@ -464,6 +465,7 @@ This starts an HTTP server and opens a web browser to access OpenCode through a | `--hostname` | Hostname to listen on | | `--mdns` | Enable mDNS discovery | | `--cors` | Additional browser origin(s) to allow CORS | +| `--root-path` | Base path for reverse proxy | --- diff --git a/packages/web/src/content/docs/config.mdx b/packages/web/src/content/docs/config.mdx index 1474cb91558..13ce9f32775 100644 --- a/packages/web/src/content/docs/config.mdx +++ b/packages/web/src/content/docs/config.mdx @@ -190,7 +190,8 @@ You can configure server settings for the `opencode serve` and `opencode web` co "port": 4096, "hostname": "0.0.0.0", "mdns": true, - "cors": ["http://localhost:5173"] + "cors": ["http://localhost:5173"], + "rootPath": "/proxy" } } ``` @@ -201,6 +202,7 @@ Available options: - `hostname` - Hostname to listen on. When `mdns` is enabled and no hostname is set, defaults to `0.0.0.0`. - `mdns` - Enable mDNS service discovery. This allows other devices on the network to discover your OpenCode server. - `cors` - Additional origins to allow for CORS when using the HTTP server from a browser-based client. Values must be full origins (scheme + host + optional port), eg `https://app.example.com`. +- `rootPath` - Base path for reverse proxy. All routes will be prefixed with this path. [Learn more about the server here](/docs/server). diff --git a/packages/web/src/content/docs/server.mdx b/packages/web/src/content/docs/server.mdx index 7229e09b22f..67d9542575e 100644 --- a/packages/web/src/content/docs/server.mdx +++ b/packages/web/src/content/docs/server.mdx @@ -13,7 +13,7 @@ The `opencode serve` command runs a headless HTTP server that exposes an OpenAPI ### Usage ```bash -opencode serve [--port ] [--hostname ] [--cors ] +opencode serve [--port ] [--hostname ] [--cors ] [--root-path ] ``` #### Options @@ -24,6 +24,7 @@ opencode serve [--port ] [--hostname ] [--cors ] | `--hostname` | Hostname to listen on | `127.0.0.1` | | `--mdns` | Enable mDNS discovery | `false` | | `--cors` | Additional browser origins to allow | `[]` | +| `--root-path` | Base path for reverse proxy | (empty) | `--cors` can be passed multiple times: