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

172 lines
13 KiB
TypeScript

/** Fixed read-only archive lookup. Its current-authority callback is supplied
* by the already authorized global reconciliation action, never request JSON.
* Original credentials authenticate history only; they are never renewed. */
import { z } from "zod"
import { decryptSecret, fingerprint, privateSecretFingerprint } from "../modules/mcp/security.js"
import { canonicalPollArchiveTimestamp, openServerPollTerminalArchive } from "./server-poll-terminal-archive.js"
import { openServerPollRetiredArchive } from "./server-poll-retired-archive.js"
export interface ServerPollHistoryReadWindow { deadlineAt: number; signal?: AbortSignal }
type Query = (text: string, values: unknown[], options: ServerPollHistoryReadWindow) => Promise<Record<string, unknown>[]>
interface Dependencies {
query: Query; decrypt: typeof decryptSecret; bindingProof(value: unknown): Promise<string>
openArchive: typeof openServerPollTerminalArchive; now(): number
}
const uuid=z.string().uuid(),hash=z.string().regex(/^[a-f0-9]{64}$/),sid=z.number().int().positive().safe()
const inputSchema=z.object({serverId:sid,receiptId:uuid,inputDigest:hash,bindingCiphertext:z.string().min(1).max(2097152)}).strict()
const bindingSchema=z.object({version:z.literal(1),operation:z.literal("servers.poll"),
principal:z.object({connectionId:uuid,credentialId:uuid,credentialExpiresAt:z.string().datetime()}).strict(),
ownerId:z.string().min(1).max(200),issuedAt:z.number().int().nonnegative().safe(),expiresAt:z.number().int().positive().safe(),
plan:z.object({request:z.object({serverId:sid,receiptId:uuid}).strict()}).passthrough()}).strict()
const QUERY=`SELECT r.version,r.receipt_id,r.execution_id,r.connection_id,r.owner_id,r.binding_proof,r.context_proof,
r.source_digest,r.source_sha256,r.terminal_digest,r.decoded_bytes,r.compressed_bytes,r.archive_proof,
to_char(r.original_activity_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS original_activity_at,
to_char(r.original_expires_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS original_expires_at,
a.retention_days,a.safety_ms,octet_length(r.ciphertext) AS ciphertext_bytes,
pg_catalog.encode(pg_catalog.sha256(pg_catalog.convert_to(r.ciphertext,'UTF8')),'hex') AS ciphertext_sha256,
CASE WHEN octet_length(r.ciphertext)<=131072 THEN r.ciphertext END AS ciphertext,
CASE WHEN octet_length(to_jsonb(a)::text)<=1048576 THEN to_jsonb(a) END AS current_admission,
CASE WHEN octet_length(to_jsonb(o)::text)+octet_length(to_jsonb(p)::text)+octet_length(to_jsonb(s)::text)<=16777216
THEN jsonb_build_object('operation',to_jsonb(o),'plan',to_jsonb(p),'step',to_jsonb(s)) END AS current_terminal
FROM public.server_poll_archives r JOIN public.server_poll_storage_admissions a USING(receipt_id)
JOIN public.mcp_connections c ON c.id=a.connection_id AND c.owner_id=a.owner_id
JOIN public.mcp_operations o ON o.id=a.execution_id AND o.connection_id=a.connection_id
JOIN public.mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id
JOIN public.mcp_operation_steps s ON s.operation_id=o.id AND s.step_index=0
WHERE a.receipt_id=$1 AND a.connection_id=$2 AND a.owner_id=$3 AND a.identity_kind='mcp' AND a.storage_state='compacted'
AND r.execution_id=a.execution_id AND r.connection_id=a.connection_id AND r.owner_id=a.owner_id
AND r.binding_proof=a.binding_proof AND r.context_proof=a.context_proof AND r.ciphertext_bytes=a.archive_bytes AND r.ciphertext_bytes=octet_length(r.ciphertext)
AND r.original_activity_at=a.original_activity_at AND r.original_expires_at=a.authority_expires_at
AND o.state='applied' AND o.verification='passed' AND o.error_code IS NULL AND o.finished_at IS NOT NULL
AND p.operation_id='servers.poll' AND p.operation_version=1 AND p.state='completed' AND p.approved_by IS NOT NULL
AND s.state='verified' AND s.server_id IS NULL AND s.finished_at IS NOT NULL
AND (SELECT count(*) FROM public.mcp_operation_steps all_steps WHERE all_steps.operation_id=o.id)=1 LIMIT 2`
const fail=():never=>{throw Error("Archived poll history is unavailable")}
const record=(value:unknown):value is Record<string,unknown>=>!!value&&typeof value==="object"&&!Array.isArray(value)
function withoutPhase(raw:Record<string,unknown>){
const result={...raw};for(const name of ["storage_state","compact_at","archive_bytes","original_activity_at"])delete result[name]
return result
}
async function read(raw:Record<string,unknown>,currentAuthorize:()=>Promise<unknown>,rawWindow:ServerPollHistoryReadWindow,deps:Dependencies):Promise<boolean>{
let authFailed=false,authError:unknown
try{
const input=inputSchema.parse(structuredClone(raw)),options=Object.freeze({...rawWindow,deadlineAt:Math.min(rawWindow.deadlineAt,deps.now()+180000)})
const live=()=>{if(!Number.isSafeInteger(options.deadlineAt)||deps.now()>=options.deadlineAt||options.signal?.aborted)fail()}
const authorize=async()=>{live();try{await currentAuthorize()}catch(error){authFailed=true;authError=error;throw error};live()}
const decrypt=async(text:string,limit:number)=>{
if(typeof text!=="string"||Buffer.byteLength(text)>limit*2)fail()
await authorize();const opened=await deps.decrypt(text);await authorize()
if(Buffer.byteLength(opened)>limit)fail();return JSON.parse(opened) as unknown
}
const binding=bindingSchema.parse(await decrypt(input.bindingCiphertext,1048576))
await authorize();const proof=await deps.bindingProof(binding);await authorize()
if(proof!==input.inputDigest||binding.plan.request.receiptId!==input.receiptId||binding.plan.request.serverId!==input.serverId||
binding.expiresAt<=binding.issuedAt||binding.issuedAt>deps.now()||binding.expiresAt>Date.parse(binding.principal.credentialExpiresAt))fail()
await authorize()
const rows=await deps.query(QUERY,[input.receiptId,binding.principal.connectionId,binding.ownerId],options)
await authorize()
if(rows.length!==1)return false
const row=structuredClone(rows[0])
if(row.receipt_id!==input.receiptId||row.connection_id!==binding.principal.connectionId||row.owner_id!==binding.ownerId||
!record(row.current_admission)||!record(row.current_terminal))fail()
await authorize()
// One bounded private decrypt/history/terminal verification boundary. It
// performs no SQL, native effects or publication while authority is checked.
const opened=await deps.openArchive(row,deps.now())
await authorize()
const original=opened.source,current=row.current_admission as Record<string,unknown>
if(original.admission.storage_state!=="full"||current.storage_state!=="compacted"||
fingerprint(withoutPhase(original.admission))!==fingerprint(withoutPhase(current))||
fingerprint(original.terminal)!==fingerprint(row.current_terminal))fail()
const originalEvidence=original.terminal.plan.evidence
if(!record(originalEvidence)||typeof originalEvidence.sealed!=="string")return fail()
const evidence=await decrypt(originalEvidence.sealed,2097152)
if(!record(evidence)||!Array.isArray(evidence.steps)||evidence.steps.length!==1||!record(evidence.steps[0]))return fail()
const step=evidence.steps[0]
if(step.kind!=="service"||step.service!=="servers.poll"||fingerprint(step.input)!==fingerprint(input))fail()
await authorize()
const fresh=await deps.query(QUERY,[input.receiptId,binding.principal.connectionId,binding.ownerId],options)
await authorize()
if(fresh.length!==1||fingerprint(fresh[0])!==fingerprint(row))fail()
await authorize()
return true
}catch{if(authFailed)throw authError;return false}
}
const production:Dependencies={
query:async(text,values,options)=>(await import("../modules/mcp/server-poll-production.js")).queryServerPollMcpMetadata(text,values,options),
decrypt:decryptSecret,bindingProof:value=>privateSecretFingerprint(fingerprint(value),"server-poll-mcp-binding-v1"),
openArchive:openServerPollTerminalArchive,now:Date.now,
}
export const readServerPollArchivedHistory=(raw:Record<string,unknown>,authorize:()=>Promise<unknown>,options:ServerPollHistoryReadWindow)=>read(raw,authorize,options,production)
/** Explicit component-only composition. No public input selects these hooks. */
export const readServerPollArchivedHistoryForTests=(raw:Record<string,unknown>,authorize:()=>Promise<unknown>,options:ServerPollHistoryReadWindow,deps:Dependencies)=>read(raw,authorize,options,deps)
const RETIRED_QUERY = `SELECT r.version,r.receipt_id,r.execution_id,r.connection_id,r.owner_id,r.binding_proof,r.context_proof,
r.source_digest,r.source_sha256,r.terminal_digest,r.decoded_bytes,r.compressed_bytes,r.archive_proof,
to_char(r.original_activity_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS original_activity_at,
to_char(r.original_expires_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS original_expires_at,
to_char(a.gc_not_before AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS gc_not_before,
a.retention_days,a.safety_ms,octet_length(r.ciphertext) AS ciphertext_bytes,
pg_catalog.encode(pg_catalog.sha256(pg_catalog.convert_to(r.ciphertext,'UTF8')),'hex') AS ciphertext_sha256,
CASE WHEN octet_length(r.ciphertext)<=33000 THEN r.ciphertext END AS ciphertext,
t.plan_id,t.target_server_ids
FROM public.server_poll_archives r JOIN public.server_poll_storage_admissions a USING(receipt_id)
JOIN public.mcp_connections c ON c.id=a.connection_id AND c.owner_id=a.owner_id
JOIN public.mcp_operation_replay_tombstones t ON t.operation_id=a.execution_id AND t.connection_id=a.connection_id
WHERE r.execution_id=$1 AND a.execution_id=$1 AND a.connection_id=$2 AND a.owner_id=$3
AND a.identity_kind='mcp' AND a.storage_state='compacted' AND r.version=2
AND r.connection_id=a.connection_id AND r.owner_id=a.owner_id AND r.binding_proof=a.binding_proof AND r.context_proof=a.context_proof
AND r.ciphertext_bytes=a.archive_bytes AND r.ciphertext_bytes=octet_length(r.ciphertext)
AND r.original_activity_at=a.original_activity_at AND r.original_expires_at=a.authority_expires_at
AND t.action_id='servers.poll' AND t.target_global IS TRUE AND cardinality(t.target_server_ids) BETWEEN 1 AND 1000
AND NOT EXISTS(SELECT 1 FROM public.mcp_operations o WHERE o.id=t.operation_id)
AND NOT EXISTS(SELECT 1 FROM public.mcp_plans p WHERE p.id=t.plan_id)
AND NOT EXISTS(SELECT 1 FROM public.mcp_operation_steps s WHERE s.operation_id=t.operation_id)
LIMIT 2`
interface RetiredDependencies {
query: Query; now(): number; open: typeof openServerPollRetiredArchive
}
export interface RetiredSourceIdentity { operationId: string; connectionId: string; ownerId: string }
async function readRetired(identity: RetiredSourceIdentity, currentAuthorize: () => Promise<unknown>,
rawWindow: ServerPollHistoryReadWindow, deps: RetiredDependencies): Promise<{ affectedServerIds: number[] } | undefined> {
let authFailure: { error: unknown } | undefined
try {
const { operationId, connectionId, ownerId } = identity
if (!uuid.safeParse(operationId).success || !uuid.safeParse(connectionId).success || !ownerId || ownerId.length > 200) fail()
const options = Object.freeze({ ...rawWindow, deadlineAt: Math.min(rawWindow.deadlineAt, deps.now() + 180000) })
const live = () => { if (!Number.isSafeInteger(options.deadlineAt) || deps.now() >= options.deadlineAt || options.signal?.aborted) fail() }
const authorize = async () => {
live()
try { await currentAuthorize() } catch (error) { authFailure = { error }; throw error }
live()
}
const values = [operationId, connectionId, ownerId]
await authorize()
const rows = await deps.query(RETIRED_QUERY, values, options)
await authorize()
if (rows.length !== 1) return undefined
const row = structuredClone(rows[0])
const { metadata, history } = await deps.open(row)
await authorize()
if (metadata.execution_id !== operationId || metadata.connection_id !== connectionId || metadata.owner_id !== ownerId
|| history.planId !== row.plan_id || history.gcNotBefore !== canonicalPollArchiveTimestamp(row.gc_not_before)) fail()
const scope = z.array(z.union([sid, z.string().regex(/^[1-9]\d{0,15}$/).transform(Number).pipe(sid)])).min(1).max(1000).parse(row.target_server_ids)
if (scope.length !== history.affectedServerIds.length || new Set(scope).size !== scope.length
|| scope.some(id => !history.affectedServerIds.includes(id))) fail()
const fresh = await deps.query(RETIRED_QUERY, values, options)
await authorize()
if (fresh.length !== 1 || fingerprint(fresh[0]) !== fingerprint(row)) fail()
return { affectedServerIds: [...history.affectedServerIds] }
} catch {
if (authFailure) throw authFailure.error
return undefined
}
}
/** The caller owns current authority and independently checks returned scope. */
export const readRetiredServerPollHistory = (identity: RetiredSourceIdentity, authorize: () => Promise<unknown>, options: ServerPollHistoryReadWindow) =>
readRetired(identity, authorize, options, { query: production.query, now: Date.now, open: openServerPollRetiredArchive })
export const readRetiredServerPollHistoryForTests = readRetired