feat(ocm-cli): workspace repo sync and manager token targeting (#233)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-23 19:49:44 -04:00
1 parent e12f319592
commit a86e4b1238
69 files changed
+4858 -161

No files matched your search

+29 -4
View File
@@ -3,17 +3,42 @@ import { timingSafeEqual } from 'node:crypto'
import type { Database } from 'bun:sqlite'
import { getOrCreateInternalToken } from '../services/internal-token'
function extractTokenFromBasic(header: string): string | null {
if (!header.startsWith('Basic ')) return null
const decoded = Buffer.from(header.slice(6), 'base64').toString('utf8')
const colonIndex = decoded.indexOf(':')
if (colonIndex === -1) return null
return decoded.slice(colonIndex + 1)
}
function tokenMatch(provided: string, expected: string): boolean {
const a = Buffer.from(provided)
const b = Buffer.from(expected)
return a.length === b.length && timingSafeEqual(a, b)
}
export function createInternalTokenMiddleware(db: Database) {
return createMiddleware(async (c, next) => {
const header = c.req.header('authorization') ?? c.req.header('Authorization')
if (!header || !header.startsWith('Bearer ')) {
if (!header) {
return c.json({ error: 'Unauthorized' }, 401)
}
const provided = Buffer.from(header.slice(7))
const expected = Buffer.from(getOrCreateInternalToken(db))
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
const expected = getOrCreateInternalToken(db)
if (header.startsWith('Bearer ')) {
if (!tokenMatch(header.slice(7), expected)) {
return c.json({ error: 'Unauthorized' }, 401)
}
} else if (header.startsWith('Basic ')) {
const password = extractTokenFromBasic(header)
if (!password || !tokenMatch(password, expected)) {
return c.json({ error: 'Unauthorized' }, 401)
}
} else {
return c.json({ error: 'Unauthorized' }, 401)
}
await next()
})
}
+2
View File
@@ -35,6 +35,7 @@ import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createInternalRoutes } from './routes/internal'
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
@@ -315,6 +316,7 @@ app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService))
const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
+6
View File
@@ -8,6 +8,9 @@ import { createInternalTokenMiddleware } from '../../auth/internal-token-middlew
import { createInternalNotificationRoutes } from './notifications'
import { createInternalSettingsRoutes } from './settings'
import { createInternalRepoRoutes } from './repos'
import { createInternalRepoSyncRoutes } from './repo-sync'
import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
export function createInternalRoutes(
db: Database,
@@ -23,6 +26,9 @@ export function createInternalRoutes(
const repos = new Hono()
repos.route('/', createInternalRepoRoutes(db, settingsService))
repos.route('/:id/schedules', createScheduleRoutes(scheduleService))
repos.route('/', createInternalRepoSyncRoutes(db))
repos.route('/', mirrorRoutes(db))
app.route('/repos', repos)
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
return app
}
@@ -0,0 +1,41 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { listRepos } from '../../db/queries'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import path from 'path'
export function createInternalOpenCodeWorkspacesRoutes(db: Database) {
const app = new Hono()
app.get('/', (c) => {
try {
const repos = listRepos(db)
const workspaces = repos
.filter((repo) => repo.cloneStatus === 'ready')
.map((repo) => ({
repoId: repo.id,
name: repo.repoUrl
? repo.repoUrl.split('/').slice(-1)[0]?.replace('.git', '') || repo.localPath
: repo.sourcePath
? path.basename(repo.sourcePath)
: repo.localPath,
branch: repo.branch ?? null,
cloneStatus: repo.cloneStatus,
directory: repo.fullPath,
originUrl: repo.repoUrl ?? null,
extra: {
repoId: repo.id,
localPath: repo.localPath,
fullPath: repo.fullPath,
},
}))
return c.json({ workspaces })
} catch (error) {
logger.error('Failed to list opencode workspaces:', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
return app
}
+224
View File
@@ -0,0 +1,224 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { spawn } from 'child_process'
import { pipeline } from 'stream/promises'
import { Readable } from 'stream'
import { mkdtempSync, mkdirSync, readdirSync, statSync, existsSync, writeFileSync } from 'fs'
import { join } from 'path'
import * as fsp from 'fs/promises'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { getRepoById, updateLastPulled, updateRepoBranch, deleteRepo } from '../../db/queries'
import { ensureMirrorTargetPath, createRepoRow, isRepoInUse } from '../../services/repo'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import { safeGitOut, gitOut } from './repo-sync-helpers'
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo']
export function createInternalRepoMirrorRoutes(db: Database) {
const app = new Hono()
app.post('/:repoId/mirror', async (c) => {
const repoIdRaw = c.req.param('repoId')
const force = c.req.query('force') === '1'
const create = c.req.query('create') === '1'
const name = c.req.query('name')
const originUrl = c.req.query('originUrl')
const branch = c.req.query('branch')
const rawBody = c.req.raw.body
if (!rawBody) return c.json({ error: 'no body provided' }, 400)
let repoId: number
let fullPath: string
let created = false
let createdRepoId: number | undefined
if (repoIdRaw === '0' && create) {
if (!name) return c.json({ error: 'name required', message: 'provide a name query param' }, 400)
const target = ensureMirrorTargetPath(name)
const { repo: newRepo, created: wasCreated } = createRepoRow(db, { name, originUrl, localPath: target.localPath, fullPath: target.fullPath, branch })
repoId = newRepo.id
fullPath = newRepo.fullPath
created = wasCreated
createdRepoId = wasCreated ? newRepo.id : undefined
if (!wasCreated && !force && isRepoInUse(db, repoId)) {
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
}
} else {
const repoIdNum = Number(repoIdRaw)
if (!Number.isFinite(repoIdNum)) return c.json({ error: 'invalid repoId' }, 400)
const repo = getRepoById(db, repoIdNum)
if (!repo) return c.json({ error: 'repo not found' }, 404)
repoId = repo.id
fullPath = repo.fullPath
if (!force && isRepoInUse(db, repoId)) {
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
}
}
let staging: string | undefined
let oldDirMoved = false
try {
const stagingParent = join(getReposPath(), '.ocm-staging')
mkdirSync(stagingParent, { recursive: true })
staging = mkdtempSync(join(stagingParent, 'recv-'))
const isGzip = c.req.header('Content-Encoding') === 'gzip'
const tarArgs = ['-x', '-f', '-', '-C', staging]
if (isGzip) tarArgs.unshift('-z')
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
const tarDone = new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) resolve()
else {
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
}
})
child.on('error', reject)
})
const body = Readable.fromWeb(rawBody as unknown as Parameters<typeof Readable.fromWeb>[0])
await pipeline(body, child.stdin)
await tarDone
const entries = readdirSync(staging)
let extractedRoot = staging
if (entries.length === 1) {
const candidate = join(staging, entries[0]!)
try {
if (statSync(candidate).isDirectory()) {
extractedRoot = candidate
}
} catch { /* ignore stat errors */ }
}
if (existsSync(fullPath)) {
try {
await fsp.rename(fullPath, fullPath + '.ocm-old')
oldDirMoved = true
} catch { /* ignore rename errors */ }
}
await fsp.rename(extractedRoot, fullPath)
const oldDir = fullPath + '.ocm-old'
await fsp.rm(oldDir, { recursive: true, force: true }).catch(() => {})
const branchName = await safeGitOut(fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
const head = await safeGitOut(fullPath, ['rev-parse', 'HEAD'])
if (branchName) {
updateRepoBranch(db, repoId, branchName.trim())
}
updateLastPulled(db, repoId)
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
return c.json({
repoId,
fullPath,
branch: branchName?.trim() || null,
head: head?.trim() || null,
created,
})
} catch (error) {
logger.error('mirror POST failed:', error)
if (oldDirMoved) {
try {
await fsp.rename(fullPath + '.ocm-old', fullPath)
} catch {
logger.error('failed to restore old repo from .ocm-old')
}
}
if (createdRepoId !== undefined) {
try {
deleteRepo(db, createdRepoId)
} catch {
logger.error('failed to delete created repo row on failure')
}
}
if (staging) {
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
}
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.get('/:repoId/mirror', async (c) => {
const repoIdRaw = c.req.param('repoId')
const repoId = Number(repoIdRaw)
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
const repo = getRepoById(db, repoId)
if (!repo) return c.json({ error: 'repo not found' }, 404)
const compress = c.req.query('compress') === 'gzip'
const fullPath = repo.fullPath
const excludeArgs: string[] = []
for (const dir of HARDCODED_EXCLUDES) {
excludeArgs.push('--exclude', dir)
}
let ignoreFile: string | undefined
try {
const ignored = await gitOut(fullPath, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'])
if (ignored.trim()) {
const excludeParent = join(getReposPath(), '.ocm-staging')
mkdirSync(excludeParent, { recursive: true })
ignoreFile = mkdtempSync(join(excludeParent, 'exclude-'))
writeFileSync(join(ignoreFile, '.gitignore'), ignored)
excludeArgs.push('--exclude-from', join(ignoreFile, '.gitignore'))
}
} catch { /* ignore git ls-files errors */ }
const tarArgs = ['-c', '-C', fullPath, ...excludeArgs, '.']
if (compress) {
tarArgs.unshift('-z')
}
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const stream = new ReadableStream({
start(controller) {
child.stdout.on('data', (chunk: Buffer) => {
controller.enqueue(new Uint8Array(chunk))
})
child.stdout.on('end', () => {
controller.close()
if (ignoreFile) {
fsp.rm(ignoreFile, { recursive: true, force: true }).catch(() => {})
}
})
child.stdout.on('error', (err: Error) => {
controller.error(err)
if (ignoreFile) {
fsp.rm(ignoreFile, { recursive: true, force: true }).catch(() => {})
}
})
},
})
child.on('close', () => {})
child.on('error', () => {})
return new Response(stream, {
headers: {
'Content-Type': 'application/x-tar',
...(compress ? { 'Content-Encoding': 'gzip' } : {}),
},
})
})
return app
}
@@ -0,0 +1,25 @@
import { resolve, normalize, isAbsolute, sep } from 'path'
import { executeCommand } from '../../utils/process'
export async function gitOut(repoPath: string, args: string[]): Promise<string> {
return executeCommand(['git', '-C', repoPath, ...args], { silent: true })
}
export async function safeGitOut(repoPath: string, args: string[]): Promise<string | null> {
try {
return await gitOut(repoPath, args)
} catch {
return null
}
}
export function isSafeRelativePath(repoPath: string, relPath: string): string | null {
if (!relPath || relPath.startsWith('/') || relPath.includes('\0')) return null
const normalized = normalize(relPath)
if (normalized.startsWith('..') || normalized.includes(`${sep}..${sep}`) || normalized === '..') return null
if (isAbsolute(normalized)) return null
const full = resolve(repoPath, normalized)
const root = resolve(repoPath) + sep
if (full !== resolve(repoPath) && !full.startsWith(root)) return null
return full
}
+42
View File
@@ -0,0 +1,42 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { getRepoById } from '../../db/queries'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import { safeGitOut } from './repo-sync-helpers'
export function createInternalRepoSyncRoutes(db: Database) {
const app = new Hono()
app.get('/:repoId/git-info', async (c) => {
const repoIdRaw = c.req.param('repoId')
const repoId = Number(repoIdRaw)
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
const repo = getRepoById(db, repoId)
if (!repo) return c.json({ error: 'repo not found' }, 404)
if (repo.cloneStatus !== 'ready') return c.json({ error: 'repo not ready' }, 409)
const repoPath = repo.fullPath
try {
const [originUrl, head, branch, status] = await Promise.all([
safeGitOut(repoPath, ['remote', 'get-url', 'origin']),
safeGitOut(repoPath, ['rev-parse', 'HEAD']),
safeGitOut(repoPath, ['rev-parse', '--abbrev-ref', 'HEAD']),
safeGitOut(repoPath, ['status', '--porcelain']),
])
return c.json({
repoId,
repoName: repo.repoUrl?.split('/').slice(-1)[0]?.replace('.git', '') ?? null,
directory: repoPath,
originUrl: originUrl?.trim() || null,
head: head?.trim() || null,
branch: branch?.trim() || null,
dirty: Boolean(status && status.trim().length > 0),
})
} catch (error) {
logger.error('git-info failed:', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
return app
}
+83
View File
@@ -0,0 +1,83 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
import { createInternalTokenMiddleware } from '../auth/internal-token-middleware'
import type { SettingsService } from '../services/settings'
const HOP_BY_HOP_HEADERS = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailers',
'upgrade',
'transfer-encoding',
'content-length',
'content-encoding',
'host',
'authorization',
])
export function createOpenCodeProxyRoutes(db: Database, settingsService: SettingsService) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
app.all('/*', async (c) => {
const connectionHeader = c.req.header('connection')?.toLowerCase() ?? ''
const upgradeHeader = c.req.header('upgrade')?.toLowerCase() ?? ''
if (connectionHeader.includes('upgrade') && upgradeHeader === 'websocket') {
return c.json({ error: 'WebSocket proxying is not supported' }, 501)
}
const url = new URL(c.req.url)
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy/, '') || '/'
const upstreamUrl = `http://127.0.0.1:${ENV.OPENCODE.PORT}${pathSuffix}${url.search}`
const headers: Record<string, string> = {}
c.req.raw.headers.forEach((value, key) => {
const lowerKey = key.toLowerCase()
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
headers[key] = value
}
})
const password = settingsService.getOpenCodeServerPassword()
const username = ENV.OPENCODE.SERVER_USERNAME
headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
let requestBody: RequestInit['body'] = undefined
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
requestBody = c.req.raw.body
}
try {
const upstreamResponse = await fetch(upstreamUrl, {
method: c.req.method,
headers,
body: requestBody,
redirect: 'manual',
duplex: 'half',
})
const responseHeaders: Record<string, string> = {}
upstreamResponse.headers.forEach((value, key) => {
const lowerKey = key.toLowerCase()
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
responseHeaders[key] = value
}
})
return new Response(upstreamResponse.body, {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
headers: responseHeaders,
})
} catch {
return c.json({ error: 'Proxy request failed' }, 502)
}
})
return app
}
+21
View File
@@ -21,6 +21,7 @@ import {
} from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
import { sseAggregator } from '../services/sse-aggregator'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import type { GitAuthService } from '../services/git-auth'
@@ -1555,5 +1556,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
})
app.get('/manager-token', async (c) => {
try {
const token = getOrCreateInternalToken(db)
return c.json({ token })
} catch (error) {
logger.error('Failed to get manager token:', error)
return c.json({ error: 'Failed to get manager token' }, 500)
}
})
app.post('/manager-token/rotate', async (c) => {
try {
const token = rotateInternalToken(db)
return c.json({ token })
} catch (error) {
logger.error('Failed to rotate manager token:', error)
return c.json({ error: 'Failed to rotate manager token' }, 500)
}
})
return app
}
+60
View File
@@ -12,6 +12,7 @@ import { isGitHubHttpsUrl, isSSHUrl, normalizeSSHUrl } from '../utils/git-auth'
import path from 'path'
import { parseSSHHost } from '../utils/ssh-key-manager'
import { getErrorMessage } from '../utils/error-utils'
import { sseAggregator } from './sse-aggregator'
const GIT_CLONE_TIMEOUT = 300000
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
@@ -1028,3 +1029,62 @@ async function createWorktreeSafely(baseRepoPath: string, worktreePath: string,
await executeCommand(addArgs, { env })
}
}
export function ensureMirrorTargetPath(name: string): { fullPath: string; localPath: string } {
const slugified = name
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
|| 'repo'
const reposRoot = getReposPath()
let candidate = slugified
let suffix = 2
while (existsSync(path.join(reposRoot, candidate))) {
candidate = `${slugified}-${suffix}`
suffix += 1
}
return {
fullPath: path.join(reposRoot, candidate),
localPath: candidate,
}
}
export function createRepoRow(
database: Database,
params: { name: string; originUrl?: string; localPath: string; fullPath: string; branch?: string }
): { repo: Repo; created: boolean } {
const { originUrl, localPath, branch } = params
const existing = originUrl
? getRepoByUrlAndBranch(database, originUrl, branch)
: getRepoByLocalPath(database, localPath)
if (existing) {
return { repo: existing, created: false }
}
const repo = createRepo(database, {
repoUrl: originUrl,
localPath,
branch,
defaultBranch: branch || 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
isLocal: !originUrl,
} as CreateRepoInput)
return { repo, created: true }
}
export function isRepoInUse(db: Database, repoId: number): boolean {
const repo = getRepoById(db, repoId)
if (!repo) {
return false
}
return sseAggregator.getActiveDirectories().includes(repo.fullPath)
}