/** Historical terminal eligibility only. The caller owns the SQL transaction, * global storage lock, exact source-row locks and nonblocking operation locks. * This module never renews a grant or creates an execution capability. */ import { publicationLayout } from "./server-poll-maintenance-groups.js" import { z } from "zod" import { openServerPollJournalAnchor } from "./server-poll-journal-anchor.js" import { decryptSecret, fingerprint, privateSecretFingerprint, redact } from "../modules/mcp/security.js" import type { ServerPollHistoryRows, VerifiedServerPollHistory } from "./server-poll-history-verification.js" export interface ServerPollTerminalSourceRows { admission: Record; journal: ServerPollHistoryRows terminal: { operation: Record; plan: Record; step: Record } } export interface ServerPollTerminalBinding { receiptId: string; executionId: string; connectionId: string; ownerId: string; bindingProof: string; contextProof: string originalActivityAt: string; originalExpiresAt: string; retentionDays: number; safetyMs: number; terminalDigest: string } interface Crypto { decrypt(value: string): Promise; proof(domain: string, value: unknown): Promise } export class ServerPollTerminalSourceInvalid extends Error { readonly code = "SERVER_POLL_TERMINAL_SOURCE_INVALID" constructor() { super("Confirmed original server poll terminal source unavailable") } } const must = (value: unknown): void => { if (!value) throw new ServerPollTerminalSourceInvalid() } const uuid = z.string().uuid(), hash = z.string().regex(/^[a-f0-9]{64}$/), sid = z.number().int().positive().safe() const time = z.union([z.date(), z.string().min(1).max(100)]).refine(value => Number.isFinite(new Date(value).getTime())) const actor = z.string().min(1).max(200).refine(value => value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value)) const sealed = z.object({ sealed: z.string().min(1).max(4194304) }).strict() const admissionSchema = z.object({ receipt_id: uuid, identity_kind: z.literal("mcp"), execution_id: uuid, connection_id: uuid, storage_state: z.literal("full"), owner_id: actor, binding_proof: hash, context_proof: hash, authority_issued_at: time, authority_expires_at: time, max_stages: z.number().int().min(8).max(2008), claim_token: z.null(), claim_attempted_at: time, created_at: time, retention_days: z.number().int().min(1).max(365), safety_ms: z.literal(60000), gc_not_before: time, used_rows: z.number().int().min(1).max(4019), used_bytes: z.union([z.number().int().nonnegative().safe(), z.string().regex(/^\d{1,16}$/)]) }).passthrough() const operationSchema = z.object({ id: uuid, plan_id: uuid, connection_id: uuid, state: z.literal("applied"), verification: z.literal("passed"), error_code: z.null(), result: z.unknown(), created_at: time, finished_at: time }).passthrough() const planSchema = z.object({ id: uuid, connection_id: uuid, operation_id: z.literal("servers.poll"), operation_version: z.literal(1), state: z.literal("completed"), created_at: time, approved_by: actor, approved_at: time, expires_at: time, payload: sealed, evidence: sealed }).passthrough() const stepSchema = z.object({ operation_id: uuid, step_index: z.literal(0), server_id: z.null(), state: z.literal("verified"), intended_state: z.unknown(), result: z.unknown(), finished_at: time }).passthrough() const inputSchema = z.object({ serverId: sid, receiptId: uuid, inputDigest: hash, bindingCiphertext: z.string().min(1).max(2097152) }).strict() const principalSchema = z.object({ connectionId: uuid, credentialId: uuid, credentialExpiresAt: z.string().datetime() }).strict() // The complete plan is authenticated by the shared history verifier. Compare // the same original plan, rather than reconstructing live maintenance/settings. const bindingSchema = z.object({ version: z.literal(1), operation: z.literal("servers.poll"), principal: principalSchema, ownerId: actor, issuedAt: z.number().int().nonnegative().safe(), expiresAt: z.number().int().positive().safe(), plan: z.record(z.string(), z.unknown()) }).strict() const at = (value: Date | string) => new Date(value).getTime() const rawTime = (value: Date | string): string => value instanceof Date ? value.toISOString() : value // Preserve PostgreSQL microseconds when selecting the original activity value. const micros = (value: Date | string): bigint => BigInt(at(value)) * 1000n + BigInt(typeof value === "string" ? Number((/\.(\d+)/.exec(value)?.[1] ?? "").padEnd(6, "0").slice(3, 6)) : 0) async function verify(raw: ServerPollTerminalSourceRows, supplied: VerifiedServerPollHistory, now: number, crypto: Crypto): Promise { try { must(Number.isSafeInteger(now) && now > 0 && raw && supplied) // Capture before crypto awaits. Unknown columns remain in the original // terminal tuple and in the caller's lossless archived source payload. const source = structuredClone(raw), history = structuredClone(supplied) must(Buffer.byteLength(JSON.stringify(source)) <= 16 * 1048576) const a = admissionSchema.parse(source.admission), o = operationSchema.parse(source.terminal.operation) const p = planSchema.parse(source.terminal.plan), s = stepSchema.parse(source.terminal.step) for (const field of ["compact_at", "archive_bytes", "original_activity_at"]) if (Object.hasOwn(source.admission, field)) must(source.admission[field] === null) const { identity, plan } = history.context, receipt = history.receipt must(identity.kind === "mcp") if (identity.kind !== "mcp") throw new ServerPollTerminalSourceInvalid() must(o.id === a.execution_id && o.connection_id === a.connection_id && p.id === o.plan_id && p.connection_id === a.connection_id && s.operation_id === o.id) must(identity.executionId === o.id && identity.ownerId === a.owner_id && identity.connectionId === a.connection_id && identity.operationName === "servers.poll") must(identity.issuedAt === at(a.authority_issued_at) && identity.expiresAt === at(a.authority_expires_at) && identity.expiresAt > identity.issuedAt) must((plan.version === 1 || plan.version === 2 || plan.version === 3 || plan.version === 4) && plan.requiresHuman === true && plan.scope === "global" && plan.request.receiptId === a.receipt_id && plan.bindingProof === a.binding_proof) const layout = publicationLayout(plan) must(a.max_stages === layout.journalMaxStages && plan.mutationCost === layout.logicalMutationCost && plan.affectedServerIds.includes(plan.request.serverId)) must(new Set(plan.affectedServerIds).size === plan.affectedServerIds.length && plan.affectedServerIds.length <= 1000) must(receipt.observation === "online" && receipt.complete && receipt.configurationVerified && receipt.maintenanceComplete && receipt.nativeReads === 4) must(history.source.nativeOutcomes.length === 4 && history.source.nativeOutcomes.every(row => row.outcome === "confirmed")) must(source.journal.quarantines.length === 0 && source.journal.acks.every(row => row.outcome === "confirmed")) must(a.used_rows === source.journal.intents.length + source.journal.acks.length + 2 && Number(a.used_bytes) > 0 && Number(a.used_bytes) <= 8388608) must(history.source.stageCount === source.journal.intents.length && source.journal.intents.length === source.journal.acks.length) const anchor = source.journal.execution, terminalReceipt = source.journal.receipt must(anchor.receipt_id === a.receipt_id && anchor.execution_id === a.execution_id && anchor.identity_kind === "mcp" && anchor.binding_proof === a.binding_proof && anchor.context_proof === a.context_proof) must(typeof anchor.context_ciphertext === "string" && typeof terminalReceipt.receipt_ciphertext === "string") const decode = async (value: string, limit: number) => { must(Buffer.byteLength(value) <= limit * 2); const text = await crypto.decrypt(value); must(Buffer.byteLength(text) <= limit); return text } const contextText = await decode(String(anchor.context_ciphertext), 1048576) await openServerPollJournalAnchor(JSON.parse(contextText),history.context,{proof:(domain,value)=>crypto.proof("server-poll-journal-v1:"+domain,value)}) must(a.context_proof === await crypto.proof("server-poll-journal-v1:context", history.context)) const receiptText = await decode(String(terminalReceipt.receipt_ciphertext), 131072) must(fingerprint(JSON.parse(receiptText)) === fingerprint(receipt) && terminalReceipt.receipt_proof === await crypto.proof("server-poll-journal-v1:receipt", receiptText)) const evidence = JSON.parse(await decode(p.evidence.sealed, 2097152)) as Record const payload = JSON.parse(await decode(p.payload.sealed, 1048576)) must(fingerprint(payload) === fingerprint({ serverId: plan.request.serverId })) if (!Array.isArray(evidence.steps) || evidence.steps.length !== 1) throw new ServerPollTerminalSourceInvalid() const step = evidence.steps[0] as { kind?: unknown; service?: unknown; input?: unknown } must(step.kind === "service" && step.service === "servers.poll") const input = inputSchema.parse(step.input), binding = bindingSchema.parse(JSON.parse(await decode(input.bindingCiphertext, 1048576))) must(input.serverId === plan.request.serverId && input.receiptId === a.receipt_id && input.inputDigest === await crypto.proof("server-poll-mcp-binding-v1", binding)) must(binding.ownerId === a.owner_id && binding.principal.connectionId === a.connection_id && binding.principal.credentialId === identity.credentialId) must(binding.issuedAt === identity.issuedAt && binding.expiresAt === identity.expiresAt && binding.expiresAt <= Date.parse(binding.principal.credentialExpiresAt) && fingerprint(binding.plan) === fingerprint(plan)) const expectedEvidence = { target: { scope: "global" }, objects: plan.affectedServerIds.map(serverId => ({ kind: "server", id: String(serverId), serverId })), snapshots: [], steps: [{ kind: "service", service: "servers.poll", input }], before: { proof: plan.beforeProof }, mutationCost: plan.mutationCost, requiresHuman: true, verificationScope: "configuration", validUntil: new Date(binding.expiresAt).toISOString(), warnings: ["Полный опрос читает устройство и изменяет общие снимки и разделы истории; требуется подтверждение человеком. Автоматический повтор запрещён."] } must(fingerprint(evidence) === fingerprint(expectedEvidence) && fingerprint(s.intended_state) === fingerprint(redact(step))) const snapshot = { ...receipt.snapshot } for (const field of ["latencyMs", "rosVersion", "boardName", "uptime", "cpuLoad", "freeMemory", "totalMemory", "identityName"] as const) snapshot[field] ??= null const publicResult = { operationId: o.id, receiptId: a.receipt_id, nativeReads: 4, confirmedPublications: receipt.confirmedPublications, completedPublications: receipt.completedPublications, complete: true, maintenanceComplete: true, configurationVerified: true, automaticReplay: false, snapshot } must(fingerprint(s.result) === fingerprint(publicResult) && fingerprint(o.result) === fingerprint({ confirmedWrites: 1, verificationScope: "configuration" })) must(identity.issuedAt <= at(p.approved_at) && micros(p.created_at) <= micros(p.approved_at) && micros(p.approved_at) <= micros(o.created_at)) must(micros(o.created_at) < micros(p.expires_at) && micros(o.created_at) < BigInt(identity.expiresAt) * 1000n && at(o.created_at) <= at(a.created_at)) must(at(a.created_at) <= at(a.claim_attempted_at) && at(a.claim_attempted_at) <= at(anchor.created_at as Date | string)) const originalExpiry = BigInt(identity.expiresAt) * 1000n must(micros(time.parse(terminalReceipt.created_at)) < originalExpiry) for (const ack of source.journal.acks) must(micros(time.parse(ack.created_at)) < originalExpiry) must(at(terminalReceipt.created_at as Date | string) <= at(s.finished_at) && at(s.finished_at) <= at(o.finished_at)) must(at(history.source.createdAt) === at(anchor.created_at as Date | string) && at(history.source.completedAt) === at(terminalReceipt.created_at as Date | string)) const dates = [a.authority_expires_at, a.created_at, a.claim_attempted_at, p.expires_at, o.finished_at, s.finished_at, time.parse(anchor.created_at), time.parse(terminalReceipt.created_at), ...source.journal.intents.map(row => time.parse(row.created_at)), ...source.journal.acks.map(row => time.parse(row.created_at))] const activity = dates.reduce((latest, value) => micros(value) > micros(latest) ? value : latest) must(micros(activity) + BigInt(a.safety_ms) * 1000n < BigInt(now) * 1000n) must(at(a.gc_not_before) >= at(a.authority_expires_at) + a.retention_days * 86400000 + a.safety_ms) const tuple = { format: "server-poll-terminal-source-v1", receiptId: a.receipt_id, executionId: a.execution_id, connectionId: a.connection_id, ownerId: a.owner_id, bindingProof: a.binding_proof, contextProof: a.context_proof, terminal: source.terminal } const terminalDigest = hash.parse(await crypto.proof("server-poll-terminal-source-v1", tuple)) return Object.freeze({ receiptId: a.receipt_id, executionId: a.execution_id, connectionId: a.connection_id, ownerId: a.owner_id, bindingProof: a.binding_proof, contextProof: a.context_proof, originalActivityAt: rawTime(activity), originalExpiresAt: rawTime(a.authority_expires_at), retentionDays: a.retention_days, safetyMs: a.safety_ms, terminalDigest }) } catch { throw new ServerPollTerminalSourceInvalid() } } export const verifyServerPollTerminalSource = (source: ServerPollTerminalSourceRows, history: VerifiedServerPollHistory, now: number) => verify(source, history, now, { decrypt: decryptSecret, proof: (domain, value) => privateSecretFingerprint(fingerprint(value), domain) }) /** Explicit unit-only crypto. No SQL/public caller can select this composition. */ export const verifyServerPollTerminalSourceForTests = (source: ServerPollTerminalSourceRows, history: VerifiedServerPollHistory, now: number, crypto: Crypto) => verify(source, history, now, crypto)