Files
opencode-manager/backend/test/routes/opencode-auth-proxy.test.ts
T
Chris Scott dacde879d6 feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
2026-09-26 13:16:45 -04:00

347 lines
14 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
import { createAuthenticatedOpenCodeProxyRoutes } from '../../src/routes/opencode-auth-proxy'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
import type { SettingsService } from '../../src/services/settings'
const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true))
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: { isLifecycleInitialized: isLifecycleInitializedMock },
}))
const forwardRawMock = vi.hoisted(() => vi.fn<OpenCodeClient['forwardRaw']>(async () => new Response('ok', { status: 200 })))
vi.mock('../../src/services/opencode/client', () => ({
createOpenCodeClient: vi.fn(),
}))
const passThroughAuth: MiddlewareHandler = async (c, next) => {
await next()
}
function buildApp() {
const app = new Hono()
app.route(
'/api/opencode',
createAuthenticatedOpenCodeProxyRoutes({ forwardRaw: forwardRawMock } as unknown as OpenCodeClient, passThroughAuth),
)
return app
}
describe('authenticated opencode proxy routes', () => {
beforeEach(() => {
vi.clearAllMocks()
isLifecycleInitializedMock.mockReturnValue(true)
forwardRawMock.mockResolvedValue(new Response('ok', { status: 200 }))
})
it('returns 503 and never forwards when the OpenCode lifecycle is not initialized', async () => {
isLifecycleInitializedMock.mockReturnValue(false)
const app = buildApp()
const res = await app.request('/api/opencode/session/ses_1/message')
expect(res.status).toBe(503)
expect(forwardRawMock).not.toHaveBeenCalled()
})
it('returns 503 through the proxy gate on a below-threshold health failure and reopens once the supervisor recovers', async () => {
const lifecycle = { initialized: true }
isLifecycleInitializedMock.mockImplementation(() => lifecycle.initialized)
const manager = {
start: vi.fn().mockResolvedValue(undefined),
stop: vi.fn().mockResolvedValue(undefined),
isOperationInProgress: vi.fn(() => false),
checkHealth: vi.fn().mockResolvedValue(true),
restart: vi.fn().mockResolvedValue(undefined),
clearStartupError: vi.fn(),
getLastStartupError: vi.fn(() => null),
isLastStartupErrorNonRecoverable: vi.fn(() => false),
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
getPort: vi.fn(() => 5551),
getVersion: vi.fn(() => '2.0.15'),
getMinVersion: vi.fn(() => '2.0.15'),
isVersionSupported: vi.fn(() => true),
}
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
failureThreshold: 2,
watchEnabled: false,
})
await supervisor.start()
const healthyRes = await buildApp().request('/api/opencode/session/ses_1/message')
expect(healthyRes.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
manager.checkHealth.mockResolvedValueOnce(false)
const status = await supervisor.checkNow('manual')
expect(status.state).toBe('unhealthy')
expect(lifecycle.initialized).toBe(false)
const blockedRes = await buildApp().request('/api/opencode/session/ses_1/message')
expect(blockedRes.status).toBe(503)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
manager.checkHealth.mockResolvedValueOnce(true)
const recovered = await supervisor.checkNow('manual')
expect(recovered.healthy).toBe(true)
expect(lifecycle.initialized).toBe(true)
const reopenedRes = await buildApp().request('/api/opencode/session/ses_1/message')
expect(reopenedRes.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(2)
})
it('forwards ordinary endpoints when enforcement is off', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/session/ses_1/message')
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalled()
})
it('returns 503 for MCP auth endpoints when the OpenCode lifecycle is not initialized', async () => {
isLifecycleInitializedMock.mockReturnValue(false)
const app = buildApp()
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
expect(res.status).toBe(503)
expect(forwardRawMock).not.toHaveBeenCalled()
})
it('forwards MCP auth endpoints through the lifecycle-gated proxy when initialized', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth')
})
it('forwards MCP auth authenticate endpoints through the lifecycle-gated proxy when initialized', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/mcp/evil-server/auth/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth/authenticate')
})
it('forwards the session shell endpoint', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/session/ses_1/shell', { method: 'POST' })
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalled()
})
it('forwards percent-encoded PTY paths when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/%70ty', { method: 'POST' })
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalled()
})
it('forwards a PATCH /config mutation with plugins exactly when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({ theme: 'dark', plugin: ['opencode-plugin-npm'] })
})
it('forwards a PATCH /config mutation with local MCP servers and formatter config exactly when enforced', async () => {
const app = buildApp()
const body = JSON.stringify({
formatter: { command: 'prettier' },
mcp: { local: { type: 'local', command: ['node', 'server.js'] } },
})
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body,
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual(JSON.parse(body))
})
it('forwards a malformed PATCH /config body exactly when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: '{not json',
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
expect(await (forwardRawMock.mock.calls[0]![0] as Request).text()).toBe('{not json')
})
it('forwards PATCH /config mutations raw when enforcement is off', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded.plugin).toEqual(['opencode-plugin-npm'])
})
it('forwards a local MCP server add when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'evil',
config: { type: 'local', command: ['node', 'server.js'] },
}),
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({
name: 'evil',
config: { type: 'local', command: ['node', 'server.js'] },
})
})
it('forwards a remote MCP server add when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'remote-server',
config: { type: 'remote', url: 'https://example.com/mcp' },
}),
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({
name: 'remote-server',
config: { type: 'remote', url: 'https://example.com/mcp' },
})
})
it('forwards MCP server adds raw when enforcement is off', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'local-server',
config: { type: 'local', command: ['node', 'server.js'] },
}),
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as { config: { type: string } }
expect(forwarded.config.type).toBe('local')
})
it('forwards a PATCH /config mutation with LSP servers and experimental hooks exactly when enforced', async () => {
const app = buildApp()
const body = JSON.stringify({
lsp: { typescript: { command: ['typescript-language-server'] } },
experimental: {
hook: { file_edited: [{ command: ['chmod', '+x', 'x'] }] },
chatMaxRetries: 4,
},
})
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body,
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual(JSON.parse(body))
})
it('forwards a PATCH /config mutation without host-execution sections unchanged when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ theme: 'dark' }),
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({ theme: 'dark' })
})
it('forwards a well-known auth write when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/auth/sso.example.com', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' })
})
it('forwards api and oauth auth writes when enforced', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/auth/anthropic', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'api', key: 'sk-test' }),
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual({ type: 'api', key: 'sk-test' })
})
it('forwards auth writes raw when enforcement is off', async () => {
const app = buildApp()
const res = await app.request('/api/opencode/auth/sso.example.com', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
})
expect(res.status).toBe(200)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded.type).toBe('wellknown')
})
it('forwards a PATCH /config mutation with custom provider npm selectors exactly when enforced', async () => {
const app = buildApp()
const body = JSON.stringify({
model: 'x',
provider: {
evil: { npm: 'file:///repo/evil-provider.js' },
builtin: { options: { apiKey: 'k' } },
},
})
const res = await app.request('/api/opencode/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body,
})
expect(res.status).toBe(200)
expect(forwardRawMock).toHaveBeenCalledTimes(1)
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
expect(forwarded).toEqual(JSON.parse(body))
})
})