// ADR-026 D3: identity-level machine binding. Adoption is an atomic // conditional transition (unbound → bound(machineId)) on the agent's bot // User row — the loser of a concurrent adopt gets a clean 409, never a // second runner. Rebinding is explicit release-then-adopt. The bound-agent // predicate is enforced HERE from the daemon credential's server-side // machineId — never from a caller-supplied value. import express from 'express'; import rateLimit from 'express-rate-limit'; import { cloudflareIpRateLimitKeyGenerator } from '../middleware/ipRateLimit'; import { createHash } from 'crypto'; import daemonAuth, { DaemonAuthedRequest } from '../middleware/daemonAuth'; import { KERNEL_RUN_RUNTIME_TYPES } from '../services/configWriteGuard'; import { GrantProjectionIdentity, grantServersForIdentities } from '../services/seatGrantBrokerProjection'; import { projectSeatEnvironments, seatEnvironmentKey, } from '../services/seatEnvironmentProjection'; import { ownsRuntimeIdentity, OwnershipFailure, describeRuntimeIdentityBlockers } from '../services/runtimeIdentityOwnership'; import { logAgentInstallRefusal } from '../middleware/logAgentInstallRefusal'; import { machineHasLiveAuthorization } from '../services/machineService'; // eslint-disable-next-line @typescript-eslint/no-require-imports const auth = require('../middleware/auth'); // eslint-disable-next-line @typescript-eslint/no-require-imports const User = require('../models/User'); // eslint-disable-next-line @typescript-eslint/no-require-imports const Machine = require('../models/Machine'); // eslint-disable-next-line @typescript-eslint/no-require-imports const AgentCredential = require('../models/AgentCredential'); // eslint-disable-next-line @typescript-eslint/no-require-imports const { getRuntimeTokenHashesForAgent, revokeRuntimeTokensForAgent, runsInProcess, } = require('./registry/tokens'); const router = express.Router(); const bindingRateLimit = rateLimit({ windowMs: 60_000, max: 120, standardHeaders: true, legacyHeaders: false, keyGenerator: (req: { get?: (h: string) => string | undefined; ip?: string }) => { const authHeader = req.get?.('authorization'); if (authHeader) { return `tok:${createHash('sha256').update(authHeader).digest('hex').slice(0, 16)}`; } return cloudflareIpRateLimitKeyGenerator(req as never); }, handler: (_req: unknown, res: { status: (n: number) => { json: (b: unknown) => void } }) => { res.status(429).json({ msg: 'rate limit exceeded: 120 binding ops per 60s' }); }, }); const normalize = (v: unknown): string => String(v ?? '').trim().toLowerCase(); type AssignedIdentity = GrantProjectionIdentity; // The per-seat grant projection lives in services/seatGrantBrokerProjection.ts, // shared with the run-path read (GET /api/agents/runtime/grant-brokers, F150), // so a daemon seat and an `agent run` seat get one answer. // Ownership predicate — SOLE-INSTALLER. Shared with // the token routes since 2026-10-14; see services/runtimeIdentityOwnership.ts. const ownsAgent = ownsRuntimeIdentity; const ownershipFailureMessage: Record = { owner_installation_missing: 'No active installation for this daemon credential owner', another_installer: 'Another user has an active installation of this agent identity', unknown_installer: 'An active legacy installation has no recorded installer', }; const ownershipRefusal = async (ownerUserId: unknown, agentName: string, instanceId: string, failure: OwnershipFailure) => { if (failure !== 'another_installer') return { message: ownershipFailureMessage[failure], code: failure }; const blockers = await describeRuntimeIdentityBlockers(ownerUserId, agentName, instanceId); const names = blockers.map((blocker) => `${blocker.podName} (${blocker.installerName})`).join(', '); return { message: names ? `This agent is also installed in ${names}. Ask that installer to remove their installation before moving it.` : 'This agent is also installed in another pod. Its installer must remove that installation before it can move.', code: failure, blockers, }; }; // Owner-only view for Settings. A removed machine can still be named by the // identity binding; keep that fact visible while offering only live targets. router.get('/placement', bindingRateLimit, auth, async (req: express.Request & { user?: { id?: string } }, res: express.Response) => { try { const agentName = normalize(req.query.agentName); const instanceId = normalize(req.query.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const ownership = await ownsAgent(req.user?.id, agentName, instanceId); if (!ownership.owned) return res.status(403).json(await ownershipRefusal(req.user?.id, agentName, instanceId, ownership.failure)); const identity = await User.findOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, }).select('botMetadata.machineId botMetadata.requestedMachineId').lean(); if (!identity) return res.status(404).json({ message: 'Agent identity not found' }); const machines = await Machine.find({ ownerUserId: req.user?.id }).select('machineId name createdAt').lean(); type PlacementMachine = { machineId: string; name: string; createdAt: Date }; const activeMachines = (await Promise.all(machines.map(async (machine: PlacementMachine) => ({ machineId: machine.machineId, name: machine.name, createdAt: machine.createdAt, active: Boolean(await AgentCredential.exists({ kind: 'daemon', ownerUserId: req.user?.id, machineId: machine.machineId, status: 'active', $or: [{ expiresAt: null }, { expiresAt: { $gt: new Date() } }] })) && await machineHasLiveAuthorization(machine.machineId, req.user!.id!), })))).filter((machine) => machine.active).map(({ machineId, name, createdAt }) => ({ machineId, name, createdAt })); const boundMachineId = identity.botMetadata?.machineId || null; return res.json({ boundMachineId, requestedMachineId: identity.botMetadata?.requestedMachineId || null, boundMachineRevoked: Boolean(boundMachineId && !activeMachines.some((machine) => machine.machineId === boundMachineId)), activeMachines, }); } catch (err) { console.error('placement status error:', err); return res.status(500).json({ message: 'Server error' }); } }); router.post('/adopt', bindingRateLimit, daemonAuth('agents:adopt'), async (req: DaemonAuthedRequest, res: express.Response) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const machine = req.machine!; if (!machine.machineId) return res.status(400).json({ message: 'Daemon credential carries no machineId' }); const ownership = await ownsAgent(machine.ownerUserId, agentName, instanceId); if (!ownership.owned) { return res.status(403).json({ message: ownershipFailureMessage[ownership.failure], code: ownership.failure, }); } // The CAS: only an UNBOUND identity transitions. matchedCount 0 with an // existing identity means someone else holds the binding → 409. const result = await User.updateOne( { isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, $or: [{ 'botMetadata.machineId': null }, { 'botMetadata.machineId': { $exists: false } }], }, // A successful adopt consumes any pending placement request — the // binding IS the fulfilled request, whichever machine it named. { $set: { 'botMetadata.machineId': machine.machineId, 'botMetadata.requestedMachineId': null } }, ); if (result.modifiedCount === 1) { return res.json({ adopted: true, agentName, instanceId, machineId: machine.machineId }); } const identity = await User.findOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, }).select('botMetadata.machineId').lean(); if (!identity) return res.status(404).json({ message: 'Agent identity not found' }); if (identity.botMetadata?.machineId === machine.machineId) { return res.json({ adopted: true, alreadyBound: true, agentName, instanceId, machineId: machine.machineId }); } return res.status(409).json({ message: 'Agent is bound to another machine — release it first', boundTo: identity.botMetadata?.machineId || null, }); } catch (err) { console.error('adopt error:', err); return res.status(500).json({ message: 'Server error' }); } }); // ADR-026 Phase 2: placement request — the OWNER (human JWT, i.e. the UI's // "run it on " choice) asks for an agent to run on one of their // machines. This writes a DIRECTIVE, never a binding: the daemon on that // machine sees the request in /assigned and performs the adopt CAS itself, // so D3's "no adoption without a user choice" and "one binding writer" both // hold. machineId: null withdraws the request. router.post('/request', logAgentInstallRefusal('/api/agent-binding/request', 'wrapper'), bindingRateLimit, auth, async (req: express.Request & { user?: { id?: string } }, res: express.Response) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const requestedMachineId = req.body?.machineId === null ? null : String(req.body?.machineId || '').trim(); if (requestedMachineId === '') return res.status(400).json({ message: 'machineId required (null to withdraw)' }); const ownership = await ownsAgent(req.user?.id, agentName, instanceId); if (!ownership.owned) { return res.status(403).json(await ownershipRefusal(req.user?.id, agentName, instanceId, ownership.failure)); } // An agent Commonly runs in-process (the person's hosted agent) can't also // run on a machine: its daemon would be refused at the runtime-token mint, // so the page said "requested" and nothing ever ran. Refused here, with the // mint's code, after the ownership check so another user's agent never // reveals how it runs. Withdrawing (machineId: null) stays allowed, so a // request stamped before this check can still be cleared. if (requestedMachineId && await runsInProcess(null, { agentName, instanceId })) { return res.status(409).json({ code: 'in_process_agent_no_token', message: `${agentName} is your hosted agent, and Commonly runs it, so it can't also run on your computer. ` + 'Choose a different name for an agent you run yourself.', }); } if (requestedMachineId) { const machine = await Machine.findOne({ machineId: requestedMachineId, ownerUserId: req.user?.id }).select('_id').lean(); if (!machine) return res.status(404).json({ message: 'Machine not found' }); const daemonActive = await AgentCredential.exists({ kind: 'daemon', machineId: requestedMachineId, ownerUserId: req.user?.id, status: 'active', $or: [{ expiresAt: null }, { expiresAt: { $gt: new Date() } }], }); if (!daemonActive || !await machineHasLiveAuthorization(requestedMachineId, req.user!.id!)) { return res.status(409).json({ message: 'Machine access revoked' }); } } const identity = await User.findOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, }).select('botMetadata.machineId').lean(); if (!identity) return res.status(404).json({ message: 'Agent identity not found' }); if (requestedMachineId && identity.botMetadata?.machineId && identity.botMetadata.machineId !== requestedMachineId) { return res.status(409).json({ message: 'Agent is bound to another machine — release it first', boundTo: identity.botMetadata.machineId, }); } await User.updateOne( { _id: identity._id }, { $set: { 'botMetadata.requestedMachineId': requestedMachineId } }, ); return res.json({ requested: Boolean(requestedMachineId), agentName, instanceId, machineId: requestedMachineId, }); } catch (err) { console.error('placement request error:', err); return res.status(500).json({ message: 'Server error' }); } }); // Owner-approved handoff: release the old binding and write the placement // directive in ONE identity update. Two HTTP calls can strand an agent when // the target is revoked between them. The target daemon still owns adopt CAS. router.post('/move', bindingRateLimit, auth, async (req: express.Request & { user?: { id?: string } }, res: express.Response) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; const machineId = String(req.body?.machineId || '').trim(); const fromMachineId = req.body?.fromMachineId === null ? null : String(req.body?.fromMachineId || '').trim(); if (!agentName || !machineId || (fromMachineId === '' && req.body?.fromMachineId !== null)) { return res.status(400).json({ message: 'agentName, machineId and fromMachineId required' }); } const ownership = await ownsAgent(req.user?.id, agentName, instanceId); if (!ownership.owned) return res.status(403).json(await ownershipRefusal(req.user?.id, agentName, instanceId, ownership.failure)); if (await runsInProcess(null, { agentName, instanceId })) { return res.status(409).json({ code: 'in_process_agent_no_token', message: 'A hosted agent cannot run on a computer' }); } const target = await Machine.findOne({ machineId, ownerUserId: req.user?.id }).select('_id').lean(); if (!target) return res.status(404).json({ code: 'target_missing', message: 'Machine not found' }); const daemonActive = await AgentCredential.exists({ kind: 'daemon', machineId, ownerUserId: req.user?.id, status: 'active', $or: [{ expiresAt: null }, { expiresAt: { $gt: new Date() } }], }); if (!daemonActive || !await machineHasLiveAuthorization(machineId, req.user!.id!)) { return res.status(409).json({ code: 'target_revoked', message: 'Machine access revoked' }); } const binding = fromMachineId === null ? { $or: [{ 'botMetadata.machineId': null }, { 'botMetadata.machineId': { $exists: false } }] } : { 'botMetadata.machineId': fromMachineId }; const changed = await User.updateOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, ...binding, }, { $set: { 'botMetadata.machineId': null, 'botMetadata.requestedMachineId': machineId } }); if (!changed.matchedCount) { const exists = await User.exists({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId }); return res.status(exists ? 409 : 404).json({ code: exists ? 'binding_changed' : 'agent_missing', message: exists ? 'Agent binding changed; refresh before moving' : 'Agent identity not found', }); } return res.json({ requested: true, agentName, instanceId, machineId }); } catch (err) { console.error('placement move error:', err); return res.status(500).json({ message: 'Server error' }); } }); // The owner explicitly asks the already-bound daemon to rotate this agent's // runtime key. A placement request cannot do that: the daemon keeps its local // token until a distinct reconnect directive arrives. router.post('/reconnect', bindingRateLimit, auth, async ( req: express.Request & { user?: { id?: string; role?: string } }, res: express.Response, ) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const isAdmin = req.user?.role === 'admin'; if (!isAdmin) { const ownership = await ownsAgent(req.user?.id, agentName, instanceId); if (!ownership.owned) return res.status(403).json({ message: ownershipFailureMessage[ownership.failure], code: ownership.failure, }); } const identity = await User.findOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, }).select('_id botMetadata.machineId').lean(); const machineId = identity?.botMetadata?.machineId; if (!machineId) return res.status(409).json({ message: 'Agent is not bound to a computer' }); const machine = await Machine.findOne(isAdmin ? { machineId } : { machineId, ownerUserId: req.user?.id }) .select('_id ownerUserId').lean(); if (!machine) return res.status(403).json({ message: 'Computer is not owned by this installer' }); const daemonCanReconnect = await AgentCredential.exists({ kind: 'daemon', machineId, ownerUserId: machine.ownerUserId, status: 'active', $or: [{ expiresAt: null }, { expiresAt: { $gt: new Date() } }], }); if (!daemonCanReconnect) return res.status(409).json({ message: 'Computer key revoked. Register the computer again before reconnecting this agent.', code: 'machine_key_revoked', }); const requestedAt = new Date(); const update = await User.updateOne({ _id: identity._id, 'botMetadata.machineId': machineId }, { $set: { 'botMetadata.reconnectRequestedAt': requestedAt }, }); if (!update.matchedCount) return res.status(409).json({ message: 'Agent binding changed. Reload and retry.' }); return res.json({ requested: true, agentName, instanceId, machineId, requestedAt }); } catch (err) { console.error('agent reconnect request error:', err); return res.status(500).json({ message: 'Server error' }); } }); // ADR-026 Phase 2: the daemon's work list. Ownership authority is the // installation set (same sole-installer basis as ownsAgent): start from the // owner's active installations, then join to identities bound to — or // requested onto — THIS machine (credential-derived machineId, never input). router.get('/assigned', bindingRateLimit, daemonAuth('agents:adopt'), async (req: DaemonAuthedRequest, res: express.Response) => { try { const machine = req.machine!; if (!machine.machineId) return res.status(400).json({ message: 'Daemon credential carries no machineId' }); // The projection is shared with the grant read (TASK-063): one definition // of what a seat receives, so the read cannot disagree with the daemon. const byIdentity = await projectSeatEnvironments({ installedBy: machine.ownerUserId }); if (!byIdentity.size) return res.json({ agents: [] }); const identities = await User.find({ isBot: true, $or: [ { 'botMetadata.machineId': machine.machineId }, { 'botMetadata.requestedMachineId': machine.machineId }, ], }).select('_id botMetadata.agentName botMetadata.instanceId botMetadata.machineId botMetadata.requestedMachineId botMetadata.reconnectRequestedAt').lean() as AssignedIdentity[]; const grantServers = await grantServersForIdentities(identities, byIdentity); const agents = identities.flatMap((identity: AssignedIdentity) => { const meta = identity.botMetadata || {}; const key = seatEnvironmentKey(meta.agentName, meta.instanceId); const entry = byIdentity.get(key); // An identity outside the owner's installation set (shared, or another // user's) never appears in this daemon's work list. if (!entry) return []; // A seat Commonly runs is not the daemon's to run, even when its identity // still names this machine from before it turned native or hosted (TASK-474). const runtime = entry.runtime as { runtimeType?: unknown } | null; if (KERNEL_RUN_RUNTIME_TYPES.has(String(runtime?.runtimeType ?? '').trim().toLowerCase())) return []; const agentId = String(identity._id || ''); const grantProjection = grantServers.get(agentId); const brokerServers = grantProjection?.servers || []; const environment = entry.environment ? { ...entry.environment, ...(brokerServers.length ? { mcp: [ ...(Array.isArray(entry.environment.mcp) ? entry.environment.mcp : []) .filter((server: any) => !brokerServers.some((broker) => broker.name === server?.name)), ...brokerServers, ], } : {}), } : (brokerServers.length ? { mcp: brokerServers } : null); return [{ agentName: entry.agentName, instanceId: entry.instanceId, state: meta.machineId === machine.machineId ? 'bound' : 'requested', podIds: entry.podIds, runtime: entry.runtime, ...(meta.machineId === machine.machineId && meta.reconnectRequestedAt ? { reconnectRequestedAt: meta.reconnectRequestedAt } : {}), ...(environment ? { environment } : {}), // Why a live grant is not on this row, for the daemon that would // otherwise have to guess: server-side refusals only (a daemon-side // refusal is a separate reporting channel, TASK-063). ...(grantProjection?.refusal ? { grantBrokerRefusal: grantProjection.refusal } : {}), }]; }); return res.json({ agents }); } catch (err) { console.error('assigned list error:', err); return res.status(500).json({ message: 'Server error' }); } }); // ADR-026 Phase 2 (D4.5 consumer): mint the runtime credential for an agent // BOUND to this machine, as a child of this machine's daemon credential — // lineage makes machine removal revoke it transitively. If a token already // exists it lives on some other machine's disk; rotate:true is the explicit // "this machine takes over" step and invalidates the old token everywhere. router.post('/runtime-token', bindingRateLimit, daemonAuth('agents:adopt'), async (req: DaemonAuthedRequest, res: express.Response) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const machine = req.machine!; if (!machine.machineId) return res.status(400).json({ message: 'Daemon credential carries no machineId' }); const ownership = await ownsAgent(machine.ownerUserId, agentName, instanceId); if (!ownership.owned) { return res.status(403).json({ message: ownershipFailureMessage[ownership.failure], code: ownership.failure, }); } const agentUser = await User.findOne({ isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId, }); if (!agentUser) return res.status(404).json({ message: 'Agent identity not found' }); if (agentUser.botMetadata?.machineId !== machine.machineId) { return res.status(409).json({ message: 'Agent is not bound to this machine — adopt it first', boundTo: agentUser.botMetadata?.machineId || null, }); } // Runtime auth accepts both the portable User row and legacy installation // copies. Count both stores before deciding whether rotate is required. const runtimeTokenHashes = await getRuntimeTokenHashesForAgent({ agentUser, agentName, instanceId, }); const hasToken = runtimeTokenHashes.length > 0; if (hasToken && req.body?.rotate !== true) { return res.status(409).json({ message: 'Agent already has a runtime token — pass rotate:true to invalidate it and mint one for this machine', code: 'token_exists', }); } if (hasToken) { await revokeRuntimeTokensForAgent({ agentUser, agentName, instanceId }); } // eslint-disable-next-line @typescript-eslint/no-require-imports const AgentCredential = require('../models/AgentCredential'); // req.machine is deliberately a minimal projection, so // re-derive the issuing daemon credential for parent lineage. const daemonCredential = await AgentCredential.findOne({ kind: 'daemon', machineId: machine.machineId, ownerUserId: machine.ownerUserId, status: 'active', }).select('_id').lean(); if (!daemonCredential) return res.status(401).json({ message: 'Issuing daemon credential revoked' }); // eslint-disable-next-line @typescript-eslint/no-require-imports const { issueRuntimeTokenForAgent, revokeRuntimeTokenEverywhere } = require('./registry/tokens'); const minted = await issueRuntimeTokenForAgent(agentUser, `Daemon mint (${machine.machineId})`, null, { ownerUserId: machine.ownerUserId, parentId: daemonCredential._id, machineId: machine.machineId, }); const issuerStillActive = await AgentCredential.exists({ _id: daemonCredential._id, status: 'active', }); const machineStillAuthorized = await machineHasLiveAuthorization(machine.machineId, machine.ownerUserId); if (!issuerStillActive || !machineStillAuthorized) { if (minted.token) await revokeRuntimeTokenEverywhere(createHash('sha256').update(minted.token).digest('hex')); return res.status(401).json({ message: 'Machine access revoked during token mint' }); } return res.status(201).json({ agentName, instanceId, token: minted.token, rotated: hasToken, }); } catch (err) { if ((err as { code?: string })?.code === 'in_process_agent_no_token') { return res.status(409).json({ code: 'in_process_agent_no_token', message: (err as Error).message }); } console.error('runtime-token mint error:', err); return res.status(500).json({ message: 'Server error' }); } }); // Release: the OWNER (human JWT) releases explicitly — rebinding is a // deliberate two-step, never a daemon-side race (D3). router.post('/release', bindingRateLimit, auth, async (req: express.Request & { user?: { id?: string } }, res: express.Response) => { try { const agentName = normalize(req.body?.agentName); const instanceId = normalize(req.body?.instanceId) || 'default'; if (!agentName) return res.status(400).json({ message: 'agentName required' }); const ownership = await ownsAgent(req.user?.id, agentName, instanceId); if (!ownership.owned) { // eslint-disable-next-line @typescript-eslint/no-require-imports const caller = await User.findById(req.user?.id).select('role').lean(); if (caller?.role !== 'admin') { return res.status(403).json(await ownershipRefusal(req.user?.id, agentName, instanceId, ownership.failure)); } } const result = await User.updateOne( { isBot: true, 'botMetadata.agentName': agentName, 'botMetadata.instanceId': instanceId }, // Withdraw any pending placement too — a release means "stop running // this anywhere", not "fail over to the requested machine". { $set: { 'botMetadata.machineId': null, 'botMetadata.requestedMachineId': null } }, ); if (!result.matchedCount) return res.status(404).json({ message: 'Agent identity not found' }); return res.json({ released: true, agentName, instanceId }); } catch (err) { console.error('release error:', err); return res.status(500).json({ message: 'Server error' }); } }); module.exports = router; export {};