Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: harden session pagination and migration indexes
Josué446df9ae6dff
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex fcc5bc243..d3cf5923d 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.223",+ "version": "0.1.224","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.223",+ "version": "0.1.224","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex eb8a4981a..4d956dfa2 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.223",+ "version": "0.1.224","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.tsindex 9ec26277b..e1ffe1c5a 100644--- a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts+++ b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it } from 'vitest'import { Conversation, ConversationState } from '../../types'-import { InMemoryConversationStore } from '../conversationStore'+import { InMemoryConversationStore, boundedTurns } from '../conversationStore'function makeConversation(userId: string): Conversation {return {@@ -140,7 +140,9 @@ describe('InMemoryConversationStore', () => {store.set('u-1:rpc:agent-x:chat-1', makeConversation('u-1'))store.set('u-1:rpc:agent-y:chat-2', makeConversation('u-1'))- const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:')+ const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {+ agent: 'agent-x',+ })expect(summaries.map(session => [session.agent, session.chatId])).toEqual([['agent-x', 'chat-1'],@@ -150,7 +152,9 @@ describe('InMemoryConversationStore', () => {it('preserves colons in chat ids under an agent-scoped prefix', async () => {store.set('u-1:rpc:agent-x:chat:with:colons', makeConversation('u-1'))- const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:')+ const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {+ agent: 'agent-x',+ })expect(summaries.map(session => [session.agent, session.chatId])).toEqual([['agent-x', 'chat:with:colons'],@@ -167,6 +171,17 @@ describe('InMemoryConversationStore', () => {expect(summaries.map(session => [session.agent, session.chatId])).toEqual([['rpc', 'chat-1']])})+ it('parses an unscoped prefix when the user subject contains :rpc:', async () => {+ const userId = 'subject:rpc:embedded'+ store.set(`${userId}:rpc:agent-x:chat-1`, makeConversation(userId))++ const summaries = await store.listSessionSummariesByPrefix(`${userId}:rpc:`)++ expect(summaries.map(session => [session.agent, session.chatId])).toEqual([+ ['agent-x', 'chat-1'],+ ])+ })+it('counts user and assistant bubbles without counting tool storage rows', async () => {const conversation = makeConversation('u-1')conversation.turns = [@@ -189,6 +204,15 @@ describe('InMemoryConversationStore', () => {})})+ describe('boundedTurns', () => {+ const turns = [makeTurn(1), makeTurn(2), makeTurn(3)]++ it.each([0, -1, 1.5])('returns no turns for an unsafe limit of %s', limit => {+ expect(boundedTurns(turns, { limit })).toEqual([])+ expect(boundedTurns(turns, { limit, afterTurn: 0 })).toEqual([])+ })+ })+describe('getSessionMessagesByKey', () => {it('returns only the requested turn window', async () => {const conv = makeConversation('u-1')diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex b3929502f..e6d7055ad 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -127,17 +127,25 @@ function afterSessionCursor(}export function boundedTurns(turns: Turn[], query: SessionMessagesQuery = {}): Turn[] {+ const limit =+ query.limit === undefined+ ? undefined+ : Number.isInteger(query.limit) && query.limit > 0+ ? query.limit+ : 0const eligibleTurns =query.afterTurn !== undefined? turns.filter(turn => turn.number > query.afterTurn!): query.beforeTurn !== undefined? turns.filter(turn => turn.number < query.beforeTurn!): turns- return query.limit === undefined+ return limit === undefined? eligibleTurns: query.afterTurn !== undefined- ? eligibleTurns.slice(0, query.limit)- : eligibleTurns.slice(-query.limit)+ ? eligibleTurns.slice(0, limit)+ : limit === 0+ ? []+ : eligibleTurns.slice(-limit)}function sessionMessagesFromConversation(@@ -409,7 +417,13 @@ export class InMemoryConversationStore implements ConversationStore {const filtered = summaries.filter(summary => afterSessionCursor(summary, query.cursor)).sort(compareSessionSummaries)- return query.limit === undefined ? filtered : filtered.slice(0, query.limit)+ const limit =+ query.limit === undefined+ ? undefined+ : Number.isInteger(query.limit) && query.limit > 0+ ? query.limit+ : 0+ return limit === undefined ? filtered : filtered.slice(0, limit)}async getSessionMessagesByKey(diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex acae21bdc..01a2cbd31 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -318,6 +318,7 @@ describe('SqliteConversationStore — session summary listing', () => {expect(handle.store['cache'].size()).toBe(0)const agentPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {+ agent: 'agent-x',limit: 2,})expect(agentPage.map(session => [session.agent, session.chatId])).toEqual([@@ -333,6 +334,7 @@ describe('SqliteConversationStore — session summary listing', () => {handle.store['ordinals'].clear()handle.store['sessionKeyById'].clear()const colonPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {+ agent: 'agent-x',limit: 10,})expect(colonPage.find(session => session.key === colonKey)).toMatchObject({@@ -370,6 +372,49 @@ describe('SqliteConversationStore — session summary listing', () => {}})+ it('keeps unscoped parsing stable when the user subject contains :rpc:', async () => {+ const handle = await freshStore({ cacheSize: 4 })+ try {+ const manager = new ConversationManager(handle.store)+ const userId = 'subject:rpc:embedded'+ const key = `${userId}:rpc:agent-x:chat-1`+ const conversation = await manager.getOrCreate(key)+ await manager.startTurn(conversation, 'hello', 'task-1')+ await manager.completeTurn(conversation, 'done')+ await handle.persistQueue.drainSessionKey(key)+ handle.store['cache'].clear()++ const summaries = await handle.store.listSessionSummariesByPrefix(`${userId}:rpc:`)++ expect(summaries.map(session => [session.agent, session.chatId])).toEqual([+ ['agent-x', 'chat-1'],+ ])+ } finally {+ await handle.shutdown()+ }+ })++ it('fails closed instead of treating unsafe limits as unbounded reads', async () => {+ const handle = await freshStore({ cacheSize: 4 })+ try {+ const manager = new ConversationManager(handle.store)+ const conversation = await manager.getOrCreate(SESSION_KEY)+ await manager.startTurn(conversation, 'hello', 'task-1')+ await manager.completeTurn(conversation, 'done')+ await handle.persistQueue.drainSessionKey(SESSION_KEY)+ handle.store['cache'].clear()++ await expect(+ handle.store.listSessionSummariesByPrefix('u-1:rpc:', { limit: -1 })+ ).resolves.toEqual([])+ await expect(+ handle.store.getSessionMessagesByKey(SESSION_KEY, 'u-1:rpc:', { limit: -1 })+ ).resolves.toMatchObject({ turns: [] })+ } finally {+ await handle.shutdown()+ }+ })+it('loads a bounded message page without hydrating the full conversation cache', async () => {const handle = await freshStore({ cacheSize: 4 })try {diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 9fd8489ea..d2992038e 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -43,7 +43,7 @@ import {type SessionTokenUsage,boundedTurns,} from '../conversationStore'-import { scopedAgentFromSessionPrefix, sessionPartsFromPrefixedKey } from '../sessionKeyParts'+import { sessionPartsFromPrefixedKey } from '../sessionKeyParts'import type { PersistQueue } from './persistQueue'import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'import {@@ -364,7 +364,7 @@ export class SqliteConversationStore implements ConversationStore {limit: query.limit,cursorUpdatedAt: query.cursor ? query.cursor.updatedAt.getTime() / 1000 : undefined,cursorKey: query.cursor?.key,- agentScoped: query.agent !== undefined || scopedAgentFromSessionPrefix(prefix) !== null,+ agentScoped: query.agent !== undefined,})const out: ConversationSessionSummary[] = []diff --git a/mcp-host/src/core/conversation/sessionKeyParts.ts b/mcp-host/src/core/conversation/sessionKeyParts.tsindex c9a643d31..182f93009 100644--- a/mcp-host/src/core/conversation/sessionKeyParts.ts+++ b/mcp-host/src/core/conversation/sessionKeyParts.ts@@ -3,27 +3,13 @@ export interface AgentChatSessionParts {chatId: string}-/**- * Return the agent embedded in an agent-scoped RPC prefix.- *- * Unscoped prefixes end immediately after `:rpc:`. Scoped prefixes append the- * agent and a trailing colon, for example `user:rpc:agent-a:`.- */-export function scopedAgentFromSessionPrefix(prefix: string): string | null {- const rpcPrefixIndex = prefix.indexOf(':rpc:')- if (rpcPrefixIndex < 0) return null- const suffix = prefix.slice(rpcPrefixIndex + ':rpc:'.length)- if (!suffix.endsWith(':')) return null- const agent = suffix.slice(0, -1)- return agent || null-}-/*** Parse a key relative to the exact prefix used to fetch it.** For an agent-scoped prefix, the entire suffix is the chat ID. This preserves- * chat IDs containing colons instead of treating their first segment as- * another agent name.+ * chat IDs containing colons instead of treating their first segment as another+ * agent name. The scoped agent must be explicit because the prefix alone is+ * ambiguous when a user subject contains `:rpc:` or the agent is named `rpc`.*/export function sessionPartsFromPrefixedKey(key: string,@@ -36,9 +22,6 @@ export function sessionPartsFromPrefixedKey(if (scopedAgent) return { agent: scopedAgent, chatId: rest }- const inferredScopedAgent = scopedAgentFromSessionPrefix(prefix)- if (inferredScopedAgent) return { agent: inferredScopedAgent, chatId: rest }-const colonIndex = rest.indexOf(':')if (colonIndex <= 0 || colonIndex === rest.length - 1) return nullreturn {diff --git a/mcp-host/src/db/migrations/001-initial-schema.ts b/mcp-host/src/db/migrations/001-initial-schema.tsindex 27548fb57..ac616c55c 100644--- a/mcp-host/src/db/migrations/001-initial-schema.ts+++ b/mcp-host/src/db/migrations/001-initial-schema.ts@@ -66,6 +66,8 @@ export function up(db: Database): void {);CREATE INDEX IF NOT EXISTS idx_messages_sessionON messages(session_id, ordinal);+ CREATE INDEX IF NOT EXISTS idx_messages_turn+ ON messages(session_id, turn_number);CREATE INDEX IF NOT EXISTS idx_messages_spilloverON messages(spillover_ref) WHERE spillover_ref IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_messages_timestampdiff --git a/mcp-host/src/db/migrations/009-session-summary-indexes.ts b/mcp-host/src/db/migrations/009-session-summary-indexes.tsindex b22312be4..8321ad351 100644--- a/mcp-host/src/db/migrations/009-session-summary-indexes.ts+++ b/mcp-host/src/db/migrations/009-session-summary-indexes.ts@@ -2,8 +2,8 @@* Migration 009 — indexes for paged session-summary catalogs.** The desktop session catalog reads sessions by key prefix and projects- * last-activity/turn-count summaries from messages. Existing databases need the- * same supporting indexes fresh installs get from migration 001.+ * last-activity/turn-count summaries from messages. This migration adds the+ * supporting indexes without changing the already-shipped initial schema.*/import type { Database } from 'better-sqlite3'diff --git a/mcp-host/src/db/migrations/010-materialized-session-summaries.ts b/mcp-host/src/db/migrations/010-materialized-session-summaries.tsindex 013af57c0..1f59d102d 100644--- a/mcp-host/src/db/migrations/010-materialized-session-summaries.ts+++ b/mcp-host/src/db/migrations/010-materialized-session-summaries.ts@@ -37,17 +37,13 @@ export function up(db: Database): void {);CREATE INDEX IF NOT EXISTS idx_sessions_summary_activity- ON sessions(last_activity_at DESC, session_key ASC);- CREATE INDEX IF NOT EXISTS idx_messages_session_turn_key_ordinal- ON messages(session_id, turn_number, ordinal)- WHERE turn_number IS NOT NULL;+ ON sessions(COALESCE(last_activity_at, started_at) DESC, session_key ASC);`)}export function down(db: Database): void {db.exec(`DROP INDEX IF EXISTS idx_sessions_summary_activity;- DROP INDEX IF EXISTS idx_messages_session_turn_key_ordinal;ALTER TABLE sessions DROP COLUMN turn_count;ALTER TABLE sessions DROP COLUMN last_activity_at;`)diff --git a/mcp-host/src/db/migrations/__tests__/009-session-summary-indexes.test.ts b/mcp-host/src/db/migrations/__tests__/009-session-summary-indexes.test.tsnew file mode 100644index 000000000..0c4b79732--- /dev/null+++ b/mcp-host/src/db/migrations/__tests__/009-session-summary-indexes.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import Database from 'better-sqlite3'+import * as m009 from '../009-session-summary-indexes'+import { migrations } from '../index'++function indexNames(db: Database.Database): string[] {+ return (+ db+ .prepare(+ `SELECT name+ FROM sqlite_master+ WHERE type = 'index'+ AND name IN (+ 'idx_messages_turn',+ 'idx_messages_session_timestamp',+ 'idx_messages_session_turn_ordinal'+ )+ ORDER BY name`+ )+ .all() as Array<{ name: string }>+ ).map(row => row.name)+}++describe('migration 009 — session summary indexes', () => {+ it('replaces the legacy turn index and supports down/up replay', () => {+ const db = new Database(':memory:')+ for (const migration of migrations) {+ if (migration.name === m009.name) break+ migration.up(db)+ }++ expect(indexNames(db)).toEqual(['idx_messages_turn'])++ m009.up(db)+ m009.up(db)+ expect(indexNames(db)).toEqual([+ 'idx_messages_session_timestamp',+ 'idx_messages_session_turn_ordinal',+ ])++ m009.down(db)+ expect(indexNames(db)).toEqual(['idx_messages_turn'])++ m009.up(db)+ expect(indexNames(db)).toEqual([+ 'idx_messages_session_timestamp',+ 'idx_messages_session_turn_ordinal',+ ])+ db.close()+ })+})diff --git a/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts b/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.tsindex b786e774a..f0b9133c7 100644--- a/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts+++ b/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts@@ -65,15 +65,39 @@ describe('migration 010 — materialized session summaries', () => {WHERE type = 'index'AND name IN ('idx_sessions_summary_activity',+ 'idx_messages_session_turn_ordinal','idx_messages_session_turn_key_ordinal')ORDER BY name`).all() as Array<{ name: string }>expect(indexes.map(index => index.name)).toEqual([- 'idx_messages_session_turn_key_ordinal',+ 'idx_messages_session_turn_ordinal','idx_sessions_summary_activity',])+ const activityIndex = db+ .prepare(+ `SELECT sql+ FROM sqlite_master+ WHERE type = 'index'+ AND name = 'idx_sessions_summary_activity'`+ )+ .get() as { sql: string }+ expect(activityIndex.sql).toContain(+ 'COALESCE(last_activity_at, started_at) DESC, session_key ASC'+ )+ const activityPlan = db+ .prepare(+ `EXPLAIN QUERY PLAN+ SELECT id+ FROM sessions+ ORDER BY COALESCE(last_activity_at, started_at) DESC, session_key ASC+ LIMIT 10`+ )+ .all() as Array<{ detail: string }>+ expect(activityPlan.some(step => step.detail.includes('idx_sessions_summary_activity'))).toBe(+ true+ )db.close()})})diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex 5b68db4f5..f57578904 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -6,7 +6,6 @@* worker_threads boilerplate.*/import type { Database } from 'better-sqlite3'-import { scopedAgentFromSessionPrefix } from '../../core/conversation/sessionKeyParts'import { PreparedStatements, prepareStatements } from '../statements'import { withBusyRetry } from './busyRetry'import type {@@ -590,7 +589,8 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkncase 'load_session_message_page': {const sessionRow = s.selectSessionBySessionKey.get(op.sessionKey) as SessionRow | undefinedif (!sessionRow) return null- const limit = op.limit ?? -1+ const limit =+ op.limit === undefined ? -1 : Number.isInteger(op.limit) && op.limit > 0 ? op.limit : 0const messageRows =op.afterTurn !== undefined? s.selectMessagesBySessionTurnsAfter.all({@@ -656,13 +656,14 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unknconst prefixEnd = `${prefixCharacters.slice(0, -1).join('')}${String.fromCodePoint(finalCodePoint + 1)}`- const agentScoped =- op.agentScoped === true || scopedAgentFromSessionPrefix(op.sessionKeyPrefix) !== null+ const agentScoped = op.agentScoped === true+ const limit =+ op.limit === undefined ? -1 : Number.isInteger(op.limit) && op.limit > 0 ? op.limit : 0const rows = s.selectSessionSummariesByPrefix.all({prefix_start: prefixStart,prefix_end: prefixEnd,agent_scoped: agentScoped ? 1 : 0,- limit: op.limit ?? -1,+ limit,cursor_updated_at: op.cursorUpdatedAt ?? null,cursor_key: op.cursorKey ?? null,}) as Array<diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.tsindex dd9942f84..1224c1445 100644--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts@@ -172,11 +172,14 @@ describe('handleSessionsListRoute', () => {it.each([['fractional limit', { limit: '1.5' }],+ ['hexadecimal limit', { limit: '0x10' }],+ ['exponential limit', { limit: '1e2' }],['repeated limit', { limit: ['1', '2'] }],['repeated cursor', { cursor: ['one', 'two'] }],['repeated agent', { agent: ['agent-a', 'agent-b'] }],['dot agent', { agent: '.' }],['colon-bearing agent', { agent: 'agent:other' }],+ ['control-bearing agent', { agent: 'agent\nother' }],])('rejects %s query input', async (_label, query) => {const sessionsListHandler: SessionsListHandler = vi.fn()const req = {@@ -307,10 +310,14 @@ describe('handleSessionMessagesRoute', () => {['beforeTurn', 'abc'],['beforeTurn', '0'],['beforeTurn', '1.5'],+ ['beforeTurn', '0x10'],+ ['beforeTurn', '1e2'],['afterTurn', 'abc'],['afterTurn', '-1'],['afterTurn', '1.5'],['limit', '1.5'],+ ['limit', '0x10'],+ ['limit', '1e2'],])('rejects malformed %s cursors', async (name, value) => {const sessionMessagesHandler: SessionMessagesHandler = vi.fn()const req = {@@ -344,6 +351,8 @@ describe('handleSessionMessagesRoute', () => {['colon-bearing agent', 'agent:other', 'chat-1'],['dot-dot chat id', 'agent', '..'],['separator-bearing chat id', 'agent', 'nested/chat'],+ ['control-bearing agent', 'agent\nother', 'chat-1'],+ ['control-bearing chat id', 'agent', 'chat\nother'],])('rejects unsafe %s route segments', async (_label, agent, chatId) => {const sessionMessagesHandler: SessionMessagesHandler = vi.fn()const req = makeReqWithParams('user-1', agent, chatId)diff --git a/mcp-host/src/server/__tests__/wireProjections.test.ts b/mcp-host/src/server/__tests__/wireProjections.test.tsindex 3db66c1b2..02fa903b6 100644--- a/mcp-host/src/server/__tests__/wireProjections.test.ts+++ b/mcp-host/src/server/__tests__/wireProjections.test.ts@@ -22,6 +22,24 @@ describe('session pagination projections', () => {JSON.stringify({ updatedAt: 'not-a-date', key: 'session-1' })).toString('base64url')expect(decodeSessionsCursor(invalidDate)).toBeNull()+ const nonCanonicalDate = Buffer.from(+ JSON.stringify({+ version: 1,+ scope: 'scope-a',+ updatedAt: '0',+ key: 'session-1',+ })+ ).toString('base64url')+ expect(decodeSessionsCursor(nonCanonicalDate, 'scope-a')).toBeNull()+ const emptyKey = Buffer.from(+ JSON.stringify({+ version: 1,+ scope: 'scope-a',+ updatedAt: '2026-01-03T00:00:00.000Z',+ key: '',+ })+ ).toString('base64url')+ expect(decodeSessionsCursor(emptyKey, 'scope-a')).toBeNull()})it('rejects legacy and cross-scope cursors', () => {diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex 7649ee278..e0c69a351 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -73,13 +73,20 @@ function parseSessionsCursorParam(return decodeSessionsCursor(cursor, expectedScope) ? cursor : null}+function parseUnsignedIntegerParam(value: unknown): number | undefined | null {+ if (value === undefined) return undefined+ if (typeof value !== 'string' || !/^\d+$/.test(value)) return null+ const parsed = Number(value)+ return Number.isSafeInteger(parsed) ? parsed : null+}+function isSafeRouteSegment(value: string): boolean {return (value.length > 0 &&value !== '.' &&value !== '..' &&value.length <= 500 &&- !/[/\\\0]/.test(value)+ !/[/\\\u0000-\u001f\u007f]/.test(value))}@@ -1134,8 +1141,8 @@ export async function handleSessionsListRoute(badRequest(res, 'Invalid sessions cursor')return}- const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined- if (req.query.limit !== undefined && (!Number.isInteger(rawLimit) || rawLimit! < 1)) {+ const rawLimit = parseUnsignedIntegerParam(req.query.limit)+ if (rawLimit === null || (rawLimit !== undefined && rawLimit < 1)) {badRequest(res, 'limit must be a positive integer')return}@@ -1219,7 +1226,7 @@ export async function handleSessionMessagesRoute(const agent = String(req.params.agent || '').trim()const chatId = String(req.params.chatId || '').trim()if (!isSafeAgentRouteSegment(agent) || !isSafeRouteSegment(chatId)) {- badRequest(res, 'agent and chatId are required')+ badRequest(res, 'Invalid agent or chatId')return}if (!handlers.sessionMessagesHandler) {@@ -1233,22 +1240,14 @@ export async function handleSessionMessagesRoute(badRequest(res, 'pagination parameters must be specified once')return}- const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined- const rawBeforeTurn =- typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined- const rawAfterTurn =- typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined- if (- req.query.beforeTurn !== undefined &&- (!Number.isInteger(rawBeforeTurn) || rawBeforeTurn! < 1)- ) {+ const rawLimit = parseUnsignedIntegerParam(req.query.limit)+ const rawBeforeTurn = parseUnsignedIntegerParam(req.query.beforeTurn)+ const rawAfterTurn = parseUnsignedIntegerParam(req.query.afterTurn)+ if (rawBeforeTurn === null || (rawBeforeTurn !== undefined && rawBeforeTurn < 1)) {badRequest(res, 'beforeTurn must be a positive integer')return}- if (- req.query.afterTurn !== undefined &&- (!Number.isInteger(rawAfterTurn) || rawAfterTurn! < 0)- ) {+ if (rawAfterTurn === null || (rawAfterTurn !== undefined && rawAfterTurn < 0)) {badRequest(res, 'afterTurn must be a non-negative integer')return}@@ -1256,7 +1255,7 @@ export async function handleSessionMessagesRoute(badRequest(res, 'beforeTurn and afterTurn are mutually exclusive')return}- if (req.query.limit !== undefined && (!Number.isInteger(rawLimit) || rawLimit! < 1)) {+ if (rawLimit === null || (rawLimit !== undefined && rawLimit < 1)) {badRequest(res, 'limit must be a positive integer')return}diff --git a/mcp-host/src/server/wireProjections.ts b/mcp-host/src/server/wireProjections.tsindex f7bca507e..118d672e9 100644--- a/mcp-host/src/server/wireProjections.ts+++ b/mcp-host/src/server/wireProjections.ts@@ -23,6 +23,11 @@ export interface SessionsCursor {key: string}+function isCanonicalIsoTimestamp(value: string): boolean {+ const milliseconds = Date.parse(value)+ return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value+}+export function sessionsCursorScope(userSub: string, agent?: string): string {return createHash('sha256').update(JSON.stringify([userSub, agent ?? null]))@@ -45,10 +50,12 @@ export function decodeSessionsCursor(if (parsed.version !== 1 ||typeof parsed.scope !== 'string' ||+ parsed.scope.length === 0 ||(expectedScope !== undefined && parsed.scope !== expectedScope) ||typeof parsed.updatedAt !== 'string' ||typeof parsed.key !== 'string' ||- !Number.isFinite(Date.parse(parsed.updatedAt))+ parsed.key.length === 0 ||+ !isCanonicalIsoTimestamp(parsed.updatedAt)) {return null}diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex 9758980db..e5bf2d469 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.106","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.106","dependencies": {"next": "16.2.11","react": "^18.3.1",@@ -696,6 +696,7 @@"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@types/prop-types": "*","csstype": "^3.2.2"@@ -894,6 +895,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -906,6 +908,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex f5c368b96..9c6d3f381 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.106","private": true,"scripts": {"dev": "next dev",diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 2732b87a8..f0a8ff4a6 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.59",+ "version": "0.1.60","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.59",+ "version": "0.1.60","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex cdc68cf8b..2b32adc09 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.59",+ "version": "0.1.60","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.tsindex ce147ec2b..2d7ae7c31 100644--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts@@ -116,6 +116,8 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {it.each(['/rpc/hosts/chatllm/sessions?limit=1.5',+ '/rpc/hosts/chatllm/sessions?limit=0x10',+ '/rpc/hosts/chatllm/sessions?limit=1e2','/rpc/hosts/chatllm/sessions?limit=1&limit=2','/rpc/hosts/chatllm/sessions?cursor=','/rpc/hosts/chatllm/sessions?cursor=one&cursor=two',@@ -124,7 +126,9 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {'/rpc/hosts/chatllm/sessions?agent=%20%20','/rpc/hosts/chatllm/sessions?agent=.','/rpc/hosts/chatllm/sessions?agent=agent:other',+ '/rpc/hosts/chatllm/sessions?agent=agent%0Aother','/rpc/hosts/chat%2Fllm/sessions',+ '/rpc/hosts/chat%0Allm/sessions',])('rejects malformed session pagination before forwarding upstream: %s', async path => {const fetchMock = vi.fn()globalThis.fetch = fetchMock as unknown as typeof fetch@@ -229,8 +233,12 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrouit.each(['?limit=1.5',+ '?limit=0x10',+ '?limit=1e2','?limit=1&limit=2','?beforeTurn=1.5',+ '?beforeTurn=0x10',+ '?beforeTurn=1e2','?beforeTurn=1&beforeTurn=2','?afterTurn=1.5','?beforeTurn=2&afterTurn=1',@@ -258,6 +266,18 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrouexpect(fetchMock).not.toHaveBeenCalled()})+ it.each([+ '/rpc/hosts/chatllm/sessions/agent%0Aother/c1/messages',+ '/rpc/hosts/chatllm/sessions/agent/chat%0Aother/messages',+ ])('rejects control-bearing transcript route segments: %s', async path => {+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp()).get(path).set('authorization', 'Bearer user-token').expect(400)++ expect(fetchMock).not.toHaveBeenCalled()+ })+it('returns 404 when the upstream returns 404', async () => {const fetchMock = vi.fn().mockResolvedValue({status: 404,diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex c44db87bb..a8d728e38 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -38,7 +38,7 @@ function isSafeUpstreamPathSegment(value: string): boolean {value !== '.' &&value !== '..' &&value.length <= 500 &&- !/[/\\\0]/.test(value)+ !/[/\\\u0000-\u001f\u007f]/.test(value))}@@ -46,6 +46,13 @@ function isSafeUpstreamAgentSegment(value: string): boolean {return isSafeUpstreamPathSegment(value) && value.length <= 200 && !value.includes(':')}+function parseUnsignedIntegerQuery(value: unknown): number | undefined | null {+ if (value === undefined) return undefined+ if (typeof value !== 'string' || !/^\d+$/.test(value)) return null+ const parsed = Number(value)+ return Number.isSafeInteger(parsed) ? parsed : null+}+/*** Pre-wake host error mapping: AbortError → 504, everything else → 502.*@@ -257,7 +264,7 @@ export function createRpcRouter(): Router {const rpcAccessToken = extractAuthToken(req)const hostRef = String(req.params.hostRef || '').trim()if (!isSafeUpstreamPathSegment(hostRef)) {- res.status(400).json({ error: 'hostRef is required' })+ res.status(400).json({ error: 'Invalid hostRef' })return}@@ -433,7 +440,7 @@ export function createRpcRouter(): Router {const rpcAccessToken = extractAuthToken(req)const hostRef = String(req.params.hostRef || '').trim()if (!isSafeUpstreamPathSegment(hostRef)) {- res.status(400).json({ error: 'hostRef is required' })+ res.status(400).json({ error: 'Invalid hostRef' })return}@@ -653,17 +660,16 @@ export function createRpcRouter(): Router {typeof rawSessionAgent === 'string' ? rawSessionAgent.trim() : undefinedconst rawSessionCursor = req.query.cursorconst sessionCursor = typeof rawSessionCursor === 'string' ? rawSessionCursor : ''- const sessionLimit =- typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined+ const sessionLimit = parseUnsignedIntegerQuery(req.query.limit)if ((rawSessionAgent !== undefined && typeof rawSessionAgent !== 'string') ||(rawSessionCursor !== undefined && typeof rawSessionCursor !== 'string') ||- (req.query.limit !== undefined && typeof req.query.limit !== 'string') ||(rawSessionAgent !== undefined &&(!sessionAgent || !isSafeUpstreamAgentSegment(sessionAgent))) ||(rawSessionCursor !== undefined && !sessionCursor) ||sessionCursor.length > 2048 ||- (sessionLimit !== undefined && (!Number.isInteger(sessionLimit) || sessionLimit < 1))+ sessionLimit === null ||+ (sessionLimit !== undefined && sessionLimit < 1)) {res.status(400).json({ error: 'Invalid session pagination query' })return@@ -757,19 +763,20 @@ export function createRpcRouter(): Router {const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`)- const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined- const beforeTurn =- typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined- const afterTurn =- typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined+ const rawLimit = parseUnsignedIntegerQuery(req.query.limit)+ const beforeTurn = parseUnsignedIntegerQuery(req.query.beforeTurn)+ const afterTurn = parseUnsignedIntegerQuery(req.query.afterTurn)const invalidQueryShape = ['limit', 'beforeTurn', 'afterTurn'].some(key => req.query[key] !== undefined && typeof req.query[key] !== 'string')if (invalidQueryShape ||- (rawLimit !== undefined && (!Number.isInteger(rawLimit) || rawLimit < 1)) ||- (beforeTurn !== undefined && (!Number.isInteger(beforeTurn) || beforeTurn < 1)) ||- (afterTurn !== undefined && (!Number.isInteger(afterTurn) || afterTurn < 0)) ||+ rawLimit === null ||+ (rawLimit !== undefined && rawLimit < 1) ||+ beforeTurn === null ||+ (beforeTurn !== undefined && beforeTurn < 1) ||+ afterTurn === null ||+ (afterTurn !== undefined && afterTurn < 0) ||(beforeTurn !== undefined && afterTurn !== undefined)) {res.status(400).json({ error: 'Invalid session messages pagination query' })