Files
MikrotikManager/backend/src/modules/mcp/routing-network-execution-session.ts
T

93 lines
7.0 KiB
TypeScript

import { createHash } from "node:crypto"
import type { QueryConfig } from "pg"
import { pool } from "../../db/index.js"
import { captureVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecutionLifetime } from "../../services/config-mutation-policy.js"
import { effectiveMcpConnection } from "./store.js"
import { findMcpOperation } from "./registry.js"
import { fingerprint, McpError, redact } from "./security.js"
import { routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
import { assertAcknowledgedRoutingForwardAttempt, type RoutingReservedForwardAllocation } from "./routing-reservation-store.js"
import type { McpPrincipal } from "./store.js"
import { createRoutingNetworkNativeSession, type RoutingNetworkNativeManifest, type RoutingNetworkSharedContext } from "./routing-network-native-session.js"
const manualEffectOwners = new WeakSet<RoutingNetworkSharedContext>()
const reservedEffectOwners = new WeakMap<RoutingNetworkSharedContext, RoutingReservedForwardAllocation>()
/** Only the verified execution factory can mark a genuine shared owner. */
export function isVerifiedManualEffectOwner(owner: RoutingNetworkSharedContext): boolean {
return manualEffectOwners.has(owner)
}
export async function assertVerifiedReservedEffectOwner(owner: RoutingNetworkSharedContext, operationId: string, principal: McpPrincipal) {
const allocation = reservedEffectOwners.get(owner)
if (!allocation) throw new McpError("STATE_CONFLICT", "Исходный зарезервированный сеанс отсутствует", 409)
return assertAcknowledgedRoutingForwardAttempt(allocation, operationId, principal)
}
/** Private producer for the existing native/configuration-round reader. The
* manifest selects reads, never identity or authority. Its exact scope, probe
* ownership and whole-session budget are still checked by the native factory.
* Only the original live verified service step can open or use this session.
* No operation/principal/deadline/authorization callback is caller supplied.
* This grants no write, recovery or authenticated log-interval coverage. */
export async function createRoutingNetworkSessionForCurrentExecution(manifest: RoutingNetworkNativeManifest,
forwardAllocation?: RoutingReservedForwardAllocation): Promise<Awaited<ReturnType<typeof createRoutingNetworkNativeSession>>> {
const fail = () => new McpError("STATE_CONFLICT", "Нет исходного running scoped execution для native acquisition", 409)
const origin = await captureVerifiedMcpServiceExecution()
const initial = await inspectVerifiedMcpServiceExecution(origin)
if (!initial.approved || initial.phase !== "forward" || initial.stepIndex !== 0 ||
initial.operationName !== "routing.community.switch" || initial.operationVersion !== findMcpOperation(initial.operationName)?.version ||
initial.serviceName !== "routing.community.scoped") throw fail()
const input = initial.serviceInput, manual = input.proofRevision === 2
if (manual && (input.manualEffectPolicy !== "observational-v1" || input.persistentProfileAuthority !== undefined ||
(input.profile as { autoRecovery?: unknown } | undefined)?.autoRecovery !== false ||
(input.originalEffectSelection as { status?: unknown } | undefined)?.status !== "prepared")) throw fail()
const reserved = (input.profile as { autoRecovery?: unknown } | undefined)?.autoRecovery === true
if (reserved !== !!forwardAllocation || reserved && (input.proofRevision !== 3 || input.persistentProfileAuthority === undefined)) throw fail()
const lifetime = await inspectVerifiedMcpServiceExecutionLifetime(origin)
const authorize = async () => {
const current = await inspectVerifiedMcpServiceExecution(origin)
if (fingerprint(current) !== fingerprint(initial)) throw fail()
}
await authorize()
const reservationExpiry = forwardAllocation
? await assertAcknowledgedRoutingForwardAttempt(forwardAllocation, initial.operationId, initial.principal) : Infinity
const connection = await effectiveMcpConnection(initial.principal)
await authorize()
// The service lifetime may be narrower than plan expiry, but it does not
// replace the operation-created-at +120s native horizon. Never renew at now.
const query: QueryConfig & { query_timeout: number } = { text: `SELECT o.created_at,p.expires_at,
CASE WHEN octet_length(p.evidence::text)<=1048576 THEN p.evidence END AS evidence,
CASE WHEN octet_length(p.payload::text)<=1048576 THEN p.payload END AS payload,
CASE WHEN octet_length(s.intended_state::text)<=1048576 THEN s.intended_state END AS intended_state FROM mcp_operations o
JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id
WHERE o.id=$1 AND o.connection_id=$2 AND o.plan_id=$3 AND o.state='running'
AND s.step_index=0 AND s.state='intent' LIMIT 2`,
values: [initial.operationId, initial.principal.connectionId, initial.planId],
query_timeout: Math.max(1, Math.min(10000, lifetime.expiresAt - Date.now())) }
const source = await pool.query(query)
await authorize()
if (source.rows.length !== 1 || !(source.rows[0].created_at instanceof Date) || !(source.rows[0].expires_at instanceof Date)) throw fail()
const sha = (value: string) => createHash("sha256").update(value).digest("hex")
if (typeof source.rows[0].evidence?.sealed !== "string" || typeof source.rows[0].payload?.sealed !== "string" ||
sha(source.rows[0].evidence.sealed) !== initial.sealedEvidenceProof || sha(source.rows[0].payload.sealed) !== initial.sealedPayloadProof) throw fail()
if (fingerprint(source.rows[0].intended_state) !== fingerprint(redact({ kind: "service", service: initial.serviceName, input: initial.serviceInput }))) throw fail()
const authorityExpiry = initial.serviceInput.persistentProfileAuthority === undefined ? Infinity :
Date.parse(routingProfileAuthorityBindingSchema.parse(initial.serviceInput.persistentProfileAuthority).packet.validUntil)
const deadline = Math.min(source.rows[0].created_at.getTime() + 120000, source.rows[0].expires_at.getTime(), lifetime.expiresAt,
Date.parse(initial.principal.credentialExpiresAt), connection.owner_valid_until.getTime(), Date.parse(connection.policy.expiresAt), authorityExpiry, reservationExpiry)
// Reserve publication/current-authority time for the existing manual result.
// This only narrows the original horizon; it never creates a renewed grant.
const readDeadline = deadline - 15000
if (!Number.isFinite(readDeadline) || Date.now() >= readDeadline || lifetime.signal.aborted || performance.now() >= lifetime.monotonicDeadline) throw fail()
const session = await createRoutingNetworkNativeSession({ sourceOperationId: initial.operationId,
context: { principal: initial.principal, connection, signal: lifetime.signal }, authorize, deadline: readDeadline, manifest })
try {
await authorize()
if (manual) manualEffectOwners.add(session.sharedContext)
if (forwardAllocation) reservedEffectOwners.set(session.sharedContext, forwardAllocation)
return session
}
catch (error) { session.close(); throw error }
}