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:
Chris Scott committed 2026-10-03 10:00:33 -04:00
1 parent 16b91ccf02
commit c60a9b35f2
72 files changed
+2039 -596

No files matched your search

+1
View File
@@ -0,0 +1 @@
export const AUTH_COOKIE_PREFIX = 'opencode'
+6 -4
View File
@@ -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,
},
})
+19 -1
View File
@@ -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
View File
@@ -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}`)
+32 -11
View File
@@ -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)
}
+53
View File
@@ -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 }
}
+26 -62
View File
@@ -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)
}
})
+10 -23
View File
@@ -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
+14 -47
View File
@@ -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')
+37 -2
View File
@@ -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 })
+2 -7
View File
@@ -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)) {
+58 -28
View File
@@ -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)
+12 -10
View File
@@ -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) {
+66 -36
View File
@@ -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) }
+3 -1
View File
@@ -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,
})),
)
+14 -1
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
export const HOP_BY_HOP_HEADERS = new Set([
const HOP_BY_HOP_HEADERS = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
+12 -2
View File
@@ -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)
+31 -9
View File
@@ -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', () => {
+7 -1
View File
@@ -31,7 +31,13 @@ const { ENV } = vi.hoisted(() => ({
},
}))
vi.mock('@opencode-manager/shared/config/env', () => ({ ENV }))
vi.mock('@opencode-manager/shared/config/env', () => ({
ENV,
getTrustedOrigins: () => ENV.AUTH.TRUSTED_ORIGINS
.split(',')
.map((origin: string) => origin.trim())
.filter((origin: string) => origin.length > 0),
}))
vi.mock('../../src/utils/logger', () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
@@ -0,0 +1,186 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import { createAuthMiddleware } from '../../src/auth/middleware'
import type { AuthInstance, Session } from '../../src/auth'
const loggerMock = vi.hoisted(() => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
}))
vi.mock('../../src/utils/logger', () => ({ logger: loggerMock }))
const TRUSTED_ORIGIN = 'http://trusted.test'
const UNTRUSTED_ORIGIN = 'http://untrusted.test'
function createSession(): Session {
return {
session: {
id: 'session-1',
userId: 'user-1',
token: 'token-1',
expiresAt: new Date(Date.now() + 1000),
createdAt: new Date(),
updatedAt: new Date(),
},
user: {
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
role: 'user',
},
}
}
function createApp(
getSession: (input: { headers: Headers }) => Promise<Session | null>,
trustedOrigins: string[] = [TRUSTED_ORIGIN],
) {
const app = new Hono<{ Variables: { session: Session['session']; user: Session['user'] } }>()
app.use('/*', createAuthMiddleware({ api: { getSession } } as unknown as AuthInstance, () => trustedOrigins))
app.get('/', (c) => c.json({ userId: c.get('user').id }))
app.post('/', (c) => c.json({ ok: true }))
app.put('/', (c) => c.json({ ok: true }))
app.patch('/', (c) => c.json({ ok: true }))
app.delete('/', (c) => c.json({ ok: true }))
return app
}
describe('createAuthMiddleware same-site guard', () => {
let getSession: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
getSession = vi.fn()
getSession.mockResolvedValue(createSession())
})
it('rejects an unsafe same-site request with an untrusted origin without looking up the session', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'POST',
headers: { 'sec-fetch-site': 'same-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(403)
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
expect(getSession).not.toHaveBeenCalled()
expect(loggerMock.warn).toHaveBeenCalledWith(expect.stringContaining('/'))
})
it('allows an unsafe same-site request from a trusted origin', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'POST',
headers: { 'sec-fetch-site': 'same-site', origin: TRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(200)
expect(getSession).toHaveBeenCalledTimes(1)
expect(loggerMock.warn).not.toHaveBeenCalled()
})
it('allows a same-origin request', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'POST',
headers: { 'sec-fetch-site': 'same-origin', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(200)
expect(getSession).toHaveBeenCalledTimes(1)
})
it('allows an unsafe request without a Sec-Fetch-Site header', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'POST',
headers: { origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(200)
expect(getSession).toHaveBeenCalledTimes(1)
})
it('allows a cross-site GET so WebSocket upgrades are unaffected', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'GET',
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(200)
expect(getSession).toHaveBeenCalledTimes(1)
})
it('rejects a cross-site unsafe request with no origin', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'DELETE',
headers: { 'sec-fetch-site': 'cross-site', cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(403)
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
expect(getSession).not.toHaveBeenCalled()
})
it('rejects a cross-site PUT with an untrusted origin', async () => {
const app = createApp(getSession)
const res = await app.request('/', {
method: 'PUT',
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
})
expect(res.status).toBe(403)
expect(getSession).not.toHaveBeenCalled()
})
})
describe('getTrustedOrigins', () => {
const originalTrustedOrigins = process.env.AUTH_TRUSTED_ORIGINS
afterEach(() => {
if (originalTrustedOrigins === undefined) {
delete process.env.AUTH_TRUSTED_ORIGINS
} else {
process.env.AUTH_TRUSTED_ORIGINS = originalTrustedOrigins
}
vi.resetModules()
})
async function loadTrustedOrigins(value?: string): Promise<string[]> {
if (value === undefined) {
delete process.env.AUTH_TRUSTED_ORIGINS
} else {
process.env.AUTH_TRUSTED_ORIGINS = value
}
vi.resetModules()
const { getTrustedOrigins } = await import('@opencode-manager/shared/config/env')
return getTrustedOrigins()
}
it('splits, trims, and drops empty entries', async () => {
await expect(loadTrustedOrigins(' http://a.test ,, http://b.test ')).resolves.toEqual(['http://a.test', 'http://b.test'])
})
it('returns an empty list when configured empty', async () => {
await expect(loadTrustedOrigins('')).resolves.toEqual([])
})
it('falls back to the local development origins', async () => {
await expect(loadTrustedOrigins(undefined)).resolves.toEqual(['http://localhost:5173', 'http://localhost:5003'])
})
})
+54 -1
View File
@@ -3,12 +3,47 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const serveMock = vi.fn<(options: unknown) => { on: () => void }>(() => ({ on: vi.fn() }))
interface MockServeServer {
on: (event: string, handler: (...args: unknown[]) => void) => void
emit: (event: string, ...args: unknown[]) => void
}
const serveServers = vi.hoisted(() => [] as MockServeServer[])
const serveMock = vi.fn<(options: unknown) => MockServeServer>(() => {
const handlers = new Map<string, Array<(...args: unknown[]) => void>>()
const server: MockServeServer = {
on: (event, handler) => {
const registered = handlers.get(event) ?? []
registered.push(handler)
handlers.set(event, registered)
},
emit: (event, ...args) => {
for (const handler of handlers.get(event) ?? []) handler(...args)
},
}
serveServers.push(server)
return server
})
vi.mock('@hono/node-server', () => ({
serve: serveMock,
}))
const previewAvailabilityInstances = vi.hoisted(() => [] as Array<{ isEnabled: () => boolean }>)
vi.mock('../src/routes/preview', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/routes/preview')>()
return {
...actual,
createPreviewAvailability: (initialEnabled: boolean) => {
const availability = actual.createPreviewAvailability(initialEnabled)
previewAvailabilityInstances.push(availability)
return availability
},
}
})
const supervisorMock = vi.hoisted(() => ({
start: vi.fn().mockResolvedValue({ healthy: true, port: 5551, state: 'running' }),
stop: vi.fn().mockResolvedValue(undefined),
@@ -143,6 +178,8 @@ describe('backend entrypoint', () => {
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
serveServers.length = 0
previewAvailabilityInstances.length = 0
tempWorkspace = await mkdtemp(join(tmpdir(), 'ocm-entrypoint-'))
previousWorkspace = process.env.WORKSPACE_PATH
process.env.WORKSPACE_PATH = tempWorkspace
@@ -175,6 +212,22 @@ describe('backend entrypoint', () => {
expect(ipcServerMock.dispose).not.toHaveBeenCalled()
})
it('marks the preview gateway unavailable instead of crashing when its port cannot be bound', async () => {
await import('../src/index')
expect(serveServers).toHaveLength(2)
const availability = previewAvailabilityInstances[0]
expect(availability?.isEnabled()).toBe(false)
const previewServer = serveServers[1]!
previewServer.emit('listening')
expect(availability?.isEnabled()).toBe(true)
const error = Object.assign(new Error('bind failed'), { code: 'EADDRINUSE' })
expect(() => previewServer.emit('error', error)).not.toThrow()
expect(availability?.isEnabled()).toBe(false)
})
it('imports home state without rewriting an existing valid config', async () => {
const configDir = join(tempWorkspace, '.config', 'opencode')
await mkdir(configDir, { recursive: true })
+99 -10
View File
@@ -1,9 +1,10 @@
import { describe, it, expect, afterEach } from 'vitest'
import { mkdtemp, mkdir, rm } from 'node:fs/promises'
import { mkdtemp, mkdir, rm, symlink } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { ENV } from '@opencode-manager/shared/config/env'
import { createPreviewRoutes } from '../../src/routes/preview'
import type { PreviewPort } from '@opencode-manager/shared/schemas'
import { createPreviewRoutes, createPreviewAvailability } from '../../src/routes/preview'
import { PreviewSessionStore } from '../../src/services/preview/gateway'
import type { PreviewPortEntry } from '../../src/services/preview/ports'
@@ -30,7 +31,7 @@ describe('Preview Routes', () => {
await mkdir(appDir)
const app = createPreviewRoutes({
enabled: true,
isEnabled: () => true,
listPorts: async () => [
entry({ port: 9000, cwd: '/somewhere/else' }),
entry({ port: 5173, cwd: appDir }),
@@ -47,7 +48,7 @@ describe('Preview Routes', () => {
it('sorts by port when no directory is given', async () => {
const app = createPreviewRoutes({
enabled: true,
isEnabled: () => true,
listPorts: async () => [entry({ port: 9000 }), entry({ port: 5173 })],
})
@@ -57,8 +58,60 @@ describe('Preview Routes', () => {
expect(body.ports.map((port) => port.port)).toEqual([5173, 9000])
})
it('marks entries inside the directory and sorts them first', async () => {
const root = await makeTempDir()
const appDir = join(root, 'app')
await mkdir(appDir)
const app = createPreviewRoutes({
isEnabled: () => true,
listPorts: async () => [
entry({ port: 5173, cwd: '/somewhere/else' }),
entry({ port: 9000, cwd: appDir }),
],
})
const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`)
const body = await res.json() as { ports: PreviewPort[] }
expect(body.ports.map((port) => ({ port: port.port, inDirectory: port.inDirectory }))).toEqual([
{ port: 9000, inDirectory: true },
{ port: 5173, inDirectory: false },
])
})
it('resolves symlinked cwds before matching the directory', async () => {
const root = await makeTempDir()
const realDir = join(root, 'real')
const linkDir = join(root, 'link')
await mkdir(realDir)
await symlink(realDir, linkDir)
const app = createPreviewRoutes({
isEnabled: () => true,
listPorts: async () => [entry({ port: 5173, cwd: linkDir })],
})
const res = await app.request(`/ports?directory=${encodeURIComponent(realDir)}`)
const body = await res.json() as { ports: PreviewPort[] }
expect(body.ports[0]?.inDirectory).toBe(true)
})
it('marks every entry outside when no directory is given', async () => {
const app = createPreviewRoutes({
isEnabled: () => true,
listPorts: async () => [entry({ port: 5173, cwd: '/repo' }), entry({ port: 9000, cwd: null })],
})
const res = await app.request('/ports')
const body = await res.json() as { ports: PreviewPort[] }
expect(body.ports.map((port) => port.inDirectory)).toEqual([false, false])
})
it('reports preview as disabled when the port is zero', async () => {
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [] })
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [] })
const res = await app.request('/ports')
@@ -67,7 +120,7 @@ describe('Preview Routes', () => {
it('issues a preview start token for a listening port', async () => {
const store = new PreviewSessionStore()
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })], store })
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })], store })
const res = await app.request('/sessions', {
method: 'POST',
@@ -84,7 +137,7 @@ describe('Preview Routes', () => {
})
it('rejects a reserved port with 400', async () => {
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
const res = await app.request('/sessions', {
method: 'POST',
@@ -96,7 +149,7 @@ describe('Preview Routes', () => {
})
it('returns 404 for a port that is not listening', async () => {
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })] })
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })] })
const res = await app.request('/sessions', {
method: 'POST',
@@ -109,7 +162,7 @@ describe('Preview Routes', () => {
})
it('returns 503 when preview is disabled', async () => {
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [entry({ port: 5173 })] })
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [entry({ port: 5173 })] })
const res = await app.request('/sessions', {
method: 'POST',
@@ -121,7 +174,7 @@ describe('Preview Routes', () => {
})
it('rejects an out-of-range port with 400', async () => {
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [] })
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [] })
const res = await app.request('/sessions', {
method: 'POST',
@@ -131,4 +184,40 @@ describe('Preview Routes', () => {
expect(res.status).toBe(400)
})
it('reads availability at request time', async () => {
let enabled = true
const app = createPreviewRoutes({ isEnabled: () => enabled, listPorts: async () => [entry({ port: 5173 })] })
const first = await app.request('/ports')
expect((await first.json() as { enabled: boolean }).enabled).toBe(true)
enabled = false
const second = await app.request('/ports')
expect((await second.json() as { enabled: boolean }).enabled).toBe(false)
const disabledSession = await app.request('/sessions', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ port: 5173 }),
})
expect(disabledSession.status).toBe(503)
})
})
describe('Preview availability', () => {
it('starts in the provided state', () => {
expect(createPreviewAvailability(true).isEnabled()).toBe(true)
expect(createPreviewAvailability(false).isEnabled()).toBe(false)
})
it('tracks availability transitions', () => {
const availability = createPreviewAvailability(true)
availability.markUnavailable()
expect(availability.isEnabled()).toBe(false)
availability.markAvailable()
expect(availability.isEnabled()).toBe(true)
})
})
@@ -89,6 +89,7 @@ describe('Repo Project Config Routes', () => {
exists: false,
trusted: false,
hash: null,
executable: null,
warnings: [],
})
})
@@ -100,6 +101,13 @@ describe('Repo Project Config Routes', () => {
expect(await res.json()).toEqual({ error: 'Repo not found' })
})
it('rejects the assistant repo id when assistant access is not allowed', async () => {
const res = await app.request('/0/project-config')
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: 'Repo not found' })
})
it('returns 404 for a repo that is not ready', async () => {
createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
@@ -214,6 +222,33 @@ describe('Repo Project Config Routes', () => {
expect((await res.json() as { code: string }).code).toBe('REPO_CONFIG_CHANGED')
})
it('returns the error code and details for an untrusted repository action', async () => {
seedRepo(db)
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-untrusted-'))
vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory)
const repoFileDir = path.join(directory, '.ocm')
fs.mkdirSync(repoFileDir, { recursive: true })
fs.writeFileSync(
path.join(repoFileDir, 'project.json'),
JSON.stringify({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }),
)
try {
const res = await app.request('/1/project-config/actions/repo-serve/run', {
method: 'POST',
headers: jsonHeaders,
body: JSON.stringify({}),
})
expect(res.status).toBe(409)
const body = await res.json() as { code: string; details: { hash: string } }
expect(body.code).toBe('REPO_CONFIG_UNTRUSTED')
expect(body.details.hash).toMatch(/^[a-f0-9]{64}$/)
} finally {
fs.rmSync(directory, { recursive: true, force: true })
}
})
it('returns 400 for an invalid move request', async () => {
seedRepo(db)
+13 -1
View File
@@ -22,6 +22,7 @@ const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as Gi
const openCodeClient: OpenCodeClient = createStubOpenCodeClient()
const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
const assistantRepo = { id: 0, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
const shellTerminal = {
id: 'pty-1',
@@ -54,7 +55,9 @@ const jsonHeaders = { 'Content-Type': 'application/json' }
describe('Repo Terminal Routes', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) => (id === 1 ? readyRepo : null))
vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) =>
id === 1 ? readyRepo : id === 0 ? assistantRepo : null,
)
vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => {
if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo'
return null
@@ -78,6 +81,15 @@ describe('Repo Terminal Routes', () => {
expect(res.status).toBe(400)
})
it('resolves the assistant repo when assistant access is allowed', async () => {
const terminals = [{ ...shellTerminal }]
const list = vi.fn(async () => terminals)
const res = await createApp(createService({ list })).request('/0/terminals')
expect(res.status).toBe(200)
expect(list).toHaveBeenCalledWith('/tmp/repo')
})
it('returns 404 for an unknown repo', async () => {
vi.mocked(resolveRepoOrAssistant).mockReturnValue(null)
const res = await createApp(createService()).request('/2/terminals')
+31
View File
@@ -871,6 +871,37 @@ describe('Repo Routes', () => {
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
})
it('removes terminals for OpenCode workspace siblings but not manager worktree repos', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
vi.mocked(repoService.getSiblingRepos).mockResolvedValue([
{ ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined },
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' },
])
const app = createTestRoutes()
const res = await app.request('/1', { method: 'DELETE' })
expect(res.status).toBe(200)
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo')
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/plugin-workspace')
expect(mockTerminalService.removeAll).not.toHaveBeenCalledWith('/tmp/repos/manager-worktree')
expect(repoService.getSiblingRepos).toHaveBeenCalledWith(mockDb, 1, {}, expect.anything(), { includeBranch: false })
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
})
it('still deletes the repo when listing workspace siblings throws', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
vi.mocked(repoService.getSiblingRepos).mockRejectedValue(new Error('siblings failed'))
const app = createTestRoutes()
const res = await app.request('/1', { method: 'DELETE' })
expect(res.status).toBe(200)
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
})
it('should return 500 when removing the repo files throws', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
vi.mocked(repoService.deleteRepoFiles).mockRejectedValue(new Error('delete failed'))
@@ -31,6 +31,17 @@ upstreamApp.get('/cookies', () => {
return new Response('ok', { status: 200, headers })
})
upstreamApp.get('/manager-cookies', () => {
const headers = new Headers()
headers.append('set-cookie', 'app=keep; Path=/')
headers.append('set-cookie', `${PREVIEW_COOKIE}=upstream; Path=/`)
headers.append('set-cookie', 'opencode.session_token=secret; Path=/')
headers.append('set-cookie', '__Secure-opencode.session_token=secure; Path=/')
headers.append('set-cookie', '__Host-opencode.session_token=host; Path=/')
headers.set('content-type', 'text/plain')
return new Response('ok', { status: 200, headers })
})
upstreamApp.all('/*', async (c) => {
if (c.req.path === '/r') {
return c.redirect(`http://localhost:${upstreamPort}/done`, 302)
@@ -42,6 +53,7 @@ upstreamApp.all('/*', async (c) => {
search: new URL(c.req.url).search,
host: c.req.header('host') ?? null,
cookie: c.req.header('cookie') ?? null,
acceptEncoding: c.req.header('accept-encoding') ?? null,
body,
})
})
@@ -129,6 +141,36 @@ describe('Preview Gateway', () => {
expect(res.headers.get('location')).toBe('/')
})
it('rejects redirect paths that resolve off-origin', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
for (const malicious of ['/\\evil.example', '//evil.example', 'https://evil.example']) {
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
const res = await app.request(
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent(malicious)}`,
{ redirect: 'manual' },
)
expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('/')
}
})
it('redirects to an allowed same-origin path with query and hash', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
const res = await app.request(
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/ok?x=1#h')}`,
{ redirect: 'manual' },
)
expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('/ok?x=1#h')
})
it('does not allow a start token to be reused', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
@@ -230,6 +272,31 @@ describe('Preview Gateway', () => {
expect(cookies).toHaveLength(2)
})
it('drops Manager and preview Set-Cookie values from upstream responses', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
const cookie = await openSession(app, store, upstreamPort)
const res = await app.request('http://localhost/manager-cookies', { headers: { cookie } })
expect(res.status).toBe(200)
expect(res.headers.getSetCookie()).toEqual(['app=keep; Path=/'])
})
it('requests identity encoding from the upstream', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
const cookie = await openSession(app, store, upstreamPort)
const res = await app.request('http://localhost/echo', {
headers: { cookie, 'accept-encoding': 'gzip, br' },
})
expect(res.status).toBe(200)
const body = await res.json() as { acceptEncoding: string | null }
expect(body.acceptEncoding).toBe('identity')
})
it('rewrites an absolute localhost location to its path', async () => {
const store = new PreviewSessionStore()
const app = createPreviewGatewayApp(store).app
@@ -140,6 +140,41 @@ describe('listListeningPorts', () => {
])
})
it('stops scanning process fd directories once every listening inode is mapped', async () => {
const base = createDeps({
files: {
'/proc/net/tcp': [PROC_HEADER, procRow('00000000:1435', '00000000:0000', '0A', '11111')].join('\n'),
'/proc/1234/comm': 'node\n',
},
links: {
'/proc/1234/fd/3': 'socket:[11111]',
'/proc/1234/cwd': '/home/user/project',
'/proc/9999/fd/2': 'socket:[11111]',
},
dirs: {
'/proc': ['1234', '9999'],
'/proc/1234/fd': ['3'],
'/proc/9999/fd': ['2'],
},
})
const readdirCalls: string[] = []
const deps: PortDiscoveryDeps = {
...base,
readdir: async (path) => {
readdirCalls.push(path)
return base.readdir(path)
},
}
const ports = await listListeningPorts(deps)
expect(ports).toEqual([
{ port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' },
])
expect(readdirCalls).toContain('/proc/1234/fd')
expect(readdirCalls).not.toContain('/proc/9999/fd')
})
it('reports an IPv6 loopback host only when the sole listener is IPv6 loopback', async () => {
const deps = createDeps({
files: {
+125 -10
View File
@@ -95,6 +95,7 @@ describe('ProjectConfigService personal settings', () => {
exists: false,
trusted: false,
hash: null,
executable: null,
warnings: [],
})
})
@@ -288,17 +289,39 @@ describe('ProjectConfigService repository file', () => {
})
})
it('keeps trust across a name-only edit and drops it on a command edit', async () => {
it('drops trust when the name, command, or autoOpenUrl changes', async () => {
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
const first = await service.getConfig(repo, directory)
await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '')
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev --host' }] })
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
const renamed = await service.getConfig(repo, directory)
await service.trustRepoFile(repo, directory, renamed.repoFile.hash ?? '')
writeRepoFile({
version: 1,
projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev', autoOpenUrl: true }],
})
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
})
it('changes the hash when only the name or autoOpenUrl changes', async () => {
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
const base = await service.getConfig(repo, directory)
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
const renamed = await service.getConfig(repo, directory)
writeRepoFile({
version: 1,
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: true }],
})
const autoOpen = await service.getConfig(repo, directory)
expect(renamed.repoFile.hash).not.toBe(base.repoFile.hash)
expect(autoOpen.repoFile.hash).not.toBe(base.repoFile.hash)
})
it('reports invalid JSON with an error and no repository items', async () => {
@@ -307,7 +330,7 @@ describe('ProjectConfigService repository file', () => {
const config = await service.getConfig(repo, directory)
expect(config.repoFile.exists).toBe(true)
expect(config.repoFile.error).toBeTruthy()
expect(config.repoFile.error).toBe('Invalid JSON')
expect(config.repoFile.hash).toBeNull()
expect(config.actions).toEqual([])
})
@@ -317,10 +340,72 @@ describe('ProjectConfigService repository file', () => {
const config = await service.getConfig(repo, directory)
expect(config.repoFile.error).toBeTruthy()
expect(config.repoFile.error).toBe('Does not match the project file schema')
expect(config.actions).toEqual([])
})
it('rejects a repository action url that is not http(s)', async () => {
writeRepoFile({
version: 1,
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'javascript:alert(1)' }],
})
const config = await service.getConfig(repo, directory)
expect(config.repoFile.error).toBe('Does not match the project file schema')
expect(config.repoFile.executable).toBeNull()
})
it('accepts an http url template', async () => {
writeRepoFile({
version: 1,
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'http://localhost:3000/{branch}' }],
})
const config = await service.getConfig(repo, directory)
expect(config.repoFile.executable?.actions[0]?.url).toBe('http://localhost:3000/{branch}')
})
it('reports a symlinked .ocm directory as invalid on read', async () => {
const realDir = path.join(directory, 'real-ocm')
fs.mkdirSync(realDir, { recursive: true })
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
const config = await service.getConfig(repo, directory)
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
expect(config.repoFile.hash).toBeNull()
expect(config.repoFile.executable).toBeNull()
})
it('reports a symlinked project.json as invalid on read', async () => {
const ocmDir = path.join(directory, '.ocm')
fs.mkdirSync(ocmDir, { recursive: true })
const target = path.join(directory, 'target.json')
fs.writeFileSync(target, JSON.stringify({ version: 1 }))
fs.symlinkSync(target, path.join(ocmDir, 'project.json'))
const config = await service.getConfig(repo, directory)
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
})
it('refuses to move an action into a symlinked repository config', async () => {
service.setPersonalActions(repo, [createAction()])
const realDir = path.join(directory, 'real-ocm')
fs.mkdirSync(realDir, { recursive: true })
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toMatchObject({
status: 400,
code: 'REPO_CONFIG_SYMLINK',
})
expect(service.getPersonalActions(repo)).toEqual([createAction()])
})
it('moves an action personal to repo preserving unknown keys and marking it trusted', async () => {
service.setPersonalActions(repo, [createAction()])
writeRepoFile({ version: 1, customKey: 'keep-me' })
@@ -416,6 +501,34 @@ describe('ProjectConfigService repository file', () => {
expect(config.repoFile.warnings[0]).toContain('serve')
})
it('lists every executable repository action including a shadowed one', async () => {
service.setPersonalActions(repo, [
createAction({ id: 'serve', name: 'Personal Serve', command: 'pnpm personal' }),
])
writeRepoFile({
version: 1,
projectActions: [
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
{ id: 'other', name: 'Other', command: 'pnpm other' },
],
setupWorktree: ['pnpm install'],
})
const config = await service.getConfig(repo, directory)
expect(config.repoFile.executable).toEqual({
actions: [
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
{ id: 'other', name: 'Other', command: 'pnpm other', url: null, autoOpenUrl: false },
],
setup: ['pnpm install'],
})
expect(config.actions).toEqual([
{ id: 'serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'personal' },
{ id: 'other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' },
])
})
it('rejects moving an unknown personal action', async () => {
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({
status: 404,
@@ -487,12 +600,13 @@ describe('ProjectConfigService repository file', () => {
it('restores the repository file and personal settings when the file write fails', async () => {
service.setPersonalActions(repo, [createAction()])
const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
throw new Error('disk full')
})
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full')
renameSpy.mockRestore()
writeSpy.mockRestore()
expect(fs.existsSync(repoFilePath())).toBe(false)
expect(service.getPersonalActions(repo)).toEqual([createAction()])
@@ -531,14 +645,15 @@ describe('ProjectConfigService repository file', () => {
],
})
const originalBytes = fs.readFileSync(repoFilePath(), 'utf8')
const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
throw new Error('disk full')
})
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow(
'disk full',
)
renameSpy.mockRestore()
writeSpy.mockRestore()
expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes)
expect(service.getPersonalActions(repo)).toEqual([])
@@ -1,10 +1,26 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { findSiblingByDirectory, resolveRepoWorkingDirectory } from '../../src/services/repo'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { createRepo } from '../../src/db/queries'
import { findSiblingByDirectory, getSiblingRepos, resolveRepoWorkingDirectory } from '../../src/services/repo'
import type { Repo } from '@opencode-manager/shared/types'
const { executeCommand, resolveProjectId, getSettings } = vi.hoisted(() => ({
executeCommand: vi.fn(),
resolveProjectId: vi.fn(),
getSettings: vi.fn(),
}))
vi.mock('../../src/utils/process', () => ({ executeCommand }))
vi.mock('../../src/services/project-id-resolver', () => ({ resolveProjectId, isGitMainCheckout: vi.fn() }))
vi.mock('../../src/services/settings', () => ({
SettingsService: vi.fn().mockImplementation(() => ({ getSettings })),
}))
describe('resolveRepoWorkingDirectory', () => {
let root: string
let repoPath: string
@@ -96,3 +112,50 @@ describe('findSiblingByDirectory', () => {
expect(findSiblingByDirectory([sibling], path.join(root, 'missing'))).toBeUndefined()
})
})
describe('getSiblingRepos branch resolution', () => {
let db: Database
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() })
resolveProjectId.mockResolvedValue('project-1')
executeCommand.mockReset()
})
afterEach(() => {
db.close()
})
function seedRepo(): Repo {
return createRepo(db, {
localPath: 'repo-a',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
isLocal: true,
})
}
it('skips branch resolution when includeBranch is false', async () => {
const repo = seedRepo()
const siblings = await getSiblingRepos(db, repo.id, {}, undefined, { includeBranch: false })
expect(siblings).toHaveLength(1)
expect(siblings[0]?.currentBranch).toBeUndefined()
expect(executeCommand).not.toHaveBeenCalled()
})
it('resolves the branch when includeBranch is true', async () => {
const repo = seedRepo()
executeCommand.mockResolvedValue('feature-branch\n')
const siblings = await getSiblingRepos(db, repo.id, {})
expect(siblings).toHaveLength(1)
expect(siblings[0]?.currentBranch).toBe('feature-branch')
expect(executeCommand).toHaveBeenCalled()
})
})
+4
View File
@@ -65,6 +65,7 @@ interface FakePeer {
closeCalls: Array<{ code?: number; reason?: string }>
send(data: string | Uint8Array): void
close(code?: number, reason?: string): void
bufferedAmount(): number
}
function createPeer(): FakePeer {
@@ -79,6 +80,9 @@ function createPeer(): FakePeer {
close(code, reason) {
closeCalls.push({ code, reason })
},
bufferedAmount() {
return 0
},
}
}
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils'
import { formatTerminalTitle, isRunningActionTerminal, parseTerminalTitle } from '@opencode-manager/shared/utils'
describe('terminal-title', () => {
describe('formatTerminalTitle', () => {
@@ -59,4 +59,22 @@ describe('terminal-title', () => {
expect(parseTerminalTitle('ocm:action:dev')).toEqual({ kind: 'shell', title: 'ocm:action:dev' })
})
})
describe('isRunningActionTerminal', () => {
it('matches a running action terminal for the action id', () => {
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'running' }, 'dev')).toBe(true)
})
it('rejects a terminal for a different action id', () => {
expect(isRunningActionTerminal({ kind: 'action', actionId: 'other', status: 'running' }, 'dev')).toBe(false)
})
it('rejects a non-action terminal', () => {
expect(isRunningActionTerminal({ kind: 'shell', status: 'running' }, 'dev')).toBe(false)
})
it('rejects an exited action terminal', () => {
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'exited' }, 'dev')).toBe(false)
})
})
})
+40 -2
View File
@@ -1,8 +1,8 @@
import { mkdtemp, realpath, rm } from 'node:fs/promises'
import { mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { canonicalPath, canonicalPathSync } from '../../src/utils/fs-safe'
import { canonicalPath, canonicalPathSync, writeFileAtomicSync } from '../../src/utils/fs-safe'
describe('canonicalPath', () => {
let workDir = ''
@@ -29,3 +29,41 @@ describe('canonicalPath', () => {
expect(canonicalPathSync(missing)).toBe(missing)
})
})
describe('writeFileAtomicSync', () => {
let workDir = ''
beforeEach(async () => {
workDir = await mkdtemp(path.join(tmpdir(), 'fs-safe-atomic-'))
})
afterEach(async () => {
await rm(workDir, { recursive: true, force: true })
})
it('writes the content and creates missing parent directories', async () => {
const target = path.join(workDir, 'nested', 'file.json')
writeFileAtomicSync(target, '{"ok":true}', { mode: 0o644 })
await expect(readFile(target, 'utf8')).resolves.toBe('{"ok":true}')
expect((await stat(target)).mode & 0o777).toBe(0o644)
})
it('overwrites an existing file', async () => {
const target = path.join(workDir, 'file.txt')
await writeFile(target, 'old')
writeFileAtomicSync(target, 'new')
await expect(readFile(target, 'utf8')).resolves.toBe('new')
})
it('leaves no temp files behind', async () => {
const target = path.join(workDir, 'file.txt')
writeFileAtomicSync(target, 'content')
await expect(readdir(workDir)).resolves.toEqual(['file.txt'])
})
})
+64 -12
View File
@@ -1,5 +1,11 @@
import { describe, it, expect, vi } from 'vitest'
import { bridgeWebSocket, type WebSocketPeer } from '../../src/utils/websocket-bridge'
import {
bridgeWebSocket,
forwardPeerMessage,
MAX_PEER_BUFFERED_BYTES,
type WebSocketBridge,
type WebSocketPeer,
} from '../../src/utils/websocket-bridge'
type Listener = (event: unknown) => void
@@ -28,21 +34,25 @@ class FakeUpstream {
interface FakePeer extends WebSocketPeer {
sent: Array<string | Uint8Array>
closeCalls: Array<{ code?: number; reason?: string }>
buffered: number
}
function createPeer(): FakePeer {
const sent: Array<string | Uint8Array> = []
const closeCalls: Array<{ code?: number; reason?: string }> = []
return {
sent,
closeCalls,
const peer: FakePeer = {
sent: [],
closeCalls: [],
buffered: 0,
send(data) {
sent.push(data)
peer.sent.push(data)
},
close(code, reason) {
closeCalls.push({ code, reason })
peer.closeCalls.push({ code, reason })
},
bufferedAmount() {
return peer.buffered
},
}
return peer
}
function asUpstream(upstream: FakeUpstream): WebSocket {
@@ -111,14 +121,32 @@ describe('bridgeWebSocket', () => {
expect(peer.closeCalls).toEqual([{ code: 1011, reason: undefined }])
})
it('applies a custom close-code mapper', () => {
it('closes the upstream and peer with 1013 when the peer buffer overflows', () => {
const upstream = new FakeUpstream()
const peer = createPeer()
bridgeWebSocket(asUpstream(upstream), peer, { mapCloseCode: () => 4000 })
peer.buffered = MAX_PEER_BUFFERED_BYTES + 1
upstream.emit('close', { code: 1006 })
bridgeWebSocket(asUpstream(upstream), peer)
upstream.emit('message', { data: 'overflow' })
expect(peer.closeCalls).toEqual([{ code: 4000, reason: undefined }])
expect(peer.closeCalls).toEqual([{ code: 1013, reason: 'Client too slow' }])
expect(upstream.close).toHaveBeenCalledTimes(1)
upstream.emit('close', { code: 1000 })
expect(peer.closeCalls).toHaveLength(1)
})
it('keeps bridging while the peer buffer stays within the limit', () => {
const upstream = new FakeUpstream()
const peer = createPeer()
peer.buffered = MAX_PEER_BUFFERED_BYTES
bridgeWebSocket(asUpstream(upstream), peer)
upstream.emit('message', { data: 'within limit' })
expect(peer.sent).toEqual(['within limit'])
expect(peer.closeCalls).toEqual([])
expect(upstream.close).not.toHaveBeenCalled()
})
it('closes the upstream only once and ignores later sends', () => {
@@ -133,3 +161,27 @@ describe('bridgeWebSocket', () => {
expect(upstream.sent).toEqual([])
})
})
describe('forwardPeerMessage', () => {
function createBridge(sent: Array<string | ArrayBuffer | Uint8Array>): WebSocketBridge {
return {
send(data) {
sent.push(data)
},
close() {},
}
}
it('forwards strings, ArrayBuffers and Blobs to the bridge', async () => {
const sent: Array<string | ArrayBuffer | Uint8Array> = []
const bridge = createBridge(sent)
await forwardPeerMessage(bridge, 'plain text')
await forwardPeerMessage(bridge, new Uint8Array([1, 2]).buffer)
await forwardPeerMessage(bridge, new Blob(['blob body']))
expect(sent[0]).toBe('plain text')
expect(sent[1]).toEqual(new Uint8Array([1, 2]).buffer)
expect(new TextDecoder().decode(sent[2] as ArrayBuffer)).toBe('blob body')
})
})