diff --git a/backend/src/index.ts b/backend/src/index.ts index 6c06b282..383b5d99 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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) { diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index 1cc3c63b..21a92788 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -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 = {}): Record { if (OPENCODE_BASIC_AUTH) { return { ...headers, Authorization: OPENCODE_BASIC_AUTH } @@ -289,8 +354,6 @@ export async function patchOpenCodeConfig(config: Record): 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 = {} - 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' }), { diff --git a/backend/test/services/proxy.test.ts b/backend/test/services/proxy.test.ts index 74093bb7..75d92d56 100644 --- a/backend/test/services/proxy.test.ts +++ b/backend/test/services/proxy.test.ts @@ -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' }, + OPENCODE: { PORT: 5551, HOST: '127.0.0.1', SERVER_PASSWORD: 'test-opencode-password', SERVER_USERNAME: 'opencode' }, DATABASE: { PATH: ':memory:' }, FILE_LIMITS: { MAX_SIZE_BYTES: 1024 * 1024, @@ -59,6 +59,108 @@ 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({ + 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 + 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({ + 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