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): enforce JWT tenant on context reads (#86)
OKNOTOK075afbb535c3
diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.tsindex 45ba1bc..b4282b8 100644--- a/server/src/__integration__/runtime-server.test.ts+++ b/server/src/__integration__/runtime-server.test.ts@@ -154,6 +154,14 @@ test('[integration] runtime: expired token → 401', async () => {assert.match(String(r.body?.error ?? ''), /expired/i)})+test('[integration] runtime: /context requires a tenant-pinned token', async () => {+ const { agentId } = await seedAgent()+ const token = signAgentToken({ agentId, companyId: null })+ const r = await call('/runtime/context', { token, body: { conversationIds: [] } })+ assert.equal(r.status, 403)+ assert.match(String(r.body?.error ?? ''), /companyId claim required/i)+})+test('[integration] runtime: /context enforces tenant and conversation membership', async () => {const { agentId, companyId, token } = await seedAgent()const peerId = `a-${randomUUID().slice(0, 8)}`@@ -178,8 +186,7 @@ test('[integration] runtime: /context enforces tenant and conversation membershiconst otherTenant = await seedAgent()const crossTenantId = await seedContextConversation({companyId: otherTenant.companyId,- // Deliberately include the caller's globally unique id: tenant binding- // must still reject a corrupt or forged cross-company members array.+ // Even a forged members array cannot override the JWT tenant boundary.members: [agentId, otherTenant.agentId],authorId: otherTenant.agentId,body: 'cross-tenant-private',@@ -201,6 +208,32 @@ test('[integration] runtime: /context enforces tenant and conversation membershi)})+test('[integration] runtime: /context binds authorization to the JWT companyId', async () => {+ const claimedTenant = await seedAgent()+ const actualTenant = await seedAgent()+ const crossTenantId = await seedContextConversation({+ companyId: actualTenant.companyId,+ members: [actualTenant.agentId],+ authorId: actualTenant.agentId,+ body: 'mismatched-claim-private',+ })+ // Simulate a stale or incorrectly minted but validly signed token. The old+ // query ignored companyId and authorized solely from sub + the target row,+ // so it returned this conversation from actualTenant.+ const mismatchedToken = signAgentToken({+ agentId: actualTenant.agentId,+ companyId: claimedTenant.companyId,+ })++ const r = await call('/runtime/context', {+ token: mismatchedToken,+ body: { conversationIds: [crossTenantId] },+ })++ assert.equal(r.status, 200)+ assert.deepEqual(r.body?.rows ?? [], [])+})+// ── identity pin: agentId comes from JWT, not request body ────────────test('[integration] runtime: /runs records the JWT subject, not whatever the body claims', async () => {diff --git a/server/src/__tests__/agents-runtime-http-client.test.ts b/server/src/__tests__/agents-runtime-http-client.test.tsindex 4cee2bf..1b1ca42 100644--- a/server/src/__tests__/agents-runtime-http-client.test.ts+++ b/server/src/__tests__/agents-runtime-http-client.test.ts@@ -120,6 +120,27 @@ test('publishTyping: failure to post the typing indicator does not break the tur// ── Read-side methods MUST still throw ────────────────────────────────+test('loadContext: sends only conversation selectors because the JWT pins the tenant', async () => {+ let requestBody: unknown+ const stubFetch = ((async (_input: unknown, init?: RequestInit) => {+ requestBody = JSON.parse(String(init?.body ?? 'null'))+ return new Response(JSON.stringify({ rows: [] }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ }) as unknown) as typeof fetch+ const client = new HttpRuntimeClient({+ baseUrl: 'http://stub.invalid',+ token: 'tenant-pinned-token',+ fetchImpl: stubFetch,+ timeoutMs: 1_000,+ })++ await client.loadContext('agent-foo', 'company-from-call-site', ['convo-1'])++ assert.deepEqual(requestBody, { conversationIds: ['convo-1'] })+})+test('regression guard: loadInbox MUST still throw on fetch failure — turn cannot run without an inbox', async () => {// Symmetric defence — if someone "fixes" loadInbox to also swallow,// the turn would silently run with no inbox and the agent woulddiff --git a/server/src/agents/runtime/client.ts b/server/src/agents/runtime/client.tsindex 61cd5cb..6872b68 100644--- a/server/src/agents/runtime/client.ts+++ b/server/src/agents/runtime/client.ts@@ -211,8 +211,8 @@ export interface AgentRuntimeClient {}): Promise<MemoryRow[]>/** Per-conversation recent history for every convo with unread items.* Implementations must treat conversationIds as selectors, not proof of- * access, and enforce the agent's tenant + current membership. */- loadContext(agentId: string, conversationIds: string[]): Promise<ContextRow[]>+ * access, and enforce the authenticated tenant + current membership. */+ loadContext(agentId: string, companyId: string, conversationIds: string[]): Promise<ContextRow[]>/** Agent's feelings about people (the climate model). */loadClimate(agentId: string): Promise<ClimateRow[]>/** Index of installed skills (name + description only — progressivediff --git a/server/src/agents/runtime/http-client.ts b/server/src/agents/runtime/http-client.tsindex 45994f4..b156340 100644--- a/server/src/agents/runtime/http-client.ts+++ b/server/src/agents/runtime/http-client.ts@@ -9,10 +9,10 @@* No DB or Redis access — that's the whole point. The pod's only side* channel is the storage layer for attachment downloads (signed URLs).*- * Shape-for-shape mirror of `InProcRuntimeClient`. The agentId argument- * on every method is the SAME id baked into the JWT — endpoints ignore- * the body's agentId and use the token. We still take it as a param so- * the interface signatures match (and tests can pass it through).+ * Shape-for-shape mirror of `InProcRuntimeClient`. The agentId and companyId+ * arguments are the SAME identity baked into the JWT — endpoints ignore+ * caller-supplied identity and use the token. We still take them as params so+ * the interface signatures match (and tests can pass them through).*/import type {AgentRuntimeClient,@@ -145,7 +145,11 @@ export class HttpRuntimeClient implements AgentRuntimeClient {return out.rows}- async loadContext(_agentId: string, conversationIds: string[]): Promise<ContextRow[]> {+ async loadContext(+ _agentId: string,+ _companyId: string,+ conversationIds: string[],+ ): Promise<ContextRow[]> {const out = await this.call<{ rows: ContextRow[] }>('POST', '/context', { conversationIds })return out.rows}diff --git a/server/src/agents/runtime/inproc-client.ts b/server/src/agents/runtime/inproc-client.tsindex 4ff46cd..d8ac038 100644--- a/server/src/agents/runtime/inproc-client.ts+++ b/server/src/agents/runtime/inproc-client.ts@@ -351,7 +351,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {* agent's own past replies — real humans don't reason from a stripped* slice, so neither should agents. Reactions get pre-aggregated as a* JSON array so the prompt renderer doesn't need a second roundtrip. */- async loadContext(agentId: string, conversationIds: string[]): Promise<ContextRow[]> {+ async loadContext(agentId: string, companyId: string, conversationIds: string[]): Promise<ContextRow[]> {if (conversationIds.length === 0) return []// conversationIds can come directly from an authenticated runtime caller.// They narrow the read but do not authorize it: bind every conversation to@@ -396,7 +396,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {FROM conversations cJOIN participants requesting_agentON requesting_agent.id = $1- AND requesting_agent.company_id = c.company_id+ AND requesting_agent.company_id = $2AND requesting_agent.kind = 'agent'AND requesting_agent.departed_at IS NULLLEFT JOIN projects pr ON pr.id = c.project_id@@ -407,7 +407,8 @@ export class InProcRuntimeClient implements AgentRuntimeClient {LIMIT 25) m ON trueLEFT JOIN participants p ON p.id = m.author_id AND p.company_id = c.company_id- WHERE c.id = ANY($2::text[])+ WHERE c.id = ANY($3::text[])+ AND c.company_id = $2AND c.members @> to_jsonb(ARRAY[$1::text]))SELECT id, conversation_id, company_id, conversation_title, conversation_kind, conversation_topic,@@ -452,7 +453,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {) AS human_reacted_atFROM recentORDER BY conversation_id, created_at ASC`,- [agentId, conversationIds],+ [agentId, companyId, conversationIds],)await refreshAttachmentUrls(rows)return rowsdiff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex f70a9c5..f2cb2a1 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -150,6 +150,7 @@ runtimeRouter.get('/inbox', withAgent(async (c, req, res) => {// cloud quota. This is the whole point of BYOA: local compute. NB: no regex// decides anything — every actionability/mode call is the small model's.runtimeRouter.get('/inbox-triage/payload', withAgent(async (c, _req, res) => {+ if (!c.companyId) { res.status(403).json({ error: 'companyId claim required' }); return }const persona = await inprocClient.loadPersona(c.sub)if (!persona) { res.status(404).json({ error: 'agent not found' }); return }const inbox = await inprocClient.loadInbox(c.sub)@@ -169,7 +170,7 @@ runtimeRouter.get('/inbox-triage/payload', withAgent(async (c, _req, res) => {} })return}- const context = await inprocClient.loadContext(c.sub, convoIds)+ const context = await inprocClient.loadContext(c.sub, c.companyId, convoIds)// Authoritative "real work here" signal (active worklog claims per// convo) — lets the gate suppress unclaimed agent-only chatter from FACT, and// sets the claim-aware loop-cap tier. Same gather the cloud path uses. The@@ -260,8 +261,9 @@ runtimeRouter.post('/memory/query', withAgent(async (c, req, res) => {}))runtimeRouter.post('/context', withAgent(async (c, req, res) => {+ if (!c.companyId) { res.status(403).json({ error: 'companyId claim required' }); return }const body = req.body as { conversationIds?: string[] } | undefined- const rows = await inprocClient.loadContext(c.sub, body?.conversationIds ?? [])+ const rows = await inprocClient.loadContext(c.sub, c.companyId, body?.conversationIds ?? [])res.json({ rows })}))diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.tsindex a0bb38d..9637b73 100644--- a/server/src/agents/scheduler.ts+++ b/server/src/agents/scheduler.ts@@ -650,7 +650,7 @@ async function triageWakeRecipient(agentId: string): Promise<WakeOptions | null>const inbox = await inprocClient.loadInbox(agentId)if (inbox.length === 0) return nullconst convoIds = [...new Set(inbox.map((m) => m.conversation_id))]- const context = await inprocClient.loadContext(agentId, convoIds)+ const context = await inprocClient.loadContext(agentId, persona.companyId, convoIds)const verdict = await classifyInboxTriage({agentId,companyId: persona.companyId,diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.tsindex 2d12c20..3ff32d1 100644--- a/server/src/agents/turn.ts+++ b/server/src/agents/turn.ts@@ -160,10 +160,11 @@ async function loadMemory(async function loadContext(agentId: string,+ companyId: string,conversationIds: string[],rc: AgentRuntimeClient = runtime,): Promise<ContextRow[]> {- return rc.loadContext(agentId, conversationIds)+ return rc.loadContext(agentId, companyId, conversationIds)}async function loadClimate(@@ -1877,7 +1878,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =(options.trigger === undefined || options.trigger === 'message.new') &&!triageNoteif (shouldRunInboxTriage) {- preloadedContext = await loadContext(agentId, convoIds)+ preloadedContext = await loadContext(agentId, persona.companyId, convoIds)const verdict = await classifyInboxTriage({agentId,companyId: runCompanyId,@@ -1958,7 +1959,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =).slice(0, 4000)const [context, memory, climate, textExcerpts, skillsIndex] = await Promise.all([- preloadedContext ? Promise.resolve(preloadedContext) : loadContext(agentId, convoIds),+ preloadedContext ? Promise.resolve(preloadedContext) : loadContext(agentId, persona.companyId, convoIds),loadMemory(agentId, memoryQuery, {}, runtime, { conversationIds: convoIds }),loadClimate(agentId),loadTextExcerpts(inbox),