import type { FastifyReply, FastifyRequest } from "fastify" import { performance } from "node:perf_hooks" import { captureVerifiedRestRequest, inspectVerifiedRestRequest } from "../plugins/auth.js" import { McpError } from "../modules/mcp/security.js" import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js" import { executeDurableServerPollRest } from "./server-poll-rest.js" function handler(execute: typeof executeDurableServerPollRest) { return async (request: FastifyRequest, reply: FastifyReply) => { const serverId = String((request.params as { id?: unknown })?.id ?? "") const disconnected = new AbortController() const aborted = () => disconnected.abort() const closed = () => { if (!reply.raw.writableEnded) disconnected.abort() } request.raw.once("aborted", aborted); reply.raw.once("close", closed) let timer: ReturnType | undefined if (request.raw.aborted || reply.raw.destroyed) disconnected.abort() try { const scope = Object.freeze({ deadlineAt: Date.now() + SERVER_POLL_WALL_BUDGET_MS, signal: disconnected.signal }) const token = await captureVerifiedRestRequest(request, scope) const authority = await inspectVerifiedRestRequest(token, scope, "mm:servers:write") if (authority.method !== "POST" || !/^\/api\/servers\/(?::id|[1-9]\d*)\/poll$/.test(authority.path)) throw new McpError("PERMISSION_DENIED", "Недопустимый источник полного опроса", 403) const deadlineAt = Math.min(authority.expiresAt, authority.acceptedAt + SERVER_POLL_WALL_BUDGET_MS) const monotonicDeadline = authority.monotonicDeadline - (authority.expiresAt - deadlineAt) const signal = AbortSignal.any([authority.signal, disconnected.signal]) const assertRequestActive = () => { if (signal.aborted || Date.now() < authority.acceptedAt || Date.now() >= deadlineAt || performance.now() >= monotonicDeadline) { throw new McpError("READ_CANCELLED", "Исходный запрос полного опроса завершён", 409) } } assertRequestActive() timer = setTimeout(aborted, Math.max(1, Math.min(deadlineAt - Date.now(), monotonicDeadline - performance.now()))) // Identity/configuration come from the genuine authentication hooks, never // request JSON, headers, a mutable authUser or a caller's request ID. const actor = authority.authentication === "jwt" ? { id: authority.ownerId, email: "", name: "", apps: [...authority.apps], permissions: [...authority.permissions], issuedAt: authority.issuedAt, expiresAt: deadlineAt } : undefined const response = await execute(serverId, { actor, authRequired: authority.authentication === "jwt", acceptedAt: authority.acceptedAt, requestId: authority.requestId, deadlineAt, signal, assertRequestActive }) assertRequestActive() const current = await inspectVerifiedRestRequest(token, scope, "mm:servers:write") if (current !== authority) throw new McpError("STATE_CONFLICT", "Изменился исходный запрос полного опроса", 409) assertRequestActive() return reply.status(response.statusCode).send(response.body) } catch (error) { if (request.raw.aborted || reply.raw.destroyed) return const code = error && typeof error === "object" && "code" in error ? error.code : undefined const status = code === "READ_CANCELLED" ? 409 : code === "OWNER_CLAIMS_REVOKED" ? 401 : code === "PERMISSION_DENIED" || code === "REST_REQUEST_PROVENANCE_REFUSED" ? 403 : 503 return reply.status(status).send({ error: status === 401 ? "Права изменены; войдите заново" : status === 403 ? "Нет подтверждённого права полного опроса" : status === 409 ? "Полный опрос отменён или истёк; обновите данные перед повтором" : "Полный опрос недоступен; автоматический повтор запрещён" }) } finally { clearTimeout(timer); request.raw.off("aborted", aborted); reply.raw.off("close", closed); disconnected.abort() } } } export const handleDurableServerPollHttp = handler(executeDurableServerPollRest) /** Trusted composition for HTTP/auth tests; never derived from a request. */ export const createDurableServerPollHttpForTests = (execute: typeof executeDurableServerPollRest) => handler(execute)