Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(runtime): revoke tokens after tenant moves (#128)
OKNOTOKb7ca1487aa51
diff --git a/server/src/__integration__/agent-steer.test.ts b/server/src/__integration__/agent-steer.test.tsindex 94317c8..8f20503 100644--- a/server/src/__integration__/agent-steer.test.ts+++ b/server/src/__integration__/agent-steer.test.ts@@ -355,6 +355,7 @@ function makeFakeSseResponse(): Response & {setHeader: (k: string, v: string) => { headers[k] = v },flushHeaders: () => { /* noop */ },write: (s: string) => { if (!fake.closed) written.push(s); return true },+ end: () => { if (!fake.closed) { fake.closed = true; ee.emit('close') } },triggerClose: () => { fake.closed = true; ee.emit('close') },}) as unknown as Response & { written: string[]; closed: boolean; triggerClose: () => void }return fake@@ -421,6 +422,28 @@ test('[integration] wire: deliverSteer publishes via Redis pubsub → wake-bus Sres.triggerClose()})+test('[integration] wake stream revalidates authorization before delivering an event', async () => {+ const agentId = `agent-${randomUUID().slice(0, 8)}`+ const res = makeFakeSseResponse()+ let checks = 0+ await attachWakeStream(agentId, res, {+ authorize: async () => { checks += 1; return false },+ })+ await new Promise((r) => setTimeout(r, 100))++ await deliverWake(agentId, {+ kind: 'wake',+ reason: 'message.new',+ conversationId: 'new-tenant-conversation',+ })+ await new Promise((r) => setTimeout(r, 100))++ const frames = parseSseFrames(res.written)+ assert.equal(checks, 1)+ assert.equal(res.closed, true)+ assert.equal(frames.some((frame) => frame.event === 'wake'), false)+})+test('[integration] wire: scheduler.wakeAgent routes BOTH wake AND steer when agent is busy', async () => {const agentId = `agent-${randomUUID().slice(0, 8)}`const res = makeFakeSseResponse()diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.tsindex 0a24421..d36d4e5 100644--- a/server/src/__integration__/runtime-server.test.ts+++ b/server/src/__integration__/runtime-server.test.ts@@ -231,7 +231,7 @@ test('[integration] runtime: /context enforces tenant and conversation membershi)})-test('[integration] runtime: /context rejects a stale production token after tenant reassignment', async () => {+test('[integration] runtime: every route rejects a stale production token after tenant reassignment', async () => {const originalTenant = await seedAgent()const currentTenant = await seedAgent()const staleToken = await mintAssignedAgentRuntimeToken(originalTenant)@@ -264,16 +264,29 @@ test('[integration] runtime: /context rejects a stale production token after ten)assert.deepEqual(currentAgentRows, [{ company_id: currentTenant.companyId }])- // The pre-fix query joined the requesting agent to the conversation's- // company instead of the JWT company. It therefore accepted this current- // tenant-B membership even though the still-valid token is pinned to A.- const r = await call('/runtime/context', {- token: staleToken,- body: { conversationIds: [crossTenantId] },- })+ // Exercise both current-tenant reads and a mutation. The auth middleware is+ // mounted before the entire runtime router, so each must fail before its+ // handler can observe or alter the reassigned agent's tenant-B state.+ for (const request of [+ { path: '/runtime/context', body: { conversationIds: [crossTenantId] } },+ { path: '/runtime/inbox', method: 'GET' },+ { path: '/runtime/persona', method: 'GET' },+ { path: '/runtime/status', body: { status: 'working' } },+ ]) {+ const r = await call(request.path, {+ method: request.method,+ token: staleToken,+ body: request.body,+ })+ assert.equal(r.status, 403, request.path)+ assert.match(String(r.body?.error ?? ''), /token tenant/i, request.path)+ }- assert.equal(r.status, 200)- assert.deepEqual(r.body?.rows ?? [], [])+ const { rows: statusRows } = await pool.query<{ status: string }>(+ `SELECT status FROM participants WHERE id = $1`,+ [originalTenant.agentId],+ )+ assert.deepEqual(statusRows, [{ status: 'avail' }])})test('[integration] runtime: /inbox-triage/payload rejects a stale token before loading the new tenant inbox', async () => {diff --git a/server/src/agents/runtime/authorization.ts b/server/src/agents/runtime/authorization.tsnew file mode 100644index 0000000..dfa8d97--- /dev/null+++ b/server/src/agents/runtime/authorization.ts@@ -0,0 +1,21 @@+import { pool } from '../../db/pool.js'++/**+ * A signed runtime token captures the agent's tenant at mint time. Resolve the+ * live participant row as the authorization source of truth so moving or+ * offboarding an agent revokes every previously minted token.+ */+export async function isRuntimeAgentAuthorized(+ agentId: string,+ companyId: string | null,+): Promise<boolean> {+ if (!companyId) return false+ const { rowCount } = await pool.query(+ `SELECT 1 FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ LIMIT 1`,+ [agentId, companyId],+ )+ return rowCount === 1+}diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex ba41963..b01339a 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -23,6 +23,7 @@ import { gatherAgentAgenda, classifyAgendaActionable, renderAgendaBrief, claimStimport { consumeAgentTurnToken } from '../scheduler.js'import { touchAgentRun, recordTriage } from '../observability.js'import { normalizeByoaSource } from './byoa-source.js'+import { isRuntimeAgentAuthorized } from './authorization.js'import { buildRuntimeArgv } from './cli-argv.js'import { attachFsEndpoints } from './fs-endpoints.js'import { inprocClient } from './inproc-client.js'@@ -35,18 +36,43 @@ interface RuntimeRequest extends Request {agent?: AgentRuntimeClaims}-function authMiddleware(req: RuntimeRequest, res: Response, next: NextFunction): void {+async function authMiddleware(req: RuntimeRequest, res: Response, next: NextFunction): Promise<void> {const header = req.headers['authorization']if (!header || typeof header !== 'string' || !header.startsWith('Bearer ')) {res.status(401).json({ error: 'missing bearer token' })return}++ let claims: AgentRuntimeClaimstry {- req.agent = verifyAgentToken(header.slice('Bearer '.length).trim())- next()+ claims = verifyAgentToken(header.slice('Bearer '.length).trim())} catch (err) {res.status(401).json({ error: err instanceof Error ? err.message : 'invalid token' })+ return}++ if (!claims.companyId) {+ res.status(403).json({ error: 'companyId claim required' })+ return+ }++ try {+ // A valid signature only proves what was true when the token was minted.+ // Re-check the globally unique agent row on every request so tenant moves+ // and offboarding revoke an old daemon token immediately, across the whole+ // runtime surface rather than only on selected data-reading endpoints.+ if (!(await isRuntimeAgentAuthorized(claims.sub, claims.companyId))) {+ res.status(403).json({ error: 'agent does not belong to token tenant' })+ return+ }+ } catch (err) {+ console.error('[runtime] token tenant validation failed', err instanceof Error ? err.message : err)+ res.status(503).json({ error: 'runtime authorization unavailable' })+ return+ }++ req.agent = claims+ next()}function withAgent(@@ -71,7 +97,11 @@ runtimeRouter.use(authMiddleware as never)// ─── wake stream: server pushes events to the agent's long-running pod ─runtimeRouter.get('/wake-stream', withAgent(async (c, _req, res) => {- await attachWakeStream(c.sub, res)+ await attachWakeStream(c.sub, res, {+ // The HTTP middleware validates at connection time. Re-check before every+ // event as well because this response can remain open across a tenant move.+ authorize: () => isRuntimeAgentAuthorized(c.sub, c.companyId),+ })// Don't end — attachWakeStream keeps the response open until the// client disconnects.}))diff --git a/server/src/agents/runtime/wake-bus.ts b/server/src/agents/runtime/wake-bus.tsindex 2927982..bb82115 100644--- a/server/src/agents/runtime/wake-bus.ts+++ b/server/src/agents/runtime/wake-bus.ts@@ -135,6 +135,12 @@ interface Subscriber {res: Response/** Set when the response closes — used to drop from the bus. */closed: boolean+ /** Optional live authorization check for long-lived runtime streams. */+ authorize?: () => Promise<boolean>+ /** Preserve event order while authorization checks are asynchronous. */+ delivery: Promise<void>+ pendingDeliveries: number+ revoke(): void}const subs = new Map<string, Set<Subscriber>>()@@ -144,8 +150,23 @@ const subs = new Map<string, Set<Subscriber>>()// under a wake flood that grows unbounded → OOM. A backed-up subscriber gets// dropped (it reconnects and re-drains the inbox, which is durable).const SSE_MAX_BUFFERED_BYTES = 1 * 1024 * 1024 // 1 MB+// An authorization database stall must not turn the per-subscriber promise+// chain into an unbounded in-memory wake queue. The inbox is the durable queue;+// reconnecting after this bound is safer than retaining more event payloads.+const SSE_MAX_PENDING_DELIVERIES = 64-function deliverTo(s: Subscriber, evt: WakeEvent): void {+async function deliverTo(s: Subscriber, evt: WakeEvent): Promise<void> {+ if (s.closed) return+ if (s.authorize) {+ try {+ if (!(await s.authorize())) { s.revoke(); return }+ } catch {+ // Authorization is fail-closed. The durable inbox lets a newly minted,+ // correctly scoped daemon recover the wake after it reconnects.+ s.revoke()+ return+ }+ }if (s.closed) return// Backpressure guard (OOM fix): if the socket's write queue is backed up the// client isn't keeping up — end the stream to reclaim the buffered memory@@ -182,7 +203,17 @@ function installRedisSubscriber(): void {if (!set || set.size === 0) returnlet evt: WakeEventtry { evt = JSON.parse(raw) as WakeEvent } catch { return }- for (const s of set) deliverTo(s, evt)+ for (const s of set) {+ if (s.pendingDeliveries >= SSE_MAX_PENDING_DELIVERIES) {+ s.revoke()+ continue+ }+ s.pendingDeliveries += 1+ s.delivery = s.delivery+ .then(() => deliverTo(s, evt))+ .catch(() => s.revoke())+ .finally(() => { s.pendingDeliveries -= 1 })+ }})}@@ -229,7 +260,11 @@ export function listLocalSubscribedAgents(): string[] {* response open. Subscribes to the per-agent Redis channel iff this* is the first local sub for that agent.*/-export async function attachWakeStream(agentId: string, res: Response): Promise<void> {+export async function attachWakeStream(+ agentId: string,+ res: Response,+ options: { authorize?: () => Promise<boolean> } = {},+): Promise<void> {installRedisSubscriber()res.setHeader('Content-Type', 'text/event-stream')@@ -241,31 +276,22 @@ export async function attachWakeStream(agentId: string, res: Response): Promise<let set = subs.get(agentId)if (!set) { set = new Set(); subs.set(agentId, set) }const isFirst = set.size === 0- const s: Subscriber = { agentId, res, closed: false }- set.add(s)-- // Subscribe to the Redis channel BEFORE we tell the Pod we're ready —- // otherwise a wake that arrives during the gap is silently dropped- // (the Pod's initial-drain catches it, but we'd rather not rely on- // that fallback when avoidable).- if (isFirst) {- await redisSub.subscribe(CH_WAKE_PREFIX + agentId)+ const s: Subscriber = {+ agentId,+ res,+ closed: false,+ authorize: options.authorize,+ delivery: Promise.resolve(),+ pendingDeliveries: 0,+ revoke: () => { /* assigned below once cleanup exists */ },}- console.log(`[wake-bus] +sub ${agentId} (${set.size} local · redis-subscribed=${isFirst})`)-- res.write(`event: ready\ndata: {"agentId":"${agentId}","at":${Date.now()}}\n\n`)-- // SSE comment ping every 25s. Clients that idle out at 30s (some- // proxies) stay alive.- const ping = setInterval(() => {- if (s.closed) return- try { res.write(`: ping ${Date.now()}\n\n`) } catch { s.closed = true }- }, 25_000)+ set.add(s)+ let ping: ReturnType<typeof setInterval> | null = nullconst cleanup = (): void => {if (s.closed && set!.has(s) === false) return // re-entrant call guards.closed = true- clearInterval(ping)+ if (ping) clearInterval(ping)set!.delete(s)const last = set!.size === 0if (last) subs.delete(agentId)@@ -280,6 +306,41 @@ export async function attachWakeStream(agentId: string, res: Response): Promise<})}}+ s.revoke = () => {+ if (s.closed) return+ try { res.end() } catch { /* ignore */ }+ cleanup()+ }res.on('close', cleanup)res.on('error', cleanup)++ // Subscribe to the Redis channel BEFORE we tell the Pod we're ready —+ // otherwise a wake that arrives during the gap is silently dropped+ // (the Pod's initial-drain catches it, but we'd rather not rely on+ // that fallback when avoidable).+ if (isFirst) {+ await redisSub.subscribe(CH_WAKE_PREFIX + agentId)+ }+ if (s.closed) return+ console.log(`[wake-bus] +sub ${agentId} (${set.size} local · redis-subscribed=${isFirst})`)++ res.write(`event: ready\ndata: {"agentId":"${agentId}","at":${Date.now()}}\n\n`)++ // SSE comment ping every 25s. Clients that idle out at 30s (some+ // proxies) stay alive.+ ping = setInterval(() => {+ if (s.closed) return+ void (async () => {+ if (s.authorize) {+ try {+ if (!(await s.authorize())) { s.revoke(); return }+ } catch {+ s.revoke()+ return+ }+ }+ try { res.write(`: ping ${Date.now()}\n\n`) } catch { s.closed = true }+ })()+ }, 25_000)+}