import type { Context, Next } from 'hono' import { apiKeyAuth, extractBearerToken } from './middleware' import { validateApiKey } from './api-key' import { resolveToken } from './token' import { resolveSessionToken } from './session' import { getDb } from '../db/sqlite' /** * Combined auth for bridge endpoints: accepts session tokens (rct_*), * in-memory issueToken tokens, or admin API keys. Also falls back to * apiKeyAuth's X-Username header support for CLI bridges. * * Extracted from routes/v1/environments.ts so the v1 sessions attach * endpoints (POST /:id/attach, GET /attachable, GET /:id/events) share the * exact same identity semantics as environment registration — attach must * resolve the caller to the same identity the env was registered under. */ export async function bridgeAuth(c: Context, next: Next) { const bearer = extractBearerToken(c) if (bearer) { // Admin API key if (validateApiKey(bearer)) { c.set('userId', c.req.header('X-Username') || c.req.query('username')) c.set('isApiAdmin', true) await next() return } // In-memory token const username = resolveToken(bearer) if (username) { c.set('userId', username) await next() return } // SQLite session token try { const db = getDb() const userId = resolveSessionToken(bearer, db) if (userId) { c.set('userId', userId) await next() return } } catch (err) { console.error('[bridge] DB error during session token resolution:', err) return c.json({ error: 'Database unavailable' }, 503) } } // Fall back to apiKeyAuth (handles X-Username + API key from body/header) return apiKeyAuth(c, next) } /** * Resolve a userId value (UUID or username) to a users.id UUID. * Returns null if no matching user exists. * * bridgeAuth's three token paths return different userId shapes: * - resolveSessionToken (rct_* SQLite token) → users.id (UUID) * - resolveToken (in-memory token) → username (string) * - validateApiKey + X-Username → X-Username header value (arbitrary string) * * Only UUIDs that exist in the users table can become env owners / session * managers, so a client-controlled X-Username value can't create an owner * for a non-existent user — resolveUserIdUuid is the safety gate. */ export function resolveUserIdUuid( db: ReturnType, value: string, ): string | null { const row = db .query( 'SELECT id FROM users WHERE id = $value OR username = $value LIMIT 1', ) .get({ $value: value }) as { id: string } | null return row?.id ?? null } /** Caller identity resolved for attach-family endpoints. */ export type AttachCaller = { /** Resolved users.id UUID — null for a bare admin API key. */ uuid: string | null isApiAdmin: boolean /** True when no identity at all was presented (bare admin API key). */ hasIdentity: boolean /** * True when the users-table lookup itself failed (DB unavailable). Routes * must return 503 BEFORE treating uuid:null as an unresolvable identity — * a DB outage must not masquerade as a 403. */ dbUnavailable: boolean } /** * Resolve the bridge caller identity for attach endpoints. * * bridgeAuth's userId may be a UUID (rct_* token), a username (in-memory * token) or an arbitrary X-Username string (shared admin API key) — only * users-table UUIDs can hold session management rights, so everything goes * through resolveUserIdUuid (G9: the API layer must self-enforce * canManageSession; the ingress WS accepting a global API key is not a * boundary we may lean on). */ export function resolveAttachCaller(c: Context): AttachCaller { const raw = c.get('userId') as string | undefined const isApiAdmin = (c.get('isApiAdmin') as boolean | undefined) ?? false if (!raw) { return { uuid: null, isApiAdmin, hasIdentity: false, dbUnavailable: false } } try { return { uuid: resolveUserIdUuid(getDb(), raw), isApiAdmin, hasIdentity: true, dbUnavailable: false, } } catch (err) { console.error('[bridge] DB error resolving attach caller identity:', err) return { uuid: null, isApiAdmin, hasIdentity: true, dbUnavailable: true } } }