From 4662d83053bf08d4e1ac907df09211f0d05f981f Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 01:31:33 +0800 Subject: [PATCH] feat(identity,sticky): purify session switches across slots and protocols WHY: When a conversation switches upstream slots/accounts (failover, sticky reset, or admin sticky delete), stale outbound session headers, foreign thinking blocks, account-scoped tool IDs, and internal SHM/session paths can leak across accounts. Reconciles session-switch purification cleanly atop #2472 without conflicting with src/lib/identity/tool-id-mapping.mjs. CHANGES: - src/lib/identity/session-switch-purify.mjs: HKDF-SHA256 Feistel account-isolated tool ID mapping, internal SHM/CRAG path sanitization, and outbound session switch purification helpers (distinct from #2472 tool-id-mapping.mjs) - src/lib/identity/identity-rewrite.mjs, src/lib/pool/{sticky-router,failover-runner,thinking-owner}.mjs, src/lib/db/repos/sticky-repo.mjs, src/lib/protocol/{handle-protocol,issued-tool-replay}.mjs, src/lib/admin/scheduler-pools-routes.mjs, src/lib/scheduler/scheduler-runtime.mjs, src/lib/transport/go-worker-client.mjs: wire generation >= 2 purification on slot switch / sticky deleteByFilter across protocols - test/unit/{agent-summary-routing,go-worker-client,identity-rewrite,sticky-router}.test.mjs: regression coverage (0 new test files) VERIFIED: - find src scripts -name '*.mjs' | xargs -n1 node --check: PASS - npx biome check (15 files): 0 fixes - KIN_SCHEDULER_BIN=... npm run test:ci: 13/13 PASS - node --test agent-summary-routing go-worker-client identity-rewrite sticky-router slot-machine-env: 202/202 PASS --- src/lib/admin/scheduler-pools-routes.mjs | 75 +- src/lib/db/repos/sticky-repo.mjs | 51 ++ src/lib/identity/identity-rewrite.mjs | 49 +- src/lib/identity/session-switch-purify.mjs | 805 +++++++++++++++++++++ src/lib/pool/failover-runner.mjs | 20 +- src/lib/pool/sticky-router.mjs | 221 +++++- src/lib/pool/thinking-owner.mjs | 16 +- src/lib/protocol/handle-protocol.mjs | 206 +++++- src/lib/protocol/issued-tool-replay.mjs | 15 +- src/lib/scheduler/scheduler-runtime.mjs | 2 + src/lib/transport/go-worker-client.mjs | 86 ++- test/unit/agent-summary-routing.test.mjs | 627 +++++++++++++++- test/unit/go-worker-client.test.mjs | 34 + test/unit/identity-rewrite.test.mjs | 195 +++++ test/unit/sticky-router.test.mjs | 45 ++ 15 files changed, 2381 insertions(+), 66 deletions(-) create mode 100644 src/lib/identity/session-switch-purify.mjs diff --git a/src/lib/admin/scheduler-pools-routes.mjs b/src/lib/admin/scheduler-pools-routes.mjs index f7399a6854..67bb3904e1 100644 --- a/src/lib/admin/scheduler-pools-routes.mjs +++ b/src/lib/admin/scheduler-pools-routes.mjs @@ -18,7 +18,9 @@ import { normalizeProviderScope, slugifyPoolName, } from '../db/repos/scheduler-pools-repo.mjs' +import { StickyRepo } from '../db/repos/sticky-repo.mjs' import { corsHeadersForRequest } from '../http/cors.mjs' +import { outboundSlotPurifyLedger } from '../identity/session-switch-purify.mjs' import { resolveCredentialScheduleLevel } from '../pool/credential-weight.mjs' import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs' import { @@ -1982,7 +1984,7 @@ export function createSchedulerPoolsHandler({ if (Array.isArray(rows)) matchedBindings.push(...rows) } catch {} - const purgeGatewayStickyAndSlotState = () => { + const purgeGatewayStickyAndSlotState = async () => { const sessionIds = new Set() const machineIds = new Set() const vmIds = new Set() @@ -2020,18 +2022,43 @@ export function createSchedulerPoolsHandler({ } } - const sr = resolveStickyRouter() + const ledgerPurged = outboundSlotPurifyLedger.purgeByFilter(filter) + let routerDeleted = 0 + const schedObj = typeof poolScheduler === 'function' ? poolScheduler() : poolScheduler + const sr = resolveStickyRouter() || schedObj?.stickyRouter || null if (sr) { try { const activeSessions = sr.stats?.({ includeSessions: true })?.sessions || {} if (filter.allowAll) { - for (const [key, ent] of Object.entries(activeSessions)) { + for (const [, ent] of Object.entries(activeSessions)) { if (ent?.session_id) sessionIds.add(String(ent.session_id).trim()) if (ent?.vm_id) { vmIds.add(String(ent.vm_id).trim()) claudeVmIds.add(String(ent.vm_id).trim()) } + } + } else { + for (const [, ent] of Object.entries(activeSessions)) { + if (!ent || typeof ent !== 'object') continue + const hitSession = ent.session_id && sessionIds.has(String(ent.session_id).trim()) + const hitDevice = ent.device_id && machineIds.has(String(ent.device_id).trim()) + const hitVm = + !filter.session_id && !filter.machine_id && ent.vm_id && vmIds.has(String(ent.vm_id).trim()) + if (hitSession || hitDevice || hitVm) { + if (ent.session_id) sessionIds.add(String(ent.session_id).trim()) + if (ent.vm_id) { + vmIds.add(String(ent.vm_id).trim()) + claudeVmIds.add(String(ent.vm_id).trim()) + } + } + } + } + if (typeof sr.deleteByFilter === 'function') { + routerDeleted = Number(await sr.deleteByFilter(filter)) || 0 + } else if (filter.allowAll) { + for (const key of Object.keys(activeSessions)) { sr.unbind?.(key) + routerDeleted += 1 } } else { for (const vmId of vmIds) { @@ -2054,16 +2081,32 @@ export function createSchedulerPoolsHandler({ const hitVm = !filter.session_id && !filter.machine_id && ent.vm_id && vmIds.has(String(ent.vm_id).trim()) if (hitSession || hitDevice || hitVm) { - if (ent.session_id) sessionIds.add(String(ent.session_id).trim()) - if (ent.vm_id) { - vmIds.add(String(ent.vm_id).trim()) - claudeVmIds.add(String(ent.vm_id).trim()) - } sr.unbind?.(key) + routerDeleted += 1 } } } - } catch {} + } catch { + routerDeleted = 0 + } + } else if (db && db.engine !== 'postgres') { + try { + const removed = new StickyRepo(db).removeByFilter({ + sessionId: filter.session_id, + machineId: filter.machine_id, + identityId: filter.identity_id, + scopeKind: filter.scope_kind, + nodeId: + filter.node_id || + (filter.node_key && String(filter.node_key).includes(':') + ? String(filter.node_key).slice(String(filter.node_key).indexOf(':') + 1) + : null), + allowAll: filter.allowAll, + }) + routerDeleted = Number(removed?.deleted) || 0 + } catch { + routerDeleted = 0 + } } const projectRoot = cfg?.paths?.project || null @@ -2103,19 +2146,22 @@ export function createSchedulerPoolsHandler({ } catch {} } } + + return Math.max(ledgerPurged, routerDeleted) } if (rt && typeof rt.deleteSticky === 'function') { try { const result = await rt.deleteSticky(filter) - const deleted = Number(result?.deleted) || 0 - purgeGatewayStickyAndSlotState() + const nodeDeleted = await purgeGatewayStickyAndSlotState() + const deleted = Math.max(Number(result?.deleted) || 0, nodeDeleted) invalidatePoolsCache(['scheduler_sticky_bindings']) return json(res, 200, { ok: true, deleted, rust_deleted: result?.rust_deleted ?? 0, db_deleted: result?.db_deleted ?? 0, + node_sticky_deleted: nodeDeleted, data: { deleted }, }) } catch (err) { @@ -2123,10 +2169,11 @@ export function createSchedulerPoolsHandler({ } } try { - const deleted = repo.deleteStickyBindings(filter) - purgeGatewayStickyAndSlotState() + const dbDeleted = repo.deleteStickyBindings(filter) + const nodeDeleted = await purgeGatewayStickyAndSlotState() + const deleted = Math.max(dbDeleted, nodeDeleted) invalidatePoolsCache(['scheduler_sticky_bindings']) - return json(res, 200, { ok: true, deleted, data: { deleted } }) + return json(res, 200, { ok: true, deleted, node_sticky_deleted: nodeDeleted, data: { deleted } }) } catch (e) { return json(res, httpStatusForPoolError(e), { ok: false, diff --git a/src/lib/db/repos/sticky-repo.mjs b/src/lib/db/repos/sticky-repo.mjs index 17def6230a..5365fd7021 100644 --- a/src/lib/db/repos/sticky-repo.mjs +++ b/src/lib/db/repos/sticky-repo.mjs @@ -81,6 +81,57 @@ export class StickyRepo { return this._deleteByAccount.run(accountId || '', vmId || '').changes } + /** + * Delete sticky_sessions rows matching panel sticky filter criteria. + * Returns `{ deleted, keys }` so callers can invalidate L1/Redis caches and record reset tombstones. + */ + removeByFilter({ + sessionId = null, + machineId = null, + identityId = null, + scopeKind = null, + nodeId = null, + accountId = null, + allowAll = false, + } = {}) { + if (allowAll) { + const keys = this._all.all().map((r) => r.key) + const changes = this.db.prepare('DELETE FROM sticky_sessions').run().changes + return { deleted: changes, keys } + } + const sid = String(sessionId || (scopeKind === 'session' ? identityId : '') || '').trim() + const mid = String(machineId || (scopeKind === 'machine' ? identityId : '') || '').trim() + const anyId = !scopeKind && identityId ? String(identityId).trim() : '' + const vm = String(nodeId || '').trim() + const acct = String(accountId || '').trim() + if (!sid && !mid && !anyId && !vm && !acct) return { deleted: 0, keys: [] } + + const matchesRow = (row) => { + const k = String(row?.key || '') + if (vm && row?.vm_id !== vm) return false + if (acct && row?.account_id !== acct) return false + const matchSession = (target) => + k === `sess:${target}` || + k === `family2:${target}` || + k.endsWith(`:sess:${target}`) || + k.endsWith(`:family:${target}`) || + k === target + const matchMachine = (target) => + row?.device_id === target || k === `dev2:${target}` || k.endsWith(`:dev2:${target}`) + if (sid && !matchSession(sid)) return false + if (mid && !matchMachine(mid)) return false + if (anyId && !matchSession(anyId) && !matchMachine(anyId)) return false + return true + } + + const keys = [] + for (const row of this._all.all()) { + if (matchesRow(row)) keys.push(row.key) + } + for (const key of keys) this._delete.run(key) + return { deleted: keys.length, keys } + } + purgeExpired(now = Date.now()) { return this._purge.run(now).changes } diff --git a/src/lib/identity/identity-rewrite.mjs b/src/lib/identity/identity-rewrite.mjs index e682b70d50..3d82217bae 100644 --- a/src/lib/identity/identity-rewrite.mjs +++ b/src/lib/identity/identity-rewrite.mjs @@ -64,6 +64,9 @@ export const AGENT_SESSION_SEED = 'kin-claude-code-agent:' /** Prefix so multi-turn headless scheduler sessions stay isolated from other derived ids. */ export const SCHEDULER_SESSION_SEED = 'kin-scheduler-session:' +/** Prefix so purified parent session ids on a switched slot never link back to the previous slot. */ +export const PURIFIED_PARENT_SESSION_SEED = 'kin-purified-parent-session:' + /** Precedence order for inbound machine_id headers (never forged from IP/UA). */ export const MACHINE_ID_HEADER_KEYS = Object.freeze(['x-machine-id', 'x-kin-machine-id', 'x-kin-device-id']) @@ -651,22 +654,46 @@ function resolvePassthroughOutboundSessionId(caller, opts) { } /** - * rebuild (default): same VM reuses the sticky outbound id; otherwise mint - * from inbound A (or the stable seed) + epoch. passthrough keeps the old - * official-keeps-A / unofficial-hash behavior. + * Derives a slot-isolated parent session UUID when a sub-agent hop switches slots, + * keeping parent/child correlation consistent inside the target slot while severing + * cross-slot linkage. + */ +export function derivePurifiedParentSessionId( + parentSessionId, + { accountId = '', vmId = '', outboundSessionId = '' } = {}, +) { + const parent = String(parentSessionId || '').trim() + if (!parent) return '' + const scope = `${String(accountId || '').trim()}|${String(vmId || '').trim()}|${String(outboundSessionId || '').trim()}` + return uuidFromSeed(`${PURIFIED_PARENT_SESSION_SEED}${scope}#${parent}`) +} + +/** + * rebuild (default): same VM + same account reuses the sticky outbound id; + * otherwise mint from inbound A (or the stable seed) + epoch. + * passthrough keeps the old official-keeps-A / unofficial-hash behavior unless + * `slotSwitched` is true, in which case a fresh purified outbound session is + * always minted so the previous slot's session_id never leaks into the new slot. */ export function resolveOutboundSessionId(callerSession, opts = {}) { const caller = String(callerSession || '').trim() const mode = opts.mode || outboundSessionMode(opts.routing) - if (mode === 'passthrough') return resolvePassthroughOutboundSessionId(caller, opts) - const boundSessionId = String(opts.boundSessionId || '').trim() const boundVmId = String(opts.boundVmId || '').trim() const vmId = String(opts.vmId || '').trim() + const boundAccountId = String(opts.boundAccountId || '').trim() + const accountId = String(opts.accountId || '').trim() const sameVm = Boolean(boundVmId && vmId && boundVmId === vmId) - if (boundSessionId && sameVm) return boundSessionId + const sameAccount = !boundAccountId || !accountId || boundAccountId === accountId + const slotSwitched = opts.slotSwitched === true + const sessionPurified = opts.sessionPurified === true || slotSwitched + + if (boundSessionId && sameVm && sameAccount && !slotSwitched && (mode !== 'passthrough' || sessionPurified)) { + return boundSessionId + } + + if (mode === 'passthrough' && !slotSwitched) return resolvePassthroughOutboundSessionId(caller, opts) - const accountId = String(opts.accountId || '').trim() const discriminator = opts.clientDiscriminator != null ? String(opts.clientDiscriminator) @@ -676,9 +703,13 @@ export function resolveOutboundSessionId(callerSession, opts = {}) { apiKeyId: opts.apiKeyId, }) const firstUserIdentity = String(opts.firstUserIdentity || '') - const identity = caller || buildStableSessionSeed(accountId, discriminator, firstUserIdentity) + const baseIdentity = caller || buildStableSessionSeed(accountId, discriminator, firstUserIdentity) + if (slotSwitched && mode === 'passthrough') { + const purifiedSeed = `${accountId}|${vmId}|${baseIdentity || crypto.randomUUID()}` + return rebuildOutboundSession({ identity: purifiedSeed, epoch: opts.epoch ?? 'pending' }) + } if (caller || stableSessionMaterial(accountId, discriminator, firstUserIdentity)) { - return rebuildOutboundSession({ identity, epoch: opts.epoch ?? 'pending' }) + return rebuildOutboundSession({ identity: baseIdentity, epoch: opts.epoch ?? 'pending' }) } return crypto.randomUUID() } diff --git a/src/lib/identity/session-switch-purify.mjs b/src/lib/identity/session-switch-purify.mjs new file mode 100644 index 0000000000..b3d8ccb829 --- /dev/null +++ b/src/lib/identity/session-switch-purify.mjs @@ -0,0 +1,805 @@ +import crypto from 'node:crypto' + +const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +const CHAR_TO_VAL = new Int16Array(128).fill(-1) +for (let i = 0; i < BASE62.length; i += 1) { + CHAR_TO_VAL[BASE62.charCodeAt(i)] = i +} + +const DEFAULT_PEPPER = 'vm2api:tool-id-feistel-default-pepper:v1' +const HKDF_SALT = Buffer.from('vm2api:tool-id-feistel:v1', 'utf8') +const FEISTEL_ROUNDS = 6 + +const TOOL_ID_PREFIX_RE = + /^(toolu_01|srvtoolu_01|mcptoolu_01|toolu_bdrk_|toolu_vrtx_|toolu_plugin_|toolu_patch_|toolu_|call_)([A-Za-z0-9_-]{8,64})$/ + +const READONLY_TOOL_CALL_RE = /(\[tool call [^\s\]]+\s+)((?:toolu_|srvtoolu_|mcptoolu_|call_)[A-Za-z0-9_-]{8,64})(\])/g +const READONLY_TOOL_RESULT_RE = /(\[tool result\s+)((?:toolu_|srvtoolu_|mcptoolu_|call_)[A-Za-z0-9_-]{8,64})(\s|\])/g + +const INTERNAL_SHM_PATH_RE = /\/(?:[^\s"'`<>]+\/)?shm-(?:w|egress)-?\d+-[0-9a-f]{6,32}(?:\/[^\s"'`<>]*)?/g +const INTERNAL_CRAG_SESSION_PATH_RE = /\/[^\s"'`<>]*\.crag-sessions\/sessions\/[^\s"'`<>]+/g + +const KEY_CACHE_MAX = 2048 +const derivedKeyCache = new Map() + +/** + * Derive an account-isolated 32-byte Feistel key via HKDF-SHA256. + * Two distinct upstream accounts produce cryptographically independent keys. + */ +export function deriveAccountToolIdKey(accountKey, secret = '') { + const acct = String(accountKey || '').trim() + if (!acct) return null + const rawSecret = String(secret || process.env.VM2API_DB_SECRET || DEFAULT_PEPPER) + const cacheId = `${acct}\u0000${crypto.createHash('sha256').update(rawSecret).digest('hex').slice(0, 16)}` + const hit = derivedKeyCache.get(cacheId) + if (hit) return hit + const key = Buffer.from( + crypto.hkdfSync('sha256', Buffer.from(rawSecret, 'utf8'), HKDF_SALT, Buffer.from(`acct:${acct}`, 'utf8'), 32), + ) + if (derivedKeyCache.size >= KEY_CACHE_MAX) { + const oldest = derivedKeyCache.keys().next().value + derivedKeyCache.delete(oldest) + } + derivedKeyCache.set(cacheId, key) + return key +} + +function normalizeKeyBuffer(key) { + if (!key) return null + if (Buffer.isBuffer(key) && key.length === 32) return key + if (key instanceof Uint8Array && key.byteLength === 32) return Buffer.from(key) + if (typeof key === 'string' && key.trim()) return deriveAccountToolIdKey(key) + return null +} + +function digitsToBigInt(digits, start, len) { + let acc = 0n + for (let i = 0; i < len; i += 1) { + acc = acc * 62n + BigInt(digits[start + i]) + } + return acc +} + +function bigIntToDigits(value, len) { + const out = new Array(len) + let rem = value + for (let i = len - 1; i >= 0; i -= 1) { + out[i] = Number(rem % 62n) + rem /= 62n + } + return out +} + +function bigIntToBase62Fixed(value, len) { + const digits = bigIntToDigits(value, len) + let str = '' + for (let i = 0; i < len; i += 1) str += BASE62[digits[i]] + return str +} + +function feistelRound(keyBuf, round, halfLen, rightVal, mod) { + const rightStr = bigIntToBase62Fixed(rightVal, halfLen) + const digest = crypto.createHmac('sha256', keyBuf).update(`${round}:${halfLen}:${rightStr}`).digest('hex') + return BigInt(`0x${digest}`) % mod +} + +function parsePermutableToolId(rawId) { + if (typeof rawId !== 'string' || rawId.length < 13 || rawId.length > 80) return null + const match = TOOL_ID_PREFIX_RE.exec(rawId) + if (!match) return null + const prefix = match[1] + const body = match[2] + const chars = Array.from(body) + const positions = [] + const digits = [] + for (let i = 0; i < chars.length; i += 1) { + const code = chars[i].charCodeAt(0) + const val = code < 128 ? CHAR_TO_VAL[code] : -1 + if (val >= 0) { + positions.push(i) + digits.push(val) + } + } + if (digits.length < 8) return null + return { prefix, chars, positions, digits } +} + +/** + * Format-preserving Base62 balanced Feistel forward bijection (public/client ID -> account upstream ID). + * Preserves prefix (`toolu_01`, `call_`, etc.), total length, and any `-`/`_` punctuation positions. + */ +export function encodeToolIdForAccount(rawId, key) { + const keyBuf = normalizeKeyBuffer(key) + if (!keyBuf) return rawId + const parsed = parsePermutableToolId(rawId) + if (!parsed) return rawId + const { prefix, chars, positions, digits } = parsed + const n = digits.length + const k = Math.floor(n / 2) + const mod = 62n ** BigInt(k) + + let left = digitsToBigInt(digits, 0, k) + let right = digitsToBigInt(digits, k, k) + for (let r = 0; r < FEISTEL_ROUNDS; r += 1) { + const f = feistelRound(keyBuf, r, k, right, mod) + const nextLeft = right + const nextRight = (left + f) % mod + left = nextLeft + right = nextRight + } + + const outDigits = [...bigIntToDigits(left, k), ...bigIntToDigits(right, k)] + if (n === 2 * k + 1) { + let pairStr = '' + for (let i = 0; i < 2 * k; i += 1) pairStr += BASE62[outDigits[i]] + const shift = crypto.createHmac('sha256', keyBuf).update(`tail:${pairStr}`).digest()[0] % 62 + outDigits.push((digits[2 * k] + shift) % 62) + } + + const outChars = chars.slice() + for (let i = 0; i < n; i += 1) { + outChars[positions[i]] = BASE62[outDigits[i]] + } + return prefix + outChars.join('') +} + +/** + * Exact inverse of `encodeToolIdForAccount` (account upstream ID -> public/client ID). + * Guarantees `encodeToolIdForAccount(decodeToolIdFromAccount(x, k), k) === x` for all valid IDs. + */ +export function decodeToolIdFromAccount(rawId, key) { + const keyBuf = normalizeKeyBuffer(key) + if (!keyBuf) return rawId + const parsed = parsePermutableToolId(rawId) + if (!parsed) return rawId + const { prefix, chars, positions, digits } = parsed + const n = digits.length + const k = Math.floor(n / 2) + const mod = 62n ** BigInt(k) + + const work = digits.slice() + if (n === 2 * k + 1) { + let pairStr = '' + for (let i = 0; i < 2 * k; i += 1) pairStr += BASE62[work[i]] + const shift = crypto.createHmac('sha256', keyBuf).update(`tail:${pairStr}`).digest()[0] % 62 + work[2 * k] = (work[2 * k] - shift + 62) % 62 + } + + let left = digitsToBigInt(work, 0, k) + let right = digitsToBigInt(work, k, k) + for (let r = FEISTEL_ROUNDS - 1; r >= 0; r -= 1) { + const prevRight = left + const f = feistelRound(keyBuf, r, k, prevRight, mod) + const prevLeft = (((right - f) % mod) + mod) % mod + left = prevLeft + right = prevRight + } + + const plainLeft = bigIntToDigits(left, k) + const plainRight = bigIntToDigits(right, k) + for (let i = 0; i < k; i += 1) { + work[i] = plainLeft[i] + work[k + i] = plainRight[i] + } + + const outChars = chars.slice() + for (let i = 0; i < n; i += 1) { + outChars[positions[i]] = BASE62[work[i]] + } + return prefix + outChars.join('') +} + +export function isToolUseBlock(block) { + return ( + block != null && + typeof block === 'object' && + (block.type === 'tool_use' || block.type === 'server_tool_use' || block.type === 'mcp_tool_use') + ) +} + +/** + * Bounded LRU tracking which upstream account originally minted a public `toolu_*` ID. + * Detects cross-account tool replay even after sticky binding expiry or manual deletion. + */ +export function createToolIdOwnerTracker({ maxEntries = 8192 } = {}) { + const owners = new Map() + + function recordId(id, accountId) { + if (typeof id !== 'string' || !id || !accountId) return + if (!parsePermutableToolId(id)) return + owners.delete(id) + owners.set(id, String(accountId)) + while (owners.size > maxEntries) { + const oldest = owners.keys().next().value + owners.delete(oldest) + } + } + + function recordMessage(message, accountId) { + const acct = String(accountId || '').trim() + if (!acct || !message || typeof message !== 'object') return + const content = Array.isArray(message.content) + ? message.content + : Array.isArray(message.message?.content) + ? message.message.content + : null + if (!content) return + for (const block of content) { + if (isToolUseBlock(block) && typeof block.id === 'string') { + recordId(block.id, acct) + } + } + } + + function recordSSELine(line, accountId) { + const acct = String(accountId || '').trim() + if (!acct || typeof line !== 'string' || !line.includes('data:')) return + if ( + !line.includes('toolu_') && + !line.includes('srvtoolu_') && + !line.includes('mcptoolu_') && + !line.includes('call_') + ) + return + const idx = line.indexOf('data:') + try { + const payload = JSON.parse(line.slice(idx + 5).trim()) + if (payload?.type === 'content_block_start' && isToolUseBlock(payload.content_block)) { + recordId(payload.content_block.id, acct) + } + } catch {} + } + + function hasForeignToolIds(body, targetAccountId) { + const acct = String(targetAccountId || '').trim() + if (!acct || !owners.size || !body || typeof body !== 'object') return false + const messages = Array.isArray(body.messages) ? body.messages : [] + for (const msg of messages) { + if (!Array.isArray(msg?.content)) continue + for (const block of msg.content) { + if (!block || typeof block !== 'object') continue + if (block._kinAccountId && String(block._kinAccountId) !== acct) return true + if (isToolUseBlock(block) && typeof block.id === 'string') { + const owner = owners.get(block.id) + if (owner && owner !== acct) return true + } + if (typeof block.tool_use_id === 'string') { + const owner = owners.get(block.tool_use_id) + if (owner && owner !== acct) return true + } + } + } + return false + } + + return { + recordId, + recordMessage, + recordSSELine, + hasForeignToolIds, + ownerOf: (id) => owners.get(id) || null, + clear: () => owners.clear(), + size: () => owners.size, + } +} + +export const defaultToolIdOwners = createToolIdOwnerTracker() + +const USER_EMAIL_SECTION_RE = + /(?:^|\n)# userEmail\r?\n[^\r\n]*(?:\r?\n(?![ \t]*#\s|[ \t]*<\/system-reminder>)[^\r\n]*)*/g +const EMPTY_CONTEXT_REMINDER_RE = + /^\s*(?:As you answer the user's questions, you can use the following context:\s*)?<\/system-reminder>$/i + +function scrubReminderAndInternalLeaks( + text, + { scrubUserEmail = false, targetEmail = '', scrubInternalPaths = false } = {}, +) { + if (typeof text !== 'string' || !text) return text + let next = text + if (scrubUserEmail && next.includes('# userEmail') && next.includes('')) { + const cleanTarget = String(targetEmail || '').trim() + next = next.replace(/[\s\S]*?<\/system-reminder>/g, (reminder) => { + if (!reminder.includes('# userEmail')) return reminder + if (cleanTarget) { + return reminder.replace( + /(# userEmail\r?\nThe user's email address is )([^\s.\r\n]+@[^\s.\r\n]+)(\.?)/g, + (_, p1, _old, p3) => `${p1}${cleanTarget}${p3}`, + ) + } + const stripped = reminder.replace(USER_EMAIL_SECTION_RE, '').replace(/\n{3,}/g, '\n\n') + if (EMPTY_CONTEXT_REMINDER_RE.test(stripped.trim())) return '' + return stripped + }) + next = next.replace(/^\n+|\n+$/g, (m, offset) => (offset === 0 && !text.startsWith('\n') ? '' : m)) + } + if (scrubInternalPaths && (next.includes('/shm-') || next.includes('.crag-sessions/'))) { + next = next.replace(INTERNAL_SHM_PATH_RE, '/tmp').replace(INTERNAL_CRAG_SESSION_PATH_RE, '/tmp/workspace') + } + return next +} + +function rewriteReadonlySummaryToolIds(text, encodeFn) { + if (typeof text !== 'string' || typeof encodeFn !== 'function') return text + if (!text.includes('[tool call ') && !text.includes('[tool result ')) return text + return text + .replace(READONLY_TOOL_CALL_RE, (_, p1, id, p3) => `${p1}${encodeFn(id)}${p3}`) + .replace(READONLY_TOOL_RESULT_RE, (_, p1, id, p3) => `${p1}${encodeFn(id)}${p3}`) +} + +function purifySystemField(system, textOpts) { + if (system == null) return system + if (typeof system === 'string') { + return scrubReminderAndInternalLeaks(system, textOpts) + } + if (!Array.isArray(system)) return system + let changed = false + const out = [] + for (const block of system) { + if (typeof block === 'string') { + const next = scrubReminderAndInternalLeaks(block, textOpts) + if (next !== block) changed = true + if (next.trim() || !block.trim()) out.push(next) + else changed = true + continue + } + if (block && typeof block === 'object' && typeof block.text === 'string') { + const next = scrubReminderAndInternalLeaks(block.text, textOpts) + if (next !== block.text) { + changed = true + if (!next.trim() && block.text.trim()) continue + out.push({ ...block, text: next }) + continue + } + } + out.push(block) + } + return changed ? out : system +} + +/** + * Purifies a session request body before entering a target CRAG slot: + * 1. Strips cross-slot stateful handles (`thread`, `diagnostics`, foreign `tool_use.extension`, `_kinAccountId`). + * 2. Bijectively permutes all `tool_use.id`, `tool_result.tool_use_id`, summary tool markers, and + * `safeguards[].classifier_context.prior_turn_context[].tool_use_ids` under the target account's Feistel key. + * 3. Scrubs foreign `# userEmail` inside `` and any leaked internal worker paths on slot switch. + */ +export function purifySessionPayloadForSlot( + body, + { + toolKey = null, + purifyTools = false, + slotSwitched = false, + sessionPurified = false, + encodeSummaryToolId = null, + targetAccountId = '', + targetEmail = '', + } = {}, +) { + if (!body || typeof body !== 'object') return body + const keyBuf = purifyTools ? normalizeKeyBuffer(toolKey) : null + const summaryToolEncoder = keyBuf + ? (id) => encodeToolIdForAccount(id, keyBuf) + : typeof encodeSummaryToolId === 'function' + ? encodeSummaryToolId + : null + const acct = String(targetAccountId || '').trim() + const shouldScrubLeaks = slotSwitched === true || sessionPurified === true || Boolean(purifyTools) + const textOpts = { + scrubUserEmail: shouldScrubLeaks, + targetEmail, + scrubInternalPaths: shouldScrubLeaks, + } + + let bodyChanged = false + let nextBody = body + const ensureBodyCopy = () => { + if (!bodyChanged) { + nextBody = { ...body } + bodyChanged = true + } + return nextBody + } + + if (slotSwitched) { + if ('thread' in body && body.thread != null) { + delete ensureBodyCopy().thread + } + if ('diagnostics' in body && body.diagnostics != null) { + delete ensureBodyCopy().diagnostics + } + } + + if (textOpts.scrubUserEmail || textOpts.scrubInternalPaths) { + const nextSystem = purifySystemField(body.system, textOpts) + if (nextSystem !== body.system) { + ensureBodyCopy().system = nextSystem + } + } + + if (Array.isArray(body.messages) && body.messages.length > 0) { + let messagesChanged = false + const nextMessages = body.messages.map((msg) => { + if (!msg || typeof msg !== 'object') return msg + if (typeof msg.content === 'string') { + let nextStr = scrubReminderAndInternalLeaks(msg.content, textOpts) + if (summaryToolEncoder) nextStr = rewriteReadonlySummaryToolIds(nextStr, summaryToolEncoder) + if (nextStr !== msg.content) { + messagesChanged = true + return { ...msg, content: nextStr } + } + return msg + } + if (!Array.isArray(msg.content)) return msg + + let contentChanged = false + const nextContent = [] + for (const block of msg.content) { + if (!block || typeof block !== 'object') { + nextContent.push(block) + continue + } + let nextBlock = block + const cloneBlock = () => { + if (nextBlock === block) { + nextBlock = { ...block } + contentChanged = true + } + return nextBlock + } + + const blockOwner = block._kinAccountId ? String(block._kinAccountId) : '' + if ('_kinAccountId' in block) { + delete cloneBlock()._kinAccountId + } + if ('extension' in block && (shouldScrubLeaks || (blockOwner && acct && blockOwner !== acct))) { + delete cloneBlock().extension + } + + if (keyBuf) { + if (isToolUseBlock(nextBlock) && typeof nextBlock.id === 'string') { + const mapped = encodeToolIdForAccount(nextBlock.id, keyBuf) + if (mapped !== nextBlock.id) cloneBlock().id = mapped + } + if (typeof nextBlock.tool_use_id === 'string') { + const mapped = encodeToolIdForAccount(nextBlock.tool_use_id, keyBuf) + if (mapped !== nextBlock.tool_use_id) cloneBlock().tool_use_id = mapped + } + } + + if (nextBlock.type === 'text' && typeof nextBlock.text === 'string') { + let nextText = scrubReminderAndInternalLeaks(nextBlock.text, textOpts) + if (summaryToolEncoder) nextText = rewriteReadonlySummaryToolIds(nextText, summaryToolEncoder) + if (nextText !== nextBlock.text) { + if (!nextText.trim() && nextBlock.text.trim() && nextBlock.text.includes('')) { + contentChanged = true + continue + } + cloneBlock().text = nextText + } + } + + nextContent.push(nextBlock) + } + + if (!contentChanged) return msg + messagesChanged = true + return { ...msg, content: nextContent } + }) + + if (messagesChanged) { + ensureBodyCopy().messages = nextMessages + } + } + + if (keyBuf && Array.isArray(body.safeguards) && body.safeguards.length > 0) { + let sgChanged = false + const nextSafeguards = body.safeguards.map((sg) => { + const prior = sg?.classifier_context?.prior_turn_context + if (!Array.isArray(prior)) return sg + let priorChanged = false + const nextPrior = prior.map((turn) => { + if (!Array.isArray(turn?.tool_use_ids)) return turn + let idsChanged = false + const nextIds = turn.tool_use_ids.map((id) => { + if (typeof id !== 'string') return id + const mapped = encodeToolIdForAccount(id, keyBuf) + if (mapped !== id) idsChanged = true + return mapped + }) + if (!idsChanged) return turn + priorChanged = true + return { ...turn, tool_use_ids: nextIds } + }) + if (!priorChanged) return sg + sgChanged = true + return { + ...sg, + classifier_context: { + ...sg.classifier_context, + prior_turn_context: nextPrior, + }, + } + }) + if (sgChanged) { + ensureBodyCopy().safeguards = nextSafeguards + } + } + + return nextBody +} + +function decodeSafeguardResults(safeguardResults, keyBuf) { + if (!Array.isArray(safeguardResults)) return { value: safeguardResults, changed: false } + let changed = false + const out = safeguardResults.map((entry) => { + const toolUses = entry?.status?.tool_uses + if (!toolUses || typeof toolUses !== 'object' || Array.isArray(toolUses)) return entry + let mapChanged = false + const nextToolUses = {} + for (const [rawId, verdict] of Object.entries(toolUses)) { + const decoded = decodeToolIdFromAccount(rawId, keyBuf) + if (decoded !== rawId) mapChanged = true + nextToolUses[decoded] = verdict + } + if (!mapChanged) return entry + changed = true + return { + ...entry, + status: { + ...entry.status, + tool_uses: nextToolUses, + }, + } + }) + return { value: changed ? out : safeguardResults, changed } +} + +function decodeContentBlocks(content, keyBuf) { + if (!Array.isArray(content)) return { value: content, changed: false } + let changed = false + const out = content.map((block) => { + if (!block || typeof block !== 'object') return block + let nextBlock = block + if (isToolUseBlock(block) && typeof block.id === 'string') { + const decoded = decodeToolIdFromAccount(block.id, keyBuf) + if (decoded !== block.id) { + nextBlock = { ...nextBlock, id: decoded } + changed = true + } + } + if (typeof block.tool_use_id === 'string') { + const decoded = decodeToolIdFromAccount(block.tool_use_id, keyBuf) + if (decoded !== block.tool_use_id) { + nextBlock = { ...nextBlock, tool_use_id: decoded } + changed = true + } + } + return nextBlock + }) + return { value: changed ? out : content, changed } +} + +/** + * Restores account-encoded tool IDs back to public/client tool IDs on a single SSE `data:` line. + * Zero-parse fast path when `key` is null or line contains no tool ID prefix. + */ +export function restoreToolIdsInSSELine(line, key) { + const keyBuf = normalizeKeyBuffer(key) + if (!keyBuf) return line + const str = String(line) + if (!str.startsWith('data:')) return line + if (!str.includes('toolu_') && !str.includes('srvtoolu_') && !str.includes('mcptoolu_') && !str.includes('call_')) { + return line + } + const dataPos = str.indexOf('data:') + const prefix = str.slice(0, dataPos + 5) + const trailingNewline = str.endsWith('\r\n') ? '\r\n' : str.endsWith('\n') ? '\n' : '' + const raw = str.slice(dataPos + 5).trim() + if (!raw || raw === '[DONE]') return line + + let payload + try { + payload = JSON.parse(raw) + } catch { + return line + } + if (!payload || typeof payload !== 'object') return line + + let changed = false + if (payload.type === 'content_block_start' && payload.content_block && typeof payload.content_block === 'object') { + const cb = payload.content_block + if (isToolUseBlock(cb) && typeof cb.id === 'string') { + const decoded = decodeToolIdFromAccount(cb.id, keyBuf) + if (decoded !== cb.id) { + payload = { ...payload, content_block: { ...cb, id: decoded } } + changed = true + } + } else if (typeof cb.tool_use_id === 'string') { + const decoded = decodeToolIdFromAccount(cb.tool_use_id, keyBuf) + if (decoded !== cb.tool_use_id) { + payload = { ...payload, content_block: { ...cb, tool_use_id: decoded } } + changed = true + } + } + } else if (payload.type === 'message_delta' && payload.delta?.safeguard_results) { + const sr = decodeSafeguardResults(payload.delta.safeguard_results, keyBuf) + if (sr.changed) { + payload = { ...payload, delta: { ...payload.delta, safeguard_results: sr.value } } + changed = true + } + } else if (payload.type === 'message_start' && Array.isArray(payload.message?.content)) { + const cb = decodeContentBlocks(payload.message.content, keyBuf) + if (cb.changed) { + payload = { ...payload, message: { ...payload.message, content: cb.value } } + changed = true + } + } + + if (!changed) return line + const space = str.slice(dataPos + 5).startsWith(' ') ? ' ' : '' + return `${prefix}${space}${JSON.stringify(payload)}${trailingNewline}` +} + +/** + * Restores account-encoded tool IDs back to public/client tool IDs in an assembled Anthropic message. + */ +export function restoreToolIdsInMessage(response, key) { + const keyBuf = normalizeKeyBuffer(key) + if (!keyBuf || !response || typeof response !== 'object') return response + let changed = false + let out = response + + const topBlocks = decodeContentBlocks(response.content, keyBuf) + if (topBlocks.changed) { + out = { ...out, content: topBlocks.value } + changed = true + } + if (response.message && typeof response.message === 'object') { + const nested = decodeContentBlocks(response.message.content, keyBuf) + if (nested.changed) { + out = { ...(changed ? out : response), message: { ...response.message, content: nested.value } } + changed = true + } + } + if (response.safeguard_results) { + const sr = decodeSafeguardResults(response.safeguard_results, keyBuf) + if (sr.changed) { + out = { ...(changed ? out : response), safeguard_results: sr.value } + changed = true + } + } + return out +} + +export function normalizePurifySessionKey(rawKey) { + let k = String(rawKey || '').trim() + if (!k) return '' + k = k.replace(/^(?:anthropic:|openai:|google:|claude:)+/i, '') + if (k.startsWith('sess:')) k = k.slice(5) + else if (k.includes(':sess:')) k = k.slice(k.indexOf(':sess:') + 6) + return k.trim() +} + +/** + * Bounded in-memory ledger tracking outbound slot/session lineage for Rust-SSOT + * session-switch purification (zero SQLite/PG writes, zero StickyRouter coupling). + */ +export function createOutboundSlotPurifyLedger({ maxEntries = 8192, ttlMs = 24 * 3600 * 1000 } = {}) { + const entries = new Map() + const resetTombstones = new Map() + + const touchMap = (map, key, val) => { + map.delete(key) + map.set(key, val) + while (map.size > maxEntries) { + const oldest = map.keys().next().value + map.delete(oldest) + } + } + + return { + inspectBeforeHop(rawKey, now = Date.now()) { + const key = normalizePurifySessionKey(rawKey) + if (!key) return { explicitReset: false, prior: null } + const tombstoneExp = resetTombstones.get(key) + let explicitReset = false + if (tombstoneExp != null) { + if (tombstoneExp > now) explicitReset = true + else resetTombstones.delete(key) + } + if (explicitReset) return { explicitReset: true, prior: null } + const rec = entries.get(key) + if (!rec) return { explicitReset: false, prior: null } + if (rec.expiresAt <= now) { + entries.delete(key) + return { explicitReset: false, prior: null } + } + return { + explicitReset: false, + prior: { + vmId: rec.vmId, + accountId: rec.accountId, + sessionId: rec.sessionId, + generation: rec.generation, + }, + } + }, + + commitSlotHop( + rawKey, + { vmId = '', accountId = '', sessionId = '', slotSwitched = false, sessionPurified = false } = {}, + now = Date.now(), + ) { + const key = normalizePurifySessionKey(rawKey) + if (!key || !sessionId) return null + const tombstoneExp = resetTombstones.get(key) + const wasReset = tombstoneExp != null && tombstoneExp > now + if (tombstoneExp != null) resetTombstones.delete(key) + + const prev = entries.get(key) + const prevValid = prev && prev.expiresAt > now ? prev : null + const prevGen = Number(prevValid?.generation) || 0 + const changed = Boolean( + prevValid && + ((vmId && prevValid.vmId && prevValid.vmId !== vmId) || + (accountId && prevValid.accountId && prevValid.accountId !== accountId)), + ) + const baseGen = prevValid ? (changed ? prevGen + 1 : prevGen || 1) : 1 + const floorGen = wasReset || slotSwitched || sessionPurified ? 2 : 1 + const generation = Math.max(floorGen, baseGen) + const next = { + vmId: String(vmId || ''), + accountId: String(accountId || ''), + sessionId: String(sessionId || ''), + generation, + expiresAt: now + ttlMs, + } + touchMap(entries, key, next) + return next + }, + + purgeByFilter(filter = {}, now = Date.now()) { + if (!filter || typeof filter !== 'object') return 0 + const allowAll = Boolean(filter.allowAll || filter.all) + const rawSession = + filter.session_id || (filter.scope_kind !== 'machine' && filter.identity_id ? filter.identity_id : '') + const targetKey = normalizePurifySessionKey(rawSession) + const nodeKey = String(filter.node_key || '').trim() + const targetVmId = String( + filter.node_id || (nodeKey.includes(':') ? nodeKey.slice(nodeKey.indexOf(':') + 1) : ''), + ).trim() + + let purged = 0 + if (allowAll) { + for (const k of entries.keys()) { + touchMap(resetTombstones, k, now + ttlMs) + purged += 1 + } + entries.clear() + return purged + } + if (targetKey) { + if (entries.delete(targetKey)) purged += 1 + touchMap(resetTombstones, targetKey, now + ttlMs) + return Math.max(1, purged) + } + if (targetVmId) { + for (const [k, rec] of entries) { + if (rec.vmId === targetVmId) { + entries.delete(k) + touchMap(resetTombstones, k, now + ttlMs) + purged += 1 + } + } + } + return purged + }, + + clear() { + entries.clear() + resetTombstones.clear() + }, + } +} + +export const outboundSlotPurifyLedger = createOutboundSlotPurifyLedger() diff --git a/src/lib/pool/failover-runner.mjs b/src/lib/pool/failover-runner.mjs index 6104846b6a..ef8e9fef5a 100644 --- a/src/lib/pool/failover-runner.mjs +++ b/src/lib/pool/failover-runner.mjs @@ -23,6 +23,7 @@ import { KERNEL_FAILURE_STATUS, } from '../core/errors.mjs' import { extractProviderCorrelation } from '../protocol/log-fields.mjs' +import { outboundSlotPurifyLedger } from '../identity/session-switch-purify.mjs' import { hasRefreshPresence, readWorkerCredentialFile } from '../oauth/oauth-credentials.mjs' import { ensureWorkerCredential } from '../transport/go-worker-client.mjs' import { kernelFaults } from '../transport/rust-kernel-client.mjs' @@ -1471,6 +1472,12 @@ export class FailoverRunner { const knownSearchRepair = hint && hint.expiresAt > Date.now() && hint.fingerprint === fingerprint() const attemptBody = knownSearchRepair ? flattenSearchResultHistory(requestBody) : requestBody + const purifySessionKey = resolvedSessionId || stickyKey || '' + const slotPurifySnap = + purifySessionKey && selected?.stickyBorrowed !== true + ? outboundSlotPurifyLedger.inspectBeforeHop(purifySessionKey) + : { explicitReset: false, prior: null } + const effectiveFreshSlot = freshSlot || slotPurifySnap.explicitReset const retireKey = `${stickyKey || resolvedSessionId || ''}:${selected.vmId || ''}` const retireGen = this.outboundSessionRetireGen.get(retireKey) || 0 const baseEpoch = `${selected?.stoodIn ? 'standin' : 'vm'}:${selected.vmId || attemptNo}` @@ -1486,7 +1493,8 @@ export class FailoverRunner { ...(repairPolicy ? [repairPolicy] : []), ], attemptStartedAt: attemptStarted, - freshSlot, + freshSlot: effectiveFreshSlot, + priorSlot: slotPurifySnap.prior, outboundEpoch, }) : clone(attemptBody) @@ -1504,6 +1512,16 @@ export class FailoverRunner { const body = wrappedAttempt ? prepared.body : prepared const attemptMeta = wrappedAttempt ? prepared.meta : null + if (purifySessionKey && selected?.stickyBorrowed !== true && attemptMeta?.sessionId) { + outboundSlotPurifyLedger.commitSlotHop(purifySessionKey, { + vmId: selected.vmId, + accountId: selected.accountId, + sessionId: String(attemptMeta.sessionId), + slotSwitched: attemptMeta.slotSwitched === true, + sessionPurified: attemptMeta.sessionPurified === true, + }) + } + result = await callAttempt({ candidate: selected, body, diff --git a/src/lib/pool/sticky-router.mjs b/src/lib/pool/sticky-router.mjs index e93a0dc7c6..901f7f5a32 100644 --- a/src/lib/pool/sticky-router.mjs +++ b/src/lib/pool/sticky-router.mjs @@ -307,6 +307,8 @@ export class StickyRouter { this._l1 = new Map() // key -> { ent, renewedAt } this._l1Neg = new Map() // key -> expiresAtMs this._latestByDevice = new Map() // `${prefix}\0${device}` -> { key, bound_at, expires_at } + this._resetKeys = new Map() // key -> expiresAtMs (explicit reset tombstones forcing generation >= 2) + this._resetAllBeforeMs = 0 this._pendingPgWrites = new Set() this._statsCache = null this._statsRefreshPromises = null @@ -981,6 +983,7 @@ export class StickyRouter { { countHit = true, ifGeneration = null, + minGeneration = 1, replaceSession = false, clearSlot = false, allowMove = false, @@ -1009,13 +1012,21 @@ export class StickyRouter { !clearSlot && (nextAccount !== prev.account_id || nextVm !== prev.vm_id || (slotIndex != null && nextSlot !== prev.slot_index)) ) - const generation = prev.vm_id ? (changed ? prevGeneration + 1 : prevGeneration || 1) : 1 - const sameVm = !!(prev.vm_id && nextVm && prev.vm_id === nextVm) + const wasExplicitlyReset = this.consumeResetMarker(key) + const baseGeneration = prev.vm_id ? (changed ? prevGeneration + 1 : prevGeneration || 1) : 1 + const floorGeneration = Math.max(1, Number(minGeneration) || 1, wasExplicitlyReset ? 2 : 1) + const generation = Math.max(floorGeneration, baseGeneration) + const sameVmAndAccount = !!( + prev.vm_id && + nextVm && + prev.vm_id === nextVm && + (!prev.account_id || !nextAccount || prev.account_id === nextAccount) + ) const nextSessionId = locked ? prev.session_id || sessionId || null : replaceSession ? sessionId || null - : sameVm + : sameVmAndAccount ? prev.session_id || sessionId || null : sessionId || prev.session_id || null const device = deviceId == null ? prev.device_id || null : String(deviceId).trim() || null @@ -1208,6 +1219,210 @@ export class StickyRouter { return this.repo.removeByAccount({ accountId, vmId }) } + _markKeyReset(key, now = Date.now()) { + if (!key) return + const ttl = (this.config.ttl_seconds || 86400) * 1000 + this._resetKeys.delete(key) + this._resetKeys.set(key, now + ttl) + while (this._resetKeys.size > 8192) { + const oldest = this._resetKeys.keys().next().value + this._resetKeys.delete(oldest) + } + } + + peekResetMarker(key, now = Date.now()) { + if (!key) return false + const exp = this._resetKeys.get(key) + if (exp != null) { + if (exp > now) return true + this._resetKeys.delete(key) + } + if (this._resetAllBeforeMs > 0 && now - this._resetAllBeforeMs < (this.config.ttl_seconds || 86400) * 1000) { + const existing = this._l1.get(key)?.ent + if (!existing || Number(existing.bound_at || 0) <= this._resetAllBeforeMs) return true + } + return false + } + + consumeResetMarker(key, now = Date.now()) { + const hit = this.peekResetMarker(key, now) + if (key) this._resetKeys.delete(key) + return hit + } + + /** + * Purge Node StickyRouter L1/Redis/SQLite/PG entries matching panel sticky filter criteria, + * and mark affected session keys so their next turn runs full session purification. + */ + async deleteByFilter(filter = {}) { + const allowAll = Boolean(filter.allowAll || filter.all) + const scopeKind = filter.scope_kind || filter.scopeKind || null + const identityId = filter.identity_id || filter.identityId || null + const sid = String( + filter.session_id || filter.sessionId || (scopeKind === 'session' ? identityId : '') || '', + ).trim() + const mid = String( + filter.machine_id || filter.machineId || (scopeKind === 'machine' ? identityId : '') || '', + ).trim() + const anyId = !scopeKind && identityId ? String(identityId).trim() : '' + let vm = String(filter.node_id || filter.nodeId || filter.vmId || '').trim() + if (!vm && filter.node_key && String(filter.node_key).includes(':')) { + vm = String(filter.node_key).split(':').slice(1).join(':').trim() + } + const acct = String(filter.account_id || filter.accountId || '').trim() + const now = Date.now() + const cache = getCacheRuntime() + const hasRedis = Boolean(cache?.client?.hasRedis) + this._statsCache = null + + if (allowAll) { + const priorKeys = [...this._l1.keys()] + this._l1.clear() + this._latestByDevice.clear() + this._resetAllBeforeMs = now + for (const k of priorKeys) { + this._putL1Neg(k) + this._markKeyReset(k, now) + } + const pgPool = this._resolvePgPool() + if (pgPool && typeof pgPool.query === 'function') { + const res = await pgPool.query('DELETE FROM sticky_sessions RETURNING key') + for (const row of res?.rows || []) { + if (row?.key) { + this._putL1Neg(row.key) + this._markKeyReset(row.key, now) + if (hasRedis) cache.concurrency.delSticky(this._redisStickyKey(row.key)).catch(() => {}) + } + } + return Number(res?.rowCount) || priorKeys.length + } + const { deleted, keys } = this.repo.removeByFilter({ allowAll: true }) + for (const k of keys) { + this._putL1Neg(k) + this._markKeyReset(k, now) + if (hasRedis) cache.concurrency.delSticky(this._redisStickyKey(k)).catch(() => {}) + } + return deleted + } + + if (!sid && !mid && !anyId && !vm && !acct) return 0 + + const matchesEntry = (key, ent) => { + const k = String(key || '') + if (vm && ent?.vm_id !== vm) return false + if (acct && ent?.account_id !== acct) return false + const matchSession = (target) => + k === `sess:${target}` || + k === `family2:${target}` || + k.endsWith(`:sess:${target}`) || + k.endsWith(`:family:${target}`) || + k === target + const matchMachine = (target) => + ent?.device_id === target || k === `dev2:${target}` || k.endsWith(`:dev2:${target}`) + if (sid && !matchSession(sid)) return false + if (mid && !matchMachine(mid)) return false + if (anyId && !matchSession(anyId) && !matchMachine(anyId)) return false + return true + } + + const keysToDelete = new Set() + if (sid) { + this._markKeyReset(`sess:${sid}`, now) + this._markKeyReset(`family2:${sid}`, now) + } + if (anyId) { + this._markKeyReset(`sess:${anyId}`, now) + this._markKeyReset(`family2:${anyId}`, now) + } + for (const [k, { ent }] of this._l1) { + if (matchesEntry(k, ent)) { + keysToDelete.add(k) + this._l1.delete(k) + this._putL1Neg(k) + this._markKeyReset(k, now) + } + } + for (const [mk, rec] of this._latestByDevice) { + if ( + keysToDelete.has(rec.key) || + (mid && mk.endsWith(`\u0000${mid}`)) || + (anyId && mk.endsWith(`\u0000${anyId}`)) + ) { + this._latestByDevice.delete(mk) + } + } + + const pgPool = this._resolvePgPool() + if (pgPool && typeof pgPool.query === 'function') { + const clauses = [] + const params = [] + const pushParam = (val) => { + params.push(val) + return `$${params.length}` + } + if (vm) clauses.push(`vm_id = ${pushParam(vm)}`) + if (acct) clauses.push(`account_id = ${pushParam(acct)}`) + if (sid) { + const pExact = pushParam(`sess:${sid}`) + const pFam = pushParam(`family2:${sid}`) + const pLikeSess = pushParam(`%:sess:${sid}`) + const pLikeFam = pushParam(`%:family:${sid}`) + const pRaw = pushParam(sid) + clauses.push( + `(key = ${pExact} OR key = ${pFam} OR key LIKE ${pLikeSess} OR key LIKE ${pLikeFam} OR key = ${pRaw})`, + ) + } + if (mid) { + const pDev = pushParam(mid) + const pDevKey = pushParam(`dev2:${mid}`) + const pLikeDev = pushParam(`%:dev2:${mid}`) + clauses.push(`(device_id = ${pDev} OR key = ${pDevKey} OR key LIKE ${pLikeDev})`) + } + if (anyId) { + const pS = pushParam(`sess:${anyId}`) + const pF = pushParam(`family2:${anyId}`) + const pLS = pushParam(`%:sess:${anyId}`) + const pLF = pushParam(`%:family:${anyId}`) + const pD = pushParam(anyId) + const pDK = pushParam(`dev2:${anyId}`) + const pLD = pushParam(`%:dev2:${anyId}`) + clauses.push( + `(key = ${pS} OR key = ${pF} OR key LIKE ${pLS} OR key LIKE ${pLF} OR device_id = ${pD} OR key = ${pDK} OR key LIKE ${pLD})`, + ) + } + const sql = `DELETE FROM sticky_sessions WHERE ${clauses.join(' AND ')} RETURNING key` + const res = await pgPool.query(sql, params) + for (const row of res?.rows || []) { + if (row?.key) { + keysToDelete.add(row.key) + this._putL1Neg(row.key) + this._markKeyReset(row.key, now) + } + } + if (hasRedis) { + for (const k of keysToDelete) cache.concurrency.delSticky(this._redisStickyKey(k)).catch(() => {}) + } + return Number(res?.rowCount) || keysToDelete.size + } + + const { deleted, keys } = this.repo.removeByFilter({ + sessionId: sid || null, + machineId: mid || null, + identityId: anyId || null, + nodeId: vm || null, + accountId: acct || null, + }) + for (const k of keys) { + keysToDelete.add(k) + this._putL1Neg(k) + this._markKeyReset(k, now) + } + if (hasRedis) { + for (const k of keysToDelete) cache.concurrency.delSticky(this._redisStickyKey(k)).catch(() => {}) + } + return deleted || keysToDelete.size + } + /** Live keys pinned to this account or VM, so their windows leave with them. */ boundKeys({ accountId = null, vmId = null } = {}) { if (!accountId && !vmId) return [] diff --git a/src/lib/pool/thinking-owner.mjs b/src/lib/pool/thinking-owner.mjs index be464a32f9..032ea9dd01 100644 --- a/src/lib/pool/thinking-owner.mjs +++ b/src/lib/pool/thinking-owner.mjs @@ -682,12 +682,18 @@ function isPureToolResultTurn(message) { * - Without a reachable database the body goes unchanged. * @returns {{ body: object, kept: number, unknownKept: number, dropped: number, droppedTurns: number, openLoop: boolean, thinkingOff: boolean, bailed: string|null }} */ -export function dropForeignThinkingForCrag(body, accountId, store = thinkingOwners, { mode = 'all' } = {}) { +export function dropForeignThinkingForCrag( + body, + accountId, + store = thinkingOwners, + { mode = 'all', purifyPrefill = false } = {}, +) { const foreignOnly = mode === 'foreign_only' const counts = { kept: 0, unknownKept: 0, foreign: 0, + knownForeign: 0, dropped: 0, droppedTurns: 0, openLoop: false, @@ -703,7 +709,10 @@ export function dropForeignThinkingForCrag(body, accountId, store = thinkingOwne try { owners = store.ownersOf([...new Set(keys)]) } catch {} - if (!owners) return { body, ...counts, bailed: 'no_db' } + if (!owners) { + if (!purifyPrefill || foreignOnly) return { body, ...counts, bailed: 'no_db' } + owners = new Map() + } let loopStart = 0 for (let i = messages.length - 1; i >= 0; i -= 1) { @@ -725,6 +734,7 @@ export function dropForeignThinkingForCrag(body, accountId, store = thinkingOwne return } counts.foreign += 1 + if (owner != null) counts.knownForeign += 1 // foreign_only: no record is not proof of another account. Keep it and // let the upstream 400 (plus the signature repair) handle the rare miss, // rather than dropping the caller's own thinking on an incomplete table. @@ -740,7 +750,7 @@ export function dropForeignThinkingForCrag(body, accountId, store = thinkingOwne }) if (!any) return { body, ...counts } const last = messages.length - 1 - if (messages[last]?.role === 'assistant' && foreignAt[last]?.size) { + if (!purifyPrefill && messages[last]?.role === 'assistant' && foreignAt[last]?.size) { return { body, ...counts, openLoop: false, bailed: 'prefill' } } diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index a7dd95de32..a549f5a4df 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -270,6 +270,13 @@ import { rewriteResponseToolIds, unmapToolUseIdFromAccount, } from '../identity/tool-id-mapping.mjs' +import { + createToolIdOwnerTracker, + deriveAccountToolIdKey, + purifySessionPayloadForSlot, + restoreToolIdsInMessage, + restoreToolIdsInSSELine, +} from '../identity/session-switch-purify.mjs' import { isCodexVm } from '../vm/vm-kind.mjs' import { createRequestBodyContext, shallowCopyBody } from './request-body-context.mjs' import { jevInterceptSessionCache } from './jev-intercept.mjs' @@ -789,6 +796,7 @@ export function shouldPreserveCliNodeZeroRoleSystem(routing = {}, capabilities = export function createHandleProtocol(deps) { const issuedTools = createIssuedToolReplay() + const toolIdOwners = createToolIdOwnerTracker() const json = (...args) => deps.json(...args) const writeSSEHeaders = (...args) => deps.writeSSEHeaders(...args) const readBody = (...args) => deps.readBody(...args) @@ -1605,6 +1613,7 @@ export function createHandleProtocol(deps) { signal, deliveryMode, toolNames = {}, + toolIdKey = null, want1m = false, preserveCacheBreakpoints = false, cliHop = false, @@ -1618,6 +1627,9 @@ export function createHandleProtocol(deps) { officialPassthrough = false, officialTraffic = false, safeguardsSanitized = false, + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, requestContext = null, routing = {}, noGoFallback = false, @@ -1663,6 +1675,9 @@ export function createHandleProtocol(deps) { officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, requestContext, slotWaitMs: candidate.slotWaitMs, slotWaitDeadlineMs: candidate.slotWaitDeadlineMs, @@ -1683,10 +1698,16 @@ export function createHandleProtocol(deps) { }) Object.assign(workerResult, mergeAssembledAssistantHop(workerResult, assembler.message)) if (workerResult?.body) { - workerResult.body = restoreToolNames(workerResult.body, toolNames) + let restoredBody = restoreToolNames(workerResult.body, toolNames) if (slotRewrite) { - workerResult.body = rewriteOutboundSlotMessage(workerResult.body, slotRewrite) + restoredBody = rewriteOutboundSlotMessage(restoredBody, slotRewrite) + if (candidate?.accountId) toolIdOwners.recordMessage(restoredBody, candidate.accountId) + } else if (toolIdKey) { + restoredBody = restoreToolIdsInMessage(restoredBody, toolIdKey) + } else if (candidate?.accountId) { + toolIdOwners.recordMessage(restoredBody, candidate.accountId) } + workerResult.body = restoredBody } return acceptAssistantHop(workerResult) } @@ -4147,23 +4168,39 @@ export function createHandleProtocol(deps) { return owned.body } const attemptStartedAt = extra.attemptStartedAt ?? Date.now() - const attemptEpoch = - extra.outboundEpoch || - (extra.freshSlot - ? `slot:${selected.slotIndex ?? 'x'}:${attemptStartedAt}` - : `${selected.stoodIn ? 'standin' : 'vm'}:${selected.vmId || extra.attemptNo || ''}`) - const attemptBound = extra.stickyBound - const keptAccount = extra.freshSlot ? '' : attemptBound?.accountId || '' - const keptVm = extra.freshSlot ? '' : attemptBound?.vmId || '' - const sessionSwitchedAccount = Boolean( - selected.stoodIn || - (Number(extra.attemptNo) > 1 && extra.freshSlot) || - (keptAccount && selected.accountId && keptAccount !== selected.accountId) || - (keptVm && - selected.vmId && - keptVm !== selected.vmId && - (!keptAccount || keptAccount !== selected.accountId)), + const attemptBound = extra.priorSlot || extra.stickyBound || null + const boundVmChanged = Boolean(attemptBound?.vmId && selected.vmId && attemptBound.vmId !== selected.vmId) + const boundAccountChanged = Boolean( + attemptBound?.accountId && selected.accountId && attemptBound.accountId !== selected.accountId, + ) + const sameBoundSlot = Boolean( + !extra.freshSlot && + attemptBound && + (attemptBound.vmId || attemptBound.accountId) && + !boundVmChanged && + !boundAccountChanged, + ) + const stickyPurifiedGen = sameBoundSlot && Number(attemptBound?.generation) > 1 + const hasForeignTools = Boolean( + !requestContext && + !stickyPurifiedGen && + selected.accountId && + toolIdOwners.hasForeignToolIds(body, selected.accountId), + ) + let slotSwitched = Boolean( + extra.freshSlot || selected.stoodIn || boundVmChanged || boundAccountChanged || hasForeignTools, ) + const keptSession = slotSwitched ? '' : attemptBound?.sessionId || '' + const keptAccount = slotSwitched ? '' : attemptBound?.accountId || '' + const keptVm = slotSwitched ? '' : attemptBound?.vmId || '' + const mintSlotEpoch = () => + `slot:${selected.accountId || ''}:${selected.vmId || ''}:${selected.slotIndex ?? 'x'}:${attemptStartedAt}:${extra.attemptNo || 1}` + const attemptEpoch = slotSwitched + ? mintSlotEpoch() + : extra.outboundEpoch || + (extra.freshSlot + ? `slot:${selected.slotIndex ?? 'x'}:${attemptStartedAt}` + : `${selected.stoodIn ? 'standin' : 'vm'}:${selected.vmId || extra.attemptNo || ''}`) const hasSlotAccountProfile = Boolean( selected?.vm && !isCodexVm(selected.vm) && @@ -4211,7 +4248,7 @@ export function createHandleProtocol(deps) { if (attemptReplayScope) { body = issuedTools.restore(attemptReplayScope, body) } - const attemptSessionId = + let attemptSessionId = slotProfile?.session_id_seed && executionSession ? deriveAccountSlotSessionId({ sessionIdSeed: slotProfile.session_id_seed, @@ -4222,11 +4259,31 @@ export function createHandleProtocol(deps) { : resolveOutboundSessionId(executionSession, { ...sessionContext, accountId: selected.accountId, + boundSessionId: keptSession, + boundAccountId: keptAccount, + boundVmId: keptVm, vmId: selected.vmId, + slotSwitched, + sessionPurified: slotSwitched || stickyPurifiedGen, epoch: attemptEpoch, }) const identity = loadVmIdentity(selected.exec) if (identity && attemptSessionId) identity.callerSessionId = attemptSessionId + const hasSlotToolMapping = Boolean(slotProfile?.tool_id_seed) + const targetToolKeySource = + selected.vm?.claude?.accountUuid || + selected.vm?.claude?.account_uuid || + identity?.accountUuid || + selected.accountId || + selected.vmId || + '' + const accountToolKey = hasSlotToolMapping + ? null + : deriveAccountToolIdKey(targetToolKeySource, cfg?.security?.dbSecret || '') + const summaryToolEncoder = hasSlotToolMapping + ? (id) => mapToolUseIdForAccount(slotProfile.tool_id_seed, id) + : null + const targetSlotEmail = selected.vm?.claude?.email || selected.vm?.email || '' const credMode = credentialModeFromOauth(selected.vm?.claude || {}) const modeOverride = slotPersonaModeOverride(selected.vm) let routingNow = getRouting() @@ -4415,20 +4472,30 @@ export function createHandleProtocol(deps) { // Default to 'foreign_only' unless explicitly disabled (false), and // always enforce foreign signature stripping when switching accounts/slots. const rawForeignSetting = routingNow?.compatibility?.crag_drop_foreign_thinking - const cragForeignMode = - rawForeignSetting === true + const cragForeignMode = cragForeignThinkingMode(rawForeignSetting) + const effectiveCragForeignMode = + slotSwitched || stickyPurifiedGen ? 'all' - : rawForeignSetting === false && !sessionSwitchedAccount - ? 'off' - : cragForeignThinkingMode(rawForeignSetting ?? 'foreign_only') + : rawForeignSetting === true + ? 'all' + : rawForeignSetting === false + ? !strictPassthrough + ? 'foreign_only' + : 'off' + : cragForeignMode !== 'off' + ? cragForeignMode + : !strictPassthrough + ? 'foreign_only' + : 'off' let cragOwned = { body: source, foreign: 0 } - let foreignThinking = sessionSwitchedAccount - if (cragForeignMode !== 'off') { + let foreignThinking = slotSwitched + if (effectiveCragForeignMode !== 'off') { cragOwned = dropForeignThinkingForCrag(source, selected.accountId, thinkingOwnerStore, { - mode: cragForeignMode, + mode: effectiveCragForeignMode, + purifyPrefill: slotSwitched || stickyPurifiedGen, }) source = cragOwned.body - if (sessionSwitchedAccount && cragOwned.bailed === 'no_db') { + if (slotSwitched && cragOwned.bailed === 'no_db') { const fallbackStripped = stripCrossSlotSignaturesFallback(source) if (fallbackStripped.dropped > 0) { source = fallbackStripped.body @@ -4440,15 +4507,31 @@ export function createHandleProtocol(deps) { } } } - foreignThinking = - sessionSwitchedAccount || (!strictPassthrough && cragOwned.foreign > 0) || cragOwned.dropped > 0 + foreignThinking = slotSwitched || (!strictPassthrough && cragOwned.foreign > 0) || cragOwned.dropped > 0 + if (!slotSwitched && !stickyPurifiedGen && cragOwned.knownForeign > 0) { + slotSwitched = true + if (!slotProfile?.session_id_seed || !executionSession) { + attemptSessionId = resolveOutboundSessionId(executionSession, { + ...sessionContext, + accountId: selected.accountId, + boundSessionId: '', + boundAccountId: '', + boundVmId: '', + vmId: selected.vmId, + slotSwitched: true, + sessionPurified: true, + epoch: mintSlotEpoch(), + }) + if (identity && attemptSessionId) identity.callerSessionId = attemptSessionId + } + } if (cragOwned.dropped || cragOwned.bailed) { const { kept, unknownKept, dropped, droppedTurns, openLoop, thinkingOff, bailed } = cragOwned logBag.hop_meta = { ...logBag.hop_meta, thinking_owner_crag: { account_id: selected.accountId, - mode: cragForeignMode, + mode: effectiveCragForeignMode, kept, unknown_kept: unknownKept, dropped, @@ -4461,7 +4544,7 @@ export function createHandleProtocol(deps) { } } else if (!strictPassthrough) { const inspected = inspectForeignThinking(source, selected.accountId, thinkingOwnerStore) - foreignThinking = sessionSwitchedAccount || inspected.foreign > 0 + foreignThinking = slotSwitched || inspected.foreign > 0 if (inspected.kept || inspected.foreign) { logBag.hop_meta = { ...logBag.hop_meta, @@ -4476,6 +4559,18 @@ export function createHandleProtocol(deps) { } } } + const sessionPurified = Boolean(!requestContext && (slotSwitched || stickyPurifiedGen)) + if (sessionPurified) { + source = purifySessionPayloadForSlot(source, { + toolKey: accountToolKey, + purifyTools: Boolean(accountToolKey), + encodeSummaryToolId: summaryToolEncoder, + slotSwitched, + sessionPurified: true, + targetAccountId: selected.accountId, + targetEmail: targetSlotEmail, + }) + } if (!strictPassthrough) { for (const policy of extra.repairs || []) source = repairAnthropicRequest(source, policy) if (!officialTraffic && !officialPassthrough && !attemptPoolOwnsSystemDirectly) { @@ -4574,7 +4669,10 @@ export function createHandleProtocol(deps) { body: hopBody, meta: { toolNames, + toolIdKey: sessionPurified ? accountToolKey : null, sessionId: attemptSessionId, + slotSwitched, + sessionPurified, slotEpoch, replayScope: attemptReplayScope, slotRewrite: cragSlotForward.slotRewrite, @@ -4691,6 +4789,18 @@ export function createHandleProtocol(deps) { if (attemptReplayScope) { hopBody = issuedTools.restore(attemptReplayScope, hopBody) } + const cliSessionPurified = Boolean(!requestContext && (slotSwitched || stickyPurifiedGen)) + if (cliSessionPurified) { + hopBody = purifySessionPayloadForSlot(hopBody, { + toolKey: accountToolKey, + purifyTools: Boolean(accountToolKey), + encodeSummaryToolId: summaryToolEncoder, + slotSwitched, + sessionPurified: true, + targetAccountId: selected.accountId, + targetEmail: targetSlotEmail, + }) + } const cliSlotForward = applySlotForwardPipeline(hopBody, { profile: slotProfile, callerCwd: callerEnvironment?.cwd, @@ -4779,7 +4889,10 @@ export function createHandleProtocol(deps) { body: hopBody, meta: { toolNames: composeToolNames(inboundToolReverse, clientToolNames), + toolIdKey: cliSessionPurified ? accountToolKey : null, sessionId: attemptSessionId, + slotSwitched, + sessionPurified: cliSessionPurified, slotEpoch, replayScope: attemptReplayScope, slotRewrite: cliSlotForward.slotRewrite, @@ -4872,6 +4985,18 @@ export function createHandleProtocol(deps) { if (attemptReplayScope) { hopBody = issuedTools.restore(attemptReplayScope, hopBody) } + const httpSessionPurified = Boolean(!requestContext && (slotSwitched || stickyPurifiedGen)) + if (httpSessionPurified) { + hopBody = purifySessionPayloadForSlot(hopBody, { + toolKey: accountToolKey, + purifyTools: Boolean(accountToolKey), + encodeSummaryToolId: summaryToolEncoder, + slotSwitched, + sessionPurified: true, + targetAccountId: selected.accountId, + targetEmail: targetSlotEmail, + }) + } const httpSlotForward = applySlotForwardPipeline(hopBody, { profile: slotProfile, callerCwd: callerEnvironment?.cwd, @@ -4934,7 +5059,10 @@ export function createHandleProtocol(deps) { body: outbound, meta: { toolNames: composeToolNames(inboundToolReverse, prepared.toolNames), + toolIdKey: httpSessionPurified ? accountToolKey : null, sessionId: attemptSessionId, + slotSwitched, + sessionPurified: httpSessionPurified, slotEpoch, replayScope: attemptReplayScope, slotRewrite: httpSlotForward.slotRewrite, @@ -4969,6 +5097,7 @@ export function createHandleProtocol(deps) { signal, deliveryMode: attemptDelivery, toolNames: attemptMeta?.toolNames || {}, + toolIdKey: attemptMeta?.toolIdKey || null, cacheTtl, preserveCacheBreakpoints, cliHop: attemptMeta?.cliHop === true, @@ -4982,6 +5111,9 @@ export function createHandleProtocol(deps) { officialPassthrough: attemptMeta?.officialPassthrough ?? officialPassthrough === true, officialTraffic: attemptMeta?.officialTraffic ?? officialTraffic === true, safeguardsSanitized: attemptMeta?.safeguardsSanitized === true, + outboundSessionId: attemptMeta?.sessionId || '', + slotSwitched: attemptMeta?.slotSwitched === true, + sessionPurified: attemptMeta?.sessionPurified === true, requestContext: attemptMeta?.requestContext || requestContext, want1m, routing: attemptMeta?.transportRouting ?? getRouting(), @@ -5081,6 +5213,9 @@ export function createHandleProtocol(deps) { officialPassthrough: attemptMeta?.officialPassthrough ?? officialPassthrough === true, officialTraffic: attemptMeta?.officialTraffic ?? officialTraffic === true, safeguardsSanitized: attemptMeta?.safeguardsSanitized === true, + outboundSessionId: attemptMeta?.sessionId || '', + slotSwitched: attemptMeta?.slotSwitched === true, + sessionPurified: attemptMeta?.sessionPurified === true, requestContext: attemptMeta?.requestContext || requestContext, body, reqHeaders: attemptReqHeaders, @@ -5112,7 +5247,12 @@ export function createHandleProtocol(deps) { if (skipResponseHeaders(rawLine)) return const restoredLine = restoreToolNamesInSSELine(rawLine, attemptMeta?.toolNames || {}) const transformedLines = slotSseRewriter ? slotSseRewriter.transformLine(restoredLine) : [restoredLine] - for (const line of transformedLines) { + for (let line of transformedLines) { + if (!slotSseRewriter && attemptMeta?.toolIdKey) { + line = restoreToolIdsInSSELine(line, attemptMeta.toolIdKey) + } else if (candidate?.accountId) { + toolIdOwners.recordSSELine(line, candidate.accountId) + } emitTransformedSseLine(line) } }, diff --git a/src/lib/protocol/issued-tool-replay.mjs b/src/lib/protocol/issued-tool-replay.mjs index de50ac8806..9d87b5b3eb 100644 --- a/src/lib/protocol/issued-tool-replay.mjs +++ b/src/lib/protocol/issued-tool-replay.mjs @@ -359,7 +359,20 @@ export function createIssuedToolReplay({ } return removed } - const api = { remember, restore, clearScopes, stats } + function clearByFilter({ sessionId = null, allowAll = false } = {}) { + if (allowAll) return clearScopes(() => true) + const sid = String(sessionId || '').trim() + if (!sid) return 0 + return clearScopes((scope) => { + try { + const parsed = JSON.parse(scope) + return Array.isArray(parsed) && parsed[1] === sid + } catch { + return scope.includes(sid) + } + }) + } + const api = { remember, restore, clearScopes, clearByFilter, stats } if (typeof WeakRef === 'function') { activeReplayBooks.add(new WeakRef(api)) } diff --git a/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index ee5dddff9c..f83e4525a5 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -24,6 +24,7 @@ import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' import { keyAllowsModel, parseKeyAllowedModels } from '../admin/key-models.mjs' +import { outboundSlotPurifyLedger } from '../identity/session-switch-purify.mjs' import { keyAllowsEndpoint, keyAllowsGeminiEnv, @@ -4047,6 +4048,7 @@ export class SchedulerRuntime { } this.#pruneStickyCache(filter) + outboundSlotPurifyLedger.purgeByFilter(filter) return { ok: true, diff --git a/src/lib/transport/go-worker-client.mjs b/src/lib/transport/go-worker-client.mjs index 2007313ffe..586b8fcc28 100644 --- a/src/lib/transport/go-worker-client.mjs +++ b/src/lib/transport/go-worker-client.mjs @@ -16,6 +16,7 @@ import { modelDirectiveForCrag } from '../protocol/model-policy.mjs' import { capOutboundBody } from '../protocol/outbound-snapshot.mjs' import { cacheTtlFromRouting } from '../protocol/cache-ttl.mjs' import { ccEntrypointFromRouting, stripSubagentBilling } from '../identity/crs-persona.mjs' +import { derivePurifiedParentSessionId } from '../identity/identity-rewrite.mjs' import { isPromptSpecV1Caps, sanitizePromptSpec } from '../identity/system-prompt-spec.mjs' import { deriveAccountSlotSessionId } from '../identity/tool-id-mapping.mjs' import { getSlotSessionEpoch } from '../protocol/issued-tool-replay.mjs' @@ -582,6 +583,52 @@ function headerValueCaseInsensitive(headers, targetLower) { return null } +export function purifyCragCallerHeaders( + headers, + { + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, + sessionDerivedBySlot = false, + accountId = '', + vmId = '', + } = {}, +) { + if (!headers || typeof headers !== 'object') return headers + if (!slotSwitched && !sessionPurified) return headers + const cleanSid = sanitizeCallerHeaderValue(outboundSessionId, 256) + const out = { ...headers } + let changed = false + if (!sessionDerivedBySlot) { + if (cleanSid && Object.hasOwn(out, 'x-claude-code-session-id') && out['x-claude-code-session-id'] !== cleanSid) { + out['x-claude-code-session-id'] = cleanSid + changed = true + } + if (Object.hasOwn(out, 'x-claude-code-parent-session-id') && out['x-claude-code-parent-session-id']) { + const purifiedParent = derivePurifiedParentSessionId(out['x-claude-code-parent-session-id'], { + accountId, + vmId, + outboundSessionId: cleanSid || out['x-claude-code-session-id'] || '', + }) + if (purifiedParent && purifiedParent !== out['x-claude-code-parent-session-id']) { + out['x-claude-code-parent-session-id'] = purifiedParent + changed = true + } + } + } + if (slotSwitched) { + if (Object.hasOwn(out, 'x-claude-code-prompt-id')) { + out['x-claude-code-prompt-id'] = randomUUID() + changed = true + } + if (Object.hasOwn(out, 'x-client-request-id')) { + out['x-client-request-id'] = randomUUID() + changed = true + } + } + return changed ? out : headers +} + function resolveCancelSessionId(cancelSessionId, reqHeaders, envelopeHeaders) { for (const candidate of [ headerValueCaseInsensitive(envelopeHeaders, 'x-claude-code-session-id'), @@ -972,6 +1019,9 @@ export function prepareWorkerPayload({ officialPassthrough = null, officialTraffic = null, safeguardsSanitized = false, + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, slotEpoch = null, } = {}) { const health = exec?.workerStatus @@ -1016,7 +1066,7 @@ export function prepareWorkerPayload({ : slotSessionSeed ? getSlotSessionEpoch({ vmId: slotVmId || '', sessionId: String(rawCallerSessionHeader).trim() }) : 0 - const callerHeaders = + const rawCallerHeaders = print && verifiedOfficial ? extractCragCallerHeaders(reqHeaders, { includeUserAgent: headlessBridge, @@ -1025,6 +1075,16 @@ export function prepareWorkerPayload({ slotEpoch: resolvedSlotEpoch, }) : undefined + const callerHeaders = rawCallerHeaders + ? purifyCragCallerHeaders(rawCallerHeaders, { + outboundSessionId, + slotSwitched, + sessionPurified, + sessionDerivedBySlot: Boolean(slotSessionSeed), + accountId: exec?.vm?.claude?.accountUuid || exec?.vm?.claude?.account_id || identity?.accountUuid || '', + vmId: exec?.vmId || exec?.vm?.id || identity?.vmId || '', + }) + : undefined const nativeOwnsHeaders = cliHop && cragPrint === true && @@ -1156,6 +1216,9 @@ export async function workerEnvelope({ officialPassthrough = null, officialTraffic = null, safeguardsSanitized = false, + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, redactionPrincipal = '', redactionSession = '', slotEpoch = null, @@ -1176,6 +1239,9 @@ export async function workerEnvelope({ officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, slotEpoch, }) const redaction = await redactionContext({ routing, exec, redactionPrincipal, redactionSession }) @@ -1395,6 +1461,9 @@ async function callGoWorkerRaw({ officialPassthrough = null, officialTraffic = null, safeguardsSanitized = false, + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, onEnvelope = null, redactionPrincipal = '', redactionSession = '', @@ -1425,6 +1494,9 @@ async function callGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, slotEpoch, }) const cleanPromptSpec = !nativeCragRequest(exec, cragPrint) && promptSpec ? sanitizePromptSpec(promptSpec) : null @@ -1501,6 +1573,9 @@ async function callGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, redactionPrincipal, redactionSession, slotEpoch, @@ -1696,6 +1771,9 @@ async function streamGoWorkerRaw({ officialPassthrough = null, officialTraffic = null, safeguardsSanitized = false, + outboundSessionId = '', + slotSwitched = false, + sessionPurified = false, onEnvelope = null, onOutboundHeaders = null, redactionPrincipal = '', @@ -1728,6 +1806,9 @@ async function streamGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, slotEpoch, }) const cleanPromptSpec = !nativeCragRequest(exec, cragPrint) && promptSpec ? sanitizePromptSpec(promptSpec) : null @@ -1875,6 +1956,9 @@ async function streamGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + outboundSessionId, + slotSwitched, + sessionPurified, redactionPrincipal, redactionSession, slotEpoch, diff --git a/test/unit/agent-summary-routing.test.mjs b/test/unit/agent-summary-routing.test.mjs index 52c92dfdc4..683ad869d0 100644 --- a/test/unit/agent-summary-routing.test.mjs +++ b/test/unit/agent-summary-routing.test.mjs @@ -258,7 +258,7 @@ function harness({ }, stickyRouter: sticky, accountQuota: { ingestHeaders() {} }, - apiKeyStore: {}, + apiKeyStore: { acquire: () => ({ ok: true }), release() {} }, apiScheduler: {}, apiEndpointStore: {}, settings: { get: (_key, fallback) => fallback }, @@ -1048,3 +1048,628 @@ test('4-module single-slot pipeline rewrites CWD, gitStatus, toolu_*, and sessio fs.rmSync(root, { recursive: true, force: true }) } }) + +test('slot switch purifies outbound session headers, foreign thinking, tool IDs, and sticky reset across protocols', async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-purify-e2e-')) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + + const sock1 = path.join(root, 'vm1.sock') + const sock2 = path.join(root, 'vm2.sock') + const vm1Envelopes = [] + const vm2Envelopes = [] + const acct1ToolId = 'toolu_01AccountOneIssuedTool99' + const acct2ToolId = 'toolu_01AccountTwoIssuedTool88' + const acct1Sig = 'sig-minted-by-account-1-0123456789abcdef' + + const http = await import('node:http') + const net = await import('node:net') + const { createSchedulerPoolsHandler } = await import('../../src/lib/admin/scheduler-pools-routes.mjs') + const { outboundSlotPurifyLedger } = await import('../../src/lib/identity/session-switch-purify.mjs') + const { mapToolUseIdForAccount } = await import('../../src/lib/identity/tool-id-mapping.mjs') + const { activateFixture, seedEncryptedPackage } = await import('../fixtures/crag-license.mjs') + outboundSlotPurifyLedger.clear() + t.after(() => outboundSlotPurifyLedger.clear()) + + const startMockCragUds = (sockPath, envelopes, emittedToolId, emittedSig) => + new Promise((resolve) => { + const srv = net.createServer() + srv.close() + const httpSrv = http.createServer(async (req, res) => { + if (req.url === '/health') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end( + JSON.stringify({ + ok: true, + healthy: true, + ready: true, + runtime_variant: 'crag-v2', + ready_slots: 2, + capabilities: ['prompt_append', 'generation_controls_v3', 'headless_claude_bridge_v1', 'caller_cwd'], + }), + ) + return + } + const chunks = [] + for await (const c of req) chunks.push(c) + const env = JSON.parse(Buffer.concat(chunks).toString('utf8')) + envelopes.push(env) + res.writeHead(200, { 'content-type': 'text/event-stream' }) + const events = [ + { + type: 'message_start', + message: { + id: 'msg_slot_hop', + type: 'message', + role: 'assistant', + model: env.body?.model || 'claude-sonnet-5-5', + content: [], + usage: { input_tokens: 20, output_tokens: 0 }, + }, + }, + ...(emittedSig + ? [ + { + type: 'content_block_start', + index: 0, + content_block: { type: 'thinking', thinking: '', signature: '' }, + }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'thinking_delta', thinking: 'slot reasoning' }, + }, + { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: emittedSig } }, + { type: 'content_block_stop', index: 0 }, + ] + : []), + { + type: 'content_block_start', + index: emittedSig ? 1 : 0, + content_block: { type: 'tool_use', id: emittedToolId, name: 'Read', input: {} }, + }, + { + type: 'content_block_delta', + index: emittedSig ? 1 : 0, + delta: { type: 'input_json_delta', partial_json: '{"file_path":"/tmp/demo.txt"}' }, + }, + { type: 'content_block_stop', index: emittedSig ? 1 : 0 }, + { + type: 'message_delta', + delta: { stop_reason: 'tool_use', stop_sequence: null }, + usage: { output_tokens: 12 }, + }, + { type: 'message_stop' }, + ] + for (const ev of events) { + res.write(`event: ${ev.type}\ndata: ${JSON.stringify(ev)}\n\n`) + } + res.end() + }) + httpSrv.listen(sockPath, () => resolve(httpSrv)) + }) + + const srv1 = await startMockCragUds(sock1, vm1Envelopes, acct1ToolId, acct1Sig) + const srv2 = await startMockCragUds(sock2, vm2Envelopes, acct2ToolId, 'sig-minted-by-account-2-abcdef0123456789') + t.after(() => { + srv1.close() + srv2.close() + }) + + const home1 = path.join(root, 'vms', 'vm-01', 'cli-home') + const home2 = path.join(root, 'vms', 'vm-02', 'cli-home') + const run1 = path.join(root, 'vms', 'vm-01', 'run') + const run2 = path.join(root, 'vms', 'vm-02', 'run') + fs.mkdirSync(home1, { recursive: true }) + fs.mkdirSync(home2, { recursive: true }) + fs.mkdirSync(run1, { recursive: true }) + fs.mkdirSync(run2, { recursive: true }) + fs.writeFileSync(path.join(run1, 'internal.token'), 'tok1\n', { mode: 0o600 }) + fs.writeFileSync(path.join(run2, 'internal.token'), 'tok2\n', { mode: 0o600 }) + fs.writeFileSync(path.join(run1, 'kernel.json'), JSON.stringify({ socket_path: sock1, internal_token: 'tok1' })) + fs.writeFileSync(path.join(run2, 'kernel.json'), JSON.stringify({ socket_path: sock2, internal_token: 'tok2' })) + + const prevKernelBin = process.env.KIN_KERNEL_BIN + process.env.KIN_KERNEL_BIN = '/bin/true' + t.after(() => { + clearRustHealthCache('vm-01') + clearRustHealthCache('vm-02') + if (prevKernelBin === undefined) delete process.env.KIN_KERNEL_BIN + else process.env.KIN_KERNEL_BIN = prevKernelBin + }) + + const vm1 = { + id: 'vm-01', + inference_engine: 'rust', + dataplane: 'crag', + crag_kernel_version: 'v2', + runtime: { + kernel_socket: sock1, + worker_run_dir: run1, + worker_token_file: path.join(run1, 'internal.token'), + }, + fingerprint: { device_id: '1'.repeat(64) }, + claude: { + accountUuid: '00000000-0000-4000-8000-000000000111', + account_uuid: '00000000-0000-4000-8000-000000000111', + account_tier: 'max', + }, + } + const vm2 = { + id: 'vm-02', + inference_engine: 'rust', + dataplane: 'crag', + crag_kernel_version: 'v2', + runtime: { + kernel_socket: sock2, + worker_run_dir: run2, + worker_token_file: path.join(run2, 'internal.token'), + }, + fingerprint: { device_id: '2'.repeat(64) }, + claude: { + accountUuid: '00000000-0000-4000-8000-000000000222', + account_uuid: '00000000-0000-4000-8000-000000000222', + account_tier: 'max', + }, + } + fs.writeFileSync(path.join(root, 'vms', 'vm-01.json'), JSON.stringify(vm1)) + fs.writeFileSync(path.join(root, 'vms', 'vm-02.json'), JSON.stringify(vm2)) + seedEncryptedPackage(root) + activateFixture(root, vm1) + activateFixture(root, vm2) + + // Use outbound_session: 'passthrough' and crag_drop_foreign_thinking: false to prove + // slot-switch purification overrides even the most permissive passthrough defaults! + const routing = { + compatibility: { crag_drop_foreign_thinking: false, official_cc_passthrough: true }, + failover: {}, + sticky: { enabled: true, outbound_session: 'passthrough' }, + } + const routingFile = path.join(root, 'routing.json') + fs.writeFileSync(routingFile, JSON.stringify(routing)) + + const sticky = new StickyRouter({ dataDir: root, config: routing }) + const db = sticky.db + const thinkingOwners = new ThinkingOwnerStore({ db }) + + let targetVm = vm1 + let targetSock = sock1 + let targetHome = home1 + let targetAccount = 'account-1' + let leaseCounter = 0 + + const mockRt = { + async acquireNode() { + const id = `lease-${++leaseCounter}` + return { + lease_id: id, + lease_ttl_ms: 30_000, + resolved_pool_id: '__default_claude__', + selected_node: { node_type: 'claude_vm', node_id: targetVm.id, node_key: `claude_vm:${targetVm.id}` }, + explain: { affinity: { why: 'sticky' } }, + } + }, + async commitLease() {}, + async releaseLease() {}, + async deleteSticky() { + return { deleted: 1, rust_deleted: 1, db_deleted: 0 } + }, + } + + const pool = new PoolScheduler({ projectRoot: root, stickyRouter: sticky, schedulerRuntime: mockRt, config: {} }) + pool.resolveCandidateForNode = (_node, meta = {}) => ({ + ok: true, + vmId: targetVm.id, + accountId: targetAccount, + vm: targetVm, + model: meta.model, + exec: { + vmId: targetVm.id, + homeDir: targetHome, + projectRoot: root, + socketPath: targetSock, + internalToken: targetVm.id === 'vm-01' ? 'tok1' : 'tok2', + vm: targetVm, + }, + nodeKey: `claude_vm:${targetVm.id}`, + leaseId: meta.leaseId, + slotIndex: 0, + selectionReason: 'sticky', + waitMs: 0, + queueWaitMs: 0, + schedulingMs: 0, + release() {}, + }) + + for (const [v, s, tok] of [ + [vm1, sock1, 'tok1'], + [vm2, sock2, 'tok2'], + ]) { + rememberRustHealth( + { vmId: v.id, homeDir: v === vm1 ? home1 : home2, projectRoot: root, socketPath: s, internalToken: tok, vm: v }, + { + ok: true, + health: { + ok: true, + healthy: true, + ready: true, + runtime_variant: 'crag-v2', + ready_slots: 2, + capabilities: ['prompt_append', 'generation_controls_v3', 'headless_claude_bridge_v1', 'caller_cwd'], + }, + }, + ) + } + + const runner = new FailoverRunner({ + scheduler: pool, + schedulerRuntime: mockRt, + stickyRouter: sticky, + config: { session_queue_timeout_ms: 2000 }, + }) + + const handler = createHandleProtocol({ + json(res, status, body) { + res.statusCode = status + res.body = body + res.headersSent = true + }, + writeSSEHeaders(res) { + res.statusCode = 200 + res.headersSent = true + }, + readBody: async (req) => req.body, + requireAuth: () => true, + admitCragInference: async () => null, + cfg: { + rewrite: { enabled: false }, + intercept: { rules: [] }, + distill: { enabled: false }, + security: { dbSecret: 'purify-e2e-secret' }, + limits: { max_body_bytes: 1024 * 1024, upstream_timeout_ms: 5000, stream_idle_timeout_ms: 5000 }, + paths: { data: root, project: root }, + }, + requestLog: { + start: (req) => ({ request_id: req.id, mode: 'normal', t0: Date.now() }), + finish() {}, + }, + stickyRouter: sticky, + accountQuota: { ingestHeaders() {} }, + apiKeyStore: { acquire: () => ({ ok: true }), release() {} }, + apiScheduler: {}, + apiEndpointStore: {}, + settings: { get: (_key, fallback) => fallback }, + stats: { errors: 0, requests: 0, by_route: {}, passthrough: 0, rewrite: 0, convert: 0 }, + routingConfigPath: routingFile, + routingConfig: routing, + groupsRepo: { rateMultiplier: () => 1 }, + thinkingOwners, + schedulerRuntime: mockRt, + failoverRunner: runner, + }) + + const sendProtocolCall = async ({ + id, + protocol = 'anthropic.messages', + pathName = '/v1/messages', + body, + extraHeaders = {}, + }) => { + const chunks = [] + const req = Object.assign(new EventEmitter(), { + id, + method: 'POST', + url: pathName, + socket: { remoteAddress: '127.0.0.1' }, + apiKeyKind: 'master', + headers: { + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'x-app': 'cli', + 'anthropic-version': '2023-06-01', + 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20', + 'anthropic-dangerous-direct-browser-access': 'true', + 'x-claude-code-session-id': OFFICIAL_AGENT_SESSION, + 'x-claude-code-parent-session-id': '33333333-3333-4333-8333-333333333333', + 'x-claude-code-prompt-id': '44444444-4444-4444-8444-444444444444', + 'x-client-request-id': '55555555-5555-4555-8555-555555555555', + 'x-stainless-lang': 'js', + 'x-stainless-package-version': '0.128.0', + 'x-stainless-os': 'Linux', + 'x-stainless-arch': 'x64', + 'x-stainless-runtime': 'node', + 'x-stainless-runtime-version': 'v26.12.1', + 'x-stainless-retry-count': '0', + 'x-stainless-timeout': '600', + ...extraHeaders, + }, + body, + }) + const res = Object.assign(new EventEmitter(), { + statusCode: 0, + body: null, + headersSent: false, + writableEnded: false, + setHeader() {}, + write(chunk) { + chunks.push(String(chunk)) + }, + end(chunk) { + if (chunk) chunks.push(String(chunk)) + this.writableEnded = true + this.emit('finish') + }, + }) + await handler.handleProtocol(req, res, protocol, pathName) + return { statusCode: res.statusCode, body: res.body, sse: chunks.join('') } + } + + const officialSystem = [{ type: 'text', text: "You are Claude Code, Anthropic's official CLI for Claude." }] + const officialMetadata = { + user_id: JSON.stringify({ device_id: OFFICIAL_AGENT_DEVICE, session_id: OFFICIAL_AGENT_SESSION }), + } + + // Turn 1 on Slot 1 (vm-01 / account-1): slot machine_profile isolates session ID & unmaps acct1ToolId once + const turn1 = await sendProtocolCall({ + id: 'turn-1-slot1', + body: { + model: 'claude-sonnet-5-5', + max_tokens: 1024, + stream: false, + system: officialSystem, + metadata: officialMetadata, + tools: [{ name: 'Read', description: 'Read file', input_schema: { type: 'object', properties: {} } }], + messages: [{ role: 'user', content: 'Please read demo.txt on my project' }], + }, + }) + assert.equal(turn1.statusCode, 200, JSON.stringify(turn1.body)) + assert.equal(vm1Envelopes.length, 1) + const slot1SessionId = vm1Envelopes[0].headers['x-claude-code-session-id'] + assert.ok(slot1SessionId && slot1SessionId !== OFFICIAL_AGENT_SESSION) + const clientSawTurn1Tool = turn1.body.content.find((b) => b.type === 'tool_use') + assert.notEqual(clientSawTurn1Tool.id, acct1ToolId) + assert.equal( + mapToolUseIdForAccount(vm1.machine_profile.tool_id_seed, clientSawTurn1Tool.id), + acct1ToolId, + 'Slot 1 tool ID must be unmapped exactly once without double-decoding', + ) + + // Switch session to Slot 2 (vm-02 / account-2)! + targetVm = vm2 + targetSock = sock2 + targetHome = home2 + targetAccount = 'account-2' + + const historyWithSlot1Residue = [ + { + role: 'user', + content: [ + { + type: 'text', + text: "\nAs you answer the user's questions, you can use the following context:\n# userEmail\nThe user's email address is slot1-owner@example.com.\n", + }, + { type: 'text', text: 'Please read demo.txt on my project' }, + ], + }, + { + role: 'assistant', + content: [ + { type: 'thinking', thinking: 'slot1 secret reasoning', signature: acct1Sig }, + { + type: 'tool_use', + id: clientSawTurn1Tool.id, + name: 'Read', + input: { file_path: '/tmp/demo.txt' }, + extension: { handoff_id: 'slot1-private-ext' }, + }, + ], + }, + { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: clientSawTurn1Tool.id, content: 'demo content' }], + }, + ] + + // Turn 2 on Slot 2 (Anthropic SSE stream): every trace of Slot 1 must be purified! + const turn2 = await sendProtocolCall({ + id: 'turn-2-slot2-sse', + body: { + model: 'claude-sonnet-5-5', + max_tokens: 1024, + stream: true, + system: officialSystem, + metadata: officialMetadata, + thinking: { type: 'adaptive' }, + thread: { type: 'continue', id: 'slot1-thread' }, + diagnostics: { previous_message_id: 'msg_slot1' }, + tools: [{ name: 'Read', description: 'Read file', input_schema: { type: 'object', properties: {} } }], + messages: historyWithSlot1Residue, + }, + }) + assert.equal(turn2.statusCode, 200) + assert.equal(vm2Envelopes.length, 1) + const env2 = vm2Envelopes[0] + + // 1. Outbound session & trace headers completely divorced from Slot 1 + const slot2SessionId = env2.headers['x-claude-code-session-id'] + assert.ok(slot2SessionId && slot2SessionId !== OFFICIAL_AGENT_SESSION && slot2SessionId !== slot1SessionId) + assert.notEqual(env2.headers['x-claude-code-parent-session-id'], '33333333-3333-4333-8333-333333333333') + assert.notEqual(env2.headers['x-claude-code-prompt-id'], '44444444-4444-4444-8444-444444444444') + assert.notEqual(env2.headers['x-client-request-id'], '55555555-5555-4555-8555-555555555555') + + // 2. Foreign thinking signature, top-level thread/diagnostics, extension, and #userEmail completely stripped + const rawEnv2Json = JSON.stringify(env2.body) + assert.equal(rawEnv2Json.includes(acct1Sig), false, 'Slot 1 signature must never enter Slot 2') + assert.equal(rawEnv2Json.includes('slot1-owner@example.com'), false, 'Slot 1 email must never enter Slot 2') + assert.equal(rawEnv2Json.includes('slot1-private-ext'), false, 'Slot 1 extension must never enter Slot 2') + assert.equal('thread' in env2.body, false) + assert.equal('diagnostics' in env2.body, false) + + // 3. Slot 1 tool_use.id & tool_result.tool_use_id bijectively remapped ONCE into Account 2 keyspace + assert.equal(rawEnv2Json.includes(acct1ToolId), false, 'Slot 1 tool ID must never enter Slot 2') + assert.equal(rawEnv2Json.includes(clientSawTurn1Tool.id), false, 'Client tool ID must be mapped for Slot 2') + const slot2AssistantCall = env2.body.messages + .find((m) => m.role === 'assistant') + .content.find((b) => b.type === 'tool_use') + const slot2UserResult = env2.body.messages + .findLast((m) => m.role === 'user') + .content.find((b) => b.type === 'tool_result') + assert.equal(slot2AssistantCall.id, slot2UserResult.tool_use_id) + assert.equal( + slot2AssistantCall.id, + mapToolUseIdForAccount(vm2.machine_profile.tool_id_seed, clientSawTurn1Tool.id), + 'Tool ID must be mapped exactly once by slot profile without double-encoding', + ) + assert.match(slot2AssistantCall.id, /^toolu_01[A-Za-z0-9]{22}$/) + + // 4. Slot 2's newly minted tool ID is decoded back to a public ID in Anthropic SSE + const sseToolStarts = [...turn2.sse.matchAll(/"content_block":\{"type":"tool_use","id":"([^"]+)"/g)].map((m) => m[1]) + assert.equal(sseToolStarts.length, 1) + const publicTurn2ToolId = sseToolStarts[0] + assert.notEqual(publicTurn2ToolId, acct2ToolId) + + // Turn 3 continuing on Slot 2 (generation=2): reuses slot2SessionId, keeps Slot 1 ID mapped identically, + // and maps publicTurn2ToolId back to exact `acct2ToolId` minted by Slot 2! + const turn3 = await sendProtocolCall({ + id: 'turn-3-slot2-continue', + body: { + model: 'claude-sonnet-5-5', + max_tokens: 1024, + stream: false, + system: officialSystem, + metadata: officialMetadata, + tools: [{ name: 'Read', description: 'Read file', input_schema: { type: 'object', properties: {} } }], + messages: [ + ...historyWithSlot1Residue, + { + role: 'assistant', + content: [{ type: 'tool_use', id: publicTurn2ToolId, name: 'Read', input: { file_path: '/tmp/demo.txt' } }], + }, + { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: publicTurn2ToolId, content: 'second result' }], + }, + ], + }, + }) + assert.equal(turn3.statusCode, 200) + assert.equal(vm2Envelopes.length, 2) + const env3 = vm2Envelopes[1] + assert.equal( + env3.headers['x-claude-code-session-id'], + slot2SessionId, + 'same target slot keeps stable outbound session', + ) + const env3ToolIds = env3.body.messages + .filter((m) => m.role === 'assistant') + .flatMap((m) => m.content.filter((b) => b.type === 'tool_use').map((b) => b.id)) + assert.deepEqual(env3ToolIds, [slot2AssistantCall.id, acct2ToolId]) + + // Verify inbound foreign tool ID remapping AND outbound decoded tool IDs across OpenAI Chat & OpenAI Responses SSE! + const chatStream = await sendProtocolCall({ + id: 'turn-4-openai-chat', + protocol: 'openai.chat', + pathName: '/v1/chat/completions', + extraHeaders: { 'x-claude-code-session-id': '22222222-2222-4222-8222-222222222222' }, + body: { + model: 'claude-sonnet-5-5', + stream: true, + tools: [{ type: 'function', function: { name: 'Read', parameters: { type: 'object', properties: {} } } }], + messages: [ + { role: 'user', content: 'run tool in chat format' }, + { + role: 'assistant', + content: null, + tool_calls: [{ id: acct1ToolId, type: 'function', function: { name: 'Read', arguments: '{}' } }], + }, + { role: 'tool', tool_call_id: acct1ToolId, content: 'first result' }, + ], + }, + }) + assert.equal(chatStream.statusCode, 200) + assert.equal( + JSON.stringify(vm2Envelopes.at(-1).body).includes(acct1ToolId), + false, + 'OpenAI Chat inbound foreign tool ID remapped', + ) + assert.equal(chatStream.sse.includes(publicTurn2ToolId), true, 'OpenAI Chat SSE receives decoded public tool ID') + assert.equal(chatStream.sse.includes(acct2ToolId), false, 'OpenAI Chat SSE never leaks raw account tool ID') + + const responsesStream = await sendProtocolCall({ + id: 'turn-5-openai-responses', + protocol: 'openai.responses', + pathName: '/v1/responses', + extraHeaders: { 'x-claude-code-session-id': '66666666-6666-4666-8666-666666666666' }, + body: { + model: 'claude-sonnet-5-5', + stream: true, + tools: [{ type: 'function', name: 'Read', parameters: { type: 'object', properties: {} } }], + input: [ + { role: 'user', content: 'run tool in responses format' }, + { type: 'function_call', call_id: acct1ToolId, name: 'Read', arguments: '{}' }, + { type: 'function_call_output', call_id: acct1ToolId, output: 'first result' }, + ], + }, + }) + assert.equal(responsesStream.statusCode, 200) + assert.equal( + JSON.stringify(vm2Envelopes.at(-1).body).includes(acct1ToolId), + false, + 'OpenAI Responses inbound foreign tool ID remapped', + ) + assert.equal( + responsesStream.sse.includes(publicTurn2ToolId), + true, + 'OpenAI Responses SSE receives decoded public tool ID', + ) + assert.equal(responsesStream.sse.includes(acct2ToolId), false, 'OpenAI Responses SSE never leaks raw account tool ID') + + // Panel DELETE /api/panel/scheduler/sticky purges StickyRouter AND forces fresh outbound session even on same VM! + const poolsHandler = createSchedulerPoolsHandler({ + getDb: () => db, + getRouting: () => routing, + poolScheduler: () => pool, + schedulerRuntime: () => mockRt, + json(res, status, payload) { + res.statusCode = status + res.body = payload + }, + readBody: async () => ({}), + }) + const delRes = { statusCode: 0, body: null, setHeader() {} } + await poolsHandler( + { + method: 'DELETE', + url: `/api/panel/scheduler/sticky?session_id=${OFFICIAL_AGENT_SESSION}`, + headers: {}, + apiKeyKind: 'master', + _testAuth: { role: 'admin', user: 'admin', userId: 'u-admin' }, + }, + delRes, + `/api/panel/scheduler/sticky`, + new URL(`http://localhost/api/panel/scheduler/sticky?session_id=${OFFICIAL_AGENT_SESSION}`), + ) + assert.equal(delRes.statusCode, 200) + assert.equal(delRes.body.node_sticky_deleted >= 1, true) + assert.equal(sticky.resolve(`sess:${OFFICIAL_AGENT_SESSION}`), null) + + // Next turn landing on the SAME vm-02 after manual sticky delete must mint a brand-new outbound session! + const turnAfterReset = await sendProtocolCall({ + id: 'turn-6-post-sticky-reset', + body: { + model: 'claude-sonnet-5-5', + max_tokens: 1024, + stream: false, + system: officialSystem, + metadata: officialMetadata, + messages: [{ role: 'user', content: 'Fresh post-reset turn on vm-02' }], + }, + }) + assert.equal(turnAfterReset.statusCode, 200) + const postResetSid = vm2Envelopes.at(-1).headers['x-claude-code-session-id'] + assert.ok( + postResetSid && + postResetSid !== slot2SessionId && + postResetSid !== slot1SessionId && + postResetSid !== OFFICIAL_AGENT_SESSION, + ) + db.close() +}) diff --git a/test/unit/go-worker-client.test.mjs b/test/unit/go-worker-client.test.mjs index 1f96bdb13f..80c7524928 100644 --- a/test/unit/go-worker-client.test.mjs +++ b/test/unit/go-worker-client.test.mjs @@ -2654,6 +2654,40 @@ test('V4: CRAG V4 happy-path and repaired retries never forward spoofed caller h 'x-client-request-id': 'creq-ok', 'x-claude-code-session-id': '11111111-1111-4111-8111-111111111111', }) + + // Slot-switched hop purifies x-claude-code-session-id, parent-session-id, prompt-id, and client-request-id + const purifiedOfficial = await workerEnvelope({ + body: { + model: 'claude-sonnet-5-5', + max_tokens: 256, + messages: [{ role: 'user', content: 'continue after failover' }], + }, + reqHeaders: { + 'user-agent': 'claude-cli/2.1.321 (external, cli-bg)', + 'x-app': 'cli-bg', + 'x-client-request-id': 'creq-old-slot1', + 'x-claude-code-prompt-id': 'prompt-old-slot1', + 'x-claude-code-session-id': '11111111-1111-4111-8111-111111111111', + 'x-claude-code-parent-session-id': '22222222-2222-4222-8222-222222222222', + }, + exec, + routing: {}, + stream: true, + cliHop: true, + cragPrint: true, + officialTraffic: true, + officialPassthrough: true, + outboundSessionId: '99999999-9999-4999-8999-999999999999', + slotSwitched: true, + sessionPurified: true, + }) + assert.equal(purifiedOfficial.envelope.headers['x-claude-code-session-id'], '99999999-9999-4999-8999-999999999999') + assert.notEqual( + purifiedOfficial.envelope.headers['x-claude-code-parent-session-id'], + '22222222-2222-4222-8222-222222222222', + ) + assert.notEqual(purifiedOfficial.envelope.headers['x-claude-code-prompt-id'], 'prompt-old-slot1') + assert.notEqual(purifiedOfficial.envelope.headers['x-client-request-id'], 'creq-old-slot1') }) test('slot machine_profile isolates x-claude-code-session-id per account/slot/epoch and gates /internal/v1/slot/reset on capability', async () => { diff --git a/test/unit/identity-rewrite.test.mjs b/test/unit/identity-rewrite.test.mjs index 5bd61cee2e..baf8f87173 100644 --- a/test/unit/identity-rewrite.test.mjs +++ b/test/unit/identity-rewrite.test.mjs @@ -17,7 +17,17 @@ import { uuidFromSeed, UNOFFICIAL_SESSION_SEED, parseUserId, + derivePurifiedParentSessionId, } from '../../src/lib/identity/identity-rewrite.mjs' +import { + createToolIdOwnerTracker, + decodeToolIdFromAccount, + deriveAccountToolIdKey, + encodeToolIdForAccount, + purifySessionPayloadForSlot, + restoreToolIdsInMessage, + restoreToolIdsInSSELine, +} from '../../src/lib/identity/session-switch-purify.mjs' import { stampBillingPromptId } from '../../src/lib/identity/crs-persona.mjs' const SLOT = { @@ -456,3 +466,188 @@ test('resolveSeatIdentity: a short one-shot probe takes no seat', () => { const probe = { max_tokens: 16, messages: [{ role: 'user', content: 'hi' }] } assert.deepEqual(resolveSeatIdentity({ inbound: probe, clientIp: '10.0.0.7' }), { key: null, source: 'probe' }) }) + +test('resolveOutboundSessionId purifies session on same-VM account swap and passthrough slot switch', () => { + const bound = '11111111-1111-4111-8111-111111111111' + // Same VM + same account reuses boundSessionId + assert.equal( + resolveOutboundSessionId('caller-sid', { + boundSessionId: bound, + boundVmId: 'vm-01', + vmId: 'vm-01', + boundAccountId: 'acct-a', + accountId: 'acct-a', + epoch: 100, + }), + bound, + ) + // Same VM + DIFFERENT account must never reuse boundSessionId + const swappedAcct = resolveOutboundSessionId('caller-sid', { + boundSessionId: bound, + boundVmId: 'vm-01', + vmId: 'vm-01', + boundAccountId: 'acct-a', + accountId: 'acct-b', + epoch: 100, + }) + assert.notEqual(swappedAcct, bound) + assert.notEqual(swappedAcct, 'caller-sid') + + // Passthrough mode still forces a fresh purified session when slotSwitched is true + const passSwitched = resolveOutboundSessionId('caller-sid', { + officialClient: true, + mode: 'passthrough', + slotSwitched: true, + accountId: 'acct-b', + vmId: 'vm-02', + epoch: 'slot:acct-b:vm-02:1:200', + }) + assert.notEqual(passSwitched, 'caller-sid') + assert.notEqual(passSwitched, bound) + assert.match(passSwitched, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + + // Purified parent session ID is deterministic within target slot and distinct across slots/accounts + const parentB = derivePurifiedParentSessionId('parent-orig', { + accountId: 'acct-b', + vmId: 'vm-02', + outboundSessionId: passSwitched, + }) + const parentC = derivePurifiedParentSessionId('parent-orig', { + accountId: 'acct-c', + vmId: 'vm-03', + outboundSessionId: passSwitched, + }) + assert.notEqual(parentB, 'parent-orig') + assert.notEqual(parentB, parentC) +}) + +test('tool-id-mapping Feistel bijection preserves format across even/odd/punctuated IDs and isolates accounts', () => { + const keyA = deriveAccountToolIdKey('00000000-0000-4000-8000-0000000000aa', 'test-pepper-1') + const keyB = deriveAccountToolIdKey('00000000-0000-4000-8000-0000000000bb', 'test-pepper-1') + const samples = [ + 'toolu_01XBPoBaQ41jJfipVBMFEt62', // standard 22-base62 (even) + 'toolu_01CaptureAutoModeTest', // 19-base62 (odd) + 'toolu_bdrk_Abc123-Def456_7890XyZ', // punctuated separators preserved + 'srvtoolu_019876543210abcdefghij', + 'mcptoolu_01ZzYyXxWwVvUuTtSsRrQq', + 'call_AbCdEfGhIjKlMnOpQrStUvWx', + ] + for (const orig of samples) { + const encA = encodeToolIdForAccount(orig, keyA) + const encB = encodeToolIdForAccount(orig, keyB) + assert.notEqual(encA, orig) + assert.notEqual(encB, orig) + assert.notEqual(encA, encB) + assert.equal(encA.length, orig.length) + assert.equal(decodeToolIdFromAccount(encA, keyA), orig) + assert.equal(encodeToolIdForAccount(decodeToolIdFromAccount(orig, keyB), keyB), orig) + } + // Short synthetic IDs (<8 base62 digits after prefix) pass through untouched + assert.equal(encodeToolIdForAccount('toolu_01REPRO', keyA), 'toolu_01REPRO') + assert.equal(decodeToolIdFromAccount('toolu_01REPRO', keyA), 'toolu_01REPRO') +}) + +test('purifySessionPayloadForSlot and SSE/JSON restorers scrub previous-slot artifacts and roundtrip safeguards', () => { + const keyB = deriveAccountToolIdKey('acct-uuid-b', 'pepper-secret') + const origId = 'toolu_01XBPoBaQ41jJfipVBMFEt62' + const mappedB = encodeToolIdForAccount(origId, keyB) + const inbound = { + model: 'claude-sonnet-5-5', + thread: { type: 'continue', id: 'thr_slot1_stale' }, + diagnostics: { previous_message_id: 'msg_slot1_prev' }, + safeguards: [ + { + type: 'dangerous_tool_use', + classifier_context: { + prior_turn_context: [{ tool_use_ids: [origId] }], + }, + }, + ], + messages: [ + { + role: 'user', + content: [ + { + type: 'text', + text: "\nAs you answer the user's questions, you can use the following context:\n# userEmail\nThe user's email address is old-slot@example.com.\n# gitStatus\nCurrent branch: main\n", + }, + { type: 'text', text: 'Inspect /run/kin/bridge/shm-workers/shm-w12-deadbeef/home/file.txt' }, + ], + }, + { + role: 'assistant', + content: [ + { + type: 'tool_use', + id: origId, + name: 'Read', + input: { file_path: '/tmp/a.txt' }, + extension: { crag_continuation: 'slot1-token' }, + }, + ], + }, + { + role: 'user', + content: [ + { type: 'tool_result', tool_use_id: origId, content: 'ok' }, + { type: 'text', text: `[tool call Read ${origId}] -> [tool result ${origId}]` }, + ], + }, + ], + } + + const purified = purifySessionPayloadForSlot(inbound, { + toolKey: keyB, + purifyTools: true, + slotSwitched: true, + targetAccountId: 'acct-b', + targetEmail: '', + }) + + assert.equal('thread' in purified, false) + assert.equal('diagnostics' in purified, false) + assert.equal(purified.messages[0].content[0].text.includes('old-slot@example.com'), false) + assert.equal(purified.messages[0].content[0].text.includes('# userEmail'), false) + assert.equal(purified.messages[0].content[0].text.includes('# gitStatus'), true) + assert.equal(purified.messages[0].content[1].text.includes('shm-w12-deadbeef'), false) + assert.equal(purified.messages[1].content[0].id, mappedB) + assert.equal('extension' in purified.messages[1].content[0], false) + assert.equal(purified.messages[2].content[0].tool_use_id, mappedB) + assert.equal(purified.messages[2].content[1].text, `[tool call Read ${mappedB}] -> [tool result ${mappedB}]`) + assert.equal(purified.safeguards[0].classifier_context.prior_turn_context[0].tool_use_ids[0], mappedB) + + // Outbound new tool call minted by Account B decodes to public ID and re-encodes back to exact Account B ID on next turn + const mintedByB = 'toolu_01MintedByAccountB998877' + const sseStart = `data: ${JSON.stringify({ + type: 'content_block_start', + index: 0, + content_block: { type: 'tool_use', id: mintedByB, name: 'Bash', input: {} }, + })}\n` + const restoredSse = restoreToolIdsInSSELine(sseStart, keyB) + const publicId = JSON.parse(restoredSse.slice(5)).content_block.id + assert.notEqual(publicId, mintedByB) + assert.equal(encodeToolIdForAccount(publicId, keyB), mintedByB) + + const sseDelta = `data: ${JSON.stringify({ + type: 'message_delta', + delta: { + stop_reason: 'tool_use', + safeguard_results: [ + { type: 'dangerous_tool_use', status: { type: 'available', tool_uses: { [mintedByB]: { ok: 1 } } } }, + ], + }, + })}` + const restoredDelta = JSON.parse(restoreToolIdsInSSELine(sseDelta, keyB).slice(5)) + assert.deepEqual(restoredDelta.delta.safeguard_results[0].status.tool_uses, { [publicId]: { ok: 1 } }) + + const restoredMsg = restoreToolIdsInMessage( + { role: 'assistant', content: [{ type: 'tool_use', id: mintedByB, name: 'Bash', input: {} }] }, + keyB, + ) + assert.equal(restoredMsg.content[0].id, publicId) + + const tracker = createToolIdOwnerTracker() + tracker.recordId(origId, 'acct-a') + assert.equal(tracker.hasForeignToolIds(inbound, 'acct-a'), false) + assert.equal(tracker.hasForeignToolIds(inbound, 'acct-b'), true) +}) diff --git a/test/unit/sticky-router.test.mjs b/test/unit/sticky-router.test.mjs index 3dcd249a9f..e7034b1bb7 100644 --- a/test/unit/sticky-router.test.mjs +++ b/test/unit/sticky-router.test.mjs @@ -1135,3 +1135,48 @@ test('StickyRouter PG mode statsAsync() & cached stats() eliminate sync DELETE a assert.equal(syncAllCalls, 0) router.db?.close?.() }) + +test('StickyRouter.deleteByFilter purges SQLite & PG bindings and marks key for generation >= 2 purification', async () => { + const dir = tmpDir() + const r = new StickyRouter({ dataDir: dir, config: { sticky: { enabled: true, ttl_seconds: 300 } } }) + r.bind('sess:purify-target', { accountId: 'acc-1', vmId: 'vm-1', sessionId: 'out-old-1' }) + r.bind('sess:keep-other', { accountId: 'acc-2', vmId: 'vm-2', sessionId: 'out-keep-2' }) + assert.equal(r.resolve('sess:purify-target')?.sessionId, 'out-old-1') + + const deleted = await r.deleteByFilter({ session_id: 'purify-target' }) + assert.equal(deleted, 1) + assert.equal(r.resolve('sess:purify-target'), null) + assert.equal(r.peekResetMarker('sess:purify-target'), true) + assert.equal(r.resolve('sess:keep-other')?.sessionId, 'out-keep-2') + + // Even when re-bound onto the exact same VM after reset, generation starts at 2 (purified) + r.bind('sess:purify-target', { accountId: 'acc-1', vmId: 'vm-1', sessionId: 'out-fresh-1' }, { replaceSession: true }) + const rebound = r.resolve('sess:purify-target') + assert.equal(rebound?.sessionId, 'out-fresh-1') + assert.equal(rebound?.generation, 2) + assert.equal(r.peekResetMarker('sess:purify-target'), false) + r.db?.close?.() + + // PG mode parameterized DELETE RETURNING key + const pgDir = tmpDir() + const pgQueries = [] + const pgRouter = new StickyRouter({ + dataDir: pgDir, + config: { sticky: { enabled: true, ttl_seconds: 300 } }, + pgPool: { + async query(sql, params = []) { + pgQueries.push({ sql, params }) + if (/DELETE FROM sticky_sessions/i.test(sql)) { + return { rowCount: 1, rows: [{ key: 'sess:pg-reset-1' }] } + } + return { rowCount: 0, rows: [] } + }, + }, + }) + await pgRouter.flushPendingWrites() + const pgDeleted = await pgRouter.deleteByFilter({ session_id: 'pg-reset-1', node_key: 'claude_vm:vm-9' }) + assert.equal(pgDeleted, 1) + assert.equal(pgRouter.peekResetMarker('sess:pg-reset-1'), true) + assert.ok(pgQueries.some((q) => q.sql.includes('DELETE FROM sticky_sessions WHERE') && q.params.includes('vm-9'))) + pgRouter.db?.close?.() +})