import { Hono } from 'hono' import { randomUUID } from 'node:crypto' import { config } from '../../config' import { registerEnvironment, deregisterEnvironment, reconnectEnvironment, touchEnvironmentActivity, } from '../../services/environment' import { acceptCliHeaders, apiKeyAuth } from '../../auth/middleware' import { bridgeAuth, resolveAttachCaller, resolveUserIdUuid, } from '../../auth/bridge-auth' import { getDb } from '../../db/sqlite' import { getClientIp } from '../../client-ip' import { isSessionClosedStatus } from '../../services/session' import { getSingleUserAdminUuid } from '../../services/single-user' import { storeBindEnvSessionsToTeam, storeGetEnvironment, storeGetEnvironmentOwnership, storeListSessionsByEnvironment, } from '../../store' const app = new Hono() /** Result of validateTeamBinding — rendered by the route layer. */ type TeamBindingCheck = | { ok: true; audit?: string } | { ok: false; status: 400 | 403; errorType: string; message: string } /** * Validate an X-Team-Id binding request. Pure (no Hono Context) so it is * unit-testable; the route renders the discriminated union. * * Semantics: * 1. Team existence is checked unconditionally — a bad team id must fail * loudly here instead of as a downstream FK error masquerading as 503. * 2. Resolved caller (rct_* token or resolvable X-Username): membership * check, admins bypass. * 3. X-Username provided but unresolvable: 403 "User not found" (config * error — preserved pre-existing behavior, no silent relaxation). * 4. No identity at all (bare admin API key): allowed with an audit trail — * RCS_API_KEYS are admin credentials. */ function validateTeamBinding( db: ReturnType, teamId: string, caller: { id: string | null rawIdentity: string | null isApiAdmin: boolean }, ): TeamBindingCheck { const team = db .query('SELECT id FROM teams WHERE id = $id AND deleted_at IS NULL') .get({ $id: teamId }) as { id: string } | null if (!team) { return { ok: false, status: 400, errorType: 'bad_request', message: `Team not found: ${teamId}`, } } if (caller.id) { // Check membership (admin users are implicit members of all teams) const user = db .query('SELECT role FROM users WHERE id = $id') .get({ $id: caller.id }) as { role: string } | null const isAdmin = user?.role === 'admin' if (!isAdmin) { const membership = db .query( 'SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId', ) .get({ $teamId: teamId, $userId: caller.id }) if (!membership) { return { ok: false, status: 403, errorType: 'forbidden', message: 'User is not a member of this team', } } } return { ok: true } } // Identity was provided but does not resolve to a real user. if (caller.rawIdentity) { return { ok: false, status: 403, errorType: 'forbidden', message: 'User not found', } } if (caller.isApiAdmin) { return { ok: true, audit: `API key linked env to team ${teamId} (no user identity)`, } } return { ok: false, status: 403, errorType: 'forbidden', message: 'User identity required to bind a team', } } /** POST /v1/environments/bridge — Register an environment */ app.post('/bridge', acceptCliHeaders, bridgeAuth, async c => { const body = await c.req.json() const userId = c.get('userId') as string | undefined const username = userId const teamId = c.req.header('X-Team-Id') const headerUserId = c.req.header('X-User-Id') const isApiAdmin = c.get('isApiAdmin') ?? false const db = getDb() // Resolve the caller's identity once (X-User-Id header and team // validation below both need it). const callerId = userId ? resolveUserIdUuid(db, userId) : null // X-User-Id explicitly sets env.owner_user_id (highest priority). It is // resolved through resolveUserIdUuid like every other identity input — // a raw username or garbage value used to be stored verbatim, silently // mismatching the Web UI's owner_user_id === users.id visibility check. // Authorization: only an admin API key may register on behalf of another // user; a personal token may only claim itself. let ownerUserId: string | null if (headerUserId) { const resolved = resolveUserIdUuid(db, headerUserId) if (!resolved) { return c.json( { error: { type: 'bad_request', message: `X-User-Id "${headerUserId}" does not match any user. ` + 'Use the usr_* ID shown in Web UI → Settings, or set ' + 'SALUZI_BRIDGE_USERNAME instead.', }, }, 400, ) } if (!isApiAdmin && resolved !== callerId) { return c.json( { error: { type: 'forbidden', message: 'Cannot register environment on behalf of another user', }, }, 403, ) } ownerUserId = resolved } else { // Auto-claim from the authenticated identity (rct_* token → UUID, // API key + X-Username → resolved username). Unresolvable → unowned // env, handled by the claim flow below. ownerUserId = callerId } // Idempotent re-registration gate: reattaching to an existing environment // requires admin, ownership, or an unowned env. Without this, any // authenticated worker could flip someone else's env active, overwrite // its identity fields, and start pulling its work items. const reuseEnvId = typeof body.environment_id === 'string' && body.environment_id ? body.environment_id : undefined if (reuseEnvId) { const existing = storeGetEnvironment(reuseEnvId) if (existing && existing.status !== 'deregistered') { const existingOwnership = storeGetEnvironmentOwnership(reuseEnvId) if ( existingOwnership?.ownerUserId && !isApiAdmin && existingOwnership.ownerUserId !== ownerUserId ) { return c.json( { error: { type: 'forbidden', message: 'Cannot reattach to an environment owned by another user', }, }, 403, ) } } } // Validate team if X-Team-Id is provided if (teamId) { const check = validateTeamBinding(db, teamId, { id: callerId, rawIdentity: userId ?? null, isApiAdmin, }) if (!check.ok) { return c.json( { error: { type: check.errorType, message: check.message } }, check.status, ) } if (check.audit) { console.log(`[audit] ${check.audit}`) } } // Single-user mode (`slz rcs one`): every worker belongs to the sole // admin account. Workers register with just the API key (no X-User-Id, // no X-Username) — instead of falling into the claim flow below, the // env is owned by the single admin immediately. Local convenience: // the server binds 127.0.0.1, so the API key is the only credential. if (config.singleUser && !ownerUserId && !teamId) { ownerUserId = getSingleUserAdminUuid(db) } // If neither X-User-Id nor the resolved userId yields an owner (or the // value is unresolvable), and X-Team-Id is also absent, the env is // "unowned" — a claim_token is generated and returned so the worker can // print a /code/claim/ URL for the first logged-in user to claim // ownership. const needsClaim = !ownerUserId && !teamId const claimToken = needsClaim ? `clm_${randomUUID().replace(/-/g, '')}` : null const claimExpiresAt = claimToken ? new Date(Date.now() + 24 * 60 * 60 * 1000) : null const result = registerEnvironment({ ...body, username, // Peer address captured at registration — surfaced in the Web UI's // environment list so a machine is identifiable beyond its hostname. ipAddress: getClientIp(c), ownerUserId, teamId: teamId || null, claimToken, claimExpiresAt, // Session Attach wait mode: worker registered without creating a session, // polling for the Web UI to bind one (surfaces as attach_waiting). session_mode: typeof body.session_mode === 'string' ? body.session_mode : null, }) // Link environment to team if X-Team-Id was provided if (teamId) { try { const link = db .query( 'INSERT OR IGNORE INTO team_environments (team_id, environment_id) VALUES ($teamId, $envId)', ) .run({ $teamId: teamId, $envId: result.environment_id }) // ACP reuse creates its session before this link exists, so the // session's team binding is missing on first link. Backfill — gated // on a fresh link so an explicit unlink isn't silently reverted. if (link.changes > 0) { storeBindEnvSessionsToTeam(result.environment_id, teamId) } } catch (err) { console.error('[bridge] DB error during team-environment link:', err) return c.json({ error: 'Database unavailable' }, 503) } } // Append claim info to response so worker can print the claim URL. // Worker reads `claim_url` and prints it to terminal; first logged-in // user to visit claims the env. A reattach that continued an existing // claim returns the CONTINUED token (persisted in the DB) — it wins over // the locally minted one, which the service layer did not store. const responseClaimToken = result.claim_token ?? claimToken if (responseClaimToken) { const host = c.req.header('host') || '' const proto = c.req.header('x-forwarded-proto') || 'http' const claimUrl = host ? `${proto}://${host}/code/claim/${responseClaimToken}` : `/code/claim/${responseClaimToken}` return c.json( { ...result, claim_token: responseClaimToken, claim_url: claimUrl }, 200, ) } return c.json(result, 200) }) /** GET /v1/environments/:id/assignment — Session Attach wait-mode poll. * A worker registered with session_mode:'attach' polls this endpoint while * waiting for the Web UI to bind a session (POST /v1/sessions/:id/attach). * Returns the first open, non-ACP session on the environment, or * assigned:false to keep waiting. Long-polling is unnecessary — the worker * already runs a poll loop cadence for work items. * Access: the env owner (the polling worker itself) or an admin. */ app.get('/:id/assignment', acceptCliHeaders, bridgeAuth, async c => { const envId = c.req.param('id')! const env = storeGetEnvironment(envId) // 'disconnected' is NOT a 404 here: the ownership gate below authorizes the // caller first, then touchEnvironmentActivity reactivates the env — a live // wait-mode worker polling a monitor-flipped env recovers instead of // dead-waiting on swallowed 404s for its 24h deadline. Deregistered is // terminal. if (!env || env.status === 'deregistered') { return c.json( { error: { type: 'not_found', message: 'Environment not found' } }, 404, ) } // Ownership gate: assignment discloses the env's bound session AND doubles // as its liveness signal (touchEnvironmentActivity below) — both are // restricted to the env owner (the wait-mode worker polls under the same // identity it registered with) and admins. Unowned envs (claim pending) // stay open: nothing is bound yet, so there is nothing to disclose or keep // alive. const caller = resolveAttachCaller(c) if (caller.dbUnavailable) { return c.json( { error: { type: 'database_unavailable', message: 'Database unavailable', }, }, 503, ) } let ownerUserId: string | null = null try { ownerUserId = storeGetEnvironmentOwnership(envId)?.ownerUserId ?? null } catch (err) { console.error('[bridge] DB error during assignment ownership lookup:', err) return c.json( { error: { type: 'database_unavailable', message: 'Database unavailable', }, }, 503, ) } if (ownerUserId && !caller.isApiAdmin && caller.uuid !== ownerUserId) { return c.json( { error: { type: 'forbidden', message: 'Not allowed to poll this environment', }, }, 403, ) } // The attach-wait worker has no work item in flight, so the work-poll // route never refreshes its heartbeat. This poll IS its liveness signal: // without touching lastPollAt the disconnect monitor flips the env to // disconnected after the idle timeout and the CLI silently spins until its // 24h deadline (P0-2). touchEnvironmentActivity also reactivates an env the // monitor already flipped (runs only after the gate — a 403 must not keep // a dead env looking alive). touchEnvironmentActivity(envId) const assigned = storeListSessionsByEnvironment(envId) .filter(s => !isSessionClosedStatus(s.status)) .filter(s => s.source !== 'acp') .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0] if (!assigned) { return c.json({ assigned: false }, 200) } return c.json( { assigned: true, session_id: assigned.id, title: assigned.title, status: assigned.status, }, 200, ) }) /** DELETE /v1/environments/bridge/:id — Deregister */ app.delete('/bridge/:id', acceptCliHeaders, apiKeyAuth, async c => { const envId = c.req.param('id')! deregisterEnvironment(envId) return c.json({ status: 'ok' }, 200) }) /** POST /v1/environments/:id/bridge/reconnect — Reconnect */ app.post('/:id/bridge/reconnect', acceptCliHeaders, apiKeyAuth, async c => { const envId = c.req.param('id')! reconnectEnvironment(envId) const { reconnectWorkForEnvironment } = await import( '../../services/work-dispatch' ) await reconnectWorkForEnvironment(envId) return c.json({ status: 'ok' }, 200) }) export default app