266 lines
27 KiB
TypeScript
266 lines
27 KiB
TypeScript
import { z } from "zod"
|
|
import { pool } from "../../db/index.js"
|
|
import { createProductionServerProbeExecutor, ServerProbeExecutionError, type PreparedServerProbe, type ServerProbeJournal, type ServerProbeReceipt } from "../../services/server-probe-execution.js"
|
|
import { serverProbeExecutionRequest } from "../../services/server-probe-execution-model.js"
|
|
import { createMcpServerProbeAuthority, createMcpServerProbeReadAuthority, SERVER_PROBE_OPERATION } from "../../services/server-probe-authority.js"
|
|
import { createServerProbeJournalHistoryReader } from "../../services/server-probe-journal-history.js"
|
|
import { createSqlServerProbeJournal, type ServerProbeJournalContext, type ServerProbeJournalDependencies } from "../../services/server-probe-journal.js"
|
|
import { resolveServerProbeRestBandwidthPeer } from "../../services/server-probe-rest-contract.js"
|
|
import { serverProbeReceiptPage } from "../../services/server-probe-public-result.js"
|
|
import { decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
|
|
import type { ActionContext, ChangeEvidence } from "./action-types.js"
|
|
import type { McpServiceHandler } from "./service-registry.js"
|
|
import type { findRetiredServerProbeHistory, ServerProbeRetiredLookup } from "../../services/server-probe-retired-history.js"
|
|
|
|
/** Foundations only: importing this module registers no tools or services. */
|
|
export const serverProbeActionSchema = z.object({ serverId: z.number().int().positive().safe(), request: serverProbeExecutionRequest }).strict()
|
|
export const SERVER_PROBE_MCP_OPERATION_VERSION = 1
|
|
export const serverProbeReceiptReadSchema = z.object({ operationId: z.string().uuid(), receiptId: z.string().uuid(), page: z.number().int().min(0).max(15) }).strict()
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/)
|
|
const serviceInputSchema = z.object({ serverId: z.number().int().positive().safe(), receiptId: z.string().uuid(), inputDigest: hash, bindingCiphertext: z.string().min(1).max(1048576) }).strict()
|
|
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string().datetime() }).strict()
|
|
const preparedSchema = z.object({ receiptId: z.string().uuid(), tool: z.enum(["ping", "traceroute", "bandwidth", "dns", "route", "mtu"]), serverId: z.number().int().positive().safe(), destinationServerId: z.number().int().positive().safe().optional(), expiresAt: z.string().datetime(), bindingCiphertext: z.string().min(1).max(524288) }).strict()
|
|
const bindingSchema = z.object({ version: z.literal(1), operation: z.literal(SERVER_PROBE_OPERATION), principal: principalSchema, ownerId: z.string().min(1).max(200), issuedAt: z.number().int().nonnegative().safe(), authorityExpiresAt: z.number().int().positive().safe(), prepared: preparedSchema, bindingProof: hash, stageBudget: z.number().int().min(1).max(11) }).strict()
|
|
export type ServerProbeMcpBinding = z.infer<typeof bindingSchema>
|
|
type Binding = ServerProbeMcpBinding
|
|
type Input = z.infer<typeof serviceInputSchema>
|
|
type OwnedStep = { operation_id: string; operation_state: string; plan_state: string; approved_by: string | null; step_state: string; step_index: number; intended_state: unknown; result: unknown; evidence: { sealed: string } }
|
|
type Query = (sql: string, values: unknown[]) => Promise<Record<string, unknown>[]>
|
|
export interface ServerProbeMcpDependencies {
|
|
authority: typeof createMcpServerProbeAuthority
|
|
historicalAuthority: typeof createMcpServerProbeReadAuthority
|
|
history: (dependencies: Parameters<typeof createServerProbeJournalHistoryReader>[0], execution?: { signal?: AbortSignal }) => ReturnType<typeof createServerProbeJournalHistoryReader>
|
|
executor: typeof createProductionServerProbeExecutor
|
|
journal: (context: ServerProbeJournalContext, dependencies: ServerProbeJournalDependencies, execution?: { signal?: AbortSignal; deadlineAt?: number }) => ServerProbeJournal
|
|
query: Query
|
|
retiredSource?: (lookup: ServerProbeRetiredLookup) => ReturnType<typeof findRetiredServerProbeHistory>
|
|
seal: (value: string) => Promise<string>
|
|
open: (value: string) => Promise<string>
|
|
proof: (value: unknown) => Promise<string>
|
|
now: () => number
|
|
}
|
|
const production: ServerProbeMcpDependencies = {
|
|
authority: createMcpServerProbeAuthority, historicalAuthority: createMcpServerProbeReadAuthority, history: createServerProbeJournalHistoryReader, executor: createProductionServerProbeExecutor, journal: createSqlServerProbeJournal,
|
|
query: async (sql, values) => (await pool.query(sql, values)).rows,
|
|
seal: encryptSecret, open: decryptSecret, proof: value => privateSecretFingerprint(fingerprint(value), "server-probe-mcp-binding-v1"), now: Date.now,
|
|
}
|
|
const denied = (): never => { throw new McpError("STATE_CONFLICT", "Привязка диагностики к операции не подтверждена", 409) }
|
|
/** Shared strict source decoding; deliberately performs no authority/native preflight. */
|
|
export async function openServerProbeMcpBinding(raw: Record<string, unknown>, crypto: Pick<ServerProbeMcpDependencies, "open" | "proof">) {
|
|
const input = serviceInputSchema.parse(raw)
|
|
let binding: Binding
|
|
try { binding = bindingSchema.parse(JSON.parse(await crypto.open(input.bindingCiphertext))) } catch { return denied() }
|
|
if (await crypto.proof(binding) !== input.inputDigest || input.receiptId !== binding.prepared.receiptId || input.serverId !== binding.prepared.serverId) return denied()
|
|
return { input, binding }
|
|
}
|
|
const ids = (prepared: PreparedServerProbe) => [...new Set([prepared.serverId, ...(prepared.destinationServerId ? [prepared.destinationServerId] : [])])].sort((a, b) => a - b)
|
|
export function serverProbeReceiptMetadata(receipt: ServerProbeReceipt, operationId: string, stageBudget: number) {
|
|
const page = serverProbeReceiptPage(receipt, 0)
|
|
if (!Number.isSafeInteger(receipt.attemptedStages) || !Number.isSafeInteger(receipt.completedStages) || receipt.completedStages < 0 || receipt.completedStages > receipt.attemptedStages || receipt.attemptedStages > stageBudget) return denied()
|
|
return { operationId, receiptId: receipt.receiptId, tool: receipt.tool, status: receipt.state, httpStatus: receipt.httpStatus, stageBudget, attemptedStages: receipt.attemptedStages, completedStages: receipt.completedStages, sha256: page.sha256, totalPages: page.totalPages, bytes: page.bytes, automaticReplay: false, forwardingVerified: false }
|
|
}
|
|
/** No native/provider message is copied into a model/audit error. Progress is
|
|
* diagnostic attempts, never confirmed configuration writes. */
|
|
export function serverProbeSafeMcpError(error: unknown, input?: { receiptId: string; operationId: string; stageBudget: number }): McpError {
|
|
if (error instanceof ServerProbeExecutionError) {
|
|
const safe = new McpError(error.code, "Диагностика не получила подтверждённый результат; автоматический повтор запрещён", error.statusCode)
|
|
if (input && error.attemptedStages >= 0 && Number.isSafeInteger(error.attemptedStages) && error.attemptedStages <= input.stageBudget && Number.isSafeInteger(error.completedStages) && error.completedStages >= 0 && error.completedStages <= error.attemptedStages) Object.assign(safe, { diagnosticProgress: { ...input, state: error.state, attemptedStages: error.attemptedStages, completedStages: error.completedStages, automaticReplay: false } })
|
|
return safe
|
|
}
|
|
if (error instanceof McpError) return error
|
|
return new McpError("STATE_UNAVAILABLE", "Состояние диагностики не подтверждено; автоматический повтор запрещён", 503)
|
|
}
|
|
|
|
export function createServerProbeMcpAdapter(overrides: Partial<ServerProbeMcpDependencies> = {}) {
|
|
const deps = { ...production, ...overrides }
|
|
const open = (raw: Record<string, unknown>) => openServerProbeMcpBinding(raw, deps)
|
|
const authority = (binding: Binding, executing = false, signal?: AbortSignal) => deps.authority(binding.principal, { executing, signal })
|
|
const preflight = async (binding: Binding, signal?: AbortSignal) => {
|
|
const result = await deps.executor(authority(binding, false, signal)).preflight(binding.prepared, signal)
|
|
if (result.bindingProof !== binding.bindingProof || result.receiptId !== binding.prepared.receiptId || fingerprint([...result.serverIds].sort((a, b) => a - b)) !== fingerprint(ids(binding.prepared))) return denied()
|
|
return result
|
|
}
|
|
// Full exact redacted step equality includes the keyed digest of the private
|
|
// ciphertext. SQL caller input never supplies owner/connection/credential.
|
|
const owned = async (input: Input, binding: Binding, operationId?: string, executing = false, readFence?: () => Promise<void>): Promise<OwnedStep> => {
|
|
await readFence?.()
|
|
const rows = await deps.query(`SELECT o.id AS operation_id,o.state AS operation_state,p.state AS plan_state,p.approved_by,s.state AS step_state,s.step_index,s.intended_state,s.result,p.evidence
|
|
FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id
|
|
JOIN mcp_connections c ON c.id=o.connection_id JOIN mcp_operation_steps s ON s.operation_id=o.id
|
|
WHERE o.connection_id=$1 AND c.owner_id=$2 AND p.operation_id=$3 AND p.operation_version=1
|
|
AND ($4::uuid IS NULL OR o.id=$4) AND s.step_index=0 AND p.approved_by IS NOT NULL
|
|
AND s.intended_state=$5::jsonb AND octet_length(p.evidence::text)<=2097152 LIMIT 2`,
|
|
[binding.principal.connectionId, binding.ownerId, SERVER_PROBE_OPERATION, operationId ?? null, JSON.stringify(redact({ kind: "service", service: SERVER_PROBE_OPERATION, input }))])
|
|
await readFence?.()
|
|
if (rows.length !== 1) return denied()
|
|
const row = rows[0] as unknown as OwnedStep
|
|
if (!z.string().uuid().safeParse(row.operation_id).success || row.step_index !== 0 || !row.approved_by || fingerprint(row.intended_state) !== fingerprint(redact({ kind: "service", service: SERVER_PROBE_OPERATION, input })) || operationId && row.operation_id !== operationId) return denied()
|
|
if (executing ? row.operation_state !== "running" || row.plan_state !== "executing" || row.step_state !== "intent" : !["running", "applied", "unknown", "failed"].includes(row.operation_state) || !["intent", "applied", "verified", "acknowledged", "unknown", "failed"].includes(row.step_state)) return denied()
|
|
// Do not rely on public step digests alone: bind the encrypted actual plan.
|
|
let evidence: ChangeEvidence
|
|
try { evidence = JSON.parse(await deps.open(row.evidence.sealed)) as ChangeEvidence } catch { return denied() }
|
|
await readFence?.()
|
|
if (evidence.steps?.length !== 1 || fingerprint(evidence.steps[0]) !== fingerprint({ kind: "service", service: SERVER_PROBE_OPERATION, input }) || evidence.requiresHuman !== true || evidence.verificationScope !== "acknowledgement" || evidence.mutationCost !== binding.stageBudget || evidence.validUntil !== binding.prepared.expiresAt || fingerprint(evidence.target) !== fingerprint({ scope: "servers", serverIds: ids(binding.prepared) })) return denied()
|
|
return row
|
|
}
|
|
const execution = (input: Input, binding: Binding, row: OwnedStep, executing: boolean, signal?: AbortSignal) => {
|
|
const guard = async (_context: Readonly<ServerProbeJournalContext>, bindingProof: string) => {
|
|
if (bindingProof !== binding.bindingProof) return denied()
|
|
await preflight(binding, signal)
|
|
await owned(input, binding, row.operation_id, executing)
|
|
await preflight(binding, signal)
|
|
}
|
|
const journal = deps.journal({ identity: { kind: "mcp", ownerId: binding.ownerId, executionId: row.operation_id, connectionId: binding.principal.connectionId, credentialId: binding.principal.credentialId, issuedAt: binding.issuedAt, expiresAt: binding.authorityExpiresAt, operationName: SERVER_PROBE_OPERATION }, sourceServerId: binding.prepared.serverId, ...(binding.prepared.destinationServerId ? { destinationServerId: binding.prepared.destinationServerId } : {}), tool: binding.prepared.tool }, { assertAuthority: guard }, { signal, deadlineAt: Date.parse(binding.prepared.expiresAt) })
|
|
return { journal, executor: deps.executor({ ...authority(binding, executing, signal), journal }), guard }
|
|
}
|
|
const read = async (input: Input, binding: Binding, operationId?: string, signal?: AbortSignal) => {
|
|
await preflight(binding, signal)
|
|
const row = await owned(input, binding, operationId)
|
|
const { journal } = execution(input, binding, row, false, signal)
|
|
const receipt = await journal.read(input.receiptId, binding.bindingProof)
|
|
await owned(input, binding, row.operation_id)
|
|
await preflight(binding, signal)
|
|
if (!receipt || receipt.receiptId !== input.receiptId || receipt.serverId !== binding.prepared.serverId || receipt.destinationServerId !== binding.prepared.destinationServerId || receipt.tool !== binding.prepared.tool) return denied()
|
|
return { row, receipt, result: serverProbeReceiptMetadata(receipt, row.operation_id, binding.stageBudget) }
|
|
}
|
|
const target = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence["target"]> => {
|
|
const input = serverProbeActionSchema.parse(raw), access = deps.authority(context.principal, { signal: context.signal })
|
|
const initial = await access.readAuthority()
|
|
if (!initial.scopeServerIds.includes(input.serverId)) return denied()
|
|
await access.assertProtections([input.serverId], initial)
|
|
let destinationId: number | undefined
|
|
if (input.request.tool === "bandwidth") {
|
|
const query: Query = context.transactionClient ? async (sql, values) => (await context.transactionClient!.query(sql, values)).rows : deps.query
|
|
const fence = async () => { const fresh = await access.readAuthority(); if (fingerprint(fresh) !== fingerprint(initial)) return denied() }
|
|
const peer = await resolveServerProbeRestBandwidthPeer(input.request.bwRemoteAddress!, input.request.dstServerId, initial.scopeServerIds, {
|
|
byId: async (id, allowed) => { await fence(); if (!allowed.includes(id)) return undefined; const rows = await query("SELECT id,host,enabled FROM servers WHERE id=ANY($1::int[]) AND id=$2 LIMIT 1", [[...allowed], id]); await fence(); return rows[0] as { id: number; host: string; enabled: boolean } | undefined },
|
|
enabledByHost: async (host, allowed) => { await fence(); const rows = await query("SELECT id,host,enabled FROM servers WHERE id=ANY($1::int[]) AND enabled=true AND lower(btrim(host))=lower(btrim($2)) LIMIT 1001", [[...allowed], host]); await fence(); return rows as Array<{ id: number; host: string; enabled: boolean }> },
|
|
})
|
|
destinationId = peer.id
|
|
}
|
|
const serverIds = [...new Set([input.serverId, ...(destinationId ? [destinationId] : [])])].sort((a, b) => a - b)
|
|
const fresh = await access.readAuthority(); if (fingerprint(fresh) !== fingerprint(initial)) return denied()
|
|
await access.assertProtections(serverIds, fresh)
|
|
return { scope: "servers", serverIds }
|
|
}
|
|
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => {
|
|
try {
|
|
const input = serverProbeActionSchema.parse(raw), access = deps.authority(context.principal, { signal: context.signal }), executor = deps.executor(access)
|
|
const prepared = await executor.prepare(input.serverId, input.request, context.signal), checked = await executor.preflight(prepared, context.signal)
|
|
const current = await access.readAuthority()
|
|
if (current.ownerId !== context.connection.owner_id || current.connectionId !== context.principal.connectionId || current.credentialId !== context.principal.credentialId || current.transport === "rest") return denied()
|
|
const stageBudget = prepared.tool === "mtu" ? 11 : ["ping", "traceroute"].includes(prepared.tool) ? 2 : 1
|
|
if (Date.parse(prepared.expiresAt) > deps.now() + 300000 || Date.parse(prepared.expiresAt) <= deps.now()) return denied()
|
|
const binding: Binding = bindingSchema.parse({ version: 1, operation: SERVER_PROBE_OPERATION, principal: context.principal, ownerId: current.ownerId, issuedAt: context.connection.owner_claims_issued_at.getTime(), authorityExpiresAt: current.expiresAt, prepared, bindingProof: checked.bindingProof, stageBudget })
|
|
const serviceInput: Input = { serverId: input.serverId, receiptId: prepared.receiptId, inputDigest: await deps.proof(binding), bindingCiphertext: await deps.seal(JSON.stringify(binding)) }
|
|
await executor.preflight(prepared, context.signal)
|
|
return { target: { scope: "servers", serverIds: ids(prepared) }, objects: ids(prepared).map(serverId => ({ kind: "server", id: String(serverId), serverId })), snapshots: [], steps: [{ kind: "service", service: SERVER_PROBE_OPERATION, input: serviceInput }], before: { proof: checked.bindingProof }, mutationCost: stageBudget, requiresHuman: true, verificationScope: "acknowledgement", validUntil: prepared.expiresAt, warnings: ["Диагностика создаёт сетевой трафик; требуется явное подтверждение. Квитанция подтверждает измерение, но не доставку пользовательского трафика.", `Лимит этапов диагностики: ${stageBudget}; автоматический повтор запрещён.`, "Проверки допуска и сохранение квитанции имеют резерв до 30 с; сетевые лимиты команд не увеличиваются.", ...(prepared.destinationServerId ? [`Фактический сервер назначения BW: ${prepared.destinationServerId}${input.request.dstServerId !== undefined && input.request.dstServerId !== prepared.destinationServerId ? ` (запрошен ${input.request.dstServerId})` : ""}.`] : [])] }
|
|
} catch (error) { throw serverProbeSafeMcpError(error) }
|
|
}
|
|
const service: McpServiceHandler = {
|
|
cancellableDiagnostic: true,
|
|
diagnosticIdentity: async (raw, context) => {
|
|
if (context.phase !== "forward" || context.stepIndex !== 0 || !z.string().uuid().safeParse(context.operationId).success) return denied()
|
|
const { input, binding } = await open(raw)
|
|
await preflight(binding)
|
|
await owned(input, binding, context.operationId, true)
|
|
await preflight(binding)
|
|
return { receiptId: input.receiptId, stageBudget: binding.stageBudget }
|
|
},
|
|
current: async raw => { try { const { binding } = await open(raw); await preflight(binding); return { proof: binding.bindingProof } } catch (error) { throw serverProbeSafeMcpError(error) } },
|
|
execute: async (raw, context) => {
|
|
let progress: { receiptId: string; operationId: string; stageBudget: number } | undefined
|
|
try {
|
|
if (!context || context.phase !== "forward" || context.stepIndex !== 0 || !z.string().uuid().safeParse(context.operationId).success) return denied()
|
|
if (context.signal?.aborted) throw new ServerProbeExecutionError("CANCELLED", "Диагностика отменена", 502, "cancelled")
|
|
const { input, binding } = await open(raw); progress = { receiptId: input.receiptId, operationId: context.operationId, stageBudget: binding.stageBudget }
|
|
await preflight(binding, context.signal)
|
|
const row = await owned(input, binding, context.operationId, true)
|
|
const { executor } = execution(input, binding, row, true, context.signal)
|
|
const receipt = await executor.execute(binding.prepared, context.signal)
|
|
await preflight(binding, context.signal); await owned(input, binding, context.operationId, true); await preflight(binding, context.signal)
|
|
return serverProbeReceiptMetadata(receipt, context.operationId, binding.stageBudget)
|
|
} catch (error) { throw serverProbeSafeMcpError(error, progress) }
|
|
},
|
|
verify: async (raw, result) => {
|
|
try { const { input, binding } = await open(raw); const operationId = z.object({ operationId: z.string().uuid() }).parse(result).operationId; const actual = await read(input, binding, operationId); return actual.receipt.state === "completed" && fingerprint(actual.result) === fingerprint(result) && fingerprint(actual.row.result) === fingerprint(result) } catch { return false }
|
|
},
|
|
reconcile: async (raw, authorize) => {
|
|
await authorize()
|
|
try { const { input, binding } = await open(raw), actual = await read(input, binding); await authorize(); return { matchesDesiredState: actual.receipt.state === "completed" && fingerprint(actual.row.result) === fingerprint(actual.result), matchesOriginalState: false } } catch { return { matchesDesiredState: false, matchesOriginalState: false } }
|
|
},
|
|
}
|
|
const historicalAccess = async (request: z.infer<typeof serverProbeReceiptReadSchema>, context: ActionContext) => {
|
|
const access = deps.historicalAuthority(context.principal, { signal: context.signal }), initial = await access.readAuthority()
|
|
if (initial.ownerId !== context.connection.owner_id || initial.connectionId !== context.principal.connectionId || initial.credentialId !== context.principal.credentialId) return denied()
|
|
const fresh = async () => { const current = await access.readAuthority(); if (fingerprint(initial) !== fingerprint(current)) return denied(); return current }
|
|
await fresh()
|
|
const rows = await deps.query(`/* probe-history:scope */ SELECT j.source_server_id,j.destination_server_id FROM server_probe_executions j
|
|
JOIN mcp_operations o ON o.id=j.execution_id AND j.identity_kind='mcp' JOIN mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id
|
|
JOIN mcp_connections c ON c.id=o.connection_id WHERE j.receipt_id=$1 AND o.id=$2 AND o.connection_id=$3 AND c.owner_id=$4
|
|
AND j.mcp_connection_id=c.id AND j.actor_id=c.owner_id AND p.operation_id=$5 AND p.operation_version=1
|
|
AND j.source_server_id=ANY($6::int[]) AND (j.destination_server_id IS NULL OR j.destination_server_id=ANY($6::int[])) LIMIT 2`,
|
|
[request.receiptId, request.operationId, context.principal.connectionId, initial.ownerId, SERVER_PROBE_OPERATION, initial.scopeServerIds])
|
|
await fresh()
|
|
const loadRetired = deps.retiredSource
|
|
const readRetired = rows.length === 0 && loadRetired ? () => loadRetired({
|
|
receiptId: request.receiptId, operationId: request.operationId, connectionId: context.principal.connectionId,
|
|
ownerId: initial.ownerId, scopeServerIds: initial.scopeServerIds,
|
|
}) : undefined
|
|
const retired = readRetired ? await readRetired() : undefined
|
|
if (readRetired) await fresh()
|
|
if (rows.length !== 1 && !retired) return denied()
|
|
const row = rows[0]
|
|
const serverIds = retired ? retired.source.serverIds : [...new Set([z.number().int().positive().safe().parse(row.source_server_id), ...(row.destination_server_id === null ? [] : [z.number().int().positive().safe().parse(row.destination_server_id)])])].sort((a, b) => a - b)
|
|
const fence = async () => { const current = await fresh(); if (serverIds.some(id => !current.scopeServerIds.includes(id))) return denied(); await access.assertProtections(serverIds, current); await fresh() }
|
|
await fence()
|
|
const retiredFence = retired && readRetired ? async () => {
|
|
await fence()
|
|
const current = await readRetired()
|
|
await fence()
|
|
if (!current || fingerprint(current) !== fingerprint(retired)) return denied()
|
|
} : undefined
|
|
return { initial, serverIds, fence, retired, retiredFence }
|
|
}
|
|
const receiptTarget = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence["target"]> => {
|
|
const request = serverProbeReceiptReadSchema.parse(raw), { serverIds, fence, retiredFence } = await historicalAccess(request, context)
|
|
await (retiredFence ?? fence)(); return { scope: "servers", serverIds }
|
|
}
|
|
const readPage = async (raw: Record<string, unknown>, context: ActionContext) => {
|
|
try {
|
|
const request = serverProbeReceiptReadSchema.parse(raw), { initial, serverIds, fence, retired, retiredFence } = await historicalAccess(request, context)
|
|
if (retired && retiredFence) {
|
|
const source = retired.source
|
|
const originalContext: ServerProbeJournalContext = {
|
|
identity: { kind: "mcp", ownerId: source.ownerId, executionId: source.executionId, connectionId: source.connectionId, credentialId: source.originalCredentialId,
|
|
issuedAt: source.issuedAt, expiresAt: Date.parse(source.authorityExpiresAt), operationName: SERVER_PROBE_OPERATION },
|
|
sourceServerId: source.sourceServerId, ...(source.destinationServerId !== undefined ? { destinationServerId: source.destinationServerId } : {}), tool: source.tool,
|
|
}
|
|
await retiredFence()
|
|
const reader = deps.history({ assertReadAuthority: retiredFence }, { signal: context.signal })
|
|
const receipt = await reader.read({ context: originalContext, receiptId: source.receiptId, bindingProof: source.bindingProof })
|
|
const page = serverProbeReceiptPage(receipt, request.page)
|
|
await retiredFence()
|
|
return page
|
|
}
|
|
await fence()
|
|
const rows = await deps.query(`SELECT p.evidence FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id JOIN mcp_connections c ON c.id=o.connection_id WHERE o.id=$1 AND o.connection_id=$2 AND c.owner_id=$3 AND p.operation_id=$4 AND p.operation_version=1 AND octet_length(p.evidence::text)<=2097152 LIMIT 2`, [request.operationId, context.principal.connectionId, initial.ownerId, SERVER_PROBE_OPERATION])
|
|
await fence(); if (rows.length !== 1) return denied()
|
|
const evidence = JSON.parse(await deps.open((rows[0].evidence as { sealed: string }).sealed)) as ChangeEvidence
|
|
await fence()
|
|
const step = evidence.steps?.[0]; if (evidence.steps?.length !== 1 || step?.kind !== "service" || step.service !== SERVER_PROBE_OPERATION) return denied()
|
|
const { input, binding } = await open(step.input)
|
|
await fence()
|
|
if (input.receiptId !== request.receiptId || binding.principal.connectionId !== context.principal.connectionId || binding.ownerId !== initial.ownerId || fingerprint(serverIds) !== fingerprint(ids(binding.prepared))) return denied()
|
|
const originalContext: ServerProbeJournalContext = { identity: { kind: "mcp", ownerId: binding.ownerId, executionId: request.operationId, connectionId: binding.principal.connectionId, credentialId: binding.principal.credentialId, issuedAt: binding.issuedAt, expiresAt: binding.authorityExpiresAt, operationName: SERVER_PROBE_OPERATION }, sourceServerId: binding.prepared.serverId, ...(binding.prepared.destinationServerId !== undefined ? { destinationServerId: binding.prepared.destinationServerId } : {}), tool: binding.prepared.tool }
|
|
const reader = deps.history({ assertReadAuthority: async () => { await fence(); await owned(input, binding, request.operationId, false, fence); await fence() } }, { signal: context.signal })
|
|
const receipt = await reader.read({ context: originalContext, receiptId: input.receiptId, bindingProof: binding.bindingProof })
|
|
await fence()
|
|
const page = serverProbeReceiptPage(receipt, request.page)
|
|
await fence(); await owned(input, binding, request.operationId, false, fence); await fence()
|
|
return page
|
|
} catch (error) { throw serverProbeSafeMcpError(error) }
|
|
}
|
|
return { schema: serverProbeActionSchema, target, prepare, service, receiptSchema: serverProbeReceiptReadSchema, receiptTarget, readPage }
|
|
}
|