mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
section 16: Phase 16: Documentation, container ports and full repository checks
This commit is contained in:
1 parent
81a9f0c8ef
commit
a383e57bc5
55 files changed
+4095
-59
No files matched your search
@@ -39,6 +39,8 @@ import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes } from './routes/preview'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
@@ -268,6 +270,7 @@ sseAggregator.setScheduledSessionsResolver(
|
||||
void scheduleRunnerInstance.start()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const previewSessionStore = new PreviewSessionStore()
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
@@ -296,6 +299,7 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/logs', createLogRoutes())
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore }))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
@@ -415,4 +419,15 @@ const server = serve({
|
||||
|
||||
injectWebSocket(server)
|
||||
|
||||
if (ENV.PREVIEW.PORT > 0) {
|
||||
const previewGateway = createPreviewGatewayApp(previewSessionStore)
|
||||
const previewServer = serve({
|
||||
fetch: previewGateway.app.fetch,
|
||||
port: ENV.PREVIEW.PORT,
|
||||
hostname: HOST,
|
||||
})
|
||||
previewGateway.injectWebSocket(previewServer)
|
||||
logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
|
||||
}
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -11,21 +11,7 @@ import {
|
||||
withDefaultOpenCodeDirectory,
|
||||
} from '../services/opencode/upstream'
|
||||
import { getRepoById } from '../db/queries'
|
||||
|
||||
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',
|
||||
])
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers'
|
||||
|
||||
interface ProxyRequestParts {
|
||||
method: string
|
||||
@@ -95,13 +81,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
const url = new URL(c.req.url)
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
const forwardedHeaders: Record<string, string> = {}
|
||||
c.req.raw.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
|
||||
forwardedHeaders[key] = value
|
||||
}
|
||||
})
|
||||
const forwardedHeaders = filterProxyHeaders(c.req.raw.headers)
|
||||
const headers = withDefaultOpenCodeDirectory(forwardedHeaders)
|
||||
|
||||
headers['Authorization'] = buildOpenCodeBasicAuth(settingsService.getOpenCodeServerPassword())
|
||||
@@ -140,13 +120,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
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
|
||||
}
|
||||
})
|
||||
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
|
||||
|
||||
return new Response(upstreamResponse.body, {
|
||||
status: upstreamResponse.status,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import path from 'node:path'
|
||||
import { Hono } from 'hono'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { CreatePreviewSessionRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { listListeningPorts, isReservedPreviewPort, type PreviewPortEntry } from '../services/preview/ports'
|
||||
import { PreviewSessionStore } from '../services/preview/gateway'
|
||||
|
||||
export interface PreviewRoutesDeps {
|
||||
enabled: boolean
|
||||
listPorts: () => Promise<PreviewPortEntry[]>
|
||||
store: PreviewSessionStore
|
||||
}
|
||||
|
||||
function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null): boolean {
|
||||
if (!cwd || !canonicalDirectory) return false
|
||||
const canonicalCwd = canonicalPathSync(cwd)
|
||||
if (canonicalCwd === canonicalDirectory) return true
|
||||
const prefix = canonicalDirectory.endsWith(path.sep) ? canonicalDirectory : `${canonicalDirectory}${path.sep}`
|
||||
return canonicalCwd.startsWith(prefix)
|
||||
}
|
||||
|
||||
export function createPreviewRoutes(deps: Partial<PreviewRoutesDeps> = {}) {
|
||||
const resolvedDeps: PreviewRoutesDeps = {
|
||||
enabled: deps.enabled ?? ENV.PREVIEW.PORT > 0,
|
||||
listPorts: deps.listPorts ?? (() => listListeningPorts()),
|
||||
store: deps.store ?? new PreviewSessionStore(),
|
||||
}
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/ports', async (c) => {
|
||||
const directory = c.req.query('directory')
|
||||
const canonicalDirectory = directory ? canonicalPathSync(directory) : null
|
||||
const ports = await resolvedDeps.listPorts()
|
||||
const sorted = [...ports].sort((left, right) => {
|
||||
const leftMatch = isInsideDirectory(left.cwd, canonicalDirectory)
|
||||
const rightMatch = isInsideDirectory(right.cwd, canonicalDirectory)
|
||||
if (leftMatch !== rightMatch) return leftMatch ? -1 : 1
|
||||
return left.port - right.port
|
||||
})
|
||||
return c.json({ enabled: resolvedDeps.enabled, ports: sorted })
|
||||
})
|
||||
|
||||
app.post('/sessions', async (c) => {
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = CreatePreviewSessionRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
if (!resolvedDeps.enabled) {
|
||||
return c.json({ error: 'Preview is disabled' }, 503)
|
||||
}
|
||||
|
||||
if (isReservedPreviewPort(parsed.data.port)) {
|
||||
return c.json({ error: 'Port is reserved' }, 400)
|
||||
}
|
||||
|
||||
const ports = await resolvedDeps.listPorts()
|
||||
const match = ports.find((entry) => entry.port === parsed.data.port)
|
||||
if (!match) {
|
||||
return c.json({ error: `Port ${parsed.data.port} is not listening` }, 404)
|
||||
}
|
||||
|
||||
const token = resolvedDeps.store.issueStartToken({ port: match.port, host: match.host })
|
||||
return c.json({
|
||||
token,
|
||||
previewPort: ENV.PREVIEW.PORT,
|
||||
publicUrl: ENV.PREVIEW.PUBLIC_URL || null,
|
||||
})
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createRepoRoutes } from './repos'
|
||||
import { createRepo, getRepoById } from '../db/queries'
|
||||
import { createRepo, getRepoById, setRepoSetting } from '../db/queries'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
@@ -33,7 +33,11 @@ const stubTerminalService = {
|
||||
removeAll: mock(async () => undefined),
|
||||
} as unknown as TerminalService
|
||||
|
||||
function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono {
|
||||
function createTestApp(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient = createStubOpenCodeClient(),
|
||||
terminalService: TerminalService = stubTerminalService,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
const scheduleService = {
|
||||
createSchedule: () => {},
|
||||
@@ -43,7 +47,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub
|
||||
deleteSchedule: () => {},
|
||||
prepareRepoDelete: () => {},
|
||||
} as any
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, stubTerminalService))
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService))
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -440,10 +444,32 @@ describe('POST /api/repos/:id/workspaces', () => {
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test' })
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } })
|
||||
expect(create).toHaveBeenCalledWith({ projectID: 'commit-A' })
|
||||
})
|
||||
|
||||
it('still returns 200 with a failed worktree setup when the setup terminal cannot start', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
setRepoSetting(db, 1, 'worktreeSetupCommands', JSON.stringify(['pnpm install']))
|
||||
const client = createStubOpenCodeClient()
|
||||
client.api.worktree.create = mock(async () => ({ directory: '/tmp/wrk-test' })) as any
|
||||
const failingTerminalService = {
|
||||
removeAll: mock(async () => undefined),
|
||||
create: mock(async () => {
|
||||
throw new Error('spawn failed')
|
||||
}),
|
||||
} as unknown as TerminalService
|
||||
const app = createTestApp(db, client, failingTerminalService)
|
||||
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
directory: '/tmp/wrk-test',
|
||||
worktreeSetup: { status: 'failed', error: 'spawn failed' },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric repo id', async () => {
|
||||
const app = createTestApp(db)
|
||||
const res = await app.request('/repos/abc/workspaces', { method: 'POST' })
|
||||
|
||||
@@ -92,7 +92,17 @@ export function createRepoRoutes(
|
||||
{ branch, directoryName, useWorktree, skipSSHVerification, baseBranch }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (repo.isWorktree) {
|
||||
const projectRepo = await projectConfigService.resolveProjectRepo(repo)
|
||||
if (projectRepo.id !== repo.id) {
|
||||
return c.json({
|
||||
...repo,
|
||||
worktreeSetup: await projectConfigService.runWorktreeSetup(projectRepo, repo.fullPath, terminalService),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(repo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create repo:', error)
|
||||
@@ -320,7 +330,10 @@ app.get('/', async (c) => {
|
||||
try {
|
||||
const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
const worktree = await openCodeClient.api.worktree.create({ projectID })
|
||||
return c.json(worktree)
|
||||
return c.json({
|
||||
...worktree,
|
||||
worktreeSetup: await projectConfigService.runWorktreeSetup(repo, worktree.directory, terminalService),
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (isWorktreeError(error)) {
|
||||
return c.json({ error: error.data.message }, 409)
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers'
|
||||
import { bridgeWebSocket, type WebSocketBridge } from '../../utils/websocket-bridge'
|
||||
|
||||
export const PREVIEW_COOKIE = 'ocm_preview'
|
||||
|
||||
const START_TOKEN_TTL_MS = 60_000
|
||||
const SESSION_TTL_MS = 12 * 60 * 60 * 1000
|
||||
|
||||
const MANAGER_COOKIE_PREFIXES = ['opencode.', '__Secure-opencode.', '__Host-opencode.']
|
||||
|
||||
export type PreviewHost = '127.0.0.1' | '::1'
|
||||
|
||||
export interface PreviewSession {
|
||||
id: string
|
||||
port: number
|
||||
host: PreviewHost
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
interface StartToken {
|
||||
port: number
|
||||
host: PreviewHost
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export interface PreviewSessionStoreOptions {
|
||||
now?: () => number
|
||||
randomToken?: () => string
|
||||
}
|
||||
|
||||
export class PreviewSessionStore {
|
||||
private readonly startTokens = new Map<string, StartToken>()
|
||||
private readonly sessions = new Map<string, PreviewSession>()
|
||||
private readonly now: () => number
|
||||
private readonly randomToken: () => string
|
||||
|
||||
constructor(options: PreviewSessionStoreOptions = {}) {
|
||||
this.now = options.now ?? Date.now
|
||||
this.randomToken = options.randomToken ?? (() => randomBytes(32).toString('base64url'))
|
||||
}
|
||||
|
||||
issueStartToken(target: { port: number; host: PreviewHost }): string {
|
||||
this.prune()
|
||||
const token = this.randomToken()
|
||||
this.startTokens.set(token, { port: target.port, host: target.host, expiresAt: this.now() + START_TOKEN_TTL_MS })
|
||||
return token
|
||||
}
|
||||
|
||||
consumeStartToken(token: string): string | null {
|
||||
this.prune()
|
||||
const entry = this.startTokens.get(token)
|
||||
if (!entry) return null
|
||||
this.startTokens.delete(token)
|
||||
const id = this.randomToken()
|
||||
this.sessions.set(id, { id, port: entry.port, host: entry.host, expiresAt: this.now() + SESSION_TTL_MS })
|
||||
return id
|
||||
}
|
||||
|
||||
getSession(id: string): PreviewSession | undefined {
|
||||
this.prune()
|
||||
return this.sessions.get(id)
|
||||
}
|
||||
|
||||
private prune(): void {
|
||||
const now = this.now()
|
||||
for (const [token, entry] of this.startTokens) {
|
||||
if (entry.expiresAt <= now) this.startTokens.delete(token)
|
||||
}
|
||||
for (const [id, session] of this.sessions) {
|
||||
if (session.expiresAt <= now) this.sessions.delete(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
|
||||
if (!cookieHeader) return undefined
|
||||
const kept = cookieHeader
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => {
|
||||
if (!part) return false
|
||||
const separator = part.indexOf('=')
|
||||
const name = separator === -1 ? part : part.slice(0, separator)
|
||||
if (name === PREVIEW_COOKIE) return false
|
||||
return !MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
|
||||
})
|
||||
return kept.length > 0 ? kept.join('; ') : undefined
|
||||
}
|
||||
|
||||
function readPreviewCookie(cookieHeader: string | undefined): string | null {
|
||||
if (!cookieHeader) return null
|
||||
for (const part of cookieHeader.split(';')) {
|
||||
const trimmed = part.trim()
|
||||
const separator = trimmed.indexOf('=')
|
||||
if (separator === -1) continue
|
||||
if (trimmed.slice(0, separator) === PREVIEW_COOKIE) {
|
||||
return trimmed.slice(separator + 1)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function htmlResponse(status: number, message: string): Response {
|
||||
return new Response(`<!doctype html><html><body><p>${message}</p></body></html>`, {
|
||||
status,
|
||||
headers: { 'content-type': 'text/html; charset=utf-8' },
|
||||
})
|
||||
}
|
||||
|
||||
function rewriteLocalLocation(location: string, port: number): string | null {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(location)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const isLocalHost =
|
||||
parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]' || parsed.hostname === '::1'
|
||||
if (!isLocalHost) return null
|
||||
const locationPort = parsed.port
|
||||
? Number.parseInt(parsed.port, 10)
|
||||
: parsed.protocol === 'https:'
|
||||
? 443
|
||||
: 80
|
||||
if (locationPort !== port) return null
|
||||
return `${parsed.pathname}${parsed.search}`
|
||||
}
|
||||
|
||||
export interface PreviewGateway {
|
||||
app: Hono
|
||||
injectWebSocket: NodeWebSocket['injectWebSocket']
|
||||
}
|
||||
|
||||
function isWebSocketUpgrade(c: Context): boolean {
|
||||
return c.req.header('upgrade')?.toLowerCase() === 'websocket'
|
||||
}
|
||||
|
||||
function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string {
|
||||
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
|
||||
return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}`
|
||||
}
|
||||
|
||||
function parseProtocols(header: string | undefined): string[] {
|
||||
if (!header) return []
|
||||
return header
|
||||
.split(',')
|
||||
.map((protocol) => protocol.trim())
|
||||
.filter((protocol) => protocol.length > 0)
|
||||
}
|
||||
|
||||
export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typeof fetch = fetch): PreviewGateway {
|
||||
const app = new Hono()
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app })
|
||||
|
||||
app.get('/__ocm_preview/start', (c) => {
|
||||
const sessionId = store.consumeStartToken(c.req.query('token') ?? '')
|
||||
if (!sessionId) {
|
||||
return htmlResponse(401, 'Preview session is invalid or expired.')
|
||||
}
|
||||
|
||||
const requestedPath = c.req.query('path') ?? ''
|
||||
const location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/'
|
||||
|
||||
const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase()
|
||||
const isSecure = forwardedProto === 'https' || new URL(c.req.url).protocol === 'https:'
|
||||
const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}`
|
||||
|
||||
return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } })
|
||||
})
|
||||
|
||||
const sessionGuard: MiddlewareHandler = async (c, next) => {
|
||||
if (!isWebSocketUpgrade(c)) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
const sessionId = readPreviewCookie(c.req.header('cookie'))
|
||||
if (!sessionId || !store.getSession(sessionId)) {
|
||||
return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.')
|
||||
}
|
||||
await next()
|
||||
}
|
||||
|
||||
app.get(
|
||||
'/*',
|
||||
sessionGuard,
|
||||
upgradeWebSocket((c) => {
|
||||
const requestUrl = new URL(c.req.url)
|
||||
const protocols = parseProtocols(c.req.header('sec-websocket-protocol'))
|
||||
let bridge: WebSocketBridge | undefined
|
||||
|
||||
return {
|
||||
onOpen(_event, ws) {
|
||||
const sessionId = readPreviewCookie(c.req.header('cookie'))
|
||||
const session = sessionId ? store.getSession(sessionId) : undefined
|
||||
if (!session) {
|
||||
ws.close(1011)
|
||||
return
|
||||
}
|
||||
|
||||
let upstream: WebSocket
|
||||
try {
|
||||
upstream = new WebSocket(upstreamWebSocketUrl(session, requestUrl), protocols.length > 0 ? protocols : undefined)
|
||||
} catch {
|
||||
ws.close(1011)
|
||||
return
|
||||
}
|
||||
|
||||
bridge = bridgeWebSocket(upstream, {
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => ws.close(code, reason),
|
||||
})
|
||||
},
|
||||
async onMessage(event) {
|
||||
if (!bridge) return
|
||||
const data = event.data
|
||||
if (typeof data === 'string') {
|
||||
bridge.send(data)
|
||||
return
|
||||
}
|
||||
if (data instanceof Blob) {
|
||||
bridge.send(await data.arrayBuffer())
|
||||
return
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
bridge.send(data)
|
||||
}
|
||||
},
|
||||
onClose() {
|
||||
bridge?.close()
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
const cookieHeader = c.req.header('cookie')
|
||||
const sessionId = readPreviewCookie(cookieHeader)
|
||||
const session = sessionId ? store.getSession(sessionId) : undefined
|
||||
if (!session) {
|
||||
return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.')
|
||||
}
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
|
||||
const target = `http://${targetHost}:${session.port}${url.pathname}${url.search}`
|
||||
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
const headers = filterProxyHeaders(c.req.raw.headers)
|
||||
const contentEncoding = hasBody ? c.req.header('content-encoding') : undefined
|
||||
if (contentEncoding) {
|
||||
headers['content-encoding'] = contentEncoding
|
||||
}
|
||||
headers['host'] = `localhost:${session.port}`
|
||||
const strippedCookies = stripManagerCookies(cookieHeader)
|
||||
if (strippedCookies) {
|
||||
headers['cookie'] = strippedCookies
|
||||
} else {
|
||||
delete headers['cookie']
|
||||
}
|
||||
headers['x-forwarded-host'] = c.req.header('host') ?? ''
|
||||
headers['x-forwarded-proto'] = c.req.header('x-forwarded-proto') ?? url.protocol.replace(':', '')
|
||||
|
||||
try {
|
||||
const upstreamResponse = await fetchFn(target, {
|
||||
method: c.req.method,
|
||||
headers,
|
||||
body: hasBody ? c.req.raw.body : undefined,
|
||||
redirect: 'manual',
|
||||
duplex: 'half',
|
||||
})
|
||||
|
||||
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
|
||||
const location = responseHeaders.get('location')
|
||||
if (location) {
|
||||
const rewritten = rewriteLocalLocation(location, session.port)
|
||||
if (rewritten) responseHeaders.set('location', rewritten)
|
||||
}
|
||||
|
||||
return new Response(upstreamResponse.body, {
|
||||
status: upstreamResponse.status,
|
||||
statusText: upstreamResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch {
|
||||
return htmlResponse(502, `Preview request failed: cannot reach port ${session.port}.`)
|
||||
}
|
||||
})
|
||||
|
||||
return { app, injectWebSocket }
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { readFile, readdir, readlink } from 'node:fs/promises'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { executeCommand } from '../../utils/process'
|
||||
|
||||
export interface PreviewPortEntry {
|
||||
port: number
|
||||
host: '127.0.0.1' | '::1'
|
||||
pid: number | null
|
||||
command: string | null
|
||||
cwd: string | null
|
||||
}
|
||||
|
||||
export interface ParsedProcNetSocket {
|
||||
port: number
|
||||
address: string
|
||||
inode: string
|
||||
}
|
||||
|
||||
export interface LsofListener {
|
||||
port: number
|
||||
address: string
|
||||
pid: number | null
|
||||
command: string | null
|
||||
}
|
||||
|
||||
export interface PortDiscoveryDeps {
|
||||
platform: NodeJS.Platform
|
||||
readFile: (path: string, encoding: 'utf8') => Promise<string>
|
||||
readdir: (path: string) => Promise<string[]>
|
||||
readlink: (path: string) => Promise<string>
|
||||
runLsof: () => Promise<string>
|
||||
}
|
||||
|
||||
const PROC_NET_FILES: ReadonlyArray<readonly [string, 4 | 6]> = [
|
||||
['/proc/net/tcp', 4],
|
||||
['/proc/net/tcp6', 6],
|
||||
]
|
||||
|
||||
const WILDCARD_V4 = '0.0.0.0'
|
||||
const WILDCARD_V6 = '::'
|
||||
|
||||
function decodeIpv4Hex(hex: string): string | null {
|
||||
if (hex.length !== 8) return null
|
||||
const octets: number[] = []
|
||||
for (let index = 6; index >= 0; index -= 2) {
|
||||
const octet = Number.parseInt(hex.slice(index, index + 2), 16)
|
||||
if (Number.isNaN(octet)) return null
|
||||
octets.push(octet)
|
||||
}
|
||||
return octets.join('.')
|
||||
}
|
||||
|
||||
function formatIpv6(groups: string[]): string {
|
||||
const normalized = groups.map((group) => group.replace(/^0+/, '') || '0')
|
||||
let bestStart = -1
|
||||
let bestLength = 0
|
||||
let currentStart = -1
|
||||
let currentLength = 0
|
||||
for (let index = 0; index < normalized.length; index += 1) {
|
||||
if (normalized[index] === '0') {
|
||||
if (currentStart === -1) {
|
||||
currentStart = index
|
||||
currentLength = 0
|
||||
}
|
||||
currentLength += 1
|
||||
if (currentLength > bestLength) {
|
||||
bestLength = currentLength
|
||||
bestStart = currentStart
|
||||
}
|
||||
} else {
|
||||
currentStart = -1
|
||||
currentLength = 0
|
||||
}
|
||||
}
|
||||
if (bestLength < 2) return normalized.join(':')
|
||||
const head = normalized.slice(0, bestStart).join(':')
|
||||
const tail = normalized.slice(bestStart + bestLength).join(':')
|
||||
return `${head}::${tail}`
|
||||
}
|
||||
|
||||
function decodeIpv6Hex(hex: string): string | null {
|
||||
if (hex.length !== 32) return null
|
||||
const groups: string[] = []
|
||||
for (let index = 0; index < 32; index += 8) {
|
||||
const word = hex.slice(index, index + 8)
|
||||
const reversed = `${word.slice(6, 8)}${word.slice(4, 6)}${word.slice(2, 4)}${word.slice(0, 2)}`
|
||||
groups.push(reversed.slice(0, 4), reversed.slice(4, 8))
|
||||
}
|
||||
return formatIpv6(groups)
|
||||
}
|
||||
|
||||
function isAllowedAddress(address: string): boolean {
|
||||
return (
|
||||
address === WILDCARD_V4 ||
|
||||
address === WILDCARD_V6 ||
|
||||
address === '::1' ||
|
||||
address.startsWith('127.')
|
||||
)
|
||||
}
|
||||
|
||||
export function isReservedPreviewPort(port: number): boolean {
|
||||
return port === ENV.SERVER.PORT || port === ENV.OPENCODE.PORT || port === ENV.PREVIEW.PORT
|
||||
}
|
||||
|
||||
export function parseProcNetTcp(text: string, family: 4 | 6): ParsedProcNetSocket[] {
|
||||
const sockets: ParsedProcNetSocket[] = []
|
||||
for (const rawLine of text.split('\n')) {
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('sl')) continue
|
||||
const parts = line.split(/\s+/)
|
||||
if (parts.length < 10) continue
|
||||
if (parts[3] !== '0A') continue
|
||||
const local = parts[1]
|
||||
if (!local) continue
|
||||
const separator = local.lastIndexOf(':')
|
||||
if (separator === -1) continue
|
||||
const addressHex = local.slice(0, separator)
|
||||
const portHex = local.slice(separator + 1)
|
||||
const port = Number.parseInt(portHex, 16)
|
||||
if (Number.isNaN(port)) continue
|
||||
const address = family === 4 ? decodeIpv4Hex(addressHex) : decodeIpv6Hex(addressHex)
|
||||
if (!address || !isAllowedAddress(address)) continue
|
||||
sockets.push({ port, address, inode: parts[9] ?? '' })
|
||||
}
|
||||
return sockets
|
||||
}
|
||||
|
||||
function parseLsofName(value: string): { address: string; port: number } | null {
|
||||
let address: string
|
||||
let portText: string
|
||||
if (value.startsWith('[')) {
|
||||
const end = value.indexOf(']')
|
||||
if (end === -1) return null
|
||||
address = value.slice(1, end)
|
||||
const rest = value.slice(end + 1)
|
||||
if (!rest.startsWith(':')) return null
|
||||
portText = rest.slice(1)
|
||||
} else {
|
||||
const separator = value.lastIndexOf(':')
|
||||
if (separator === -1) return null
|
||||
address = value.slice(0, separator)
|
||||
portText = value.slice(separator + 1)
|
||||
}
|
||||
if (address === '*') address = WILDCARD_V4
|
||||
const port = Number.parseInt(portText, 10)
|
||||
if (Number.isNaN(port)) return null
|
||||
return { address, port }
|
||||
}
|
||||
|
||||
export function parseLsofListen(output: string): LsofListener[] {
|
||||
const listeners: LsofListener[] = []
|
||||
let pid: number | null = null
|
||||
let command: string | null = null
|
||||
for (const rawLine of output.split('\n')) {
|
||||
const field = rawLine.trim()
|
||||
if (!field) continue
|
||||
const type = field[0]
|
||||
const value = field.slice(1)
|
||||
if (type === 'p') {
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
pid = Number.isNaN(parsed) ? null : parsed
|
||||
} else if (type === 'c') {
|
||||
command = value
|
||||
} else if (type === 'n') {
|
||||
const parsed = parseLsofName(value)
|
||||
if (parsed) listeners.push({ ...parsed, pid, command })
|
||||
}
|
||||
}
|
||||
return listeners
|
||||
}
|
||||
|
||||
function toHost(address: string): '127.0.0.1' | '::1' {
|
||||
return address === '::1' ? '::1' : '127.0.0.1'
|
||||
}
|
||||
|
||||
function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
|
||||
const byPort = new Map<number, PreviewPortEntry[]>()
|
||||
for (const entry of entries) {
|
||||
const existing = byPort.get(entry.port)
|
||||
if (existing) {
|
||||
existing.push(entry)
|
||||
} else {
|
||||
byPort.set(entry.port, [entry])
|
||||
}
|
||||
}
|
||||
const result: PreviewPortEntry[] = []
|
||||
for (const group of byPort.values()) {
|
||||
const first = group[0]!
|
||||
const onlyIpv6Loopback = group.every((entry) => entry.host === '::1')
|
||||
result.push({ ...first, host: onlyIpv6Loopback ? '::1' : '127.0.0.1' })
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, number>> {
|
||||
const map = new Map<string, number>()
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await deps.readdir('/proc')
|
||||
} catch {
|
||||
return map
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const fdDir = `/proc/${entry}/fd`
|
||||
let fds: string[]
|
||||
try {
|
||||
fds = await deps.readdir(fdDir)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const fd of fds) {
|
||||
let target: string
|
||||
try {
|
||||
target = await deps.readlink(`${fdDir}/${fd}`)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const match = /^socket:\[(\d+)\]$/.exec(target)
|
||||
if (match?.[1]) map.set(match[1], Number.parseInt(entry, 10))
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
async function readOptional(deps: PortDiscoveryDeps, file: string): Promise<string | null> {
|
||||
try {
|
||||
return (await deps.readFile(file, 'utf8')).trim() || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function readLinkOptional(deps: PortDiscoveryDeps, file: string): Promise<string | null> {
|
||||
try {
|
||||
return await deps.readlink(file)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function listLinuxPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry[]> {
|
||||
const sockets: ParsedProcNetSocket[] = []
|
||||
for (const [file, family] of PROC_NET_FILES) {
|
||||
let text: string
|
||||
try {
|
||||
text = await deps.readFile(file, 'utf8')
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
sockets.push(...parseProcNetTcp(text, family))
|
||||
}
|
||||
if (sockets.length === 0) return []
|
||||
|
||||
const inodeToPid = await mapInodesToPids(deps)
|
||||
const processMeta = new Map<number, { command: string | null; cwd: string | null }>()
|
||||
const entries: PreviewPortEntry[] = []
|
||||
for (const socket of sockets) {
|
||||
const pid = inodeToPid.get(socket.inode) ?? null
|
||||
let command: string | null = null
|
||||
let cwd: string | null = null
|
||||
if (pid !== null) {
|
||||
const cached = processMeta.get(pid)
|
||||
if (cached) {
|
||||
command = cached.command
|
||||
cwd = cached.cwd
|
||||
} else {
|
||||
command = await readOptional(deps, `/proc/${pid}/comm`)
|
||||
cwd = await readLinkOptional(deps, `/proc/${pid}/cwd`)
|
||||
processMeta.set(pid, { command, cwd })
|
||||
}
|
||||
}
|
||||
entries.push({ port: socket.port, host: toHost(socket.address), pid, command, cwd })
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
async function listMacPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry[]> {
|
||||
let output: string
|
||||
try {
|
||||
output = await deps.runLsof()
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
return parseLsofListen(output)
|
||||
.filter((listener) => isAllowedAddress(listener.address))
|
||||
.map((listener) => ({
|
||||
port: listener.port,
|
||||
host: toHost(listener.address),
|
||||
pid: listener.pid,
|
||||
command: listener.command,
|
||||
cwd: null,
|
||||
}))
|
||||
}
|
||||
|
||||
export async function listListeningPorts(deps: PortDiscoveryDeps = defaultPortDeps): Promise<PreviewPortEntry[]> {
|
||||
const entries =
|
||||
deps.platform === 'linux'
|
||||
? await listLinuxPorts(deps)
|
||||
: deps.platform === 'darwin'
|
||||
? await listMacPorts(deps)
|
||||
: []
|
||||
|
||||
return dedupeByPort(entries)
|
||||
.filter((entry) => entry.port >= 1024 && !isReservedPreviewPort(entry.port))
|
||||
.sort((left, right) => left.port - right.port)
|
||||
}
|
||||
|
||||
const defaultPortDeps: PortDiscoveryDeps = {
|
||||
platform: process.platform,
|
||||
readFile: (path, encoding) => readFile(path, encoding),
|
||||
readdir: (path) => readdir(path),
|
||||
readlink: (path) => readlink(path),
|
||||
runLsof: async () => {
|
||||
const result = await executeCommand(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'], {
|
||||
ignoreExitCode: true,
|
||||
})
|
||||
return typeof result === 'string' ? result : (result as { stdout: string }).stdout
|
||||
},
|
||||
}
|
||||
@@ -13,10 +13,12 @@ import {
|
||||
type ProjectConfigResponse,
|
||||
type RepoProjectFile,
|
||||
type RunProjectActionResponse,
|
||||
type WorktreeSetupResult,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import type { GitService } from './git/GitService'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
@@ -126,9 +128,7 @@ export class ProjectConfigService {
|
||||
worktreeSetup.push({ command, source: 'repo' })
|
||||
}
|
||||
|
||||
const trusted =
|
||||
repoFile.hash !== null &&
|
||||
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
|
||||
const trusted = this.isRepoFileTrusted(projectRepo, repoFile)
|
||||
|
||||
const resolvedActions = await Promise.all(
|
||||
actions.map(async (action) =>
|
||||
@@ -233,6 +233,45 @@ export class ProjectConfigService {
|
||||
return result
|
||||
}
|
||||
|
||||
async runWorktreeSetup(
|
||||
projectRepo: Repo,
|
||||
worktreeDirectory: string,
|
||||
terminalService: TerminalService,
|
||||
): Promise<WorktreeSetupResult> {
|
||||
const commands = [...this.getPersonalSetup(projectRepo)]
|
||||
const repoFile = this.readRepoFile(worktreeDirectory)
|
||||
const repoCommands = repoFile.file?.setupWorktree ?? []
|
||||
const repoCommandsSkipped = repoCommands.length > 0 && !this.isRepoFileTrusted(projectRepo, repoFile)
|
||||
if (!repoCommandsSkipped) {
|
||||
commands.push(...repoCommands)
|
||||
}
|
||||
|
||||
if (commands.length === 0) {
|
||||
return repoCommandsSkipped ? { status: 'skipped', reason: 'untrusted' } : { status: 'none' }
|
||||
}
|
||||
|
||||
try {
|
||||
const terminal = await terminalService.create(worktreeDirectory, {
|
||||
kind: 'setup',
|
||||
name: 'Worktree setup',
|
||||
command: '/bin/sh',
|
||||
args: ['-c', ['set -e', ...commands].join('\n')],
|
||||
env: { ROOT_PROJECT_PATH: projectRepo.fullPath },
|
||||
})
|
||||
return { status: 'started', terminal, repoCommandsSkipped }
|
||||
} catch (error: unknown) {
|
||||
logger.warn(`Failed to start worktree setup for ${worktreeDirectory}:`, error)
|
||||
return { status: 'failed', error: getErrorMessage(error) }
|
||||
}
|
||||
}
|
||||
|
||||
private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
|
||||
return (
|
||||
repoFile.hash !== null &&
|
||||
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
|
||||
)
|
||||
}
|
||||
|
||||
readRepoFile(directory: string): RepoFileState {
|
||||
const filePath = this.getRepoFilePath(directory)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export 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 filterProxyHeaders(
|
||||
headers: Headers,
|
||||
extraExcluded: ReadonlySet<string> = new Set(),
|
||||
): Record<string, string> {
|
||||
const result: Record<string, string> = {}
|
||||
headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (HOP_BY_HOP_HEADERS.has(lowerKey) || extraExcluded.has(lowerKey)) return
|
||||
result[key] = value
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
export function buildProxyResponseHeaders(
|
||||
source: Headers,
|
||||
extraExcluded: ReadonlySet<string> = new Set(),
|
||||
): Headers {
|
||||
const excluded = new Set(extraExcluded)
|
||||
excluded.add('set-cookie')
|
||||
const headers = new Headers(filterProxyHeaders(source, excluded))
|
||||
for (const cookie of source.getSetCookie()) {
|
||||
headers.append('set-cookie', cookie)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
Reference in new issue
Block a user