60 lines
5.5 KiB
TypeScript
60 lines
5.5 KiB
TypeScript
import { randomUUID } from "node:crypto"
|
|
import type { AuthUser } from "../lib/permissions.js"
|
|
import { McpError, fingerprint } from "../modules/mcp/security.js"
|
|
import { createProductionServerProbeExecutor, ServerProbeExecutionError } from "./server-probe-execution.js"
|
|
import { createRestServerProbeAuthority } from "./server-probe-authority.js"
|
|
import { createSqlServerProbeJournal } from "./server-probe-journal.js"
|
|
import { normalizeServerProbeRestRequest, parseServerProbeRestServerId, serverProbeRestErrorReply, serverProbeRestReceiptReply } from "./server-probe-rest-contract.js"
|
|
import { withConfigurationActor } from "./config-mutation-policy.js"
|
|
import type { ServerProbeRequest } from "./server-probe-execution-model.js"
|
|
import type { ProbeStorageHostJournal } from "./server-probe-storage-host-io.js"
|
|
|
|
export interface ServerProbeRestContext { actor?: AuthUser; requestId: string; acceptedAt: number; authRequired: boolean; signal?: AbortSignal }
|
|
export interface ServerProbeRestTarget { serverId: number; request: ServerProbeRequest }
|
|
const authority = (actor: AuthUser | undefined, context: ServerProbeRestContext, _target?: ServerProbeRestTarget) => createRestServerProbeAuthority(actor, context)
|
|
const journal: ProbeStorageHostJournal = createSqlServerProbeJournal
|
|
const production = { authority, executor: createProductionServerProbeExecutor, journal, executionId: randomUUID, actor: withConfigurationActor }
|
|
export type ServerProbeRestExecutionDependencies = typeof production
|
|
|
|
/** One common executor for every REST tool. A fresh server-owned execution UUID
|
|
* is never accepted from JSON; REST has no fabricated MCP connection/operation.
|
|
* Importing this module neither registers a route nor starts any collector. */
|
|
export function createServerProbeRestExecution(overrides: Partial<ServerProbeRestExecutionDependencies> = {}) {
|
|
const deps = { ...production, ...overrides }
|
|
return async (rawServerId: string, body: unknown, context: ServerProbeRestContext) => {
|
|
try {
|
|
const serverId = parseServerProbeRestServerId(rawServerId), request = normalizeServerProbeRestRequest(body)
|
|
const access = deps.authority(context.actor, context, { serverId, request }), planner = deps.executor(access)
|
|
const initial = await access.readAuthority()
|
|
if (initial.transport !== "rest" || initial.connectionId !== undefined || initial.credentialId !== undefined) throw new McpError("STATE_CONFLICT", "HTTP-контекст диагностики изменился", 409)
|
|
// REST write permission covers the fleet. Existence is checked only after
|
|
// current authentication and before reading source credentials.
|
|
if (!initial.scopeServerIds.includes(serverId)) throw new ServerProbeExecutionError("NOT_FOUND", "Server not found", 404)
|
|
const prepared = await planner.prepare(serverId, request, context.signal), before = await planner.preflight(prepared, context.signal)
|
|
const principal = await access.readAuthority()
|
|
if (principal.transport !== "rest" || principal.connectionId !== undefined || principal.credentialId !== undefined || !principal.requestId || principal.issuedAt === undefined) throw new McpError("STATE_CONFLICT", "HTTP-контекст диагностики изменился", 409)
|
|
const journal = deps.journal({ identity: { kind: "rest", authentication: context.actor ? "jwt" : "local", ownerId: principal.ownerId, executionId: deps.executionId(), requestId: principal.requestId, issuedAt: principal.issuedAt, expiresAt: principal.expiresAt }, sourceServerId: prepared.serverId, ...(prepared.destinationServerId !== undefined ? { destinationServerId: prepared.destinationServerId } : {}), tool: prepared.tool }, {
|
|
assertAuthority: async (_scope, bindingProof) => {
|
|
if (bindingProof !== before.bindingProof) throw new McpError("STATE_CONFLICT", "Привязка журнала диагностики изменилась", 409)
|
|
const fresh = await planner.preflight(prepared, context.signal)
|
|
if (fingerprint(fresh) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "Допуск или источник диагностики изменился", 409)
|
|
},
|
|
}, { signal: context.signal, deadlineAt: Date.parse(prepared.expiresAt) })
|
|
const executor = deps.executor({ ...access, journal })
|
|
return await deps.actor(principal.ownerId, async () => {
|
|
const receipt = await executor.execute(prepared, context.signal)
|
|
await planner.preflight(prepared, context.signal)
|
|
const recorded = await journal.read(prepared.receiptId, before.bindingProof)
|
|
if (!recorded || fingerprint(recorded) !== fingerprint(receipt)) throw new McpError("STATE_CONFLICT", "Нет точной постоянной квитанции диагностики", 409)
|
|
await planner.preflight(prepared, context.signal)
|
|
return serverProbeRestReceiptReply(recorded)
|
|
})
|
|
} catch (failure) {
|
|
if (failure instanceof McpError && ["UNAUTHORIZED", "OWNER_CLAIMS_REVOKED"].includes(failure.code)) return { statusCode: 401, body: { error: "Доступ отозван; требуется новый вход" } }
|
|
if (failure instanceof McpError && ["PROTECTED_OBJECT", "APPROVAL_REQUIRED"].includes(failure.code)) return { statusCode: 409, body: { error: "Диагностика требует разрешённого плана MCP" } }
|
|
return serverProbeRestErrorReply(failure && typeof failure === "object" ? failure as { code?: string; statusCode?: number } : {})
|
|
}
|
|
}
|
|
}
|
|
export const executeServerProbeRest = createServerProbeRestExecution()
|