import { Hono } from 'hono' import { sessionAuth } from '../../auth/middleware' import { config } from '../../config' import { canUseEnvironment, listActiveEnvironmentsResponse, } from '../../services/environment' import { isSessionClosedStatus, listSessions, listWebSessionsByOwnerUuid, } from '../../services/session' import { storeGetEnvironment, storeListActiveEnvironments } from '../../store' import { getDb } from '../../db/sqlite' import { resolveUserIdUuid } from '../../auth/bridge-auth' import { EnvironmentRpcError, requestDirectoryListing, } from '../../services/environment-rpc' const app = new Hono() /** GET /web/environments — List active environments. * Admin sees all (bypass). Non-admin sees only environments they own * (owner_user_id = me) OR environments linked to teams they belong to. * Optional ?team_id= narrows to one team (server-side scope, mirrors * GET /web/sessions). Unowned personal envs (no owner, no team) are * invisible — they're in claim flow pending state. */ app.get('/environments', sessionAuth, async c => { const userId = c.get('userId') as string const isAdmin = c.get('isAdmin') as boolean // Include disconnected machines so the registry stays stable while a // worker is offline (their sessions remain visible and attributable). const allEnvs = listActiveEnvironmentsResponse(true) if (isAdmin) { return c.json(allEnvs, 200) } // Resolve the user's team memberships so we can filter environments. // Auth yields either a users.id UUID (SQLite session token) or a username // (legacy in-memory token) — normalize so ownership/team checks agree with // the machine-level ACL in canUseEnvironment. const db = getDb() const callerUuid = resolveUserIdUuid(db, userId) const identity = callerUuid ?? userId const teamRows = db .query('SELECT team_id FROM team_members WHERE user_id = $userId') .all({ $userId: identity }) as Array<{ team_id: string }> const teamIds = new Set(teamRows.map(r => r.team_id)) // Visible if: env.owner_user_id is me OR env.team_id is one of my teams. const visible = allEnvs.filter( env => env.owner_user_id === identity || env.owner_user_id === userId || (env.team_id !== null && teamIds.has(env.team_id)), ) // Optional server-side team scope narrows to one team. const teamId = c.req.query('team_id') if (teamId) { return c.json( visible.filter(env => env.team_id === teamId), 200, ) } return c.json(visible, 200) }) /** GET /web/environments/:id/recent-dirs — Recently used session directories. * Derived from session history (no extra table), scoped to sessions the * caller can see. Used as quick picks in the new-session dialog; it is not * an access-control list — any directory on the machine is allowed. */ app.get('/environments/:id/recent-dirs', sessionAuth, async c => { const userId = c.get('userId')! const isAdmin = c.get('isAdmin') as boolean const envId = c.req.param('id')! if (!storeGetEnvironment(envId)) { return c.json( { error: { type: 'not_found', message: 'Environment not found' } }, 404, ) } if (!canUseEnvironment(envId, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'You do not have access to this machine', }, }, 403, ) } const sessions = isAdmin ? listSessions() : listWebSessionsByOwnerUuid(userId) const seen = new Set() const dirs: string[] = [] for (const session of sessions .filter( s => s.environment_id === envId && typeof s.cwd === 'string' && s.cwd.length > 0 && !isSessionClosedStatus(s.status), ) .sort((a, b) => b.updated_at - a.updated_at)) { const dir = session.cwd! if (seen.has(dir)) continue seen.add(dir) dirs.push(dir) if (dirs.length >= 8) break } return c.json({ dirs }, 200) }) /** GET /web/environments/:id/dirs — Browse directories on a daemon machine. * * Unlike recent-dirs (which is derived from session history), this asks the * worker over the work-poll RPC channel, so the list reflects the live * filesystem. Only workers advertising capabilities.fs_browse answer. */ app.get('/environments/:id/dirs', sessionAuth, async c => { const userId = c.get('userId')! const isAdmin = c.get('isAdmin') as boolean const envId = c.req.param('id')! if (!storeGetEnvironment(envId)) { return c.json( { error: { type: 'not_found', message: 'Environment not found' } }, 404, ) } if (!canUseEnvironment(envId, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'You do not have access to this machine', }, }, 403, ) } const path = c.req.query('path') ?? '' if (path.length > 4096 || path.includes('\0')) { return c.json( { error: { type: 'bad_request', message: 'Invalid directory path' } }, 400, ) } try { const listing = await requestDirectoryListing(envId, path) return c.json(listing, 200) } catch (err) { const code = err instanceof EnvironmentRpcError ? err.code : 'failed' const status = code === 'unsupported' ? 400 : code === 'offline' ? 409 : code === 'timeout' ? 504 : 500 return c.json( { error: { type: code, message: err instanceof Error ? err.message : 'Directory browse failed', }, }, status, ) } }) /** GET /web/server-info — Aggregate server status for Web UI identity panel */ app.get('/server-info', sessionAuth, async c => { const uuid = c.get('userId')! const envs = storeListActiveEnvironments() const sessions = listWebSessionsByOwnerUuid(uuid) return c.json( { version: config.version, uptime_seconds: Math.floor(process.uptime()), workers_active: envs.filter(e => e.status === 'active').length, workers_total: envs.length, sessions_owned: sessions.length, sessions_active: sessions.length, }, 200, ) }) export default app