mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: switch workspace plugin to remote adaptor with manager proxy
Switch the @opencode-manager/workspace-plugin adaptor from type local to type remote so opencode TUIs running on machines without filesystem access can use the manager's managed opencode server as their workspace backend. Phase 1 - Plugin adaptor: - Update target() to return type remote with manager URL and bearer auth - Export makeAdaptor for testing - Add tests for remote URL construction, slug encoding, and trailing slash Phase 2 - HTTP proxy route: - Add ALL /opencode/:slug/* catch-all proxy in workspace-plugin routes - Reuses existing proxyRequest helper with slug-to-directory translation - Rewrites inbound URL to /api/opencode/* shape for shared proxy logic - Includes bearer token scope validation and project service Phase 3 - WebSocket proxy: - Extract verifyPluginBearerAuth as named function for reuse - Attach second WebSocket proxy mount for /api/workspace-plugin/opencode prefix - Both /api/opencode and /api/workspace-plugin/opencode prefixes supported Phase 4 - Tests: - Add 8 backend route tests covering auth, proxy forwarding, and POST body - Add 3 plugin adaptor tests for remote target construction
This commit is contained in:
1 parent
ffab02f386
commit
d07eb7f523
5 files changed
+318
-15
No files matched your search
+21
-11
@@ -413,20 +413,30 @@ const server = serve({
|
||||
|
||||
import { OPENCODE_SERVER_URL } from './services/proxy'
|
||||
|
||||
const verifyPluginBearerAuth = async (headers: Headers): Promise<{ userId: string; scope: string } | null> => {
|
||||
const authHeader = headers.get('authorization')
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
const raw = authHeader.slice(7).trim()
|
||||
const verified = apiTokenService.verify(raw)
|
||||
if (verified) {
|
||||
return { userId: verified.userId, scope: verified.scope }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
attachWorkspacePluginWs(server, {
|
||||
upstreamBaseUrl: OPENCODE_SERVER_URL,
|
||||
verifyAuth: async (headers) => {
|
||||
const authHeader = headers.get('authorization')
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
const raw = authHeader.slice(7).trim()
|
||||
const verified = apiTokenService.verify(raw)
|
||||
if (verified) {
|
||||
return { userId: verified.userId, scope: verified.scope }
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
verifyAuth: verifyPluginBearerAuth,
|
||||
projectService,
|
||||
pathPrefix: '/api/opencode',
|
||||
})
|
||||
|
||||
attachWorkspacePluginWs(server, {
|
||||
upstreamBaseUrl: OPENCODE_SERVER_URL,
|
||||
verifyAuth: verifyPluginBearerAuth,
|
||||
projectService,
|
||||
pathPrefix: '/api/workspace-plugin/opencode',
|
||||
})
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -4,6 +4,7 @@ import { listRepos } from '../db/queries'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { logger } from '../utils/logger'
|
||||
import type { Session } from '../auth'
|
||||
import { proxyRequest, type ProxyProjectService } from '../services/proxy'
|
||||
|
||||
type AppVariables = {
|
||||
session: Session['session']
|
||||
@@ -23,6 +24,17 @@ const ALLOWED_WORKSPACE_PLUGIN_SCOPES = new Set(['*', 'workspace-plugin'])
|
||||
export function createWorkspacePluginRoutes(db: Database) {
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
|
||||
const projectService: ProxyProjectService = {
|
||||
getBySlug: (slug: string) => {
|
||||
const settingsService = new SettingsService(db)
|
||||
const settings = settingsService.getSettings()
|
||||
const repos = listRepos(db, settings.preferences.repoOrder)
|
||||
const repo = repos.find((r) => r.id.toString() === slug)
|
||||
if (!repo) return null
|
||||
return { directory: repo.fullPath }
|
||||
},
|
||||
}
|
||||
|
||||
app.get('/projects', async (c) => {
|
||||
try {
|
||||
const session = c.get('session')
|
||||
@@ -60,5 +72,38 @@ export function createWorkspacePluginRoutes(db: Database) {
|
||||
}
|
||||
})
|
||||
|
||||
app.all('/opencode/:slug/*', async (c) => {
|
||||
const session = c.get('session')
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const tokenScope = c.get('tokenScope')
|
||||
if (tokenScope !== undefined && !ALLOWED_WORKSPACE_PLUGIN_SCOPES.has(tokenScope)) {
|
||||
logger.warn(`Token with scope '${tokenScope}' attempted to access workspace-plugin opencode proxy`)
|
||||
return c.json({ error: 'Forbidden: insufficient token scope' }, 403)
|
||||
}
|
||||
|
||||
const slug = c.req.param('slug')
|
||||
const inbound = c.req.raw
|
||||
const inboundUrl = new URL(inbound.url)
|
||||
|
||||
const rewritten = new URL(inbound.url)
|
||||
const prefix = `/api/workspace-plugin/opencode/${slug}`
|
||||
const rest = inboundUrl.pathname.slice(prefix.length) || '/'
|
||||
rewritten.pathname = `/api/opencode${rest}`
|
||||
|
||||
const forwardedHeaders = new Headers(inbound.headers)
|
||||
forwardedHeaders.set('x-opencode-manager-project', slug)
|
||||
const forwarded = new Request(rewritten.toString(), {
|
||||
method: inbound.method,
|
||||
headers: forwardedHeaders,
|
||||
body: inbound.method === 'GET' || inbound.method === 'HEAD' ? undefined : inbound.body,
|
||||
duplex: 'half',
|
||||
})
|
||||
|
||||
return proxyRequest(forwarded, projectService)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { createAuth } from '../../src/auth'
|
||||
import { createAuthMiddleware } from '../../src/auth/middleware'
|
||||
import { ApiTokenService } from '../../src/services/api-tokens'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createWorkspacePluginRoutes } from '../../src/routes/workspace-plugin'
|
||||
import type { Session } from '../../src/auth'
|
||||
|
||||
type AppVariables = {
|
||||
session: Session['session']
|
||||
user: Session['user']
|
||||
tokenScope?: string
|
||||
}
|
||||
|
||||
function seedUser(db: Database, id: string, email = `${id}@example.com`, name = `User ${id}`) {
|
||||
const now = new Date().toISOString()
|
||||
db.prepare(
|
||||
`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt, role)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
).run(id, name, email, 1, now, now, 'user')
|
||||
}
|
||||
|
||||
function seedRepo(db: Database, id: number, localPath: string, repoUrl?: string, sourcePath?: string) {
|
||||
db.prepare(
|
||||
`INSERT INTO repos (id, local_path, repo_url, source_path, clone_status, cloned_at)
|
||||
VALUES (?, ?, ?, ?, 'cloned', strftime('%s','now'))`
|
||||
).run(id, localPath, repoUrl ?? null, sourcePath ?? null)
|
||||
}
|
||||
|
||||
describe('Workspace Plugin Routes', () => {
|
||||
let db: Database
|
||||
let auth: ReturnType<typeof createAuth>
|
||||
let apiTokenService: ApiTokenService
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
auth = createAuth(db)
|
||||
apiTokenService = new ApiTokenService(db)
|
||||
})
|
||||
|
||||
describe('GET /projects', () => {
|
||||
it('returns projects list with valid session', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
seedRepo(db, 1, 'test-repo', 'https://github.com/test/repo', '/workspace/repos/test-repo')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token')
|
||||
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/projects', {
|
||||
headers: { Authorization: `Bearer ${tokenResult.token}` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json() as { projects: Array<{ slug: string; name: string; directory: string }> }
|
||||
expect(json.projects).toHaveLength(1)
|
||||
expect(json.projects[0]?.slug).toBe('1')
|
||||
expect(json.projects[0]?.name).toBe('test-repo')
|
||||
expect(json.projects[0]?.directory).toBe('/workspace/repos/test-repo')
|
||||
})
|
||||
|
||||
it('returns 401 without session', async () => {
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/projects')
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 with insufficient token scope', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token', 'other-scope')
|
||||
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/projects', {
|
||||
headers: { Authorization: `Bearer ${tokenResult.token}` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ALL /opencode/:slug/*', () => {
|
||||
it('returns 401 without session', async () => {
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session')
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 with insufficient token scope', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token', 'other-scope')
|
||||
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session', {
|
||||
headers: { Authorization: `Bearer ${tokenResult.token}` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 for unknown slug', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin')
|
||||
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/opencode/unknown-slug/session', {
|
||||
headers: { Authorization: `Bearer ${tokenResult.token}` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('forwards request to upstream with directory query param', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
seedRepo(db, 42, 'my-repo', undefined, '/workspace/repos/my-repo')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin')
|
||||
|
||||
const mockFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
|
||||
const url = typeof input === 'string' ? input : 'url' in input ? input.url : ''
|
||||
void url
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
})
|
||||
|
||||
try {
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session', {
|
||||
headers: { Authorization: `Bearer ${tokenResult.token}` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
const calledUrl = mockFetch.mock.calls[0]?.[0] as string
|
||||
expect(calledUrl).toContain('directory=%2Fworkspace%2Frepos%2Fmy-repo')
|
||||
expect(calledUrl).toMatch(/\/session/)
|
||||
} finally {
|
||||
mockFetch.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards POST body to upstream', async () => {
|
||||
seedUser(db, 'user-123')
|
||||
seedRepo(db, 42, 'my-repo', undefined, '/workspace/repos/my-repo')
|
||||
const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin')
|
||||
|
||||
const mockFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
|
||||
void input
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
})
|
||||
|
||||
try {
|
||||
const app = new Hono<{ Variables: AppVariables }>()
|
||||
app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db))
|
||||
app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db))
|
||||
|
||||
const body = JSON.stringify({ action: 'test' })
|
||||
await app.request('http://localhost/api/workspace-plugin/opencode/42/session/action', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenResult.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body,
|
||||
})
|
||||
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
const calledInit = mockFetch.mock.calls[0]?.[1] as RequestInit
|
||||
expect(calledInit?.body).toBeDefined()
|
||||
} finally {
|
||||
mockFetch.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -12,7 +12,7 @@ export function resolveConfig(options: unknown): { url: string; token: string }
|
||||
return { url, token }
|
||||
}
|
||||
|
||||
function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProject): WorkspaceAdaptor {
|
||||
export function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProject): WorkspaceAdaptor {
|
||||
return {
|
||||
name: `Manager: ${project.name}`,
|
||||
description: `Connect to the "${project.name}" project on opencode-manager at ${cfg.url}`,
|
||||
@@ -32,9 +32,15 @@ function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProjec
|
||||
pluginLogger.info(`adaptor.remove slug=${project.slug} info=${JSON.stringify(info)}`)
|
||||
},
|
||||
target(info) {
|
||||
const result = { type: "local" as const, directory: project.directory }
|
||||
const base = cfg.url.replace(/\/$/, "")
|
||||
const url = `${base}/api/workspace-plugin/opencode/${encodeURIComponent(project.slug)}`
|
||||
const result = {
|
||||
type: "remote" as const,
|
||||
url,
|
||||
headers: { Authorization: `Bearer ${cfg.token}` },
|
||||
}
|
||||
pluginLogger.info(
|
||||
`adaptor.target slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify(result)}`,
|
||||
`adaptor.target slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify({ type: result.type, url: result.url })}`,
|
||||
)
|
||||
return result
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { PluginOptionsSchema } from '../src/types'
|
||||
import { resolveConfig } from '../src/index'
|
||||
import type { WorkspaceInfo } from '@opencode-ai/plugin'
|
||||
|
||||
describe('PluginOptionsSchema', () => {
|
||||
it('accepts url from options', () => {
|
||||
@@ -69,3 +70,40 @@ describe('resolveConfig', () => {
|
||||
expect(() => resolveConfig({})).toThrow(/missing `token`/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('adaptor.target', () => {
|
||||
const sampleInfo: WorkspaceInfo = {
|
||||
name: 'Test Workspace',
|
||||
directory: '/test/dir',
|
||||
extra: {},
|
||||
}
|
||||
|
||||
it('returns { type: "remote", url, headers } with bearer auth when target is invoked', async () => {
|
||||
const { makeAdaptor } = await import('../src/index.js')
|
||||
const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' }
|
||||
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
|
||||
const adaptor = makeAdaptor(cfg, project)
|
||||
const result = adaptor.target(sampleInfo)
|
||||
expect(result.type).toBe('remote')
|
||||
expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42')
|
||||
expect(result.headers).toEqual({ Authorization: 'Bearer tok-abc' })
|
||||
})
|
||||
|
||||
it('url-encodes special slug characters', async () => {
|
||||
const { makeAdaptor } = await import('../src/index.js')
|
||||
const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' }
|
||||
const project = { slug: 'a/b c', name: 'Test Project', directory: '/workspace/repos/test' }
|
||||
const adaptor = makeAdaptor(cfg, project)
|
||||
const result = adaptor.target(sampleInfo)
|
||||
expect(result.url).toContain('a%2Fb%20c')
|
||||
})
|
||||
|
||||
it('strips trailing slash from manager url', async () => {
|
||||
const { makeAdaptor } = await import('../src/index.js')
|
||||
const cfg = { url: 'http://manager.test:5003/', token: 'tok-abc' }
|
||||
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
|
||||
const adaptor = makeAdaptor(cfg, project)
|
||||
const result = adaptor.target(sampleInfo)
|
||||
expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user