mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
fix(terminal-dev-loop): address branch review findings
Security: - Reject same-site and cross-site state-changing requests on cookie-authenticated routes unless the origin is trusted - Drop Manager and ocm_preview Set-Cookie headers from preview responses - Show and hash the full executable content of .ocm/project.json at trust time - Restrict action URLs to http(s) and refuse symlinked repo config paths - Keep the preview start redirect on the gateway origin Lifecycle: - Stop terminals in OpenCode workspace siblings when a repo is deleted - Report preview as unavailable instead of crashing when the gateway port cannot be bound Performance: - Skip branch lookups when validating terminal and project-config directories - Stop the /proc scan once all listening sockets are mapped and pause port polling while a preview is open - Close slow WebSocket clients with 1013 so they reconnect with replay - Lazy-load the xterm terminal view and skip unchanged resize requests - Request uncompressed responses from preview targets Cleanup: - Share one repo directory resolver, trusted-origins parser, cookie prefix, WebSocket frame forwarder, header filter, icon map and dialog-param helper - Remove unused props, options and exports Docs: update terminal, preview, project actions, sandboxing, internal API and environment pages
This commit is contained in:
1 parent
16b91ccf02
commit
c60a9b35f2
72 files changed
+2039
-596
No files matched your search
@@ -0,0 +1 @@
|
||||
export const AUTH_COOKIE_PREFIX = 'opencode'
|
||||
@@ -2,7 +2,8 @@ import { betterAuth } from 'better-auth'
|
||||
import { APIError } from 'better-auth/api'
|
||||
import { passkey } from '@better-auth/passkey'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import { AUTH_COOKIE_PREFIX } from './cookies'
|
||||
|
||||
export type AuthInstance = ReturnType<typeof createAuth>
|
||||
|
||||
@@ -34,14 +35,15 @@ export function createAuth(db: Database) {
|
||||
}
|
||||
}
|
||||
|
||||
const baseURL = ENV.AUTH.TRUSTED_ORIGINS.split(',')[0]?.trim() || `http://localhost:${ENV.SERVER.PORT}`
|
||||
const trustedOrigins = getTrustedOrigins()
|
||||
const baseURL = trustedOrigins[0] || `http://localhost:${ENV.SERVER.PORT}`
|
||||
|
||||
const auth = betterAuth({
|
||||
baseURL,
|
||||
basePath: '/api/auth',
|
||||
database: db,
|
||||
secret: ENV.AUTH.SECRET,
|
||||
trustedOrigins: ENV.AUTH.TRUSTED_ORIGINS.split(',').map((o: string) => o.trim()),
|
||||
trustedOrigins,
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
@@ -90,7 +92,7 @@ export function createAuth(db: Database) {
|
||||
},
|
||||
},
|
||||
advanced: {
|
||||
cookiePrefix: 'opencode',
|
||||
cookiePrefix: AUTH_COOKIE_PREFIX,
|
||||
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import type { AuthInstance, Session } from './index'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export function createAuthMiddleware(auth: AuthInstance) {
|
||||
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
||||
const UNTRUSTED_FETCH_SITES = new Set(['same-site', 'cross-site'])
|
||||
|
||||
export function createAuthMiddleware(
|
||||
auth: AuthInstance,
|
||||
resolveTrustedOrigins: () => string[] = getTrustedOrigins,
|
||||
) {
|
||||
return createMiddleware<{
|
||||
Variables: {
|
||||
session: Session['session']
|
||||
@@ -11,6 +18,17 @@ export function createAuthMiddleware(auth: AuthInstance) {
|
||||
}>(async (c, next) => {
|
||||
const cookies = c.req.header('cookie')
|
||||
const origin = c.req.header('origin')
|
||||
|
||||
const fetchSite = c.req.header('sec-fetch-site')
|
||||
if (
|
||||
UNSAFE_METHODS.has(c.req.method) &&
|
||||
fetchSite !== undefined &&
|
||||
UNTRUSTED_FETCH_SITES.has(fetchSite) &&
|
||||
(!origin || !resolveTrustedOrigins().includes(origin))
|
||||
) {
|
||||
logger.warn(`Rejected cross-site request - Path: ${c.req.path}, Method: ${c.req.method}, Origin: ${origin ?? 'none'}`)
|
||||
return c.json({ error: 'Cross-site request rejected' }, 403)
|
||||
}
|
||||
|
||||
logger.debug(`Auth check - Path: ${c.req.path}, Origin: ${origin}, Has cookies: ${!!cookies}`)
|
||||
if (cookies) {
|
||||
|
||||
+14
-4
@@ -39,7 +39,7 @@ 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 { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
getConfigPath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
getTrustedOrigins,
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
|
||||
@@ -93,7 +94,7 @@ app.use('/*', cors({
|
||||
if (origin && REFLECT_ANY_ORIGIN_PREFIXES.some(prefix => c.req.path.startsWith(prefix))) {
|
||||
return origin
|
||||
}
|
||||
const trustedOrigins = ENV.AUTH.TRUSTED_ORIGINS.split(',').map(o => o.trim())
|
||||
const trustedOrigins = getTrustedOrigins()
|
||||
if (!origin) return trustedOrigins[0]
|
||||
if (trustedOrigins.includes(origin)) return origin
|
||||
return trustedOrigins[0]
|
||||
@@ -271,6 +272,7 @@ void scheduleRunnerInstance.start()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const previewSessionStore = new PreviewSessionStore()
|
||||
const previewAvailability = createPreviewAvailability(false)
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
@@ -299,7 +301,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 }))
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled }))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
@@ -426,8 +428,16 @@ if (ENV.PREVIEW.PORT > 0) {
|
||||
port: ENV.PREVIEW.PORT,
|
||||
hostname: HOST,
|
||||
})
|
||||
previewServer.on('listening', () => {
|
||||
previewAvailability.markAvailable()
|
||||
logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
|
||||
})
|
||||
previewServer.on('error', (error: Error) => {
|
||||
previewAvailability.markUnavailable()
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
logger.warn(`Preview gateway failed to listen on port ${ENV.PREVIEW.PORT}${code ? ` (${code})` : ''}; preview disabled`)
|
||||
})
|
||||
previewGateway.injectWebSocket(previewServer)
|
||||
logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
|
||||
}
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -6,15 +6,34 @@ import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { listListeningPorts, isReservedPreviewPort, type PreviewPortEntry } from '../services/preview/ports'
|
||||
import { PreviewSessionStore } from '../services/preview/gateway'
|
||||
|
||||
export interface PreviewAvailability {
|
||||
isEnabled: () => boolean
|
||||
markAvailable: () => void
|
||||
markUnavailable: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks whether the preview gateway is usable at request time. It starts in
|
||||
* the given state and is flipped by the server lifecycle: available once the
|
||||
* port is bound, unavailable after a bind error.
|
||||
*/
|
||||
export function createPreviewAvailability(initialEnabled: boolean): PreviewAvailability {
|
||||
let enabled = initialEnabled
|
||||
return {
|
||||
isEnabled: () => enabled,
|
||||
markAvailable: () => { enabled = true },
|
||||
markUnavailable: () => { enabled = false },
|
||||
}
|
||||
}
|
||||
|
||||
export interface PreviewRoutesDeps {
|
||||
enabled: boolean
|
||||
isEnabled: () => boolean
|
||||
listPorts: () => Promise<PreviewPortEntry[]>
|
||||
store: PreviewSessionStore
|
||||
}
|
||||
|
||||
function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null): boolean {
|
||||
if (!cwd || !canonicalDirectory) return false
|
||||
const canonicalCwd = canonicalPathSync(cwd)
|
||||
function isInsideDirectory(canonicalCwd: string | null, canonicalDirectory: string | null): boolean {
|
||||
if (!canonicalCwd || !canonicalDirectory) return false
|
||||
if (canonicalCwd === canonicalDirectory) return true
|
||||
const prefix = canonicalDirectory.endsWith(path.sep) ? canonicalDirectory : `${canonicalDirectory}${path.sep}`
|
||||
return canonicalCwd.startsWith(prefix)
|
||||
@@ -22,7 +41,7 @@ function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null
|
||||
|
||||
export function createPreviewRoutes(deps: Partial<PreviewRoutesDeps> = {}) {
|
||||
const resolvedDeps: PreviewRoutesDeps = {
|
||||
enabled: deps.enabled ?? ENV.PREVIEW.PORT > 0,
|
||||
isEnabled: deps.isEnabled ?? (() => ENV.PREVIEW.PORT > 0),
|
||||
listPorts: deps.listPorts ?? (() => listListeningPorts()),
|
||||
store: deps.store ?? new PreviewSessionStore(),
|
||||
}
|
||||
@@ -32,13 +51,15 @@ export function createPreviewRoutes(deps: Partial<PreviewRoutesDeps> = {}) {
|
||||
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
|
||||
const decorated = ports.map((entry) => ({
|
||||
...entry,
|
||||
inDirectory: isInsideDirectory(entry.cwd ? canonicalPathSync(entry.cwd) : null, canonicalDirectory),
|
||||
}))
|
||||
decorated.sort((left, right) => {
|
||||
if (left.inDirectory !== right.inDirectory) return left.inDirectory ? -1 : 1
|
||||
return left.port - right.port
|
||||
})
|
||||
return c.json({ enabled: resolvedDeps.enabled, ports: sorted })
|
||||
return c.json({ enabled: resolvedDeps.isEnabled(), ports: decorated })
|
||||
})
|
||||
|
||||
app.post('/sessions', async (c) => {
|
||||
@@ -48,7 +69,7 @@ export function createPreviewRoutes(deps: Partial<PreviewRoutesDeps> = {}) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
if (!resolvedDeps.enabled) {
|
||||
if (!resolvedDeps.isEnabled()) {
|
||||
return c.json({ error: 'Preview is disabled' }, 503)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Context } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { getSiblingRepos, resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
|
||||
export interface RepoDirectoryDeps {
|
||||
database: Database
|
||||
gitAuthService: GitAuthService
|
||||
openCodeClient: OpenCodeClient
|
||||
}
|
||||
|
||||
export interface RepoDirectoryOptions {
|
||||
allowAssistant: boolean
|
||||
}
|
||||
|
||||
export async function resolveRepoRequestDirectory(
|
||||
c: Context,
|
||||
deps: RepoDirectoryDeps,
|
||||
repoIdParam: string,
|
||||
directory: string | undefined,
|
||||
options: RepoDirectoryOptions,
|
||||
): Promise<{ repo: Repo; directory: string } | Response> {
|
||||
const id = Number.parseInt(repoIdParam, 10)
|
||||
if (Number.isNaN(id)) {
|
||||
return c.json({ error: 'Invalid repo id' }, 400)
|
||||
}
|
||||
|
||||
const repo = options.allowAssistant
|
||||
? resolveRepoOrAssistant(deps.database, id)
|
||||
: getRepoById(deps.database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
getSiblingRepos(
|
||||
deps.database,
|
||||
repo.id,
|
||||
deps.gitAuthService.getGitEnvironment(),
|
||||
deps.openCodeClient,
|
||||
{ includeBranch: false },
|
||||
),
|
||||
)
|
||||
|
||||
if (!resolved) {
|
||||
return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
}
|
||||
|
||||
return { repo, directory: resolved }
|
||||
}
|
||||
@@ -1,18 +1,12 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema, RunProjectActionRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import * as repoService from '../services/repo'
|
||||
import { resolveRepoWorkingDirectory } from '../services/repo'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import { ProjectConfigError, type ProjectConfigService } from '../services/project-config'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { handleServiceError } from '../utils/route-helpers'
|
||||
import { resolveRepoRequestDirectory } from './repo-directory'
|
||||
|
||||
export interface RepoProjectConfigDeps {
|
||||
database: Database
|
||||
@@ -22,17 +16,6 @@ export interface RepoProjectConfigDeps {
|
||||
terminalService: TerminalService
|
||||
}
|
||||
|
||||
function handleProjectConfigError(c: Context, error: unknown): Response {
|
||||
if (error instanceof ProjectConfigError) {
|
||||
return c.json(
|
||||
{ error: error.message, code: error.code, details: error.details },
|
||||
error.status as ContentfulStatusCode,
|
||||
)
|
||||
}
|
||||
logger.error('Project config request failed:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
|
||||
export function createRepoProjectConfigRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -49,45 +32,16 @@ export function createRepoProjectConfigRoutes(
|
||||
}
|
||||
const app = new Hono()
|
||||
|
||||
async function resolveRepoDirectory(
|
||||
c: Context,
|
||||
repoIdParam: string,
|
||||
directory: string | undefined,
|
||||
): Promise<{ repo: Repo; directory: string } | Response> {
|
||||
const id = Number.parseInt(repoIdParam, 10)
|
||||
if (Number.isNaN(id)) {
|
||||
return c.json({ error: 'Invalid repo id' }, 400)
|
||||
}
|
||||
|
||||
const repo = getRepoById(deps.database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
repoService.getSiblingRepos(
|
||||
deps.database,
|
||||
repo.id,
|
||||
deps.gitAuthService.getGitEnvironment(),
|
||||
deps.openCodeClient,
|
||||
),
|
||||
)
|
||||
|
||||
if (!resolved) {
|
||||
return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
}
|
||||
|
||||
return { repo, directory: resolved }
|
||||
}
|
||||
|
||||
app.get('/:id/project-config', async (c) => {
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -98,7 +52,9 @@ export function createRepoProjectConfigRoutes(
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
@@ -106,7 +62,7 @@ export function createRepoProjectConfigRoutes(
|
||||
deps.projectConfigService.setPersonalActions(projectRepo, parsed.data.actions)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -117,7 +73,9 @@ export function createRepoProjectConfigRoutes(
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
@@ -125,7 +83,7 @@ export function createRepoProjectConfigRoutes(
|
||||
deps.projectConfigService.setPersonalSetup(projectRepo, parsed.data.commands)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -136,14 +94,16 @@ export function createRepoProjectConfigRoutes(
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
await deps.projectConfigService.trustRepoFile(resolved.repo, resolved.directory, parsed.data.hash)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -154,14 +114,16 @@ export function createRepoProjectConfigRoutes(
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
await deps.projectConfigService.moveItem(resolved.repo, resolved.directory, parsed.data)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -172,7 +134,9 @@ export function createRepoProjectConfigRoutes(
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
|
||||
allowAssistant: false,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
@@ -184,7 +148,7 @@ export function createRepoProjectConfigRoutes(
|
||||
)
|
||||
return c.json(response)
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -2,25 +2,21 @@ import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { UpgradeWebSocket } from 'hono/ws'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import type { WebSocketBridge } from '../utils/websocket-bridge'
|
||||
import { forwardPeerMessage, peerBufferedAmount, type WebSocketBridge } from '../utils/websocket-bridge'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { resolveTerminalDirectory } from './repo-terminals'
|
||||
import { resolveRepoRequestDirectory } from './repo-directory'
|
||||
|
||||
export interface RepoTerminalSocketVariables {
|
||||
interface RepoTerminalSocketVariables {
|
||||
terminalDirectory: string
|
||||
terminalCursor: number | undefined
|
||||
}
|
||||
|
||||
const MAX_CLOSE_REASON_BYTES = 120
|
||||
|
||||
const DEFAULT_TRUSTED_ORIGINS = ENV.AUTH.TRUSTED_ORIGINS.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
function isAllowedUpgradeOrigin(
|
||||
origin: string | undefined,
|
||||
trustedOrigins: readonly string[],
|
||||
@@ -50,7 +46,7 @@ export function createRepoTerminalSocketRoutes(
|
||||
openCodeClient: OpenCodeClient,
|
||||
terminalService: TerminalService,
|
||||
upgradeWebSocket: UpgradeWebSocket,
|
||||
trustedOrigins: readonly string[] = DEFAULT_TRUSTED_ORIGINS,
|
||||
trustedOrigins: readonly string[] = getTrustedOrigins(),
|
||||
) {
|
||||
const app = new Hono<{ Variables: RepoTerminalSocketVariables }>()
|
||||
const deps = { database, gitAuthService, openCodeClient }
|
||||
@@ -65,7 +61,9 @@ export function createRepoTerminalSocketRoutes(
|
||||
return c.json({ error: 'Invalid cursor' }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory'), {
|
||||
allowAssistant: true,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
c.set('terminalDirectory', resolved.directory)
|
||||
@@ -91,6 +89,7 @@ export function createRepoTerminalSocketRoutes(
|
||||
.connect(directory, ptyID, cursor, {
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => ws.close(code, reason),
|
||||
bufferedAmount: () => peerBufferedAmount(ws),
|
||||
})
|
||||
.then((connected) => {
|
||||
if (closed) {
|
||||
@@ -107,19 +106,7 @@ export function createRepoTerminalSocketRoutes(
|
||||
async onMessage(event) {
|
||||
await connectPromise
|
||||
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)
|
||||
}
|
||||
await forwardPeerMessage(bridge, event.data)
|
||||
},
|
||||
onClose() {
|
||||
closed = true
|
||||
|
||||
@@ -1,57 +1,16 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { CreateTerminalRequestSchema, ResizeTerminalRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import * as repoService from '../services/repo'
|
||||
import { resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { TerminalService, TerminalNotFoundError } from '../services/terminal'
|
||||
import { handleOpenCodeError } from '../utils/route-helpers'
|
||||
import { resolveRepoRequestDirectory, type RepoDirectoryDeps } from './repo-directory'
|
||||
|
||||
export interface TerminalDirectoryDeps {
|
||||
database: Database
|
||||
gitAuthService: GitAuthService
|
||||
openCodeClient: OpenCodeClient
|
||||
}
|
||||
|
||||
export interface TerminalRoutesDeps extends TerminalDirectoryDeps {
|
||||
export interface TerminalRoutesDeps extends RepoDirectoryDeps {
|
||||
terminalService: TerminalService
|
||||
}
|
||||
|
||||
export async function resolveTerminalDirectory(
|
||||
c: Context,
|
||||
deps: TerminalDirectoryDeps,
|
||||
repoIdParam: string,
|
||||
directory: string | undefined,
|
||||
): Promise<{ repo: Repo; directory: string } | Response> {
|
||||
const id = Number.parseInt(repoIdParam, 10)
|
||||
if (Number.isNaN(id)) {
|
||||
return c.json({ error: 'Invalid repo id' }, 400)
|
||||
}
|
||||
|
||||
const repo = resolveRepoOrAssistant(deps.database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
repoService.getSiblingRepos(
|
||||
deps.database,
|
||||
repo.id,
|
||||
deps.gitAuthService.getGitEnvironment(),
|
||||
deps.openCodeClient,
|
||||
),
|
||||
)
|
||||
|
||||
if (!resolved) {
|
||||
return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
}
|
||||
|
||||
return { repo, directory: resolved }
|
||||
}
|
||||
|
||||
export function createRepoTerminalRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -62,7 +21,9 @@ export function createRepoTerminalRoutes(
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:id/terminals', async (c) => {
|
||||
const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
|
||||
allowAssistant: true,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
@@ -80,7 +41,9 @@ export function createRepoTerminalRoutes(
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory)
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
|
||||
allowAssistant: true,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
@@ -101,7 +64,9 @@ export function createRepoTerminalRoutes(
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory)
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
|
||||
allowAssistant: true,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
@@ -119,7 +84,9 @@ export function createRepoTerminalRoutes(
|
||||
})
|
||||
|
||||
app.delete('/:id/terminals/:ptyID', async (c) => {
|
||||
const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory'))
|
||||
const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
|
||||
allowAssistant: true,
|
||||
})
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
@@ -45,6 +45,39 @@ async function removeDirectoryTerminals(terminalService: TerminalService, direct
|
||||
}
|
||||
}
|
||||
|
||||
async function listWorkspaceSiblings(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitAuthService: GitAuthService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
): Promise<Array<Repo & { worktreeStrategy?: string }>> {
|
||||
const siblings = await repoService.getSiblingRepos(
|
||||
database,
|
||||
repoId,
|
||||
gitAuthService.getGitEnvironment(),
|
||||
openCodeClient,
|
||||
{ includeBranch: false },
|
||||
)
|
||||
return siblings.filter(isWorktreeSibling)
|
||||
}
|
||||
|
||||
async function removeWorkspaceSiblingTerminals(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitAuthService: GitAuthService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
terminalService: TerminalService,
|
||||
): Promise<void> {
|
||||
let siblings: Array<Repo & { worktreeStrategy?: string }>
|
||||
try {
|
||||
siblings = await listWorkspaceSiblings(database, repoId, gitAuthService, openCodeClient)
|
||||
} catch (error: unknown) {
|
||||
logger.warn(`Failed to list OpenCode workspace siblings for repo ${repoId}:`, error)
|
||||
return
|
||||
}
|
||||
await Promise.all(siblings.map((sibling) => removeDirectoryTerminals(terminalService, sibling.fullPath)))
|
||||
}
|
||||
|
||||
export function createRepoRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -293,8 +326,8 @@ app.get('/', async (c) => {
|
||||
if (!parsed.success) return c.json({ error: 'directory is required' }, 400)
|
||||
const directory = parsed.data.directory
|
||||
|
||||
const siblings = await repoService.getSiblingRepos(database, id, gitAuthService.getGitEnvironment(), openCodeClient)
|
||||
const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory)
|
||||
const siblings = await listWorkspaceSiblings(database, id, gitAuthService, openCodeClient)
|
||||
const worktree = repoService.findSiblingByDirectory(siblings, directory)
|
||||
if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400)
|
||||
|
||||
await removeDirectoryTerminals(terminalService, worktree.fullPath)
|
||||
@@ -362,6 +395,8 @@ app.get('/', async (c) => {
|
||||
|
||||
await removeDirectoryTerminals(terminalService, repo.fullPath)
|
||||
|
||||
await removeWorkspaceSiblingTerminals(database, id, gitAuthService, openCodeClient, terminalService)
|
||||
|
||||
await repoService.deleteRepoFiles(database, id)
|
||||
|
||||
return c.json({ success: true })
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { filterProxyHeaders } from '../../utils/proxy-headers'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
|
||||
|
||||
@@ -73,13 +74,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
body: req.body,
|
||||
})
|
||||
|
||||
const filteredHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
filteredHeaders[key] = value
|
||||
}
|
||||
})
|
||||
const filteredHeaders = filterProxyHeaders(response.headers)
|
||||
|
||||
const noBodyStatuses = new Set([101, 204, 205, 304])
|
||||
if (noBodyStatuses.has(response.status)) {
|
||||
|
||||
@@ -2,17 +2,28 @@ import { randomBytes } from 'node:crypto'
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
|
||||
import type { PreviewPort } from '@opencode-manager/shared/schemas'
|
||||
import { AUTH_COOKIE_PREFIX } from '../../auth/cookies'
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers'
|
||||
import { bridgeWebSocket, type WebSocketBridge } from '../../utils/websocket-bridge'
|
||||
import {
|
||||
bridgeWebSocket,
|
||||
forwardPeerMessage,
|
||||
peerBufferedAmount,
|
||||
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.']
|
||||
const MANAGER_COOKIE_PREFIXES = [
|
||||
`${AUTH_COOKIE_PREFIX}.`,
|
||||
`__Secure-${AUTH_COOKIE_PREFIX}.`,
|
||||
`__Host-${AUTH_COOKIE_PREFIX}.`,
|
||||
]
|
||||
|
||||
export type PreviewHost = '127.0.0.1' | '::1'
|
||||
export type PreviewHost = PreviewPort['host']
|
||||
|
||||
export interface PreviewSession {
|
||||
id: string
|
||||
@@ -76,21 +87,32 @@ export class PreviewSessionStore {
|
||||
}
|
||||
}
|
||||
|
||||
export function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
|
||||
function readCookieName(cookie: string): string {
|
||||
const separator = cookie.indexOf('=')
|
||||
return (separator === -1 ? cookie : cookie.slice(0, separator)).trim()
|
||||
}
|
||||
|
||||
function isManagerCookieName(name: string): boolean {
|
||||
return name === PREVIEW_COOKIE || MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
|
||||
}
|
||||
|
||||
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))
|
||||
})
|
||||
.filter((part) => part.length > 0 && !isManagerCookieName(readCookieName(part)))
|
||||
return kept.length > 0 ? kept.join('; ') : undefined
|
||||
}
|
||||
|
||||
function stripPreviewSetCookies(headers: Headers): void {
|
||||
const kept = headers.getSetCookie().filter((cookie) => !isManagerCookieName(readCookieName(cookie)))
|
||||
headers.delete('set-cookie')
|
||||
for (const cookie of kept) {
|
||||
headers.append('set-cookie', cookie)
|
||||
}
|
||||
}
|
||||
|
||||
function readPreviewCookie(cookieHeader: string | undefined): string | null {
|
||||
if (!cookieHeader) return null
|
||||
for (const part of cookieHeader.split(';')) {
|
||||
@@ -140,8 +162,24 @@ function isWebSocketUpgrade(c: Context): boolean {
|
||||
}
|
||||
|
||||
function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string {
|
||||
return `${previewUpstreamOrigin(session, 'ws')}${requestUrl.pathname}${requestUrl.search}`
|
||||
}
|
||||
|
||||
function previewUpstreamOrigin(session: PreviewSession, protocol: 'http' | 'ws'): string {
|
||||
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
|
||||
return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}`
|
||||
return `${protocol}://${targetHost}:${session.port}`
|
||||
}
|
||||
|
||||
function resolveRedirectPath(requestUrl: URL, requestedPath: string): string {
|
||||
if (!requestedPath) return '/'
|
||||
let resolved: URL
|
||||
try {
|
||||
resolved = new URL(requestedPath, requestUrl)
|
||||
} catch {
|
||||
return '/'
|
||||
}
|
||||
if (resolved.origin !== requestUrl.origin) return '/'
|
||||
return `${resolved.pathname}${resolved.search}${resolved.hash}`
|
||||
}
|
||||
|
||||
function parseProtocols(header: string | undefined): string[] {
|
||||
@@ -163,10 +201,11 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
|
||||
}
|
||||
|
||||
const requestedPath = c.req.query('path') ?? ''
|
||||
const location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/'
|
||||
const requestUrl = new URL(c.req.url)
|
||||
const location = resolveRedirectPath(requestUrl, requestedPath)
|
||||
|
||||
const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase()
|
||||
const isSecure = forwardedProto === 'https' || new URL(c.req.url).protocol === 'https:'
|
||||
const isSecure = forwardedProto === 'https' || requestUrl.protocol === 'https:'
|
||||
const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}`
|
||||
|
||||
return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } })
|
||||
@@ -212,22 +251,12 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
|
||||
bridge = bridgeWebSocket(upstream, {
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => ws.close(code, reason),
|
||||
bufferedAmount: () => peerBufferedAmount(ws),
|
||||
})
|
||||
},
|
||||
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)
|
||||
}
|
||||
await forwardPeerMessage(bridge, event.data)
|
||||
},
|
||||
onClose() {
|
||||
bridge?.close()
|
||||
@@ -245,8 +274,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
|
||||
}
|
||||
|
||||
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 target = `${previewUpstreamOrigin(session, 'http')}${url.pathname}${url.search}`
|
||||
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
@@ -256,6 +284,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
|
||||
headers['content-encoding'] = contentEncoding
|
||||
}
|
||||
headers['host'] = `localhost:${session.port}`
|
||||
headers['accept-encoding'] = 'identity'
|
||||
const strippedCookies = stripManagerCookies(cookieHeader)
|
||||
if (strippedCookies) {
|
||||
headers['cookie'] = strippedCookies
|
||||
@@ -275,6 +304,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
|
||||
})
|
||||
|
||||
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
|
||||
stripPreviewSetCookies(responseHeaders)
|
||||
const location = responseHeaders.get('location')
|
||||
if (location) {
|
||||
const rewritten = rewriteLocalLocation(location, session.port)
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import { readFile, readdir, readlink } from 'node:fs/promises'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { PreviewPort } from '@opencode-manager/shared/schemas'
|
||||
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 type PreviewPortEntry = Omit<PreviewPort, 'inDirectory'>
|
||||
|
||||
export interface ParsedProcNetSocket {
|
||||
port: number
|
||||
@@ -192,8 +187,9 @@ function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
|
||||
return result
|
||||
}
|
||||
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, number>> {
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps, wantedInodes: ReadonlySet<string>): Promise<Map<string, number>> {
|
||||
const map = new Map<string, number>()
|
||||
if (wantedInodes.size === 0) return map
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await deps.readdir('/proc')
|
||||
@@ -201,6 +197,7 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
|
||||
return map
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (map.size >= wantedInodes.size) break
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const fdDir = `/proc/${entry}/fd`
|
||||
let fds: string[]
|
||||
@@ -217,7 +214,8 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
|
||||
continue
|
||||
}
|
||||
const match = /^socket:\[(\d+)\]$/.exec(target)
|
||||
if (match?.[1]) map.set(match[1], Number.parseInt(entry, 10))
|
||||
const inode = match?.[1]
|
||||
if (inode && wantedInodes.has(inode)) map.set(inode, Number.parseInt(entry, 10))
|
||||
}
|
||||
}
|
||||
return map
|
||||
@@ -252,7 +250,11 @@ async function listLinuxPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry
|
||||
}
|
||||
if (sockets.length === 0) return []
|
||||
|
||||
const inodeToPid = await mapInodesToPids(deps)
|
||||
const wantedInodes = new Set<string>()
|
||||
for (const socket of sockets) {
|
||||
if (socket.inode) wantedInodes.add(socket.inode)
|
||||
}
|
||||
const inodeToPid = await mapInodesToPids(deps, wantedInodes)
|
||||
const processMeta = new Map<number, { command: string | null; cwd: string | null }>()
|
||||
const entries: PreviewPortEntry[] = []
|
||||
for (const socket of sockets) {
|
||||
|
||||
@@ -15,11 +15,12 @@ import {
|
||||
type RunProjectActionResponse,
|
||||
type WorktreeSetupResult,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { isRunningActionTerminal } from '@opencode-manager/shared/utils'
|
||||
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 { canonicalPathSync, writeFileAtomicSync } from '../utils/fs-safe'
|
||||
import type { GitService } from './git/GitService'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import type { TerminalService } from './terminal'
|
||||
@@ -28,6 +29,7 @@ const PROJECT_ACTIONS_KEY = 'projectActions'
|
||||
const WORKTREE_SETUP_KEY = 'worktreeSetupCommands'
|
||||
const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
|
||||
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
|
||||
const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link'
|
||||
|
||||
export interface RepoFileState {
|
||||
exists: boolean
|
||||
@@ -50,8 +52,8 @@ interface RepoFileSnapshot {
|
||||
|
||||
export class ProjectConfigError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
public status: number,
|
||||
public code?: string,
|
||||
public details?: unknown,
|
||||
) {
|
||||
@@ -85,7 +87,7 @@ export class ProjectConfigService {
|
||||
const ids = new Set<string>()
|
||||
for (const action of actions) {
|
||||
if (ids.has(action.id)) {
|
||||
throw new ProjectConfigError(400, 'Duplicate action id')
|
||||
throw new ProjectConfigError('Duplicate action id', 400)
|
||||
}
|
||||
ids.add(action.id)
|
||||
}
|
||||
@@ -144,6 +146,7 @@ export class ProjectConfigService {
|
||||
exists: repoFile.exists,
|
||||
trusted,
|
||||
hash: repoFile.hash,
|
||||
executable: repoFile.file ? this.buildRepoFileExecutable(repoFile.file) : null,
|
||||
...(repoFile.error ? { error: repoFile.error } : {}),
|
||||
warnings,
|
||||
},
|
||||
@@ -178,11 +181,11 @@ export class ProjectConfigService {
|
||||
const config = await this.getConfig(repo, directory)
|
||||
const action = config.actions.find((item) => item.id === actionId)
|
||||
if (!action) {
|
||||
throw new ProjectConfigError(404, 'Action not found')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
|
||||
if (action.source === 'repo' && !config.repoFile.trusted) {
|
||||
throw new ProjectConfigError(409, 'Repository commands are not trusted', 'REPO_CONFIG_UNTRUSTED', {
|
||||
throw new ProjectConfigError('Repository commands are not trusted', 409, 'REPO_CONFIG_UNTRUSTED', {
|
||||
hash: config.repoFile.hash,
|
||||
})
|
||||
}
|
||||
@@ -190,9 +193,7 @@ export class ProjectConfigService {
|
||||
const key = this.actionRunKey(directory, actionId)
|
||||
return this.enqueueActionRun(key, async () => {
|
||||
const terminals = await terminalService.list(directory)
|
||||
const running = terminals.find(
|
||||
(terminal) => terminal.kind === 'action' && terminal.actionId === actionId && terminal.status === 'running',
|
||||
)
|
||||
const running = terminals.find((terminal) => isRunningActionTerminal(terminal, actionId))
|
||||
const terminal =
|
||||
running ??
|
||||
(await terminalService.create(directory, {
|
||||
@@ -288,34 +289,53 @@ export class ProjectConfigService {
|
||||
|
||||
readRepoFile(directory: string): RepoFileState {
|
||||
const filePath = this.getRepoFilePath(directory)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { exists: false, file: null, hash: null }
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = RepoProjectFileSchema.safeParse(JSON.parse(fs.readFileSync(filePath, 'utf8')))
|
||||
if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
|
||||
return { exists: true, file: null, hash: null, error: REPO_CONFIG_SYMLINK_MESSAGE }
|
||||
}
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { exists: false, file: null, hash: null }
|
||||
}
|
||||
|
||||
let parsedJson: unknown
|
||||
try {
|
||||
parsedJson = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
} catch {
|
||||
return { exists: true, file: null, hash: null, error: 'Invalid JSON' }
|
||||
}
|
||||
|
||||
const parsed = RepoProjectFileSchema.safeParse(parsedJson)
|
||||
if (!parsed.success) {
|
||||
return { exists: true, file: null, hash: null, error: 'Invalid repository config' }
|
||||
return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' }
|
||||
}
|
||||
return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) }
|
||||
} catch (error: unknown) {
|
||||
return { exists: true, file: null, hash: null, error: getErrorMessage(error) }
|
||||
} catch {
|
||||
return { exists: fs.existsSync(filePath), file: null, hash: null, error: 'Invalid repository config' }
|
||||
}
|
||||
}
|
||||
|
||||
buildRepoFileExecutable(file: RepoProjectFile): NonNullable<ProjectConfigResponse['repoFile']['executable']> {
|
||||
return {
|
||||
actions: (file.projectActions ?? []).map((action) => ({
|
||||
id: action.id,
|
||||
name: action.name,
|
||||
command: action.command,
|
||||
url: action.url ?? null,
|
||||
autoOpenUrl: action.autoOpenUrl,
|
||||
})),
|
||||
setup: file.setupWorktree ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
hashRepoFile(file: RepoProjectFile): string {
|
||||
const executable = {
|
||||
actions: (file.projectActions ?? []).map(({ id, command, url }) => ({ id, command, url: url ?? null })),
|
||||
setup: file.setupWorktree ?? [],
|
||||
}
|
||||
return createHash('sha256').update(JSON.stringify(executable)).digest('hex')
|
||||
return createHash('sha256').update(JSON.stringify(this.buildRepoFileExecutable(file))).digest('hex')
|
||||
}
|
||||
|
||||
async trustRepoFile(repo: Repo, directory: string, hash: string): Promise<void> {
|
||||
const projectRepo = await this.resolveProjectRepo(repo)
|
||||
const repoFile = this.readRepoFile(directory)
|
||||
if (repoFile.hash === null || repoFile.hash !== hash) {
|
||||
throw new ProjectConfigError(409, 'Repository config changed', 'REPO_CONFIG_CHANGED')
|
||||
throw new ProjectConfigError('Repository config changed', 409, 'REPO_CONFIG_CHANGED')
|
||||
}
|
||||
this.setRepoTrust(projectRepo, repoFile.hash)
|
||||
}
|
||||
@@ -323,6 +343,7 @@ export class ProjectConfigService {
|
||||
async moveItem(repo: Repo, directory: string, request: MoveProjectItemRequest): Promise<void> {
|
||||
const projectRepo = await this.resolveProjectRepo(repo)
|
||||
const filePath = this.getRepoFilePath(directory)
|
||||
this.assertRepoFilePathNotSymlink(filePath)
|
||||
const state = this.readRepoFile(directory)
|
||||
const commit =
|
||||
request.to === 'repo'
|
||||
@@ -334,7 +355,7 @@ export class ProjectConfigService {
|
||||
|
||||
private planMoveToRepo(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
|
||||
if (state.exists && !state.file) {
|
||||
throw new ProjectConfigError(409, 'Repository config is invalid')
|
||||
throw new ProjectConfigError('Repository config is invalid', 409)
|
||||
}
|
||||
|
||||
const file: RepoProjectFile = state.file ? { ...state.file } : { version: 1 }
|
||||
@@ -343,11 +364,11 @@ export class ProjectConfigService {
|
||||
const personal = this.getPersonalActions(projectRepo)
|
||||
const action = personal.find((item) => item.id === request.id)
|
||||
if (!action) {
|
||||
throw new ProjectConfigError(404, 'Action not found')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
const repoActions = file.projectActions ?? []
|
||||
if (repoActions.some((existing) => existing.id === action.id)) {
|
||||
throw new ProjectConfigError(409, 'Action already exists in repository config')
|
||||
throw new ProjectConfigError('Action already exists in repository config', 409)
|
||||
}
|
||||
const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] }
|
||||
this.assertRepoFileValid(nextFile)
|
||||
@@ -361,7 +382,7 @@ export class ProjectConfigService {
|
||||
const personal = this.getPersonalSetup(projectRepo)
|
||||
const index = personal.indexOf(request.command)
|
||||
if (index === -1) {
|
||||
throw new ProjectConfigError(404, 'Setup command not found')
|
||||
throw new ProjectConfigError('Setup command not found', 404)
|
||||
}
|
||||
const nextFile: RepoProjectFile = {
|
||||
...file,
|
||||
@@ -380,14 +401,14 @@ export class ProjectConfigService {
|
||||
private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
|
||||
const file = state.file
|
||||
if (!file) {
|
||||
throw new ProjectConfigError(404, 'Item not found')
|
||||
throw new ProjectConfigError('Item not found', 404)
|
||||
}
|
||||
|
||||
if (request.kind === 'action') {
|
||||
const repoActions = file.projectActions ?? []
|
||||
const action = repoActions.find((item) => item.id === request.id)
|
||||
if (!action) {
|
||||
throw new ProjectConfigError(404, 'Action not found')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
const nextFile = this.pruneRepoFile({
|
||||
...file,
|
||||
@@ -406,7 +427,7 @@ export class ProjectConfigService {
|
||||
const repoSetup = file.setupWorktree ?? []
|
||||
const index = repoSetup.indexOf(request.command)
|
||||
if (index === -1) {
|
||||
throw new ProjectConfigError(404, 'Setup command not found')
|
||||
throw new ProjectConfigError('Setup command not found', 404)
|
||||
}
|
||||
const nextFile = this.pruneRepoFile({
|
||||
...file,
|
||||
@@ -494,8 +515,8 @@ export class ProjectConfigService {
|
||||
const result = RepoProjectFileSchema.safeParse(file)
|
||||
if (!result.success) {
|
||||
throw new ProjectConfigError(
|
||||
409,
|
||||
'Repository config limit exceeded',
|
||||
409,
|
||||
'PROJECT_CONFIG_LIMIT_EXCEEDED',
|
||||
result.error.flatten(),
|
||||
)
|
||||
@@ -506,8 +527,8 @@ export class ProjectConfigService {
|
||||
const result = WorktreeSetupCommandsSchema.safeParse(commands)
|
||||
if (!result.success) {
|
||||
throw new ProjectConfigError(
|
||||
409,
|
||||
'Personal setup command limit exceeded',
|
||||
409,
|
||||
'PROJECT_CONFIG_LIMIT_EXCEEDED',
|
||||
result.error.flatten(),
|
||||
)
|
||||
@@ -523,17 +544,26 @@ export class ProjectConfigService {
|
||||
}
|
||||
|
||||
private writeRepoFile(filePath: string, file: RepoProjectFile): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
const tmpPath = `${filePath}.tmp`
|
||||
writeFileAtomicSync(filePath, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o644 })
|
||||
}
|
||||
|
||||
private isSymbolicLink(target: string): boolean {
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, `${JSON.stringify(file, null, 2)}\n`)
|
||||
fs.renameSync(tmpPath, filePath)
|
||||
return fs.lstatSync(target).isSymbolicLink()
|
||||
} catch (error) {
|
||||
fs.rmSync(tmpPath, { force: true })
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private assertRepoFilePathNotSymlink(filePath: string): void {
|
||||
if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
|
||||
throw new ProjectConfigError(REPO_CONFIG_SYMLINK_MESSAGE, 400, 'REPO_CONFIG_SYMLINK')
|
||||
}
|
||||
}
|
||||
|
||||
private snapshotFile(filePath: string): RepoFileSnapshot {
|
||||
try {
|
||||
return { exists: true, content: fs.readFileSync(filePath) }
|
||||
|
||||
@@ -1194,6 +1194,7 @@ export async function getSiblingRepos(
|
||||
repoId: number,
|
||||
gitEnv: Record<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
options: { includeBranch?: boolean } = {},
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings()
|
||||
@@ -1217,10 +1218,11 @@ export async function getSiblingRepos(
|
||||
.filter((entry) => entry.projectId === targetProjectId)
|
||||
.map((entry) => entry.repo)
|
||||
|
||||
const includeBranch = options.includeBranch ?? true
|
||||
const repoSiblings = await Promise.all(
|
||||
matching.map(async (repo) => ({
|
||||
...repo,
|
||||
currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined,
|
||||
currentBranch: includeBranch ? (await getCurrentBranch(repo, gitEnv)) ?? undefined : undefined,
|
||||
})),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import path from 'path'
|
||||
import { promises as fs, mkdirSync, accessSync, constants, realpathSync } from 'node:fs'
|
||||
import { promises as fs, mkdirSync, accessSync, constants, realpathSync, writeFileSync, renameSync, rmSync } from 'node:fs'
|
||||
|
||||
interface MkdirSafeOptions {
|
||||
mode?: number
|
||||
@@ -39,6 +39,19 @@ export async function writeFileAtomic(filePath: string, content: string, options
|
||||
}
|
||||
}
|
||||
|
||||
export function writeFileAtomicSync(filePath: string, content: string, options: { mode?: number } = {}): void {
|
||||
const dir = path.dirname(filePath)
|
||||
mkdirSyncSafe(dir)
|
||||
const tempPath = path.join(dir, `.${path.basename(filePath)}.ocm-tmp-${process.pid}-${Date.now()}`)
|
||||
try {
|
||||
writeFileSync(tempPath, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 })
|
||||
renameSync(tempPath, filePath)
|
||||
} catch (error) {
|
||||
rmSync(tempPath, { force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const HOP_BY_HOP_HEADERS = new Set([
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
|
||||
@@ -25,6 +25,8 @@ interface ServiceError {
|
||||
message: string
|
||||
statusCode?: number
|
||||
status?: number
|
||||
code?: string
|
||||
details?: unknown
|
||||
}
|
||||
|
||||
type ServiceErrorConstructor = new (message: string, statusOrStatusCode: number) => ServiceError
|
||||
@@ -36,8 +38,16 @@ export function handleServiceError(
|
||||
ErrorClass: ServiceErrorConstructor,
|
||||
) {
|
||||
if (error instanceof ErrorClass) {
|
||||
const status = (error as ServiceError).statusCode ?? (error as ServiceError).status ?? 500
|
||||
return c.json({ error: error.message }, status as ContentfulStatusCode)
|
||||
const serviceError = error as ServiceError
|
||||
const status = serviceError.statusCode ?? serviceError.status ?? 500
|
||||
return c.json(
|
||||
{
|
||||
error: error.message,
|
||||
...(serviceError.code !== undefined ? { code: serviceError.code } : {}),
|
||||
...(serviceError.details !== undefined ? { details: serviceError.details } : {}),
|
||||
},
|
||||
status as ContentfulStatusCode,
|
||||
)
|
||||
}
|
||||
logger.error(fallback, error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface WebSocketPeer {
|
||||
send(data: string | Uint8Array<ArrayBuffer>): void
|
||||
close(code?: number, reason?: string): void
|
||||
bufferedAmount(): number
|
||||
}
|
||||
|
||||
export interface WebSocketBridge {
|
||||
@@ -8,8 +9,28 @@ export interface WebSocketBridge {
|
||||
close(): void
|
||||
}
|
||||
|
||||
export interface BridgeWebSocketOptions {
|
||||
mapCloseCode?: (code: number) => number
|
||||
export const MAX_PEER_BUFFERED_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export function peerBufferedAmount(peer: { raw?: unknown }): number {
|
||||
const raw = peer.raw as { bufferedAmount?: number } | undefined
|
||||
return typeof raw?.bufferedAmount === 'number' ? raw.bufferedAmount : 0
|
||||
}
|
||||
|
||||
export async function forwardPeerMessage(
|
||||
bridge: WebSocketBridge,
|
||||
data: string | Blob | ArrayBufferLike,
|
||||
): Promise<void> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMapCloseCode(code: number): number {
|
||||
@@ -22,13 +43,8 @@ function toBytes(data: ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {
|
||||
return data instanceof Uint8Array ? (data as Uint8Array<ArrayBuffer>) : new Uint8Array(data)
|
||||
}
|
||||
|
||||
export function bridgeWebSocket(
|
||||
upstream: WebSocket,
|
||||
peer: WebSocketPeer,
|
||||
options: BridgeWebSocketOptions = {},
|
||||
): WebSocketBridge {
|
||||
export function bridgeWebSocket(upstream: WebSocket, peer: WebSocketPeer): WebSocketBridge {
|
||||
upstream.binaryType = 'arraybuffer'
|
||||
const mapCloseCode = options.mapCloseCode ?? defaultMapCloseCode
|
||||
|
||||
const queue: Array<string | Uint8Array> = []
|
||||
let upstreamOpen = false
|
||||
@@ -46,18 +62,24 @@ export function bridgeWebSocket(
|
||||
})
|
||||
|
||||
upstream.addEventListener('message', (event) => {
|
||||
if (finished) return
|
||||
const data = (event as MessageEvent).data
|
||||
if (typeof data === 'string') {
|
||||
peer.send(data)
|
||||
} else if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
|
||||
peer.send(toBytes(data))
|
||||
}
|
||||
if (peer.bufferedAmount() > MAX_PEER_BUFFERED_BYTES) {
|
||||
finish()
|
||||
upstream.close()
|
||||
peer.close(1013, 'Client too slow')
|
||||
}
|
||||
})
|
||||
|
||||
upstream.addEventListener('close', (event) => {
|
||||
if (finished) return
|
||||
finish()
|
||||
peer.close(mapCloseCode((event as CloseEvent).code))
|
||||
peer.close(defaultMapCloseCode((event as CloseEvent).code))
|
||||
})
|
||||
|
||||
upstream.addEventListener('error', () => {
|
||||
|
||||
Reference in new issue
Block a user