import { createHash, randomUUID, timingSafeEqual } from "node:crypto" import { z } from "zod" import type { IpsecCertBundle } from "@mmapp/contracts/ipsec" import { pool } from "../../db/index.js" import { hasPermission, type AuthUser } from "../../lib/permissions.js" import { getServerRowById } from "../servers/repository/servers-repository.js" import { ipsecPeerDeleteSourceProof } from "../../services/ipsec-peer-delete.js" import { readIpsecUserCreateState } from "../../services/ipsec-user-create.js" import { assertLogArtifactBudget } from "./log-artifacts.js" import { assertPortalClaimsCurrent } from "./portal-revocation.js" import { connectionWrite, effectiveMcpConnection } from "./store.js" import { decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError } from "./security.js" const digest = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid() export const ipsecUserBundleAuthoritySchema = z.object({ principal: z.object({ connectionId: uuid, credentialId: uuid, credentialExpiresAt: z.string().datetime() }).strict(), ownerId: z.string().min(1), policyProof: digest, ownerProof: digest, generation: z.string().min(1), serverId: z.number().int().positive(), clientName: z.string().min(1).max(64), receiptId: uuid, sourceProof: digest, inputProof: digest, }).strict() export type IpsecUserBundleAuthority = z.infer const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("ipsec-user-bundle"), authority: ipsecUserBundleAuthoritySchema, afterProof: digest, bytes: z.number().int().positive().max(1048576), sha256: digest, encryptedSha256: digest, proof: digest }).strict() type Header = { id: string; connection_id: string; filename: string; media_type: string; expires_at: Date } type Meta = Header & { access_scope: z.infer; encrypted_bytes: number } const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex") const sign = (value: unknown) => privateSecretFingerprint(fingerprint(value), "ipsec-user-bundle-artifact-v1") const signed = (header: Header, scope: Omit) => ({ id: header.id, connection_id: header.connection_id, filename: header.filename, media_type: header.media_type, expires_at: header.expires_at.toISOString(), scope }) const fail = (message: string, code = "ARTIFACT_INVALID") => new McpError(code, message, 409) export const ipsecUserBundleReceipt = (header: Pick, scope: Pick) => ({ artifactId: header.id, downloadPath: `/api/mcp/artifacts/${header.id}`, expiresInSeconds: 900, bytes: scope.bytes, sha256: scope.sha256, humanDownloadOnly: true, ipsecContentReturned: false }) async function access(authority: IpsecUserBundleAuthority, client: Pick = pool) { const current = await effectiveMcpConnection(authority.principal, client) if (current.owner_id !== authority.ownerId || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write") || !current.policy.scope.operationIds.includes("network.ipsec.users.create") || !current.policy.scope.serverIds.includes(authority.serverId) || current.policy.mode === "observer" || Date.parse(authority.principal.credentialExpiresAt) <= Date.now()) throw new McpError("PERMISSION_DENIED", "Нет допуска к приватному пакету IPsec", 403) if (current.generation !== authority.generation || fingerprint(current.policy) !== authority.policyProof || fingerprint(current.owner_permissions) !== authority.ownerProof) throw fail("Допуск пакета IPsec изменился", "RESET_REQUIRED") const denied = (await client.query("SELECT 1 FROM mcp_protections WHERE object_ref->>'protection'='deny' AND (object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1)) LIMIT 1", [String(authority.serverId)])).rows[0] if (denied) throw fail("Пакет IPsec заблокирован защитой", "PROTECTED_OBJECT") } async function source(authority: IpsecUserBundleAuthority, authorize: () => Promise = async () => {}) { const check = async () => { await authorize(); await access(authority) } await check() const server = await getServerRowById(authority.serverId) if (!server || await ipsecPeerDeleteSourceProof(server) !== authority.sourceProof) throw fail("Источник пакета IPsec изменился", "STATE_CONFLICT") return readIpsecUserCreateState(server, check) } export async function createIpsecUserBundleArtifact(authority: IpsecUserBundleAuthority, bundle: IpsecCertBundle, afterProof: string, authorize: () => Promise) { ipsecUserBundleAuthoritySchema.parse(authority) await authorize(); await access(authority) const content = Buffer.from(JSON.stringify(bundle)), ciphertext = await encryptSecret(content.toString("base64")) if (!content.length || content.length > 1048576 || Buffer.byteLength(ciphertext) > 2097152) throw fail("Приватный пакет IPsec превышает предел", "EXPORT_LIMIT") if ((await source(authority, authorize)).proof !== afterProof) throw fail("IPsec изменился перед сохранением пакета", "STATE_CONFLICT") const header: Header = { id: randomUUID(), connection_id: authority.principal.connectionId, filename: "ipsec-client-bundle.json", media_type: "application/json", expires_at: new Date(Date.now() + 900000) } const unsigned = { version: 1 as const, kind: "ipsec-user-bundle" as const, authority, afterProof, bytes: content.length, sha256: hash(content), encryptedSha256: hash(ciphertext) } const scope = scopeSchema.parse({ ...unsigned, proof: await sign(signed(header, unsigned)) }) await connectionWrite(async client => { await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [header.connection_id]); await access(authority, client) await client.query("SELECT pg_advisory_xact_lock(hashtextextended('mcp-log-artifact-storage',0))") await client.query("DELETE FROM mcp_artifacts WHERE expires_at<=now()") const usage = (await client.query("SELECT count(*) FILTER(WHERE connection_id=$1)::text AS files,COALESCE(sum(octet_length(ciphertext)) FILTER(WHERE connection_id=$1),0)::text AS own_bytes,COALESCE(sum(octet_length(ciphertext)),0)::text AS total_bytes FROM mcp_artifacts", [header.connection_id])).rows[0] assertLogArtifactBudget(BigInt(usage.files), BigInt(usage.own_bytes), BigInt(usage.total_bytes), Buffer.byteLength(ciphertext)) await client.query("INSERT INTO mcp_artifacts(id,connection_id,filename,media_type,ciphertext,access_scope,expires_at) VALUES($1,$2,$3,$4,$5,$6::jsonb,$7)", [header.id, header.connection_id, header.filename, header.media_type, ciphertext, JSON.stringify(scope), header.expires_at]) }) await authorize(); await access(authority) return ipsecUserBundleReceipt(header, scope) } async function meta(id: string): Promise { const row = (await pool.query("SELECT id,connection_id,filename,media_type,expires_at,CASE WHEN octet_length(access_scope::text)<=32768 THEN access_scope ELSE NULL END AS access_scope,octet_length(ciphertext)::int AS encrypted_bytes FROM mcp_artifacts WHERE id=$1 AND expires_at>now() AND octet_length(filename)<=1024 AND octet_length(media_type)<=200", [id])).rows[0] if (!row) throw new McpError("NOT_FOUND", "Пакет IPsec отсутствует или срок истёк", 404) const scope = scopeSchema.safeParse(row.access_scope) if (!scope.success || !(row.expires_at instanceof Date) || !Number.isFinite(row.expires_at.getTime()) || !Number.isSafeInteger(row.encrypted_bytes) || row.encrypted_bytes <= 0 || row.encrypted_bytes > 2097152) throw fail("Метаданные пакета IPsec не подтверждены") const { proof, ...unsigned } = scope.data if (row.connection_id !== unsigned.authority.principal.connectionId || !timingSafeEqual(Buffer.from(proof, "hex"), Buffer.from(await sign(signed(row, unsigned)), "hex"))) throw fail("Подпись пакета IPsec не совпала") return { ...row, access_scope: scope.data } } async function checkpoint(row: Meta) { const scope = row.access_scope const rows = (await pool.query("SELECT s.intended_state,s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id JOIN mcp_plans p ON p.id=o.plan_id WHERE o.connection_id=$1 AND o.state='applied' AND p.operation_id='network.ipsec.users.create' AND p.approved_by IS NOT NULL AND s.state='verified' AND s.intended_state->>'kind'='service' AND s.intended_state->>'service'='network.ipsec.users.create' AND s.result->>'artifactId'=$2 LIMIT 2", [row.connection_id, row.id])).rows const candidate = rows[0], input = candidate?.intended_state?.input, result = candidate?.result if (rows.length !== 1 || fingerprint(input) !== scope.authority.inputProof || !result || result.receiptId !== scope.authority.receiptId || result.clientId !== scope.authority.clientName || result.historyRecorded !== true || result.revisionRecorded !== true || result.verified !== true || result.ok !== true || result.completedCommands !== result.commandCount || result.confirmedWrites !== result.commandCount || result.afterProof !== scope.afterProof || result.automaticReplay !== false || result.forwardingVerified !== false || Object.entries(ipsecUserBundleReceipt(row, scope)).some(([key, value]) => result[key] !== value)) throw fail("Нет точной проверенной квитанции приватного экспорта IPsec", "STATE_CONFLICT") } export async function verifyIpsecUserBundleArtifact(id: string, authority: IpsecUserBundleAuthority, afterProof: string) { const row = await meta(id), scope = row.access_scope await access(authority) if (fingerprint(authority) !== fingerprint(scope.authority) || scope.afterProof !== afterProof) return false const payload = (await pool.query("SELECT ciphertext FROM mcp_artifacts WHERE id=$1 AND access_scope->>'proof'=$2 AND expires_at>now() AND octet_length(ciphertext)<=2097152", [id, scope.proof])).rows[0] await access(authority) return !!payload && hash(payload.ciphertext) === scope.encryptedSha256 && (await source(authority)).proof === afterProof } export async function humanIpsecUserBundleMetadata(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent) { const row = await meta(id), scope = row.access_scope await checkClaims(actor) if (actor.id !== scope.authority.ownerId || !hasPermission(actor.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Пакет IPsec доступен только владельцу", 403) await access(scope.authority); await checkpoint(row) return scope } export async function readHumanIpsecUserBundleArtifact(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent, signal?: AbortSignal) { const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(45000)]) : AbortSignal.timeout(45000) const row = await meta(id), scope = row.access_scope const authorize = async () => { bounded.throwIfAborted(); await checkClaims(actor); if (actor.id !== scope.authority.ownerId || !hasPermission(actor.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Пакет IPsec доступен только владельцу", 403); await access(scope.authority); await checkpoint(row); if (row.expires_at.getTime() <= Date.now()) throw fail("Срок пакета IPsec истёк") } await authorize() if ((await source(scope.authority, authorize)).proof !== scope.afterProof) throw fail("IPsec изменился после создания пакета", "STATE_CONFLICT") const payload = (await pool.query("SELECT ciphertext FROM mcp_artifacts WHERE id=$1 AND access_scope->>'proof'=$2 AND expires_at>now() AND octet_length(ciphertext)<=2097152", [id, scope.proof])).rows[0] await authorize() if (!payload || hash(payload.ciphertext) !== scope.encryptedSha256) throw fail("Шифротекст пакета IPsec изменился") let content: Buffer try { content = Buffer.from(await decryptSecret(payload.ciphertext), "base64") } catch { throw fail("Пакет IPsec не расшифрован") } if (content.length !== scope.bytes || hash(content) !== scope.sha256) throw fail("Размер или SHA-256 пакета IPsec не совпал") if ((await source(scope.authority, authorize)).proof !== scope.afterProof) throw fail("IPsec изменился при выдаче пакета", "STATE_CONFLICT") await authorize() return { filename: row.filename, mediaType: row.media_type, content } }