revert(backend): remove OpenCode proxy Basic Auth experiment

This commit is contained in:
Chris Scott committed 2026-04-29 00:16:52 +00:00
1 parent 986554df66
commit efae3b86c1
3 files changed
+25 -193

No files matched your search

+6 -15
View File
@@ -1,6 +1,5 @@
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'
@@ -40,7 +39,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, isOpenCodeProxyBasicAuth } from './services/proxy'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { migrateGlobalSkills } from './services/skills'
@@ -81,14 +80,6 @@ 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'
@@ -291,25 +282,25 @@ protectedApi.route('/memory', createMemoryRoutes(db))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
app.post('/api/opencode/mcp/:name/auth', requireOpenCodeProxyAuth, async (c) => {
app.route('/api', protectedApi)
app.post('/api/opencode/mcp/:name/auth', requireAuth, 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', requireOpenCodeProxyAuth, async (c) => {
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
const serverName = c.req.param('name')
const directory = c.req.query('directory')
return proxyMcpAuthAuthenticate(serverName, directory)
})
app.all('/api/opencode/*', requireOpenCodeProxyAuth, async (c) => {
app.all('/api/opencode/*', requireAuth, async (c) => {
const request = c.req.raw
return proxyRequest(request)
})
app.route('/api', protectedApi)
const isProduction = ENV.SERVER.NODE_ENV === 'production'
if (isProduction) {
+18 -75
View File
@@ -1,7 +1,6 @@
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { timingSafeEqual } from 'crypto'
const OPENCODE_CONNECT_HOST = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
export const OPENCODE_SERVER_URL = `http://${OPENCODE_CONNECT_HOST}:${ENV.OPENCODE.PORT}`
@@ -12,70 +11,6 @@ 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 }
@@ -355,6 +290,8 @@ 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}`
@@ -370,20 +307,26 @@ export async function proxyRequest(request: Request) {
}
})
const body = request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined
const init: RequestInit & { duplex?: 'half' } = {
const response = await fetch(targetUrl, {
method: request.method,
headers: withOpenCodeAuth(headers),
body: body ?? undefined,
signal: request.signal,
}
if (body) {
init.duplex = 'half'
}
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
})
const response = await fetch(targetUrl, init)
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
}
})
return createProxyResponse(response)
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
+1 -103
View File
@@ -15,7 +15,7 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1', SERVER_PASSWORD: 'test-opencode-password', SERVER_USERNAME: 'opencode' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
DATABASE: { PATH: ':memory:' },
FILE_LIMITS: {
MAX_SIZE_BYTES: 1024 * 1024,
@@ -59,108 +59,6 @@ const createMockFetch = (response: Response) => {
}
describe('proxy service', () => {
describe('isOpenCodeProxyBasicAuth', () => {
it('should accept OpenCode Basic auth with the server password', async () => {
const { isOpenCodeProxyBasicAuth } = await import('../../src/services/proxy')
const auth = Buffer.from('opencode:test-opencode-password').toString('base64')
const request = new Request('http://manager.test/api/opencode/global/health', {
headers: { Authorization: `Basic ${auth}` },
})
expect(isOpenCodeProxyBasicAuth(request)).toBe(true)
})
it('should reject OpenCode Basic auth with the wrong password', async () => {
const { isOpenCodeProxyBasicAuth } = await import('../../src/services/proxy')
const auth = Buffer.from('opencode:wrong-password').toString('base64')
const request = new Request('http://manager.test/api/opencode/global/health', {
headers: { Authorization: `Basic ${auth}` },
})
expect(isOpenCodeProxyBasicAuth(request)).toBe(false)
})
})
describe('proxyRequest', () => {
const originalFetch = global.fetch
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
global.fetch = originalFetch
})
it('should stream upstream responses without buffering', async () => {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('data: {}\n\n'))
controller.close()
},
})
const upstreamResponse = new Response(stream, {
status: 200,
statusText: 'OK',
headers: {
'content-type': 'text/event-stream',
'content-length': '128',
'content-encoding': 'gzip',
},
})
const fetchMock = vi.fn().mockResolvedValue(upstreamResponse)
global.fetch = fetchMock as unknown as typeof fetch
const { proxyRequest } = await import('../../src/services/proxy')
const clientAuth = `Basic ${Buffer.from('opencode:client-password').toString('base64')}`
const response = await proxyRequest(new Request('http://manager.test/api/opencode/global/event?directory=/repo', {
headers: {
Authorization: clientAuth,
'X-Test': 'yes',
},
}))
expect(response.body).toBe(upstreamResponse.body)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('text/event-stream')
expect(response.headers.has('content-length')).toBe(false)
expect(response.headers.has('content-encoding')).toBe(false)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [targetUrl, init] = fetchMock.mock.calls[0] as [string, RequestInit]
const headers = init.headers as Record<string, string>
expect(targetUrl).toBe('http://127.0.0.1:5551/global/event?directory=/repo')
expect(headers.Authorization).toBe(`Basic ${Buffer.from('opencode:test-opencode-password').toString('base64')}`)
expect(headers.authorization).toBeUndefined()
expect(headers['x-test']).toBe('yes')
})
it('should set duplex when forwarding a streamed request body', async () => {
const upstreamResponse = new Response('{}', { status: 200 })
const fetchMock = vi.fn().mockResolvedValue(upstreamResponse)
global.fetch = fetchMock as unknown as typeof fetch
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('{"prompt":"hi"}'))
controller.close()
},
})
const request = new Request('http://manager.test/api/opencode/session', {
method: 'POST',
body,
headers: { 'Content-Type': 'application/json' },
duplex: 'half',
} as RequestInit & { duplex: 'half' })
const { proxyRequest } = await import('../../src/services/proxy')
await proxyRequest(request)
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit & { duplex?: 'half' }]
expect(init.body).toBe(request.body)
expect(init.duplex).toBe('half')
})
})
describe('patchOpenCodeConfig', () => {
const originalFetch = global.fetch