Files
MikrotikManager/backend/src/services/server-poll-history-verification.ts
T

123 lines
11 KiB
TypeScript

import { publicationLayout, serverPollMaintenancePublications } from "./server-poll-maintenance-groups.js"
import { z } from "zod"
import { openServerPollJournalAnchor } from "./server-poll-journal-anchor.js"
import { parseServerPollJournalIdentity, type ServerPollJournalContext } from "./server-poll-journal.js"
import { SERVER_POLL_NATIVE_READS } from "./server-poll-execution-model.js"
import { serverPollPublications, validateServerPollJournalReceipt, type ServerPollJournalStage } from "./server-poll-journal-validation.js"
import type { ServerPollDependencies, ServerPollReceipt } from "./server-poll-execution.js"
import type { ProbeJournalCrypto } from "./server-probe-journal.js"
/** Internal raw rows read under the storage owner's SQL locks. Not a public
* JSON request or a capability. Current read/maintenance access and transaction
* ownership must be established by that trusted caller, outside this verifier. */
export interface ServerPollHistoryRows {
execution: Record<string, unknown>; intents: Record<string, unknown>[]; acks: Record<string, unknown>[]
receipt: Record<string, unknown>; quarantines: Record<string, unknown>[]
}
export interface VerifiedServerPollHistory {
context: ServerPollJournalContext; receipt: ServerPollReceipt
source: { createdAt: string; completedAt: string; stageCount: number; publications: number
nativeOutcomes: { stage: string; outcome: "confirmed" | "read-failed"; resultProof: string }[] }
}
export class ServerPollHistoryInvalid extends Error {
readonly code = "SERVER_POLL_HISTORY_INVALID"
constructor() { super("Complete authenticated server poll history unavailable") }
}
const hash = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid(), sid = z.number().int().positive().safe()
const timestamp = z.union([z.date(), z.string().min(1).max(100)]).refine(value => Number.isFinite(new Date(value).getTime()))
const executionSchema = z.object({ receipt_id: uuid, identity_kind: z.enum(["mcp", "rest"]), execution_id: uuid, binding_proof: hash,
context_ciphertext: z.string().min(1).max(2097152), context_proof: hash, created_at: timestamp }).strict()
const intentSchema = z.object({ receipt_id: uuid, stage: z.string().min(1).max(64), before_proof: hash, effect_proof: hash, intent_proof: hash, created_at: timestamp }).strict()
const ackSchema = z.object({ receipt_id: uuid, stage: z.string().min(1).max(64), result_proof: hash, outcome: z.enum(["confirmed", "read-failed"]), ack_proof: hash, created_at: timestamp }).strict()
const receiptSchema = z.object({ receipt_id: uuid, receipt_ciphertext: z.string().min(1).max(262144), receipt_proof: hash, created_at: timestamp }).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: 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")))
interface HistoryDependencies { crypto: Pick<ProbeJournalCrypto, "decrypt" | "proof">; executionProof: ServerPollDependencies["proof"] }
const must = (value: unknown): void => { if (!value) throw new ServerPollHistoryInvalid() }
const at = (value: Date | string) => new Date(value).getTime()
async function verify(raw: ServerPollHistoryRows, deps: HistoryDependencies): Promise<VerifiedServerPollHistory> {
try {
must(raw && Object.keys(raw).sort().join(",") === "acks,execution,intents,quarantines,receipt")
must(Array.isArray(raw.intents) && raw.intents.length <= 2010 && Array.isArray(raw.acks) && raw.acks.length <= 2010 && Array.isArray(raw.quarantines) && raw.quarantines.length === 0)
must(Buffer.byteLength(JSON.stringify(raw)) <= 8 * 1048576)
const anchor = executionSchema.parse(raw.execution), terminal = receiptSchema.parse(raw.receipt)
must(Buffer.byteLength(anchor.context_ciphertext) <= 2097152 && Buffer.byteLength(terminal.receipt_ciphertext) <= 262144)
const contextText = await deps.crypto.decrypt(anchor.context_ciphertext)
must(Buffer.byteLength(contextText) <= 1048576)
const parsed: unknown = JSON.parse(contextText)
must(parsed && typeof parsed === "object" && !Array.isArray(parsed) && ["identity,plan", "executionStart,identity,plan"].includes(Object.keys(parsed).sort().join(",")))
const body = parsed as Record<string, unknown>
const context: ServerPollJournalContext = { identity: parseServerPollJournalIdentity(body.identity), plan: planSchema.parse(body.plan) }
const executionStartProof = await openServerPollJournalAnchor(parsed, context, deps.crypto)
const { identity, plan } = context, { bindingProof, ...core } = plan
const layout = publicationLayout(plan), maintenance = serverPollMaintenancePublications(plan)
must(identity.expiresAt > identity.issuedAt && new Set(plan.affectedServerIds).size === plan.affectedServerIds.length && plan.affectedServerIds.includes(plan.request.serverId) && plan.mutationCost === plan.maintenance.length + 8)
must(anchor.receipt_id === plan.request.receiptId && anchor.identity_kind === identity.kind && anchor.execution_id === identity.executionId && anchor.binding_proof === bindingProof && terminal.receipt_id === anchor.receipt_id)
must(anchor.context_proof === hash.parse(await deps.crypto.proof("context", context)) && bindingProof === hash.parse(await deps.executionProof(core)))
const receiptText = await deps.crypto.decrypt(terminal.receipt_ciphertext)
must(Buffer.byteLength(receiptText) <= 131072 && terminal.receipt_proof === hash.parse(await deps.crypto.proof("receipt", receiptText)))
const receipt = JSON.parse(receiptText) as ServerPollReceipt
const intents = raw.intents.map(row => intentSchema.parse(row)), acks = raw.acks.map(row => ackSchema.parse(row))
must(intents.length === acks.length && intents.length <= layout.journalMaxStages)
must(new Set(intents.map(row => row.stage)).size === intents.length && new Set(acks.map(row => row.stage)).size === acks.length)
const ackByStage = new Map(acks.map(row => [row.stage, row])), stages: ServerPollJournalStage[] = []
const native = new Set<string>(SERVER_POLL_NATIVE_READS.map(value => "native." + value))
for (const intent of intents) {
const ack = ackByStage.get(intent.stage)
must(ack && intent.receipt_id === anchor.receipt_id && ack.receipt_id === anchor.receipt_id)
if (!ack) throw new ServerPollHistoryInvalid()
must(native.has(intent.stage) || /^publish\.(0|[1-9]\d{0,3})$/.test(intent.stage))
must(at(anchor.created_at) <= at(intent.created_at) && at(intent.created_at) <= at(ack.created_at) && at(ack.created_at) <= at(terminal.created_at))
must(intent.intent_proof === hash.parse(await deps.crypto.proof("intent", { receiptId: anchor.receipt_id, stage: intent.stage, beforeProof: intent.before_proof, effectProof: intent.effect_proof })))
must(ack.ack_proof === hash.parse(await deps.crypto.proof("ack", { receiptId: anchor.receipt_id, stage: ack.stage, resultProof: ack.result_proof, outcome: ack.outcome })))
if (native.has(intent.stage)) {
must(intent.before_proof === executionStartProof)
if (ack.outcome === "read-failed") must(ack.result_proof === hash.parse(await deps.executionProof({ unavailable: true })))
} else must(ack.outcome === "confirmed")
stages.push({ ...intent, result_proof: ack.result_proof, outcome: ack.outcome, ack_proof: ack.ack_proof })
}
// Duplicate/orphan ACKs cannot be hidden by a join or a count-only check.
must(acks.every(ack => intents.some(intent => intent.stage === ack.stage)))
validateServerPollJournalReceipt(plan, receipt, stages, executionStartProof)
const pubs = serverPollPublications(stages)
const nativeAckAt = Math.max(...acks.filter(row => native.has(row.stage)).map(row => at(row.created_at)))
must(at(pubs[0].created_at as Date | string) >= nativeAckAt)
for (let index = 0; index < pubs.length; index++) must(pubs[index].before_proof === (index === 0 ? executionStartProof : pubs[index - 1].result_proof))
for (let index = 1; index < pubs.length; index++) must(at(pubs[index].created_at as Date | string) >= at(ackByStage.get(pubs[index - 1].stage)!.created_at))
const offset = pubs.length - maintenance.length
for (let index = 0; index < maintenance.length; index++) must(pubs[offset + index].effect_proof === hash.parse(await deps.executionProof(maintenance[index])))
const nativeOutcomes = SERVER_POLL_NATIVE_READS.map(value => {
const row = stages.find(row => row.stage === "native." + value)
must(row && (row.outcome === "confirmed" || row.outcome === "read-failed"))
if (!row) throw new ServerPollHistoryInvalid()
return { stage: row.stage, outcome: row.outcome as "confirmed" | "read-failed", resultProof: String(row.result_proof) }
})
return { context, receipt, source: { createdAt: new Date(anchor.created_at).toISOString(), completedAt: new Date(terminal.created_at).toISOString(),
stageCount: stages.length, publications: pubs.length, nativeOutcomes } }
} catch { throw new ServerPollHistoryInvalid() }
}
/** Fixed historical cryptographic purposes. Does not consult or renew the old
* grant, execute SQL/native work, or issue any execution/maintenance capability. */
export async function verifyServerPollHistory(rows: ServerPollHistoryRows): Promise<VerifiedServerPollHistory> {
const security = await import("../modules/mcp/security.js")
const signers = new Map<string, Promise<(value: string) => string>>()
const signer = (domain: string) => {
let value = signers.get(domain)
if (!value) { value = security.privateFingerprinter(domain); signers.set(domain, value) }
return value
}
return verify(rows, { crypto: { decrypt: security.decryptSecret, proof: async (domain, value) => (await signer("server-poll-journal-v1:" + domain))(security.fingerprint(value)) },
executionProof: async value => (await signer("server-poll-production-v1"))(security.fingerprint(value)) })
}
/** Isolated test dependencies only; never a caller signer or production input. */
export const verifyServerPollHistoryForTests = (rows: ServerPollHistoryRows, deps: HistoryDependencies) => verify(rows, deps)