import { log, error as logError } from '../../logger' import { Hono } from 'hono' import { archiveSession, canManageSession, createSession, getSession, isSessionClosedStatus, resolveExistingSessionId, updateSessionTitle, } from '../../services/session' import { createWorkItem } from '../../services/work-dispatch' import { publishSessionEvent } from '../../services/transport' import { ingestBridgeMessage } from '../../transport/ws-handler' import { loadPersistedEvents } from '../../services/event-persistence' import { getEventBus } from '../../transport/event-bus' import { touchEnvironmentActivity } from '../../services/environment' import { acceptCliHeaders, apiKeyAuth } from '../../auth/middleware' import { bridgeAuth, resolveAttachCaller, type AttachCaller, } from '../../auth/bridge-auth' import { getDb } from '../../db/sqlite' import { storeBindSession, storeConsumeAttachCode, storeGetEnvironment, storeGetEnvironmentOwnership, storeGetActiveWorkItemBySession, storeListSessions, storeListSessionsByEnvironment, storeRebindSessionEnvironment, type SessionRecord, } from '../../store' const app = new Hono() // --------------------------------------------------------------------------- // Session Attach — bind an existing session to a CLI-registered environment // --------------------------------------------------------------------------- /** 503 body shared by every attach-family route on a DB outage. */ function dbUnavailable(c: import('hono').Context): Response { return c.json( { error: { type: 'database_unavailable', message: 'Database unavailable', }, }, 503, ) } /** * Management check for attach endpoints. Returns an error Response, or null * when the caller may manage the session: * - rct (SQLite) or in-memory identity → must resolve to a user with manage * rights (canManageSession: direct owner, team owner/admin, system admin) * - bare admin API key (no identity) → allowed with an audit trail * (RCS_API_KEYS are admin credentials — mirrors validateTeamBinding) */ function ensureAttachAccess( c: import('hono').Context, caller: AttachCaller, sessionId: string, ): Response | null { if (caller.uuid) { if (!canManageSession(sessionId, caller.uuid, getDb())) { return c.json( { error: { type: 'forbidden', message: 'Not allowed to manage this session', }, }, 403, ) } return null } if (!caller.hasIdentity && caller.isApiAdmin) { console.log(`[audit] Bare admin API key attached session ${sessionId}`) return null } return c.json( { error: { type: caller.hasIdentity ? 'forbidden' : 'unauthorized', message: caller.hasIdentity ? 'Identity does not resolve to a user' : 'User identity required to attach sessions', }, }, caller.hasIdentity ? 403 : 401, ) } /** * Occupancy check shared by POST /:id/attach and GET /attachable. * A session is occupied when: * 1. A non-completed work item exists on a DIFFERENT, STILL-ACTIVE * environment (a live worker holds the lease). A work item on a * dead/deregistered env does NOT occupy: a crashed attach CLI's acked * item would otherwise block re-attach forever (deregisterEnvironment * completes that env's open items too, but a kill -9 that skips the * deregister leaves the item behind until the server restarts — the * env-status check is the recovery path). * 2. No work item remains but the session is mid-turn (running / * requires_action) on a live, active, non-ACP environment. * An active work item on the TARGET environment is not occupied — that is * the idempotent re-entry path (CLI retry after a network blip). */ function isSessionOccupied( sessionId: string, targetEnvId: string | null, ): boolean { const active = storeGetActiveWorkItemBySession(sessionId) if (active) { if (active.environmentId === targetEnvId) return false const holdingEnv = storeGetEnvironment(active.environmentId) // No env record / not active → the lease holder is gone; the session is // free to attach. if (!holdingEnv || holdingEnv.status !== 'active') return false return true } const session = getSession(sessionId) if (!session) return false if (session.status !== 'running' && session.status !== 'requires_action') { return false } if (!session.environment_id || session.environment_id === targetEnvId) { return false } const curEnv = storeGetEnvironment(session.environment_id) return !!curEnv && curEnv.status === 'active' && curEnv.workerType !== 'acp' } /** Shape returned by GET /attachable and consumed by the CLI picker. */ function toAttachableEntry(session: SessionRecord) { return { id: session.id, title: session.title, status: session.status, source: session.source, environment_id: session.environmentId, updated_at: session.updatedAt.getTime() / 1000, busy: isSessionOccupied(session.id, null), } } /** POST /v1/sessions — Create session. * Used by replBridge/ACP workers to auto-create their initial session. * Session ownership: user owner = env.owner_user_id, team owner = env.team_id * (auto-inherited). If env has no owner_user_id yet (claim flow pending), * returns 409 so the worker can retry after claim completes. */ app.post('/', acceptCliHeaders, apiKeyAuth, async c => { const body = await c.req.json() const username = c.get('userId') // Worker liveness: this route is the claim-wait loop's only traffic (an // unowned env retries POST /v1/sessions every 5s until the claim URL is // opened, up to 24h). Without touching the env here the disconnect monitor // flips it to 'disconnected' after RCS_DISCONNECT_TIMEOUT, and when the // claim finally lands the session is created but createWorkItem rejects // the non-active env — a session that exists yet never receives work, so // the CLI polls 204s forever and never connects. Touch BEFORE the unowned // 409 so the retry loop itself keeps the env alive; touchEnvironmentActivity // also reactivates an env the monitor already flipped. if (typeof body.environment_id === 'string' && body.environment_id) { touchEnvironmentActivity(body.environment_id) } // Resolve env ownership to bind session_owners. let envOwnerUserId: string | null = null let envTeamId: string | null = null if (body.environment_id) { const ownership = storeGetEnvironmentOwnership(body.environment_id) if (ownership) { envOwnerUserId = ownership.ownerUserId envTeamId = ownership.teamId // Claim flow pending: env exists but has no user owner yet. Worker // should retry after claim completes (Q4 = option A). if (!ownership.ownerUserId) { return c.json( { error: { type: 'environment_unowned', message: 'Environment has no owner yet; claim it via the printed URL before creating sessions', }, }, 409, ) } } } const session = createSession({ ...body, username, visibility: envTeamId ? 'team' : 'private', }) // Write session_owners: team owner inherited from env, user owner = env owner. // This is the key fix for the "not your sessions" bug — previously /v1/sessions // only set sessions.username, never wrote session_owners, so the Web UI list // (which filters by session_owners) never showed these sessions. if (envTeamId) { storeBindSession(session.id, envTeamId, 'team') } if (envOwnerUserId) { storeBindSession(session.id, envOwnerUserId, 'user') } // Create work item if environment is specified if (body.environment_id) { try { await createWorkItem(body.environment_id, session.id) } catch (err) { logError(`[RCS] Failed to create work item: ${(err as Error).message}`) } } // Publish initial events if provided if (body.events && Array.isArray(body.events)) { for (const evt of body.events) { // CCR wire format { type: 'event', data: SDKMessage } — unwrap and run // the inner SDK message through the standard ingest path (event-type // derivation + payload normalization, e.g. system/init's // slash_command_details / remote_capabilities preservation). Publishing // the raw wrapper as-is yields an opaque 'event'-typed entry no // consumer recognizes. const data = evt && typeof evt === 'object' && evt.type === 'event' && evt.data && typeof evt.data === 'object' && typeof evt.data.type === 'string' ? evt.data : null if (data) { ingestBridgeMessage(session.id, data) } else { publishSessionEvent(session.id, evt.type || 'init', evt, 'outbound') } } } return c.json(session, 200) }) /** GET /v1/sessions/attachable — List sessions the caller can attach to. * Must be registered BEFORE GET /:id so "attachable" is not captured as an * id. Visibility = canManageSession (direct owner, team owner/admin, system * admin); bare admin API key sees all. ACP sessions are excluded — their * transport is bound to the acp-link WS and cannot be driven by a bridge * worker. */ app.get('/attachable', bridgeAuth, async c => { const caller = resolveAttachCaller(c) if (caller.dbUnavailable) { return dbUnavailable(c) } // An explicit-but-unresolvable identity (e.g. admin API key + // X-Username matching no user) is a misconfiguration, not "see // everything": 403, mirroring POST /:id/attach's ensureAttachAccess — // the listing previously was the laxer of the two. if (caller.uuid === null && caller.hasIdentity) { return c.json( { error: { type: 'forbidden', message: 'Identity does not resolve to a user', }, }, 403, ) } if (caller.uuid === null && !caller.hasIdentity && !caller.isApiAdmin) { return c.json( { error: { type: 'unauthorized', message: 'User identity required' } }, 401, ) } const uuid = caller.uuid const open = storeListSessions() .filter(s => !isSessionClosedStatus(s.status)) .filter(s => s.source !== 'acp') // Bare admin API key (uuid null) sees all; an identity sees only what it // can manage. getDb() is touched only when the filter actually runs. let visible = open if (uuid !== null) { const db = getDb() visible = open.filter(s => canManageSession(s.id, uuid, db)) } return c.json( visible.map(s => toAttachableEntry(s)), 200, ) }) /** POST /v1/sessions/:id/attach — Bind an existing session to a CLI * environment (Session Attach). Re-points session.environment_id (ownership * in session_owners is NEVER touched) and dispatches a work item so the * polling worker picks the session up through the standard work path. * Idempotent: an active work item on the same environment returns 200 with * the existing binding instead of 409 (CLI network retries). */ app.post('/:id/attach', bridgeAuth, async c => { const caller = resolveAttachCaller(c) const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const body = await c.req.json().catch(() => ({}) as Record) const envId = typeof body.environment_id === 'string' ? body.environment_id : undefined if (!envId) { return c.json( { error: { type: 'bad_request', message: 'environment_id is required', }, }, 400, ) } return performAttach(c, { sessionId, envId, caller, skipAccessCheck: false, }) }) /** * Core attach logic shared by POST /:id/attach (identity-based) and * POST /attach-code/exchange (code-based — the one-time code replaces the * caller's own manage rights, everything else is identical). */ async function performAttach( c: import('hono').Context, opts: { sessionId: string envId: string caller: AttachCaller skipAccessCheck: boolean }, ): Promise { const { sessionId, envId, caller, skipAccessCheck } = opts if (caller.dbUnavailable) { return dbUnavailable(c) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } // Idempotent re-entry BEFORE session-manage authorization: a CLI retrying // after a network blip re-presents the same session+env pair — returning // the existing binding is not a new grant, so it must not depend on the // caller still holding manage rights (e.g. a doReconnect re-bind where the // bound session was assigned by a team admin, or an expired share). The // check only matches an existing work item on the SAME environment — no // state is created. // // Still gated on environment ownership (or admin): the CLI re-entering is // the env's own worker, so ownership always holds for legitimate retries, // while a random authenticated caller who merely knows session+env IDs // must not be able to probe the binding (the response echoes the work // item id). Non-owners fall through to the full checks below, which // reject them. const activeItem = storeGetActiveWorkItemBySession(sessionId) if (activeItem && activeItem.environmentId === envId) { let idempotentOwner = false try { const ownership = storeGetEnvironmentOwnership(envId) idempotentOwner = caller.isApiAdmin || (caller.uuid !== null && ownership?.ownerUserId === caller.uuid) } catch (err) { logError( `[RCS] Ownership lookup failed during attach re-entry (session=${sessionId} env=${envId}): ${err}`, ) return dbUnavailable(c) } if (idempotentOwner) { log( `[RCS] Attach idempotent re-entry: session=${sessionId} env=${envId} work=${activeItem.id}`, ) return c.json( { status: 'attached', session_id: sessionId, work_item_id: activeItem.id, rebind: false, idempotent: true, }, 200, ) } } // Authorization: identity-based attach requires manage rights (G9). The // code-based path skips this — presenting a valid unconsumed code IS the // authorization (the code was minted by a session manager). if (!skipAccessCheck) { const accessError = ensureAttachAccess(c, caller, sessionId) if (accessError) return accessError } if (isSessionClosedStatus(session.status)) { return c.json( { error: { type: 'session_closed', message: `Session is ${session.status}`, }, }, 409, ) } // ACP sessions are transport-bound to the acp-link WebSocket. if (session.source === 'acp') { return c.json( { error: { type: 'acp_session', message: 'ACP sessions cannot be attached to a bridge worker', }, }, 409, ) } const env = storeGetEnvironment(envId) if (!env || env.status === 'deregistered') { return c.json( { error: { type: 'not_found', message: 'Environment not found' } }, 404, ) } if (env.status !== 'active') { return c.json( { error: { type: 'environment_inactive', message: `Environment is ${env.status}`, }, }, 409, ) } if (env.workerType === 'acp') { return c.json( { error: { type: 'acp_environment', message: 'ACP environments manage their own sessions', }, }, 409, ) } // Environment ownership: the attaching worker must be driving an env it // owns (the env it just registered). Admin may attach on behalf. const ownership = storeGetEnvironmentOwnership(envId) if (!ownership?.ownerUserId) { // The documented self-hosted worker setup authenticates with a bare // RCS_API_KEYS admin key (SALUZI_BRIDGE_OAUTH_TOKEN, no // SALUZI_BRIDGE_USERNAME) — its env is unowned until claimed, so a hard // 409 here made `/rc --attach ` fail out of the box with a claim URL // the direct-attach path never prints. Bare admin keys are trusted // credentials (ensureAttachAccess already audited their session-manage // bypass) — allow the bind. Identity callers still get the claim-flow // guidance (the wait-mode CLI prints the URL). if (!caller.isApiAdmin || caller.hasIdentity) { return c.json( { error: { type: 'environment_unowned', message: 'Environment has no owner yet; claim it via the printed URL before attaching sessions', }, }, 409, ) } log( `[audit] Bare admin API key attached session ${sessionId} to unowned env ${envId}`, ) } // Optional chain: the bare-admin fallthrough above leaves ownership // possibly-null/unowned here — but isApiAdmin is true on that path, so the // short-circuit keeps the semantics identical. if (!caller.isApiAdmin && ownership?.ownerUserId !== caller.uuid) { return c.json( { error: { type: 'forbidden', message: 'Cannot attach to an environment owned by another user', }, }, 403, ) } // In-process (replBridge) workers serve exactly one session at a time. if (env.workerType === 'repl') { const openOthers = storeListSessionsByEnvironment(envId).filter( s => s.id !== sessionId && !isSessionClosedStatus(s.status), ) if (openOthers.length > 0) { return c.json( { error: { type: 'worker_at_capacity', message: '该 worker 为 in-process 模式(slz 默认),只支持单会话。请用 `slz rc` 启动 spawn 模式 worker 支持多会话。', }, }, 409, ) } } // Occupancy: a live worker elsewhere holds the session. Same-environment // re-entry was already handled above (before authorization). if (isSessionOccupied(sessionId, envId)) { return c.json( { error: { type: 'session_busy', message: 'Session is being driven by another worker', }, }, 409, ) } const rebind = session.environment_id !== envId if (rebind) { storeRebindSessionEnvironment(sessionId, envId) } let workItemId: string try { workItemId = await createWorkItem(envId, sessionId) } catch (err) { // Roll the rebind back so a failed dispatch doesn't leave the session // pointing at an environment that never picked it up — including back to // "no environment" when the session had none. A rollback failure must // not mask the original dispatch error. if (rebind) { try { storeRebindSessionEnvironment(sessionId, session.environment_id) } catch (rollbackErr) { logError( `[RCS] Attach rollback failed for session ${sessionId}: ${rollbackErr}`, ) } } return c.json( { error: { type: 'work_dispatch_failed', message: (err as Error).message, }, }, 409, ) } log( `[RCS] Session ${sessionId} attached to env=${envId} (rebind=${rebind} work=${workItemId})`, ) return c.json( { status: 'attached', session_id: sessionId, work_item_id: workItemId, rebind, }, 200, ) } /** POST /v1/sessions/attach-code/exchange — Redeem a one-time attach code. * The code was minted by a session manager (POST /web/sessions/:id/attach-code) * and IS the authorization: the CLI holding it needs no manage rights of * its own (typical for shared admin API keys that can't enumerate * sessions). Single-use — the code is consumed on success AND on any * validation failure after redemption to prevent replay probing. */ app.post('/attach-code/exchange', bridgeAuth, async c => { const caller = resolveAttachCaller(c) const body = await c.req.json().catch(() => ({}) as Record) const code = typeof body.code === 'string' ? body.code.trim() : '' const envId = typeof body.environment_id === 'string' ? body.environment_id : undefined if (!code || !envId) { return c.json( { error: { type: 'bad_request', message: 'code and environment_id are required', }, }, 400, ) } const record = storeConsumeAttachCode(code) if (!record) { return c.json( { error: { type: 'invalid_attach_code', message: 'Attach code is unknown, expired, or already used', }, }, 403, ) } return performAttach(c, { sessionId: record.sessionId, envId, caller, skipAccessCheck: true, }) }) /** GET /v1/sessions/:id/events — Historical events for session (bridge auth). * CLI-side hydration for Session Attach: merges the durable SQLite log with * the in-memory bus window (same merge as the web /history route), deduped * by id, chronological. * * Access: session management rights (canManageSession), a bare admin API * key, OR ownership of the environment the session is currently bound to. * The env-owner relaxation is what makes wait-mode hydration work: a * team-admin binds a session to someone else's CLI env, and that CLI must * read the history to hydrate — it already sees the live traffic through * the work-item ingress token, so refusing only the history would gate the * wrong layer (P0-1). */ app.get('/:id/events', bridgeAuth, async c => { const caller = resolveAttachCaller(c) if (caller.dbUnavailable) { return dbUnavailable(c) } const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const db = getDb() const manages = (caller.uuid !== null && canManageSession(sessionId, caller.uuid, db)) || (!caller.hasIdentity && caller.isApiAdmin) let envOwned = false if ( !manages && caller.uuid !== null && session.environment_id !== null && session.environment_id !== undefined ) { const ownership = storeGetEnvironmentOwnership(session.environment_id) envOwned = ownership?.ownerUserId === caller.uuid } if (!manages && !envOwned) { return c.json( { error: { type: caller.hasIdentity ? 'forbidden' : 'unauthorized', message: caller.hasIdentity ? 'Not allowed to read this session' : 'User identity required to read session events', }, }, caller.hasIdentity ? 403 : 401, ) } const persisted = loadPersistedEvents(sessionId) const inMemory = getEventBus(sessionId).getEventsSince(0) const byId = new Map() for (const event of persisted) byId.set(event.id, event) for (const event of inMemory) { if (!byId.has(event.id)) byId.set(event.id, event) } const events = [...byId.values()].sort( (a, b) => a.createdAt - b.createdAt || a.seqNum - b.seqNum, ) // models_state fallback — mirrors the web history route so a CLI attaching // right after a /clear still receives the model selector snapshot. if (!events.some(e => e.type === 'models_state')) { const snapshot = getEventBus(sessionId).modelsStateSnapshot if (snapshot) { const lastCreated = events[events.length - 1]?.createdAt ?? Date.now() events.push({ id: `models_state_snapshot_${sessionId}`, sessionId, seqNum: 0, type: 'models_state', payload: { models_state: snapshot }, direction: 'inbound', createdAt: lastCreated + 1, }) } } return c.json({ events }, 200) }) /** GET /v1/sessions/:id — Get session */ app.get('/:id', acceptCliHeaders, apiKeyAuth, async c => { const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } return c.json(session, 200) }) /** PATCH /v1/sessions/:id — Update session title */ app.patch('/:id', acceptCliHeaders, apiKeyAuth, async c => { const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const existing = getSession(sessionId) if (!existing) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const body = await c.req.json() if (body.title) { updateSessionTitle(sessionId, body.title) } const session = getSession(sessionId) return c.json(session, 200) }) /** POST /v1/sessions/:id/archive — Archive session */ app.post('/:id/archive', acceptCliHeaders, apiKeyAuth, async c => { const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } try { archiveSession(sessionId) } catch { return c.json({ status: 'ok' }, 409) } return c.json({ status: 'ok' }, 200) }) /** POST /v1/sessions/:id/events — Send event to session */ app.post('/:id/events', acceptCliHeaders, apiKeyAuth, async c => { const sessionId = resolveExistingSessionId(c.req.param('id')!) ?? c.req.param('id')! const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const body = await c.req.json() const events = body.events ? Array.isArray(body.events) ? body.events : [body.events] : Array.isArray(body) ? body : [body] const published = [] for (const evt of events) { const result = publishSessionEvent( sessionId, evt.type || 'message', evt, 'inbound', ) published.push(result) } return c.json({ status: 'ok', events: published.length }, 200) }) export default app