Files
MikrotikManager/backend/src/modules/mcp/routing-reservation-runtime.ts
T

87 lines
6.5 KiB
TypeScript

import type { PoolClient } from "pg"
import { selectManualInverseAdmissionWithinOwner } from "./routing-manual-inverse-store.js"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import type { ChangeEvidence } from "./action-types.js"
import type { McpPrincipal, StoredPlan } from "./store.js"
import { decryptSecret, fingerprint, McpError } from "./security.js"
import { assertScopedCommunityRequest, readScopedPathCheckpoint } from "./routing-community-scoped-request.js"
import { assertPersistentScopedProfileAuthority, routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
import { loadRoutingMainTransitionPreparation } from "./routing-main-transition.js"
export function requiresScopedRoutingOwnerApproval(evidence: ChangeEvidence) {
const step = evidence.steps[0]
return evidence.steps.length === 1 && step.kind === "service" &&
step.service === "routing.community.scoped" && step.input.proofRevision === 3
}
export async function readScopedRoutingPathAdmissionDeadline(db: PoolClient, evidence: ChangeEvidence, connectionId: string) {
const step = evidence.steps[0]
if (step.kind !== "service" || step.service !== "routing.community.scoped" || step.input.proofRevision !== 3 ||
routeAiProfileSchema.parse(step.input.profile).autoRecovery) return
const { pathCheckId, pathCheckpointProof } = step.input
if (typeof pathCheckId !== "string" || typeof pathCheckpointProof !== "string") {
throw new McpError("MEASUREMENT_UNKNOWN", "Подтверждение пути изменилось", 409)
}
const checkpoint = await readScopedPathCheckpoint(db, pathCheckId, connectionId)
if (checkpoint.proof !== pathCheckpointProof) throw new McpError("MEASUREMENT_UNKNOWN", "Подтверждение пути изменилось", 409)
return checkpoint.validUntil
}
/** Only authenticated encrypted evidence can select this admission lane. */
export async function routingReservationEvidence(plan: Pick<StoredPlan, "operation_id" | "operation_version">, evidence: ChangeEvidence) {
if (plan.operation_id !== "routing.community.switch" || evidence.steps.length !== 1) return undefined
const step = evidence.steps[0]
if (step.kind !== "service" || step.service !== "routing.community.scoped" || step.input.proofRevision !== 3) return undefined
await assertScopedCommunityRequest(step.input)
const profile = routeAiProfileSchema.parse(step.input.profile)
if (!profile.autoRecovery) return undefined
if (plan.operation_version !== 7 || evidence.recovery) throw new McpError("STATE_CONFLICT", "Incompatible reserved routing plan", 409)
const authority = routingProfileAuthorityBindingSchema.parse(step.input.persistentProfileAuthority)
await assertPersistentScopedProfileAuthority(step.input)
return { input: step.input, authority }
}
/** Same profile-row owner for every existing persistent forward lane. This
* selects locks only; it creates no slot, debit or dispatch authority. */
async function nonReservedPersistentAdmissionEvidence(plan: Pick<StoredPlan, "operation_id" | "operation_version">, evidence: ChangeEvidence) {
if (plan.operation_id !== "routing.community.switch" || evidence.steps.length !== 1) return undefined
const step = evidence.steps[0]
if (step.kind !== "service" || step.input.persistentProfileAuthority === undefined) return undefined
if (step.service === "routing.community.scoped" && step.input.proofRevision === 3) {
await assertScopedCommunityRequest(step.input)
if (routeAiProfileSchema.parse(step.input.profile).autoRecovery) throw new McpError("STATE_CONFLICT", "Reserved profile must use its original admission", 409)
await assertPersistentScopedProfileAuthority(step.input)
} else if (step.service === "routing.community") await loadRoutingMainTransitionPreparation(step.input)
else throw new McpError("STATE_CONFLICT", "Persistent profile admission source is incompatible", 409)
if (plan.operation_version !== 7) throw new McpError("STATE_CONFLICT", "Persistent routing operation version changed", 409)
return { input: step.input, authority: routingProfileAuthorityBindingSchema.parse(step.input.persistentProfileAuthority) }
}
/** Connection and global runner admission are already locked by applyPlan.
* Lock profile/credential BEFORE the plan and operation, on the same owner. */
export async function lockRoutingReservationAdmissionSource(db: PoolClient, initial: StoredPlan, principal: McpPrincipal) {
const initialEvidence = JSON.parse(await decryptSecret(initial.evidence.sealed)) as ChangeEvidence
const reserved = await routingReservationEvidence(initial, initialEvidence)
const manual = await selectManualInverseAdmissionWithinOwner(db, initial, initialEvidence, principal)
const selected = reserved ?? await nonReservedPersistentAdmissionEvidence(initial, initialEvidence) ?? manual
if (selected) {
const packet = selected.authority.packet
if (packet.connectionId !== principal.connectionId || !manual && packet.credentialId !== principal.credentialId) throw new McpError("STATE_CONFLICT", "Original routing principal differs", 409)
await db.query("SELECT id FROM mcp_routing_profiles WHERE id=$1 FOR UPDATE", [packet.profileId])
for (const credentialId of [...new Set([packet.credentialId, principal.credentialId])].sort()) {
await db.query("SELECT id FROM mcp_credentials WHERE id=$1 AND connection_id=$2 FOR SHARE", [credentialId, principal.connectionId])
}
}
const rows = (await db.query<StoredPlan>("SELECT * FROM mcp_plans WHERE id=$1 FOR UPDATE", [initial.id])).rows
if (rows.length !== 1) throw new McpError("NOT_FOUND", "План не найден", 404)
const plan = rows[0]
if (fingerprint(plan.evidence) !== fingerprint(initial.evidence) || plan.operation_id !== initial.operation_id || plan.operation_version !== initial.operation_version || plan.connection_id !== initial.connection_id) throw new McpError("STATE_CONFLICT", "Plan changed before ordered admission locks", 409)
if (manual) {
await db.query("SELECT o.id FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id WHERE o.id=$1 AND o.connection_id=$2 FOR UPDATE OF o,p", [manual.source.row.id, principal.connectionId])
const after = await selectManualInverseAdmissionWithinOwner(db, plan, initialEvidence, principal)
if (!after || fingerprint(after) !== fingerprint(manual)) throw new McpError("STATE_CONFLICT", "Manual inverse source changed before ordered admission", 409)
}
if (selected) await assertPersistentScopedProfileAuthority(selected.input, undefined, db)
return { plan, evidence: initialEvidence, reserved: !!reserved }
}