feat(backend): add OpenCode Basic Auth for proxy endpoints

Enable remote OpenCode TUI clients to authenticate via Basic Auth when
accessing /api/opencode/* routes. Normal WebUI session auth continues to
work for browser clients.

- Add requireOpenCodeProxyAuth middleware that checks Basic Auth first
- Add isOpenCodeProxyBasicAuth with timing-safe password comparison
- Stream proxy responses without buffering (SSE support)
- Drop hop-by-hop headers from proxied responses
- Add tests for auth validation and streaming behavior
This commit is contained in:
Chris Scott committed 2026-04-28 22:52:28 +00:00
1 parent 04400c91cc
commit 26a8532cc6
3 files changed
+193 -25

No files matched your search

+15 -6
View File
@@ -1,5 +1,6 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { cors } from 'hono/cors'
import { serveStatic } from '@hono/node-server/serve-static'
import { readFile } from 'fs/promises'
@@ -39,7 +40,7 @@ import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate, isOpenCodeProxyBasicAuth } from './services/proxy'
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { migrateGlobalSkills } from './services/skills'
@@ -80,6 +81,14 @@ app.use('/*', cors({
const db = initializeDatabase(DB_PATH)
const auth = createAuth(db)
const requireAuth = createAuthMiddleware(auth)
const requireOpenCodeProxyAuth = createMiddleware(async (c, next) => {
if (isOpenCodeProxyBasicAuth(c.req.raw)) {
await next()
return
}
return requireAuth(c, next)
})
import { DEFAULT_AGENTS_MD } from './constants'
@@ -282,25 +291,25 @@ protectedApi.route('/memory', createMemoryRoutes(db))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
app.route('/api', protectedApi)
app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => {
app.post('/api/opencode/mcp/:name/auth', requireOpenCodeProxyAuth, async (c) => {
const serverName = c.req.param('name')
const directory = c.req.query('directory')
return proxyMcpAuthStart(serverName, directory)
})
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
app.post('/api/opencode/mcp/:name/auth/authenticate', requireOpenCodeProxyAuth, async (c) => {
const serverName = c.req.param('name')
const directory = c.req.query('directory')
return proxyMcpAuthAuthenticate(serverName, directory)
})
app.all('/api/opencode/*', requireAuth, async (c) => {
app.all('/api/opencode/*', requireOpenCodeProxyAuth, async (c) => {
const request = c.req.raw
return proxyRequest(request)
})
app.route('/api', protectedApi)
const isProduction = ENV.SERVER.NODE_ENV === 'production'
if (isProduction) {
+75 -18
View File
@@ -1,6 +1,7 @@
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { timingSafeEqual } from 'crypto'
export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
@@ -10,6 +11,70 @@ const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
: ''
const RESPONSE_HEADERS_TO_DROP = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
function safeEqual(left: string, right: string): boolean {
const leftBuffer = Buffer.from(left)
const rightBuffer = Buffer.from(right)
if (leftBuffer.length !== rightBuffer.length) {
return false
}
return timingSafeEqual(leftBuffer, rightBuffer)
}
function getBasicCredentials(header: string | null): { username: string; password: string } | undefined {
if (!header?.startsWith('Basic ')) {
return undefined
}
try {
const decoded = Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')
const separator = decoded.indexOf(':')
if (separator === -1) {
return undefined
}
return {
username: decoded.slice(0, separator),
password: decoded.slice(separator + 1),
}
} catch {
return undefined
}
}
function createProxyResponse(response: Response): Response {
const responseHeaders = new Headers()
response.headers.forEach((value, key) => {
if (!RESPONSE_HEADERS_TO_DROP.has(key.toLowerCase())) {
responseHeaders.set(key, value)
}
})
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
}
export function isOpenCodeProxyBasicAuth(request: Request): boolean {
if (!OPENCODE_SERVER_PASSWORD) {
return false
}
const credentials = getBasicCredentials(request.headers.get('authorization'))
if (!credentials) {
return false
}
return credentials.username === OPENCODE_SERVER_USERNAME && safeEqual(credentials.password, OPENCODE_SERVER_PASSWORD)
}
export function withOpenCodeAuth(headers: Record<string, string> = {}): Record<string, string> {
if (OPENCODE_BASIC_AUTH) {
return { ...headers, Authorization: OPENCODE_BASIC_AUTH }
@@ -289,8 +354,6 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
export async function proxyRequest(request: Request) {
const url = new URL(request.url)
// Remove /api/opencode prefix from pathname before forwarding
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}`
@@ -306,26 +369,20 @@ export async function proxyRequest(request: Request) {
}
})
const response = await fetch(targetUrl, {
const body = request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined
const init: RequestInit & { duplex?: 'half' } = {
method: request.method,
headers: withOpenCodeAuth(headers),
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
})
body: body ?? undefined,
signal: request.signal,
}
if (body) {
init.duplex = 'half'
}
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
const response = await fetch(targetUrl, init)
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
return createProxyResponse(response)
} catch (error) {
logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {