section 16: Phase 16: Documentation, container ports and full repository checks

This commit is contained in:
Chris Scott committed 2026-10-03 04:07:44 -04:00
1 parent 81a9f0c8ef
commit a383e57bc5
55 files changed
+4095 -59

No files matched your search

+295
View File
@@ -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 }
}
+320
View File
@@ -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
},
}
+42 -3
View File
@@ -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)) {