240 lines
23 KiB
TypeScript
240 lines
23 KiB
TypeScript
import { carryPollError } from "../../services/server-poll-error-provenance.js"
|
|
import { publicationLayout } from "../../services/server-poll-maintenance-groups.js"
|
|
import { randomUUID } from "node:crypto"
|
|
import { z } from "zod"
|
|
import type { DurableServerPollSessionInput } from "../../services/server-poll-durable-session.js"
|
|
import type { ServerPollPlan, ServerPollReceipt } from "../../services/server-poll-execution.js"
|
|
import { ServerPollProblem } from "../../services/server-poll-execution-model.js"
|
|
import { SERVER_POLL_OPERATION, isCombinedRuntimeMcpServerPollAuthority, type createMcpServerPollAuthority } from "../../services/server-poll-authority.js"
|
|
import type { ActionContext, ChangeEvidence } from "./action-types.js"
|
|
import type { McpServiceHandler } from "./service-registry.js"
|
|
import { fingerprint, McpError, redact } from "./security.js"
|
|
|
|
export const SERVER_POLL_MCP_OPERATION_VERSION = 1
|
|
export const serverPollActionSchema = z.object({ serverId: z.number().int().positive().safe() }).strict()
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/), sid = z.number().int().positive().safe()
|
|
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string().datetime() }).strict()
|
|
const partition = { parent: z.string().min(1).max(100), name: z.string().min(1).max(100) }
|
|
const maintenanceSchema = z.discriminatedUnion("kind", [
|
|
z.object({ kind: z.literal("partition.drop"), ...partition }).strict(),
|
|
z.object({ kind: z.literal("partition.ensure"), ...partition, from: z.string().datetime(), to: z.string().datetime() }).strict(),
|
|
z.object({ kind: z.literal("partition.storage"), ...partition, settings: z.record(z.string(), z.string()) }).strict(),
|
|
])
|
|
const planSchema = z.object({ version: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]), approvalProof: hash.optional(), maintenanceGroupSize: z.literal(8).optional(), requiresHuman: z.literal(true), scope: z.literal("global"), request: z.object({ serverId: sid, receiptId: z.string().uuid() }).strict(),
|
|
around: z.string().datetime(), beforeProof: hash, authorityProof: hash, bindingProof: hash, maintenance: z.array(maintenanceSchema).max(2000),
|
|
affectedServerIds: z.array(sid).min(1).max(1000), mutationCost: z.number().int().min(8).max(2008) }).strict().refine(plan => ((plan.version === 3 || plan.version === 4) ? plan.approvalProof !== undefined : !Object.hasOwn(plan, "approvalProof")) && (plan.version === 4 ? plan.maintenanceGroupSize === 8 : !Object.hasOwn(plan, "maintenanceGroupSize")))
|
|
const bindingSchema = z.object({ version: z.literal(1), operation: z.literal(SERVER_POLL_OPERATION), principal: principalSchema,
|
|
ownerId: z.string().min(1).max(200), issuedAt: z.number().int().nonnegative().safe(), expiresAt: z.number().int().positive().safe(), plan: planSchema }).strict()
|
|
type Binding = z.infer<typeof bindingSchema>
|
|
const inputSchema = z.object({ serverId: sid, receiptId: z.string().uuid(), inputDigest: hash, bindingCiphertext: z.string().min(1).max(2097152) }).strict()
|
|
type Input = z.infer<typeof inputSchema>
|
|
const snapshotSchema = z.object({ id: sid, serverId: sid, polledAt: z.string().datetime(), status: z.enum(["online", "offline"]),
|
|
latencyMs: z.number().nonnegative().nullable().optional(), rosVersion: z.string().nullable().optional(), boardName: z.string().nullable().optional(), uptime: z.string().nullable().optional(),
|
|
cpuLoad: z.number().nullable().optional(), freeMemory: z.number().nonnegative().nullable().optional(), totalMemory: z.number().nonnegative().nullable().optional(), identityName: z.string().nullable().optional() }).strict()
|
|
const resultSchema = z.object({ operationId: z.string().uuid(), receiptId: z.string().uuid(), nativeReads: z.literal(4), confirmedPublications: z.number().int().nonnegative(), completedPublications: z.number().int().nonnegative(),
|
|
complete: z.literal(true), maintenanceComplete: z.literal(true), configurationVerified: z.literal(true), automaticReplay: z.literal(false), snapshot: snapshotSchema }).strict()
|
|
type Window = { deadlineAt: number; signal?: AbortSignal }
|
|
export interface ServerPollMcpDependencies {
|
|
authority: typeof createMcpServerPollAuthority
|
|
combinedAuthority?(principal: Parameters<typeof createMcpServerPollAuthority>[0], options: Parameters<typeof createMcpServerPollAuthority>[1]): ReturnType<typeof createMcpServerPollAuthority> | undefined
|
|
session(input: DurableServerPollSessionInput): { prepare(signal?: AbortSignal): Promise<ServerPollPlan>; execute(plan: ServerPollPlan, signal?: AbortSignal): Promise<ServerPollReceipt>; readExisting(plan: ServerPollPlan, signal?: AbortSignal): Promise<ServerPollReceipt | undefined> }
|
|
query(sql: string, values: unknown[], options: Window): Promise<Record<string, unknown>[]>
|
|
/** Current authorized global reconciliation only; never the old live grant. */
|
|
readArchived?(raw:Record<string,unknown>,authorize:()=>Promise<unknown>,options:Window):Promise<boolean>
|
|
seal(value: string): Promise<string>
|
|
open(value: string): Promise<string>
|
|
proof(value: unknown): Promise<string>
|
|
verified(): Promise<void>
|
|
now(): number
|
|
}
|
|
const denied = (): never => { throw new McpError("STATE_CONFLICT", "Привязка полного опроса к подтверждённой операции не подтверждена", 409) }
|
|
const safe = (error: unknown): McpError => {
|
|
if (error instanceof McpError) return carryPollError(new McpError(error.code, "Полный опрос не получил подтверждённый результат; автоматический повтор запрещён", error.statusCode), error, "poll.safe")
|
|
if (error instanceof ServerPollProblem) return carryPollError(new McpError(error.code, "Полный опрос не получил подтверждённый результат; автоматический повтор запрещён", 409), error, "poll.safe")
|
|
return carryPollError(new McpError("STATE_UNAVAILABLE", "Состояние полного опроса не подтверждено; автоматический повтор запрещён", 503), error, "poll.safe")
|
|
}
|
|
/** Trusted composition only. Model JSON cannot provide a principal, receipt,
|
|
* journal, clock, connector, authority or prepared plan. */
|
|
export function createServerPollMcpAdapterForTests(rawDeps: ServerPollMcpDependencies) {
|
|
const deps = Object.freeze({ ...rawDeps })
|
|
// Only parsed-artifact authentication is reused within ONE owned window.
|
|
// The fresh SQL row, SHA-256, ownership, approval and live authority are not.
|
|
const artifacts = new WeakMap<Window, Map<string, string>>()
|
|
// Derived constants only: parsed input is immutable and local to this window.
|
|
// No database row, policy, grant, approval or current digest is stored here.
|
|
type Subject = Readonly<{ key: string; intendedJson: string; intendedProof: string }>
|
|
const subjects = new WeakMap<Window, WeakMap<Input, Map<string, Subject>>>()
|
|
const subject = (input: Input, operationId: string, options: Window): Subject => {
|
|
if (!Object.isFrozen(input)) return denied()
|
|
let inputs = subjects.get(options)
|
|
if (!inputs) { inputs = new WeakMap(); subjects.set(options, inputs) }
|
|
let operations = inputs.get(input)
|
|
if (!operations) { operations = new Map(); inputs.set(input, operations) }
|
|
let value = operations.get(operationId)
|
|
if (!value) {
|
|
const intended = redact({ kind: "service", service: SERVER_POLL_OPERATION, input })
|
|
value = Object.freeze({ key: fingerprint({ operationId, input }), intendedJson: JSON.stringify(intended), intendedProof: fingerprint(intended) })
|
|
operations.set(operationId, value)
|
|
}
|
|
return value
|
|
}
|
|
const live = (binding: Binding, signal?: AbortSignal) => { if (signal?.aborted || deps.now() < binding.issuedAt || deps.now() >= binding.expiresAt) return denied() }
|
|
const window = async <T>(expiresAt: number, signal: AbortSignal | undefined, work: (options: Window) => Promise<T>): Promise<T> => {
|
|
const deadlineAt = Math.min(expiresAt, deps.now() + 180000), controller = new AbortController()
|
|
const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
|
|
let timer: ReturnType<typeof setTimeout> | undefined, abort!: () => void
|
|
const stopped = new Promise<never>((_yes, reject) => { abort = () => { controller.abort(); reject(deniedError()) }; timer = setTimeout(abort, Math.max(1, deadlineAt - deps.now())) })
|
|
combined.addEventListener("abort", abort, { once: true })
|
|
try { if (deadlineAt <= deps.now() || combined.aborted) abort(); return await Promise.race([Promise.resolve().then(() => { combined.throwIfAborted(); return work({ deadlineAt, signal: combined }) }), stopped]) }
|
|
catch (error) { throw safe(error) }
|
|
finally { clearTimeout(timer); combined.removeEventListener("abort", abort); controller.abort() }
|
|
}
|
|
const open = async (raw: Record<string, unknown>, historical=false) => {
|
|
const input = Object.freeze(inputSchema.parse(raw))
|
|
const text = await deps.open(input.bindingCiphertext)
|
|
if (Buffer.byteLength(text) > 1048576) return denied()
|
|
const binding = bindingSchema.parse(JSON.parse(text)); if(!historical)live(binding)
|
|
if (input.inputDigest !== await deps.proof(binding) || input.receiptId !== binding.plan.request.receiptId || input.serverId !== binding.plan.request.serverId
|
|
|| binding.plan.mutationCost !== binding.plan.maintenance.length + 8 || !binding.plan.affectedServerIds.includes(input.serverId)
|
|
|| new Set(binding.plan.affectedServerIds).size !== binding.plan.affectedServerIds.length || binding.expiresAt > Date.parse(binding.principal.credentialExpiresAt)) return denied()
|
|
if(binding.expiresAt<=binding.issuedAt||binding.issuedAt>deps.now())return denied()
|
|
if(!historical)live(binding); return { input, binding }
|
|
}
|
|
const session = (binding: Binding, options: Window, executionId: string, authorize?: DurableServerPollSessionInput["authorize"]) => deps.session({ request: binding.plan.request,
|
|
identity: { kind: "mcp", ownerId: binding.ownerId, executionId, connectionId: binding.principal.connectionId, credentialId: binding.principal.credentialId,
|
|
issuedAt: binding.issuedAt, expiresAt: binding.expiresAt, operationName: SERVER_POLL_OPERATION }, authorize: authorize ?? deps.authority(binding.principal, options) })
|
|
const preflight = async (binding: Binding, options: Window) => {
|
|
live(binding, options.signal)
|
|
const fresh = await session(binding, options, randomUUID()).prepare(options.signal)
|
|
live(binding, options.signal)
|
|
const epochPlan = binding.plan.version === 3 || binding.plan.version === 4
|
|
if (epochPlan && fresh.version !== 3 && fresh.version !== 4) return denied()
|
|
if (binding.plan.version === 4 && (fresh.version !== 4 || fresh.maintenanceGroupSize !== binding.plan.maintenanceGroupSize)) return denied()
|
|
for (const key of [epochPlan ? "approvalProof" : "beforeProof", "authorityProof", "maintenance", "affectedServerIds", "mutationCost"] as const) if (fingerprint(fresh[key]) !== fingerprint(binding.plan[key])) return denied()
|
|
return { proof: binding.plan.beforeProof }
|
|
}
|
|
const expectedEvidence = (binding: Binding, input: Input) => ({ target: { scope: "global" }, objects: binding.plan.affectedServerIds.map(serverId => ({ kind: "server", id: String(serverId), serverId })),
|
|
snapshots: [], steps: [{ kind: "service", service: SERVER_POLL_OPERATION, input }], before: { proof: binding.plan.beforeProof }, mutationCost: binding.plan.mutationCost,
|
|
requiresHuman: true, verificationScope: "configuration", validUntil: new Date(binding.expiresAt).toISOString(), warnings: ["Полный опрос читает устройство и изменяет общие снимки и разделы истории; требуется подтверждение человеком. Автоматический повтор запрещён."] })
|
|
const owned = async (binding: Binding, input: Input, operationId: string, executing: boolean, options: Window) => {
|
|
live(binding, options.signal)
|
|
if (deps.now() >= options.deadlineAt) return denied()
|
|
let cache = artifacts.get(options)
|
|
if (!cache) { cache = new Map(); artifacts.set(options, cache) }
|
|
const { key, intendedJson, intendedProof } = subject(input, operationId, options), previous = cache.get(key)
|
|
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,
|
|
${previous ? "NULL AS evidence" : "p.evidence AS evidence"},pg_catalog.encode(pg_catalog.sha256(pg_catalog.convert_to(p.evidence::text,'UTF8')),'hex') AS evidence_sha256
|
|
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.id=$1 AND o.connection_id=$2 AND c.owner_id=$3 AND p.operation_id=$4 AND p.operation_version=1
|
|
AND p.approved_by IS NOT NULL AND s.step_index=0 AND s.intended_state=$5::jsonb AND octet_length(p.evidence::text)<=4194304 LIMIT 2`,
|
|
[operationId, binding.principal.connectionId, binding.ownerId, SERVER_POLL_OPERATION, intendedJson], options)
|
|
live(binding, options.signal)
|
|
if (rows.length !== 1) return denied()
|
|
const row = rows[0]
|
|
if (row.operation_id !== operationId || row.step_index !== 0 || !row.approved_by || fingerprint(row.intended_state) !== intendedProof) return denied()
|
|
if (executing ? row.operation_state !== "running" || row.plan_state !== "executing" || row.step_state !== "intent"
|
|
: !["running", "applied", "unknown", "failed"].includes(String(row.operation_state)) || !["intent", "applied", "verified", "acknowledged", "unknown", "failed"].includes(String(row.step_state))) return denied()
|
|
if (!hash.safeParse(row.evidence_sha256).success) return denied()
|
|
if (previous && previous === row.evidence_sha256) return row
|
|
if (previous) {
|
|
// A changed server digest cannot inherit the old artifact validation.
|
|
// Refetch the full sealed source and repeat all fresh row predicates.
|
|
cache.delete(key)
|
|
return owned(binding, input, operationId, executing, options)
|
|
}
|
|
const evidence = row.evidence as { sealed?: unknown }
|
|
if (typeof evidence?.sealed !== "string") return denied()
|
|
const text = await deps.open(evidence.sealed); live(binding, options.signal)
|
|
if (Buffer.byteLength(text) > 2097152 || fingerprint(JSON.parse(text)) !== fingerprint(expectedEvidence(binding, input))) return denied()
|
|
cache.set(key, String(row.evidence_sha256))
|
|
return row
|
|
}
|
|
const result = (receipt: ServerPollReceipt, binding: Binding, operationId: string) => {
|
|
if (receipt.receiptId !== binding.plan.request.receiptId || !receipt.complete || !receipt.maintenanceComplete || !receipt.configurationVerified
|
|
|| receipt.confirmedPublications !== receipt.completedPublications || receipt.confirmedPublications < publicationLayout(binding.plan).maintenancePublications + 2 || receipt.confirmedPublications > publicationLayout(binding.plan).maintenancePublications + 4) return denied()
|
|
const parsed = snapshotSchema.parse(receipt.snapshot)
|
|
if (parsed.serverId !== binding.plan.request.serverId) return denied()
|
|
const snapshot = { id: parsed.id, serverId: parsed.serverId, polledAt: parsed.polledAt, status: parsed.status,
|
|
latencyMs: parsed.latencyMs ?? null, rosVersion: parsed.rosVersion ?? null, boardName: parsed.boardName ?? null, uptime: parsed.uptime ?? null,
|
|
cpuLoad: parsed.cpuLoad ?? null, freeMemory: parsed.freeMemory ?? null, totalMemory: parsed.totalMemory ?? null, identityName: parsed.identityName ?? null }
|
|
return resultSchema.parse({ operationId, receiptId: receipt.receiptId, nativeReads: receipt.nativeReads, confirmedPublications: receipt.confirmedPublications, completedPublications: receipt.completedPublications,
|
|
complete: true, maintenanceComplete: true, configurationVerified: true, automaticReplay: false, snapshot })
|
|
}
|
|
const persisted = async (input: Input, binding: Binding, operationId: string, options: Window) => {
|
|
const authority = deps.authority(binding.principal, options)
|
|
const authorize: typeof authority = async (...args) => { live(binding, options.signal); await owned(binding, input, operationId, false, options); const grant = await authority(...args); live(binding, options.signal); return grant }
|
|
await authorize(binding.plan.request, binding.plan.affectedServerIds, options.signal)
|
|
const receipt = await session(binding, options, operationId, authorize).readExisting(binding.plan, options.signal)
|
|
if (!receipt) return undefined
|
|
const row = await owned(binding, input, operationId, false, options)
|
|
await authorize(binding.plan.request, binding.plan.affectedServerIds, options.signal)
|
|
return { row, result: result(receipt, binding, operationId) }
|
|
}
|
|
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => window(Date.parse(context.principal.credentialExpiresAt), context.signal, async options => {
|
|
const input = serverPollActionSchema.parse(raw), principal = principalSchema.parse(structuredClone(context.principal)), connection = context.connection
|
|
const expiresAt = Math.min(deps.now() + 300000, Date.parse(principal.credentialExpiresAt), connection.owner_valid_until.getTime(), Date.parse(connection.policy.expiresAt))
|
|
const seed = { version: 1 as const, operation: SERVER_POLL_OPERATION, principal, ownerId: connection.owner_id, issuedAt: connection.owner_claims_issued_at.getTime(), expiresAt }
|
|
const request = { serverId: input.serverId, receiptId: randomUUID() }, authorize = deps.authority(principal, { ...options, deadlineAt: Math.min(options.deadlineAt, expiresAt) })
|
|
await authorize(request, [input.serverId], options.signal)
|
|
const plan = await deps.session({ request, identity: { kind: "mcp", executionId: randomUUID(), ownerId: seed.ownerId, issuedAt: seed.issuedAt, expiresAt,
|
|
connectionId: principal.connectionId, credentialId: principal.credentialId, operationName: SERVER_POLL_OPERATION }, authorize }).prepare(options.signal)
|
|
const binding = bindingSchema.parse({ ...seed, plan }); live(binding, options.signal)
|
|
if (plan.request.serverId !== request.serverId || plan.request.receiptId !== request.receiptId || plan.mutationCost !== plan.maintenance.length + 8) return denied()
|
|
const serviceInput: Input = { ...request, inputDigest: await deps.proof(binding), bindingCiphertext: await deps.seal(JSON.stringify(binding)) }
|
|
await preflight(binding, options)
|
|
return expectedEvidence(binding, serviceInput) as ChangeEvidence
|
|
})
|
|
const service: McpServiceHandler = {
|
|
current: raw => window(deps.now() + 180000, undefined, async options => { const { binding } = await open(raw); return preflight(binding, { ...options, deadlineAt: Math.min(options.deadlineAt, binding.expiresAt) }) }),
|
|
execute: (raw, context) => window(deps.now() + 180000, context?.phase === "forward" ? context.signal : undefined, async options => {
|
|
if (!context || context.phase !== "forward" || context.stepIndex !== 0 || !z.string().uuid().safeParse(context.operationId).success) return denied()
|
|
await deps.verified()
|
|
const { input, binding } = await open(raw), bounded = { ...options, deadlineAt: Math.min(options.deadlineAt, binding.expiresAt) }
|
|
await owned(binding, input, context.operationId, true, bounded)
|
|
const candidateAuthority = deps.combinedAuthority?.(binding.principal, bounded)
|
|
const combinedAuthority = isCombinedRuntimeMcpServerPollAuthority(candidateAuthority) ? candidateAuthority : undefined
|
|
const authority = combinedAuthority ?? deps.authority(binding.principal, bounded)
|
|
const authorize: typeof authority = async (...args) => {
|
|
live(binding, bounded.signal)
|
|
// Independent read-only sources must all be current at this boundary.
|
|
// Run them together; retain no policy/approval decision for later I/O.
|
|
const verification = combinedAuthority ? [] : [deps.verified()]
|
|
const ownership = owned(binding, input, context.operationId, true, bounded), granted = authority(...args)
|
|
const checks = await Promise.allSettled([...verification, ownership, granted])
|
|
live(binding, bounded.signal)
|
|
for (const check of checks) if (check.status === "rejected") throw check.reason
|
|
return granted
|
|
}
|
|
const receipt = await session(binding, bounded, context.operationId, authorize).execute(binding.plan, bounded.signal)
|
|
await authorize(binding.plan.request, binding.plan.affectedServerIds, bounded.signal)
|
|
return result(receipt, binding, context.operationId)
|
|
}),
|
|
verify: async (raw, value) => { try { return await window(deps.now() + 180000, undefined, async options => {
|
|
const parsed = resultSchema.parse(value), { input, binding } = await open(raw), actual = await persisted(input, binding, parsed.operationId, { ...options, deadlineAt: Math.min(options.deadlineAt, binding.expiresAt) })
|
|
return !!actual && fingerprint(actual.result) === fingerprint(parsed) && fingerprint(actual.row.result) === fingerprint(parsed)
|
|
}) } catch { return false } },
|
|
reconcile: async (raw, authorize) => { await authorize(); let authFailed=false,authError:unknown
|
|
const current=async()=>{try{await authorize()}catch(error){authFailed=true;authError=error;throw error}}
|
|
try { return await window(deps.now() + 180000, undefined, async options => {
|
|
await current();const { input, binding } = await open(raw,true);await current()
|
|
if(deps.now()>=binding.expiresAt){
|
|
if(!deps.readArchived)return {matchesDesiredState:false,matchesOriginalState:false}
|
|
const matches=await deps.readArchived(input,current,options);await current()
|
|
return {matchesDesiredState:matches===true,matchesOriginalState:false}
|
|
}
|
|
// A read-only lookup resolves the actual op ID from this exact sealed step.
|
|
const rows = await deps.query("SELECT o.id FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id WHERE o.connection_id=$1 AND p.operation_id=$2 AND s.step_index=0 AND s.intended_state=$3::jsonb LIMIT 2", [binding.principal.connectionId, SERVER_POLL_OPERATION, JSON.stringify(redact({ kind: "service", service: SERVER_POLL_OPERATION, input }))], options)
|
|
if (rows.length !== 1 || !z.string().uuid().safeParse(rows[0].id).success) return { matchesDesiredState: false, matchesOriginalState: false }
|
|
const actual = await persisted(input, binding, String(rows[0].id), { ...options, deadlineAt: Math.min(options.deadlineAt, binding.expiresAt) }); await current()
|
|
return { matchesDesiredState: !!actual && fingerprint(actual.row.result) === fingerprint(actual.result), matchesOriginalState: false }
|
|
}) } catch { if(authFailed)throw authError;return { matchesDesiredState: false, matchesOriginalState: false } } },
|
|
}
|
|
return { schema: serverPollActionSchema, target: async (raw: Record<string, unknown>, context: ActionContext) => {
|
|
const { serverId } = serverPollActionSchema.parse(raw), request = { serverId, receiptId: randomUUID() }
|
|
await window(Date.parse(context.principal.credentialExpiresAt), context.signal, async options => { await deps.authority(context.principal, options)(request, [serverId], options.signal) })
|
|
return { scope: "global" as const }
|
|
}, prepare, service }
|
|
}
|
|
function deniedError() { return new McpError("STATE_CONFLICT", "Полный опрос отменён или срок исходного плана истёк", 409) }
|