Files
MikrotikManager/backend/src/modules/mcp/speed-bandwidth-original.ts
T

431 lines
40 KiB
TypeScript

/** Sealed MCP full uptime speed command only. No bandwidth dispatch, enrollment,
* runtime wiring, history publication or substitute diagnostic workflow. */
import type { QueryConfig } from "pg"
import { createHash } from "node:crypto"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import { performance } from "node:perf_hooks"
import { isDeepStrictEqual } from "node:util"
import { z } from "zod"
import { speedTestCommandSchema, type SpeedTestCommand } from "@mmapp/contracts"
import { mcpConnectionPolicySchema, mcpTemporaryGrantSchema } from "@mmapp/contracts/mcp"
import { pool } from "../../db/index.js"
import { captureVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecutionLifetime } from "../../services/config-mutation-policy.js"
import { readCurrentMcpServiceExecution } from "./service-execution-origin.js"
import { effectiveMcpConnection } from "./store.js"
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
import { hasPermission } from "../../lib/permissions.js"
import { fingerprint, McpError, mcpStateDirectory, privateFingerprinterExisting, redact } from "./security.js"
import type { RoutingEndpoint } from "./routing-observation-source.js"
import type { BandwidthScope } from "../../services/bandwidth-admission.js"
import type { BandwidthPeerExecutionIntent } from "../../services/bandwidth-peer-execution-host.js"
import { readBandwidthPeerCompletion } from "../../services/bandwidth-peer-execution-host.js"
import type { BandwidthPeerSourceSnapshot } from "../../services/bandwidth-peer-observation.js"
import { parseBandwidthPeerRef, type BandwidthPeerRef } from "../../services/bandwidth-peer-reference.js"
import { assertSpeedProbeContext } from "../../services/speed-run-persistence.js"
import { MikrotikClient } from "../../services/mikrotik.js"
import { createBandwidthSpeedRunIdentity, BANDWIDTH_SPEED_RUN_HISTORY_SQL, assertBandwidthSpeedRunHistoryAbsent, BandwidthSpeedRunIdUnavailable } from "../../services/bandwidth-speed-run-identity.js"
declare const mcpSpeedBrand: unique symbol
export type McpSpeedBandwidthOriginal = Readonly<{ [mcpSpeedBrand]: true }>
export interface McpSpeedBandwidthContext {
readonly command: Readonly<SpeedTestCommand>; readonly srcAddress: string; readonly dstAddress: string
readonly address: string; readonly srcInterfaceAddress: string | null; readonly dstInterfaceAddress: string | null
}
const providers = new WeakSet<object>()
// All private tokens from the SAME genuine service scope expose this one
// controller signal. Another provider factory cannot renew its first window.
const serviceCaptures = new WeakMap<AbortSignal, Readonly<{ deadlineAt: number; inputSignal?: AbortSignal; end: number; lifecycleSignal: AbortSignal }>>()
const deny = (): never => { throw new McpError("PERMISSION_DENIED", "Исходный MCP speed-контекст изменён или недоступен", 403) }
export function assertMcpSpeedBandwidthOriginalProvider(value: unknown): asserts value is ReturnType<typeof createMcpSpeedBandwidthOriginalProvider> {
if (!value || typeof value !== "object" || !providers.has(value)) deny()
}
function freeze<T>(value: T): T {
if (value && typeof value === "object") { Object.values(value).forEach(freeze); Object.freeze(value) }
return value
}
const commandFields = new Set(["runId", "probeId", "srcServerId", "dstServerId", "srcInterface", "dstInterface", "protocol", "direction", "durationSec"])
function commandSnapshot(raw: unknown): Readonly<SpeedTestCommand> {
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype) return deny()
const fields = Object.getOwnPropertyDescriptors(raw)
if (Reflect.ownKeys(raw).length !== Object.keys(fields).length || Object.keys(fields).some(key => !commandFields.has(key))
|| Object.values(fields).some(field => !("value" in field) || !field.enumerable || field.value !== undefined && !["string", "number"].includes(typeof field.value))) deny()
const parsed = speedTestCommandSchema.parse(Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value])))
// Keep optional absent IDs out of admission JSON while preserving the exact
// shared contract's coercion/defaults/trim behavior.
return freeze(Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== undefined)) as SpeedTestCommand)
}
function scopeSnapshot(raw: Readonly<BandwidthScope>): Readonly<BandwidthScope> {
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype || Reflect.ownKeys(raw).length !== Object.keys(raw).length) deny()
const fields = Object.getOwnPropertyDescriptors(raw)
if (Object.keys(fields).some(key => !["deadlineAt", "signal"].includes(key)) || Object.values(fields).some(field => !("value" in field) || !field.enumerable)) deny()
const deadlineAt = fields.deadlineAt?.value, signal = fields.signal?.value
if (typeof deadlineAt !== "number" || !Number.isSafeInteger(deadlineAt) || signal !== undefined && !(signal instanceof AbortSignal)) return deny()
return Object.freeze({ deadlineAt, signal })
}
const metadataSchema = z.array(z.object({ id: z.number().int().positive().safe(), enabled: z.literal(true), routingEndpointEpoch: z.string().uuid() }).strict()).length(2)
const endpointSchema = z.object({ id: z.number().int().positive().safe(), enabled: z.literal(true), routingEndpointEpoch: z.string().uuid(), host: z.string().min(1).max(1000),
port: z.number().int().min(1).max(65535), useSsl: z.boolean(), verifySsl: z.boolean(), username: z.string().max(1000), password: z.string().max(65536) }).strict()
const probeSchema = z.object({ id: z.string(), srcServerId: z.number().int().positive().safe(), dstServerId: z.number().int().positive().safe(),
srcInterface: z.string(), dstInterface: z.string(), protocol: z.enum(["tcp", "udp"]), direction: z.enum(["both", "transmit", "receive"]), durationSec: z.number().int().min(3).max(2147483647), enabled: z.boolean() }).strict()
type Metadata = z.infer<typeof metadataSchema>
type Probe = z.infer<typeof probeSchema> | undefined
const currentActorSchema = z.object({ id: z.string().uuid(), ownerId: z.string(), ownerPermissions: z.array(z.string()).max(1000), policy: mcpConnectionPolicySchema,
generation: z.string(), ownerValidUntil: z.string().datetime({ offset: true }), ownerClaimsIssuedAt: z.string().datetime({ offset: true }),
grants: z.array(z.object({ id: z.string().uuid(), payload: z.record(z.string(), z.unknown()) }).strict()).max(1) }).strict()
export interface McpSpeedBandwidthInput {
readonly command: Readonly<SpeedTestCommand>
readonly expectedEndpoints: ReadonlyArray<Readonly<{ serverId: number; proof: string }>>
readonly expectedProbe: z.infer<typeof probeSchema> | null
}
function inputSnapshot(raw: unknown): Readonly<McpSpeedBandwidthInput> {
let bytes = 0; const seen = new Set<object>()
const visit = (value: unknown, depth: number): void => {
if (depth > 10) deny()
if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return
if (typeof value === "string") { bytes += Buffer.byteLength(value); if (bytes > 131072) deny(); return }
if (!value || typeof value !== "object" || seen.has(value)) return deny(); seen.add(value)
const fields = Object.getOwnPropertyDescriptors(value)
if (Array.isArray(value)) {
if (Reflect.ownKeys(value).length !== value.length + 1) deny()
for (let i = 0; i < value.length; i++) { const field = fields[String(i)]; if (!field || !("value" in field) || !field.enumerable) deny(); visit(field.value, depth + 1) }
} else {
if (Object.getPrototypeOf(value) !== Object.prototype || Reflect.ownKeys(value).length !== Object.keys(fields).length) deny()
for (const field of Object.values(fields)) { if (!("value" in field) || !field.enumerable) deny(); visit(field.value, depth + 1) }
}
}
visit(raw, 0)
const value = z.object({ command: z.unknown(), expectedEndpoints: z.array(z.object({ serverId: z.number().int().positive().safe(), proof: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).length(2), expectedProbe: probeSchema.nullable() }).strict().parse(raw)
const command = commandSnapshot(value.command)
if (!command.runId || !isDeepStrictEqual(command, value.command) || !!command.probeId !== !!value.expectedProbe || value.expectedProbe && value.expectedProbe.id !== command.probeId
|| !isDeepStrictEqual(value.expectedEndpoints.map(row => row.serverId), [command.srcServerId, command.dstServerId].sort((a, b) => a - b))) deny()
return freeze(structuredClone({ command, expectedEndpoints: value.expectedEndpoints, expectedProbe: value.expectedProbe }))
}
/** Pure workflow consistency only. This never grants authority or mints a cap;
* the caller must already hold this provider's genuine private original. */
export function assertMcpSpeedBandwidthWorkflowRequest(request: unknown, command: Readonly<SpeedTestCommand>, expiresAt: number): void {
if (!request || typeof request !== "object" || Array.isArray(request) || Reflect.ownKeys(request).length !== 2) deny()
const fields = Object.getOwnPropertyDescriptors(request), commandField = fields.command, originField = fields.mcp
if (!commandField || !("value" in commandField) || !originField || !("value" in originField) || !isDeepStrictEqual(commandField.value, command)) deny()
const origin = originField.value as Awaited<ReturnType<typeof readCurrentMcpServiceExecution>>
if (!origin || origin.operationName !== "uptime.speed-test" || origin.serviceName !== "uptime.speed-test" || origin.operationVersion !== 1
|| origin.phase !== "forward" || origin.originalExpiresAt !== expiresAt || !isDeepStrictEqual(inputSnapshot(origin.serviceInput).command, command)
|| [command.srcServerId, command.dstServerId].some(id => !origin.serverIds?.includes(id) || !origin.objects?.some(object => object.kind === "server" && object.serverId === id && object.id === String(id)))) deny()
}
const purpose = "routing-observation-source-v1", keyMessage = "routing-observation-source-purpose-key-epoch-v1"
async function existingGeneration(directory: string) {
const bytes = await readFile(join(directory, "access-generation"))
if (bytes.length !== 32) return deny()
return bytes.toString("hex")
}
/** Fixed current-facts projection. Captured credentials are private parameters
* compared INSIDE PostgreSQL. Bounded authority metadata stays private; the
* same contract schemas normalize policy/grant rather than SQL approximations.
* Completion uses a separate fixed query omitting ONLY the selected probe. */
function currentSnapshotSql(includeProbe: boolean): string {
return `/* mcp-speed-original:${includeProbe ? "current-snapshot" : "completion-snapshot"} */ WITH input AS MATERIALIZED (SELECT $2::jsonb AS probe,$3::text AS id), expected AS MATERIALIZED (
SELECT * FROM pg_catalog.jsonb_to_recordset($1::jsonb) AS e(id bigint,enabled boolean,"routingEndpointEpoch" uuid,
host text,port integer,"useSsl" boolean,"verifySsl" boolean,username text,password text)),
matched AS MATERIALIZED (
SELECT s.id FROM public.servers s JOIN expected e ON e.id=s.id WHERE s.enabled=true
AND pg_catalog.jsonb_build_object('id',s.id,'enabled',s.enabled,'routingEndpointEpoch',s.routing_endpoint_epoch,
'host',s.host,'port',s.port,'useSsl',s.use_ssl,'verifySsl',s.verify_ssl,'username',s.username,'password',s.password)=pg_catalog.to_jsonb(e)),
endpoints_current AS MATERIALIZED (SELECT count(*)=2 AND count(DISTINCT id)=2
AND (SELECT count(*) FROM matched)=2 AS current FROM expected)${includeProbe ? `,
chosen_probe AS MATERIALIZED (SELECT pg_catalog.jsonb_build_object('id',p.id,'srcServerId',p.src_server_id,'dstServerId',p.dst_server_id,
'srcInterface',p.src_interface,'dstInterface',p.dst_interface,'protocol',p.protocol,'direction',p.direction,'durationSec',p.duration_sec,'enabled',p.enabled) AS projection
FROM public.uptime_speed_probes p WHERE p.id=$3::text LIMIT 2)` : ""}
, current_actor AS MATERIALIZED (SELECT c.id,c.owner_id,c.owner_permissions,c.policy,c.generation,c.owner_valid_until,c.owner_claims_issued_at,
coalesce((SELECT jsonb_agg(g) FROM (SELECT id::text,CASE WHEN octet_length(payload::text)<=1048576 THEN payload END AS payload
FROM public.mcp_grants WHERE connection_id=c.id AND revoked_at IS NULL AND payload->>'credentialId'=$4::jsonb->>'credentialId' LIMIT 2)g),'[]'::jsonb) AS grants,
EXISTS(SELECT 1 FROM public.mcp_credentials k WHERE k.id=($4::jsonb->>'credentialId')::uuid AND k.connection_id=c.id AND k.revoked_at IS NULL AND k.expires_at>now()) AS credential_current,
EXISTS(SELECT 1 FROM public.mcp_settings WHERE id=1 AND enabled=true) AS settings_current,
NOT EXISTS(SELECT 1 FROM public.mcp_owner_revocations r WHERE r.owner_id=c.owner_id AND r.invalid_before>to_timestamp(0)
AND (c.owner_claims_issued_at IS NULL OR c.owner_claims_issued_at<=r.invalid_before)) AS portal_current
FROM public.mcp_connections c WHERE c.id=($4::jsonb->>'connectionId')::uuid LIMIT 2),
actor_projection AS MATERIALIZED (SELECT jsonb_build_object('id',id,'ownerId',owner_id,'ownerPermissions',owner_permissions,
'policy',policy,'generation',generation,'ownerValidUntil',owner_valid_until,'ownerClaimsIssuedAt',owner_claims_issued_at,'grants',grants) AS authority,
credential_current AND settings_current AND portal_current AS current FROM current_actor),
sealed_source AS MATERIALIZED (SELECT o.state AS operation_state,p.state AS plan_state,s.state AS step_state,p.operation_id,p.operation_version,p.policy_version,
p.generation,p.expires_at,p.approved_by,c.owner_id,s.server_id,s.intended_state,
encode(sha256(convert_to(p.evidence->>'sealed','UTF8')),'hex') AS evidence_proof,
encode(sha256(convert_to(p.payload->>'sealed','UTF8')),'hex') AS payload_proof
FROM public.mcp_operations o JOIN public.mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id
JOIN public.mcp_connections c ON c.id=o.connection_id JOIN public.mcp_operation_steps s ON s.operation_id=o.id AND s.step_index=($4::jsonb->>'stepIndex')::integer
WHERE o.id=($4::jsonb->>'operationId')::uuid AND p.id=($4::jsonb->>'planId')::uuid AND o.connection_id=($4::jsonb->>'connectionId')::uuid LIMIT 2)
SELECT (e.current${includeProbe ? ` AND ($2::jsonb IS NULL OR ((SELECT count(*) FROM chosen_probe)=1
AND (SELECT projection FROM chosen_probe LIMIT 1)=$2::jsonb))` : ""}
AND (SELECT count(*) FROM actor_projection)=1 AND (SELECT current FROM actor_projection LIMIT 1)
AND (SELECT count(*) FROM sealed_source)=1 AND EXISTS(SELECT 1 FROM sealed_source s WHERE s.operation_state='running' AND s.plan_state='executing' AND s.step_state='intent'
AND s.server_id IS NULL AND s.operation_id=$4::jsonb->>'operationName' AND s.operation_version=($4::jsonb->>'operationVersion')::integer
AND s.policy_version=($4::jsonb->>'policyVersion')::integer AND s.generation=$4::jsonb->>'generation' AND s.owner_id=$4::jsonb->>'ownerId'
AND (s.approved_by IS NOT NULL)=($4::jsonb->>'approved')::boolean AND s.expires_at>=to_timestamp(($4::jsonb->>'originalExpiresAt')::double precision/1000)
AND s.evidence_proof=$4::jsonb->>'sealedEvidenceProof' AND s.payload_proof=$4::jsonb->>'sealedPayloadProof' AND s.intended_state=$4::jsonb->'intendedState')) IS TRUE AS current,
(SELECT CASE WHEN octet_length(authority::text)<=1048576 THEN authority END FROM actor_projection LIMIT 1) AS authority FROM endpoints_current e`
}
const CURRENT_SNAPSHOT_SQL = currentSnapshotSql(true), COMPLETION_SNAPSHOT_SQL = currentSnapshotSql(false)
// Per-physical-connection pg statement names cache parsing/planning only. All
// values, SQL execution, live facts and authority checks remain fresh per call.
const snapshotStatementName = (sql: string) => "mcp-speed-" + createHash("sha256").update(sql).digest("hex").slice(0, 48)
const CURRENT_STATEMENT = snapshotStatementName(CURRENT_SNAPSHOT_SQL), COMPLETION_STATEMENT = snapshotStatementName(COMPLETION_SNAPSHOT_SQL)
/** Same static-first/filter/order selection as executeBandwidthSpeedTestInner. */
function firstUsableIp(rows: Record<string, unknown>[], iface: string): string {
const candidates = rows.filter(row => String(row.interface ?? "").trim() === iface.trim()
&& String(row.disabled ?? "false").toLowerCase() !== "true" && String(row.invalid ?? "false").toLowerCase() !== "true" && String(row.address ?? "").trim().includes("/"))
candidates.sort((a, b) => (String(a.dynamic ?? "false").toLowerCase() === "true" ? 1 : 0) - (String(b.dynamic ?? "false").toLowerCase() === "true" ? 1 : 0))
return candidates[0]?.address ? String(candidates[0].address).split("/")[0]?.trim() ?? "" : ""
}
async function window<T>(input: Readonly<BandwidthScope>, authority: Readonly<{ expiresAt: number; monotonicDeadline: number; signal: AbortSignal }>, originalEnd: number, originalSignal: AbortSignal | undefined, work: (scope: Readonly<BandwidthScope>, live: () => void) => Promise<T>): Promise<T> {
const controller = new AbortController()
const scope = Object.freeze({ deadlineAt: Math.min(input.deadlineAt, authority.expiresAt), signal: AbortSignal.any([controller.signal, authority.signal, ...(input.signal ? [input.signal] : []), ...(originalSignal ? [originalSignal] : [])]) })
const end = Math.min(originalEnd, performance.now() + Math.max(0, scope.deadlineAt - Date.now()))
const signals = [...new Set([scope.signal, originalSignal, authority.signal].filter((signal): signal is AbortSignal => !!signal))]
let active = true, rejectStopped!: (error: Error) => void
const live = () => { if (!active || Date.now() >= scope.deadlineAt || performance.now() >= end || signals.some(signal => signal.aborted)) deny() }
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = reject })
const stop = () => { if (!active) return; active = false; controller.abort(); rejectStopped(new McpError("PERMISSION_DENIED", "MCP speed-контекст завершён", 403)) }
const timer = setTimeout(stop, Math.max(1, Math.min(scope.deadlineAt - Date.now(), end - performance.now())))
for (const signal of signals) signal.addEventListener("abort", stop, { once: true })
try { live(); return await Promise.race([Promise.resolve().then(async () => { live(); const result = await work(scope, live); live(); return result }), stopped]) }
finally { active = false; clearTimeout(timer); for (const signal of signals) signal.removeEventListener("abort", stop); controller.abort() }
}
/** Fixed production dependencies only. Constructor does no I/O and accepts no
* actor/client/SQL/proof callbacks. Capabilities remain bound to the live MCP
* service; they are not background job or independent wire-mapping authority. */
export function createMcpSpeedBandwidthOriginalProvider() {
type Entry = { intent: BandwidthPeerExecutionIntent; context: Readonly<McpSpeedBandwidthContext>; peers: ReadonlyMap<number, Readonly<BandwidthPeerSourceSnapshot>>
authority: Readonly<{ expiresAt: number; monotonicDeadline: number; signal: AbortSignal }>; end: number; signal?: AbortSignal; assertCurrent(scope: Readonly<BandwidthScope>, live: () => void): Promise<void>
assertAuthorityCurrent(scope: Readonly<BandwidthScope>, live: () => void): Promise<void> }
const entries = new WeakMap<object, Entry>()
const read = async (token: unknown, rawScope: Readonly<BandwidthScope>) => {
const scope = scopeSnapshot(rawScope), entry = token && typeof token === "object" ? entries.get(token) : undefined
if (!entry) return deny()
await window(scope, entry.authority, entry.end, entry.signal, (current, live) => entry.assertCurrent(current, live))
return entry
}
const provider = Object.freeze({
async capture(raw: unknown, rawScope: Readonly<BandwidthScope>): Promise<McpSpeedBandwidthOriginal> {
const input = inputSnapshot(raw), command = input.command, scope = scopeSnapshot(rawScope), entered = Date.now(), enteredMono = performance.now()
const provisional = Object.freeze({ expiresAt: scope.deadlineAt, monotonicDeadline: enteredMono + Math.max(0, scope.deadlineAt - entered), signal: scope.signal ?? new AbortController().signal })
return window(scope, provisional, provisional.monotonicDeadline, scope.signal, async (initial, initialLive) => {
// Existing private material is checked before entering a generic runtime
// authorizer. This provider never bootstraps a missing key/generation.
const sourceDirectory = mcpStateDirectory(), generation = await existingGeneration(sourceDirectory); initialLive()
const sign = await privateFingerprinterExisting(purpose); initialLive(); const keyProof = sign(keyMessage)
const original = await captureVerifiedMcpServiceExecution(); initialLive()
const metadata = await readCurrentMcpServiceExecution(original, initial); initialLive()
if (metadata.operationName !== "uptime.speed-test" || metadata.serviceName !== "uptime.speed-test" || metadata.operationVersion !== 1 || metadata.phase !== "forward"
|| !isDeepStrictEqual(metadata.serviceInput, input)) return deny()
const ids = [command.srcServerId, command.dstServerId].sort((a, b) => a - b)
if (ids.some(id => !metadata.serverIds.includes(id) || !metadata.objects.some(object => object.kind === "server" && object.serverId === id && object.id === String(id)))) deny()
const lifetime = await inspectVerifiedMcpServiceExecutionLifetime(original); initialLive()
let captured = serviceCaptures.get(lifetime.signal)
if (captured) {
if (captured.deadlineAt !== scope.deadlineAt || captured.inputSignal !== scope.signal || captured.lifecycleSignal.aborted) deny()
} else {
captured = Object.freeze({ deadlineAt: scope.deadlineAt, inputSignal: scope.signal, end: Math.min(lifetime.monotonicDeadline, provisional.monotonicDeadline),
lifecycleSignal: scope.signal ? AbortSignal.any([lifetime.signal, scope.signal]) : lifetime.signal })
serviceCaptures.set(lifetime.signal, captured)
}
const authority = Object.freeze({ ...lifetime, monotonicDeadline: captured.end, signal: captured.lifecycleSignal })
const run = createBandwidthSpeedRunIdentity(command.runId), sealedCommand = command
const end = captured.end
return window(initial, authority, end, scope.signal, async (current, live) => {
if (mcpStateDirectory() !== sourceDirectory || generation !== metadata.generation || await existingGeneration(sourceDirectory) !== generation) deny(); live()
const actorCurrent = async (next: Readonly<BandwidthScope>, checkLive: () => void) => {
checkLive(); const connection = await effectiveMcpConnection(metadata.principal); checkLive()
if (connection.id !== metadata.connectionId || connection.owner_id !== metadata.ownerId || connection.generation !== metadata.generation
|| !hasPermission(connection.owner_permissions, "mm:uptime:write") || !hasPermission(connection.policy.permissions, "mm:uptime:write")
|| !connection.policy.scope.operationIds.includes("uptime.speed-test") || ids.some(id => !connection.policy.scope.serverIds.includes(id))
|| next.signal?.aborted) deny()
if (!isDeepStrictEqual(await readCurrentMcpServiceExecution(original, next), metadata)) deny(); checkLive()
}
const basic = async (next: Readonly<BandwidthScope>, checkLive: () => void) => {
checkLive(); if (mcpStateDirectory() !== sourceDirectory) deny()
// This guard already reads effective current rights AND the sealed
// SQL origin, with fresh private authorization on both sides.
await actorCurrent(next, checkLive)
if (await existingGeneration(sourceDirectory) !== generation || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
if ((await privateFingerprinterExisting(purpose))(keyMessage) !== keyProof || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
await actorCurrent(next, checkLive)
}
const query = async (text: string, values: unknown[], next: Readonly<BandwidthScope>, checkLive: () => void) => {
const name = text === CURRENT_SNAPSHOT_SQL ? CURRENT_STATEMENT : text === COMPLETION_SNAPSHOT_SQL ? COMPLETION_STATEMENT : undefined
checkLive(); const config: QueryConfig & { query_timeout: number } = { text, values, query_timeout: Math.max(1, Math.min(5000, next.deadlineAt - Date.now())), ...(name ? { name } : {}) }
const result = await pool.query(config); checkLive(); return result
}
const endpointMetadata = async (next: Readonly<BandwidthScope>, checkLive: () => void): Promise<Metadata> => {
await basic(next, checkLive)
const result = await query('/* mcp-speed-original:metadata */ SELECT id,enabled,routing_endpoint_epoch AS "routingEndpointEpoch" FROM public.servers WHERE id=ANY($1::bigint[]) ORDER BY id LIMIT 3', [ids], next, checkLive)
await basic(next, checkLive)
const rows = metadataSchema.parse(result.rows)
if (!isDeepStrictEqual(rows.map(row => row.id), ids)) deny()
return rows
}
const probe = async (next: Readonly<BandwidthScope>, checkLive: () => void): Promise<Probe> => {
if (!command.probeId) return undefined
await basic(next, checkLive)
const rows = (await query('/* mcp-speed-original:probe */ SELECT id,src_server_id AS "srcServerId",dst_server_id AS "dstServerId",src_interface AS "srcInterface",dst_interface AS "dstInterface",protocol,direction,duration_sec AS "durationSec",enabled FROM public.uptime_speed_probes WHERE id=$1 LIMIT 2', [command.probeId], next, checkLive)).rows
await basic(next, checkLive); if (rows.length !== 1) return deny()
const value = probeSchema.parse(rows[0]); assertSpeedProbeContext(value, { ...command, id: command.probeId }); return value
}
const endpoints = async (next: Readonly<BandwidthScope>, expected: Metadata, checkLive: () => void) => {
await basic(next, checkLive)
// Enabled/epoch completeness gates credential projection on the SAME
// command snapshot, including a change after the earlier metadata IO.
const result = await query(`/* mcp-speed-original:credentials */ WITH expected AS MATERIALIZED (
SELECT * FROM pg_catalog.jsonb_to_recordset($1::jsonb) AS e(id bigint,epoch uuid)),
matched AS MATERIALIZED (SELECT s.id FROM public.servers s JOIN expected e ON e.id=s.id AND e.epoch=s.routing_endpoint_epoch WHERE s.enabled=true),
allowed AS MATERIALIZED (SELECT count(*)=2 AND ($2::jsonb IS NULL OR EXISTS (
SELECT 1 FROM public.uptime_speed_probes p WHERE p.id=$3::text
AND pg_catalog.jsonb_build_object('id',p.id,'srcServerId',p.src_server_id,'dstServerId',p.dst_server_id,
'srcInterface',p.src_interface,'dstInterface',p.dst_interface,'protocol',p.protocol,'direction',p.direction,'durationSec',p.duration_sec,'enabled',p.enabled)=$2::jsonb)) AS complete FROM matched),
chosen AS MATERIALIZED (SELECT s.id,jsonb_build_object('id',s.id,'host',s.host,'port',s.port,'username',s.username,'password',s.password,
'useSsl',s.use_ssl,'verifySsl',s.verify_ssl,'enabled',s.enabled,'routingEndpointEpoch',s.routing_endpoint_epoch) AS endpoint
FROM public.servers s JOIN matched m ON m.id=s.id CROSS JOIN allowed a WHERE a.complete),
budget AS (SELECT coalesce(sum(octet_length(endpoint::text)),0) AS bytes FROM chosen)
SELECT id,CASE WHEN budget.bytes<=1048576 THEN endpoint END AS endpoint,budget.bytes>1048576 AS overflow FROM chosen CROSS JOIN budget ORDER BY id LIMIT 3`,
[JSON.stringify(expected.map(row => ({ id: row.id, epoch: row.routingEndpointEpoch }))), originalProbe ? JSON.stringify(originalProbe) : null, originalProbe?.id ?? null], next, checkLive)
await basic(next, checkLive)
if (result.rows.some(row => row.overflow)) deny()
const rows = z.array(endpointSchema).length(2).parse(result.rows.map(row => row.endpoint))
if (rows.length !== 2 || !isDeepStrictEqual(rows.map(row => ({ id: row.id, enabled: row.enabled, routingEndpointEpoch: row.routingEndpointEpoch })), expected)) deny()
return freeze(rows)
}
const originalMetadata = freeze(await endpointMetadata(current, live)), originalProbe = freeze(await probe(current, live))
if (!isDeepStrictEqual(originalProbe ?? null, input.expectedProbe)) deny()
await basic(current, live)
let history: unknown
try { history = await query(BANDWIDTH_SPEED_RUN_HISTORY_SQL, [run.runId], current, live) }
catch { throw new BandwidthSpeedRunIdUnavailable(run.runId) }
assertBandwidthSpeedRunHistoryAbsent(history, run.runId)
await basic(current, live)
const originalEndpoints = await endpoints(current, originalMetadata, live)
if (!isDeepStrictEqual(input.expectedEndpoints, originalEndpoints.map(endpoint => ({ serverId: endpoint.id, proof: sign("endpoint:" + fingerprint({ generation, endpoint })) })))) deny()
const expectedEndpoints = JSON.stringify(originalEndpoints), expectedProbe = originalProbe ? JSON.stringify(originalProbe) : null
const expectedSource = JSON.stringify({ ...metadata, credentialId: metadata.principal.credentialId,
intendedState: redact({ kind: "service", service: metadata.serviceName, input: metadata.serviceInput }) })
const filesCurrent = async (checkLive: () => void) => {
checkLive(); if (mcpStateDirectory() !== sourceDirectory) deny()
const [currentGeneration, currentSign] = await Promise.all([existingGeneration(sourceDirectory), privateFingerprinterExisting(purpose)])
checkLive(); if (mcpStateDirectory() !== sourceDirectory || currentGeneration !== generation || currentSign(keyMessage) !== keyProof) deny()
}
const assertSnapshot = async (next: Readonly<BandwidthScope>, checkLive: () => void, includeProbe: boolean) => {
const originCurrent = async () => {
checkLive(); if (mcpStateDirectory() !== sourceDirectory) deny()
if (!isDeepStrictEqual(await inspectVerifiedMcpServiceExecution(original), metadata)) deny()
checkLive(); if (mcpStateDirectory() !== sourceDirectory) deny()
}
const joinedSnapshot = async () => {
const result = await query(includeProbe ? CURRENT_SNAPSHOT_SQL : COMPLETION_SNAPSHOT_SQL,
[expectedEndpoints, includeProbe ? expectedProbe : null, includeProbe ? originalProbe?.id ?? null : null, expectedSource], next, checkLive)
if (!result || typeof result !== "object" || result.command !== "SELECT" || result.rowCount !== 1 || !Array.isArray(result.rows) || result.rows.length !== 1) deny()
const row = result.rows[0]
if (!row || typeof row !== "object" || Array.isArray(row) || Reflect.ownKeys(row).length !== 2) deny()
const fields = Object.getOwnPropertyDescriptors(row)
if (!fields.current || !("value" in fields.current) || !fields.current.enumerable || fields.current.value !== true
|| !fields.authority || !("value" in fields.authority) || !fields.authority.enumerable) deny()
const actor = currentActorSchema.parse(fields.authority.value)
if (Buffer.byteLength(JSON.stringify(fields.authority.value)) > 1048576 || actor.id !== metadata.connectionId || actor.ownerId !== metadata.ownerId
|| actor.generation !== generation || actor.policy.status !== "active" || Date.parse(actor.policy.expiresAt) <= Date.now() || Date.parse(actor.ownerValidUntil) <= Date.now()
|| !hasPermission(actor.ownerPermissions, "mm:uptime:write") || !hasPermission(actor.policy.permissions, "mm:uptime:write")) deny()
let grant: z.infer<typeof mcpTemporaryGrantSchema> | undefined
let grantProof = fingerprint({ credentialId: metadata.principal.credentialId, grant: null }), grantExpiresAt: number | null = null
if (actor.grants.length) {
const held = actor.grants[0]
if (held.payload.credentialId !== metadata.principal.credentialId) deny()
const { credentialId: _credential, ...raw } = held.payload
grant = mcpTemporaryGrantSchema.parse(raw); grantExpiresAt = Date.parse(grant.expiresAt)
if (Date.parse(grant.startsAt) > Date.now() || grantExpiresAt <= Date.now()) deny()
grantProof = fingerprint({ rowId: held.id, credentialId: metadata.principal.credentialId, grant })
}
if (grantProof !== metadata.originalTemporaryGrantProof || grantExpiresAt !== metadata.originalTemporaryGrantExpiresAt
|| !actor.policy.scope.operationIds.includes("uptime.speed-test") || ids.some(id => !actor.policy.scope.serverIds.includes(id))
|| grant && (!grant.scope.operationIds.includes("uptime.speed-test") || ids.some(id => !grant!.scope.serverIds.includes(id)))) deny()
return actor
}
// No cached authority: fresh private authorizers bracket files and
// the fixed SQL. A closing SQL/files fence also catches source or
// credential drift caused DURING the last authorizer's own await.
// Three file fences: BEFORE each bootstrap-capable authorizer and
// AFTER all closing read-only SQL/portal work. Intervening fixed
// queries neither project credentials nor create MCP material.
await filesCurrent(checkLive)
await originCurrent()
await joinedSnapshot(); await filesCurrent(checkLive)
await originCurrent()
const closingActor = await joinedSnapshot()
// The portal cutoff also has a durable external file; SQL alone
// cannot see a revocation written during the last authorizer.
await assertPortalClaimsCurrent({ id: closingActor.ownerId, issuedAt: Date.parse(closingActor.ownerClaimsIssuedAt) }); checkLive()
await filesCurrent(checkLive)
}
const assertCurrent = (next: Readonly<BandwidthScope>, checkLive: () => void) => assertSnapshot(next, checkLive, true)
const assertAuthorityCurrent = (next: Readonly<BandwidthScope>, checkLive: () => void) => assertSnapshot(next, checkLive, false)
const source = originalEndpoints.find(endpoint => endpoint.id === command.srcServerId)!, destination = originalEndpoints.find(endpoint => endpoint.id === command.dstServerId)!
const addresses = async (endpoint: RoutingEndpoint): Promise<Record<string, unknown>[]> => {
let guardFailed = false
const guard = async () => { try { await assertCurrent(current, live) } catch (error) { guardFailed = true; throw error } }
await guard()
let result: unknown
const signal = current.signal ? AbortSignal.any([current.signal, authority.signal]) : authority.signal
try { result = await new MikrotikClient(endpoint, endpoint.id).get("/ip/address", Math.max(1, Math.min(10000, current.deadlineAt - Date.now())), signal, undefined, guard) }
catch { if (guardFailed) return deny(); await guard(); return [] }
await guard(); return z.array(z.record(z.string(), z.unknown())).max(10000).parse(result)
}
// Preserve existing order and fallbacks: destination first, then source.
const destinationRows = command.dstInterface ? await addresses(destination) : []
const sourceRows = command.srcInterface ? await addresses(source) : []
const dstAddress = command.dstInterface ? firstUsableIp(destinationRows, command.dstInterface) : destination.host
if (command.dstInterface && !dstAddress) throw new Error(`На интерфейсе назначения '${command.dstInterface}' нет активного IP (проверьте /ip/address — не disabled).`)
const srcAddress = command.srcInterface ? firstUsableIp(sourceRows, command.srcInterface) : source.host
const context = freeze({ command: sealedCommand, srcAddress, dstAddress, address: dstAddress || destination.host,
srcInterfaceAddress: command.srcInterface ? srcAddress || null : null, dstInterfaceAddress: command.dstInterface ? dstAddress || null : null })
const nativeBody = { address: context.address, user: destination.username, password: destination.password, protocol: command.protocol, direction: command.direction, duration: command.durationSec + "s" }
const authorityGeneration = generation + ":" + metadata.operationVersion + ":" + metadata.policyVersion
const intent = freeze({ attemptId: run.attemptId, operationId: run.operationId, callerKind: "mcp-speed" as const, sourceServerId: source.id,
actualRemotePeer: { kind: "server" as const, serverId: destination.id }, credentialServerId: destination.id,
// Genuine metadata's JSON payload is checked by the private verifier;
// McpPrincipal's nominal TS interface alone lacks an index signature.
request: { command: sealedCommand, mcp: metadata } as unknown as BandwidthPeerExecutionIntent["request"], nativeBody, durationSec: command.durationSec,
// MikrotikClient.bandwidthTest's existing fixed timeout is 30_000ms.
socketTimeoutMs: 30000, authorityProof: sign("mcp-speed-authority:" + fingerprint({ metadata, command, run, generation })), authorityGeneration, expiresAt: authority.expiresAt })
await assertCurrent(current, live)
const peers = new Map(originalEndpoints.map(endpoint => [endpoint.id, freeze({ peerRef: { kind: "server" as const, serverId: endpoint.id }, enabled: endpoint.enabled,
sourceProof: sign("endpoint:" + fingerprint({ generation, endpoint })), authorityGeneration,
endpoint: { host: endpoint.host, port: endpoint.port, useSsl: endpoint.useSsl, verifySsl: endpoint.verifySsl, username: endpoint.username, password: endpoint.password, routingEndpointEpoch: endpoint.routingEndpointEpoch } })]))
live(); const token = Object.freeze(Object.create(null)) as McpSpeedBandwidthOriginal
entries.set(token, { intent, context, peers, authority, end, signal: scope.signal, assertCurrent, assertAuthorityCurrent }); return token
})
})
},
async readOriginal(token: unknown, scope: Readonly<BandwidthScope>): Promise<BandwidthPeerExecutionIntent> { return (await read(token, scope)).intent },
/** Internal transport lifetime only. The genuine context is checked before
* exposing its fixed horizon and cancellation; this data cannot mint a cap. */
async readLifetime(token: unknown, scope: Readonly<BandwidthScope>): Promise<Readonly<{ expiresAt: number; monotonicDeadline: number; signal: AbortSignal }>> {
const entry = await read(token, scope)
return Object.freeze({ expiresAt: entry.intent.expiresAt, monotonicDeadline: entry.end, signal: entry.authority.signal })
},
/** Internal full speed workflow metadata only; no credentials/public DTO. */
async readSpeedContext(token: unknown, scope: Readonly<BandwidthScope>): Promise<Readonly<McpSpeedBandwidthContext>> { return (await read(token, scope)).context },
async readPeer(token: unknown, rawPeer: BandwidthPeerRef, scope: Readonly<BandwidthScope>): Promise<Readonly<BandwidthPeerSourceSnapshot>> {
const peer = parseBandwidthPeerRef(rawPeer)
const entry = token && typeof token === "object" ? entries.get(token) : undefined
if (!entry || peer.kind !== "server" || !entry.peers.has(peer.serverId)) return deny()
await read(token, scope); return entry.peers.get(peer.serverId)!
},
/** Probe edits after a genuinely completed run affect history association,
* not the already sealed command. Actor/key/endpoint checks remain current. */
async readPeerAfterCompletion(token: unknown, result: unknown, rawPeer: BandwidthPeerRef, rawScope: Readonly<BandwidthScope>): Promise<Readonly<BandwidthPeerSourceSnapshot>> {
const scope = scopeSnapshot(rawScope), peer = parseBandwidthPeerRef(rawPeer)
const entry = token && typeof token === "object" ? entries.get(token) : undefined
if (!entry || peer.kind !== "server" || !entry.peers.has(peer.serverId)) return deny()
if (!isDeepStrictEqual(readBandwidthPeerCompletion(result, token), entry.intent)) return deny()
await window(scope, entry.authority, entry.end, entry.signal, (current, live) => entry.assertAuthorityCurrent(current, live))
return entry.peers.get(peer.serverId)!
},
})
providers.add(provider); return provider
}