import { randomUUID } from "node:crypto" import type { PoolClient, QueryResultRow } from "pg" import { z } from "zod" import { MCP_SERVICE_EXPIRATION, mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema, type McpConnection, type McpConnectionCreate, type McpConnectionPolicy, } from "@mmapp/contracts/mcp" import { pool } from "../../db/index.js" import { SYSTEM_DATABASE_OPERATION_LOCK } from "../../db/operation-lock.js" import { hasPermission, type AuthUser } from "../../lib/permissions.js" import { admitPartitionWriter, withPartitionWrite } from "../../services/partition-write-transaction.js" import { accessGeneration, mcpStateDirectory, canonicalMcpUrl, McpError, randomToken, redact, tokenDigest } from "./security.js" import { assertPortalClaimsCurrent, lockPortalOwner, readCurrentPrincipalSecuritySource } from "./portal-revocation.js" export interface ConnectionRow extends QueryResultRow { id: string; name: string; owner_id: string; owner_permissions: string[]; policy: McpConnectionPolicy; generation: string; created_at: Date; updated_at: Date; last_used_at: Date | null owner_valid_until: Date owner_claims_issued_at: Date } function ownerValidUntil(actor: AuthUser) { return new Date(Math.min(actor.expiresAt ?? Date.now() + 900000, Date.now() + 86400000)) } function connectionExpiration(input: McpConnectionCreate, actor: AuthUser) { if (input.authority === "service" && input.expiresAt === null) { if (!hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("PERMISSION_DENIED", "Сервисный доступ выдаёт администратор MCP", 403) return MCP_SERVICE_EXPIRATION } const expires = Date.parse(input.expiresAt ?? ""), now = Date.now() if (!input.expiresAt || !Number.isFinite(expires) || expires <= now || expires > now + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400) return input.expiresAt } async function resolveConnectionScope(scope: McpConnectionCreate["scope"], selectAllServers: boolean, client: PoolClient) { if (selectAllServers) { if (scope.serverIds.length) throw new McpError("INVALID_CONFIGURATION", "Выберите все серверы или укажите конкретные ID", 400) const { rows } = await client.query<{ id: string }>("SELECT id FROM servers ORDER BY id LIMIT 1001") if (rows.length > 1000) throw new McpError("INVALID_CONFIGURATION", "Подключению можно выдать доступ не более чем к 1000 серверам", 400) return { ...scope, serverIds: rows.map(row => Number(row.id)) } } if (scope.serverIds.length) { const { rows } = await client.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [scope.serverIds]) if (rows.length !== scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400) } return scope } export interface McpPrincipal { connectionId: string; credentialId: string; credentialExpiresAt: string } export function intersectGrant(connection: ConnectionRow, grant?: z.infer): ConnectionRow { if (!grant) return connection return { ...connection, policy: { ...connection.policy, scope: { serverIds: connection.policy.scope.serverIds.filter(id => grant.scope.serverIds.includes(id)), operationIds: connection.policy.scope.operationIds.filter(id => grant.scope.operationIds.includes(id)), allowGlobal: connection.policy.scope.allowGlobal && grant.scope.allowGlobal, } } } } /** One current principal/grant read. The raw source is private metadata for * same-invocation proof binding, never a reusable authority or public DTO. */ export async function effectiveMcpConnectionSource(principal: McpPrincipal, client: Pick = pool) { const { connection, grantRows: rows, grantOversized } = await currentPrincipalSource(principal, client, true) if (!rows.length) return { connection, grantRows: rows } if (rows.length !== 1) throw new McpError("GRANT_INACTIVE", "Неоднозначный временный доступ") if (grantOversized) throw new McpError("STATE_UNAVAILABLE", "Текущий источник прав недоступен", 503) const { credentialId: _credential, ...payload } = rows[0].payload as Record, grant = mcpTemporaryGrantSchema.parse(payload) if (Date.parse(grant.startsAt) > Date.now() || Date.parse(grant.expiresAt) <= Date.now()) throw new McpError("GRANT_INACTIVE", "Временный доступ не действует", 403) return { connection: intersectGrant(connection, grant), grantRows: rows } } export async function effectiveMcpConnection(principal: McpPrincipal, client: Pick = pool) { return (await effectiveMcpConnectionSource(principal, client)).connection } export interface StoredPlan extends QueryResultRow { id: string; connection_id: string; operation_id: string; operation_version: number; policy_version: number; generation: string; payload: { sealed: string }; evidence: { sealed: string; approvalSource?: "connection-policy" }; state: string; expires_at: Date; approved_by: string | null; created_at: Date } export interface StoredOperation extends QueryResultRow { id: string; plan_id: string; connection_id: string; state: string; verification: string; result: unknown; error_code: string | null; created_at: Date } export async function transaction(work: (client: PoolClient) => Promise): Promise { const client = await pool.connect() try { await client.query("BEGIN"); const result = await work(client); await client.query("COMMIT"); return result } catch (error) { await client.query("ROLLBACK"); throw error } finally { client.release() } } export function connectionWrite(work: (client: PoolClient) => Promise): Promise { // Keep domain errors from connection validation visible to the HTTP handler. return transaction(async client => { await admitPartitionWriter(client) return work(client) }) } export function requestAccountingWrite(work: (client: PoolClient) => Promise): Promise { return transaction(async client => { // POLL owns the partition key, so its status reads must use the database-operation key. const { rows: [lock] } = await client.query<{ acquired: boolean }>( "SELECT pg_catalog.pg_try_advisory_xact_lock_shared($1::bigint) AS acquired", [SYSTEM_DATABASE_OPERATION_LOCK]) if (lock?.acquired !== true) throw new McpError("PROTOCOL_STORAGE_BUSY", "Выполняется операция с базой приложения", 503) return work(client) }) } export async function audit(client: Pick, actorId: string, action: string, connectionId: string | null, payload: unknown): Promise { await client.query("INSERT INTO mcp_audit(actor_id,action,connection_id,payload) VALUES($1,$2,$3,$4::jsonb)", [actorId, action, connectionId, JSON.stringify(redact(payload))]) } export async function getMcpSettings(retentionOwner?: PoolClient) { const { rows: [row] } = await (retentionOwner ?? pool).query(`SELECT enabled,requests_retention_days AS "requestsRetentionDays", audit_retention_days AS "auditRetentionDays" FROM mcp_settings WHERE id=1${retentionOwner ? " FOR SHARE" : ""}`) if (!row) throw new McpError("STATE_UNAVAILABLE", "Настройки MCP отсутствуют; выполните миграции", 503) return mcpSettingsSchema.parse(row) } export async function updateMcpSettings(patch: Partial>, actor: AuthUser) { return withPartitionWrite(async ({ client }) => { const { rows: [before] } = await client.query("SELECT * FROM mcp_settings WHERE id=1 FOR UPDATE") await client.query("UPDATE mcp_settings SET enabled=COALESCE($1,enabled),requests_retention_days=COALESCE($2,requests_retention_days),audit_retention_days=COALESCE($3,audit_retention_days),updated_at=now() WHERE id=1", [patch.enabled, patch.requestsRetentionDays, patch.auditRetentionDays]) await audit(client, actor.id, "settings.update", null, { before, patch }) return { enabled: patch.enabled ?? before.enabled, requestsRetentionDays: patch.requestsRetentionDays ?? before.requests_retention_days, auditRetentionDays: patch.auditRetentionDays ?? before.audit_retention_days } }) } export function publicConnection(row: ConnectionRow, generation: string): McpConnection { return mcpConnectionSchema.parse({ id: row.id, name: row.name, ownerId: row.owner_id, policy: row.policy, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), lastUsedAt: row.last_used_at?.toISOString() ?? null, generationValid: row.generation === generation, ownerValidUntil: row.owner_valid_until.toISOString(), }) } export async function listMcpConnections(actor: AuthUser): Promise { const admin = hasPermission(actor.permissions, "mm:mcp:admin") const { rows } = await pool.query("SELECT * FROM mcp_connections WHERE ($1::boolean OR owner_id=$2) ORDER BY created_at DESC LIMIT 500", [admin, actor.id]) const generation = await accessGeneration() return rows.map(row => publicConnection(row, generation)) } export async function getConnection(id: string, client: Pick = pool): Promise { const { rows: [row] } = await client.query("SELECT * FROM mcp_connections WHERE id=$1", [id]) if (!row) throw new McpError("NOT_FOUND", "Подключение не найдено", 404) row.policy = mcpConnectionPolicySchema.parse(row.policy) return row } export function assertConnectionVisible(row: ConnectionRow, actor: AuthUser): void { if (row.owner_id !== actor.id && !hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("NOT_FOUND", "Подключение не найдено", 404) } export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) { const expiresAt = connectionExpiration(input, actor) if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права") const id = randomUUID(), generation = await accessGeneration() const { name, scope: requestedScope, selectAllServers, ...configuration } = input const token = randomToken("bearer") return connectionWrite(async client => { await lockPortalOwner(client, actor.id) await assertPortalClaimsCurrent(actor, client) const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client) const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: 1, status: "active" }) const service = policy.authority === "service" const { rows: [row] } = await client.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,$2,$3,$4::jsonb,$5::jsonb,$6,$7,$8) RETURNING *", [id, name, actor.id, JSON.stringify(service ? policy.permissions : actor.permissions), JSON.stringify(policy), generation, service ? expiresAt : ownerValidUntil(actor), new Date(actor.issuedAt ?? 0)]) await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [randomUUID(), id, tokenDigest(token), expiresAt]) await audit(client, actor.id, "connection.create", id, { name, policy }) return { connection: publicConnection(row, generation), token } }) } export async function updateMcpConnection(id: string, input: McpConnectionCreate, actor: AuthUser) { const expiresAt = connectionExpiration(input, actor) const service = input.authority === "service" if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие права") return connectionWrite(async client => { if (service) { await lockPortalOwner(client, actor.id) await assertPortalClaimsCurrent(actor, client) } await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id]) const before = await getConnection(id, client) if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав") if (before.policy.authority !== input.authority) throw new McpError("INVALID_CONFIGURATION", "Для смены типа доступа создайте новое подключение", 400) if (Date.parse(expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400) const { name, scope: requestedScope, selectAllServers, ...configuration } = input const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client) const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: before.policy.version + 1, status: before.policy.status }) const { rows: [row] } = await client.query("UPDATE mcp_connections SET name=$2,policy=$3::jsonb,owner_permissions=$4::jsonb,owner_valid_until=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, name, JSON.stringify(policy), JSON.stringify(service ? policy.permissions : actor.permissions), service ? before.owner_valid_until : ownerValidUntil(actor)]) await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','awaiting-approval','approved')", [id]) await audit(client, actor.id, "connection.policy.update", id, { before: before.policy, after: policy }) return publicConnection(row, await accessGeneration()) }) } export async function setConnectionStatus(id: string, status: "active" | "paused" | "revoked", actor: AuthUser) { return connectionWrite(async client => { await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id]) const row = await getConnection(id, client) if (row.policy.status === "revoked" && status !== "revoked") throw new McpError("CONNECTION_REVOKED", "Отозванное подключение нельзя активировать", 409) const policy = { ...row.policy, status, version: row.policy.version + 1 } await client.query("UPDATE mcp_connections SET policy=$2::jsonb,updated_at=now() WHERE id=$1", [id, JSON.stringify(policy)]) if (status !== "active") await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','awaiting-approval','approved')", [id]) if (status === "revoked") await client.query("UPDATE mcp_credentials SET revoked_at=now() WHERE connection_id=$1 AND revoked_at IS NULL", [id]) await audit(client, actor.id, "connection." + status, id, {}) }) } export async function revalidateMcpOwner(id: string, actor: AuthUser) { return connectionWrite(async client => { await lockPortalOwner(client, actor.id) await assertPortalClaimsCurrent(actor, client) await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id]) const connection = await getConnection(id, client) if (connection.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Права подтверждает владелец подключения") if (connection.policy.authority === "service") throw new McpError("INVALID_CONFIGURATION", "Сервисное подключение не требует подтверждения прав владельца", 400) const policy = { ...connection.policy, version: connection.policy.version + 1 } const until = ownerValidUntil(actor) const { rows: [row] } = await client.query("UPDATE mcp_connections SET owner_permissions=$2::jsonb,owner_valid_until=$3,policy=$4::jsonb,owner_claims_issued_at=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, JSON.stringify(actor.permissions), until, JSON.stringify(policy), new Date(actor.issuedAt ?? 0)]) await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','approved','awaiting-approval')", [id]) await client.query("UPDATE mcp_routing_profiles SET enabled=false,state=state || '{\"pausedReason\":\"Требуется новый допуск после подтверждения прав владельца\"}'::jsonb WHERE connection_id=$1 AND enabled", [id]) await audit(client, actor.id, "owner.revalidate", id, { permissions: actor.permissions, validUntil: until }) return publicConnection(row, await accessGeneration()) }) } export async function rotateConnectionToken(id: string, actor: AuthUser) { const token = randomToken("bearer") return connectionWrite(async client => { await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id]) const row = await getConnection(id, client) if (row.policy.status === "revoked") throw new McpError("CONNECTION_REVOKED", "Доступ отозван", 409) await client.query("UPDATE mcp_credentials SET revoked_at=now() WHERE connection_id=$1 AND kind='bearer' AND revoked_at IS NULL", [id]) await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [randomUUID(), id, tokenDigest(token), row.policy.expiresAt]) await audit(client, actor.id, "connection.token.rotate", id, {}) return { token } }) } export async function authenticateMcpToken(token: string): Promise { if (!/^mmcp_(bearer|access)_[A-Za-z0-9_-]{43}$/.test(token)) throw new McpError("UNAUTHORIZED", "Требуется токен MCP", 401) const { rows: [credential] } = await pool.query<{ id: string; connection_id: string; expires_at: Date; kind: string; audience: string | null }>("SELECT id,connection_id,expires_at,kind,audience FROM mcp_credentials WHERE digest=$1 AND revoked_at IS NULL AND expires_at>now() AND kind IN ('bearer','access')", [tokenDigest(token)]) if (!credential) throw new McpError("UNAUTHORIZED", "Токен недействителен или отозван", 401) if (credential.kind === "access" && credential.audience !== canonicalMcpUrl().href) throw new McpError("UNAUTHORIZED", "Токен выдан другому MCP resource", 401) const row = await getConnection(credential.connection_id) await assertPortalClaimsCurrent({ id: row.owner_id, issuedAt: row.owner_claims_issued_at.getTime() }) if (row.generation !== await accessGeneration() || row.policy.status !== "active" || Date.parse(row.policy.expiresAt) <= Date.now() || row.owner_valid_until.getTime() <= Date.now()) throw new McpError("UNAUTHORIZED", "Подключение недействительно или требуется подтверждение прав владельца", 401) if (!(await getMcpSettings()).enabled) throw new McpError("MCP_DISABLED", "MCP выключен", 503) return { connectionId: row.id, credentialId: credential.id, credentialExpiresAt: credential.expires_at.toISOString() } } async function currentPrincipalSource(principal: McpPrincipal, client: Pick, includeGrants: boolean) { const source = await readCurrentPrincipalSecuritySource(principal, client, includeGrants), { connection } = source // Original final short-circuit order and fresh generation/clock checks remain. // SQL credential expiry deliberately retains PostgreSQL now() semantics. if (!source.credentialCurrent || !source.enabled || connection.generation !== await accessGeneration() || connection.policy.status !== "active" || Date.parse(connection.policy.expiresAt) <= Date.now() || connection.owner_valid_until.getTime() <= Date.now()) throw new McpError("UNAUTHORIZED", "Доступ MCP прекращён или требуется подтверждение прав владельца", 401) return source } export async function validatePrincipal(principal: McpPrincipal, client: Pick = pool): Promise { return (await currentPrincipalSource(principal, client, false)).connection } /** Fixed synchronous source exchange. Packets retire before any callback await. */ declare const principalBoundaryBrand: unique symbol export type PrincipalBoundaryPacket = Readonly<{ [principalBoundaryBrand]: true }> export const fixedPrincipalBoundarySource = Object.freeze({ reader: readCurrentPrincipalSecuritySource, generation: accessGeneration, directory: mcpStateDirectory }) type PrincipalBoundarySource = Awaited> function freezePrincipalProjection(value: T): T { if (value && typeof value === "object") { for (const child of Object.values(value)) freezePrincipalProjection(child); Object.freeze(value) } return value } const principalBoundaryPackets = new WeakMap }>() /** Only within the original synchronous packet callback. Exposes no client. */ export function assertPrincipalBoundaryClient(packet: PrincipalBoundaryPacket, client: Pick) { const entry = principalBoundaryPackets.get(packet) if (!entry || entry.client !== client) throw new McpError("PERMISSION_DENIED", "Чужой или завершённый SQL источник MCP", 403) } export function principalBoundaryProjection(packet: PrincipalBoundaryPacket, expected: McpPrincipal, directory: string, effective: boolean) { const entry = principalBoundaryPackets.get(packet) if (!entry || entry.directory !== directory || entry.principal.connectionId !== expected.connectionId || entry.principal.credentialId !== expected.credentialId || entry.principal.credentialExpiresAt !== expected.credentialExpiresAt) throw new McpError("PERMISSION_DENIED", "Чужая или завершённая граница MCP", 403) const source = entry.source if (!source.credentialCurrent || !source.enabled || source.connection.generation !== entry.generation || source.connection.policy.status !== "active" || Date.parse(source.connection.policy.expiresAt) <= Date.now() || source.connection.owner_valid_until.getTime() <= Date.now() || typeof source.credentialExpiresAt !== "string" || Date.parse(source.credentialExpiresAt) <= Date.now() || Date.parse(expected.credentialExpiresAt) <= Date.now()) throw new McpError("UNAUTHORIZED", "Источник MCP истёк", 401) const raw = structuredClone(source.connection), rows = structuredClone(source.grantRows) if (!effective || !rows.length) return freezePrincipalProjection({ connection: raw, grantRows: rows, generation: entry.generation }) if (rows.length !== 1) throw new McpError("GRANT_INACTIVE", "Неоднозначный временный доступ") if (source.grantOversized) throw new McpError("STATE_UNAVAILABLE", "Текущий источник прав недоступен", 503) const { credentialId: _credential, ...payload } = rows[0].payload as Record, grant = mcpTemporaryGrantSchema.parse(payload) if (Date.parse(grant.startsAt) > Date.now() || Date.parse(grant.expiresAt) <= Date.now()) throw new McpError("GRANT_INACTIVE", "Временный доступ не действует", 403) return freezePrincipalProjection({ connection: intersectGrant(raw, grant), grantRows: rows, generation: entry.generation }) } export async function readSynchronousPrincipalBoundary(principal: McpPrincipal, client: Pick, consume: (packet: PrincipalBoundaryPacket) => T): Promise { const directory = mcpStateDirectory(), source = await currentPrincipalSource(principal, client, true), generation = await accessGeneration() if (directory !== mcpStateDirectory()) throw new McpError("STATE_CONFLICT", "Источник файлов MCP изменился", 409) const packet = Object.freeze(Object.create(null)) as PrincipalBoundaryPacket principalBoundaryPackets.set(packet, { principal: Object.freeze({ ...principal }), directory, source, generation, client }) try { const result = consume(packet) if (result && typeof result === "object" && "then" in result) { void Promise.resolve(result).catch(() => {}); throw new McpError("STATE_CONFLICT", "Нужна синхронная граница MCP", 409) } return result } finally { principalBoundaryPackets.delete(packet) } }