228 lines
24 KiB
TypeScript
228 lines
24 KiB
TypeScript
import { isDeepStrictEqual } from "node:util"
|
|
import { z } from "zod"
|
|
import type { ServerProbeJournal, ServerProbeJournalBinding, ServerProbeReceipt } from "./server-probe-execution.js"
|
|
import { ProbePayloadExpired, ProbePayloadUnavailable, type ServerProbeStorageJournalBoundary } from "./server-probe-storage-journal-adapter.js"
|
|
|
|
const uuid = z.string().uuid(), hash = z.string().regex(/^[a-f0-9]{64}$/), toolSchema = z.enum(["ping", "traceroute", "bandwidth", "dns", "route", "mtu"])
|
|
const actor = z.string().min(1).max(200).refine(value => value.trim() === value && !/[\x00-\x1f\x7f]/.test(value))
|
|
const baseIdentity = { ownerId: actor, executionId: uuid, issuedAt: z.number().int().nonnegative().safe(), expiresAt: z.number().int().positive().safe() }
|
|
const identitySchema = z.discriminatedUnion("kind", [
|
|
z.object({ ...baseIdentity, kind: z.literal("mcp"), connectionId: uuid, credentialId: uuid, operationName: z.string().regex(/^[a-z][a-z0-9_.]{0,199}$/) }).strict(),
|
|
z.object({ ...baseIdentity, kind: z.literal("rest"), requestId: actor, authentication: z.enum(["jwt", "local"]) }).strict(),
|
|
])
|
|
/** MCP executionId is the ACTUAL mcp_operations.id, never a made-up owner or
|
|
* plan. REST executionId belongs to a trusted request execution; requestId and
|
|
* issuedAt come from the real JWT/local accepted request, never request JSON.
|
|
* Local identity may be selected only by the AUTH_REQUIRED=false host adapter. */
|
|
export type ServerProbeJournalIdentity = z.infer<typeof identitySchema>
|
|
export interface ServerProbeJournalContext { identity: ServerProbeJournalIdentity; sourceServerId: number; destinationServerId?: number; tool: z.infer<typeof toolSchema> }
|
|
export interface ProbeJournalSql { query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> }
|
|
export interface ProbeJournalConnection extends ProbeJournalSql { release(destroy?: boolean): void }
|
|
export interface ProbeJournalConnections { connect(): Promise<ProbeJournalConnection> }
|
|
export interface ProbeJournalCrypto { encrypt(value: string): Promise<string>; decrypt(value: string): Promise<string>; proof(domain: string, value: unknown): Promise<string> }
|
|
export interface ServerProbeJournalDependencies {
|
|
/** Fresh trusted owner/credential/policy/protections + full source/destination
|
|
* epoch/credential checks for this real execution. Quarantine intentionally
|
|
* bypasses revocable access so loss after revocation remains durable. */
|
|
assertAuthority(context: Readonly<ServerProbeJournalContext>, bindingProof: string): Promise<void>
|
|
connections?: ProbeJournalConnections; crypto?: ProbeJournalCrypto; now?: () => number
|
|
/** Explicit opt-in v2 schema only. Default journal/0035 remain unchanged. */
|
|
storageBoundary?: ServerProbeStorageJournalBoundary
|
|
}
|
|
const ownedConnections: ProbeJournalConnections = { async connect() { return (await import("../db/index.js")).pool.connect() } }
|
|
const privateCrypto: ProbeJournalCrypto = {
|
|
async encrypt(value) { return (await import("../modules/mcp/security.js")).encryptSecret(value) },
|
|
async decrypt(value) { return (await import("../modules/mcp/security.js")).decryptSecret(value) },
|
|
async proof(domain, value) { const security = await import("../modules/mcp/security.js"); return security.privateSecretFingerprint(security.fingerprint(value), "server-probe-journal-v1:" + domain) },
|
|
}
|
|
export class ServerProbeJournalConflict extends Error { readonly automaticReplay = false; constructor() { super("Probe journal refused: execution, binding, authority or immutable state mismatch; no replay") } }
|
|
export class ServerProbeJournalOutcomeUnknown extends Error { readonly automaticReplay = false; readonly requiresDurableQuarantine = true; constructor() { super("Probe journal commit outcome unknown; durable quarantine required, no retry or dispatch") } }
|
|
function must(condition: unknown): asserts condition { if (!condition) throw new ServerProbeJournalConflict() }
|
|
const counts = z.object({ attemptedStages: z.number().int().min(0).max(11), completedStages: z.number().int().min(0).max(11) }).refine(value => value.completedStages <= value.attemptedStages)
|
|
const receiptSchema = z.object({ receiptId: uuid, tool: toolSchema, serverId: z.number().int().positive().safe(), destinationServerId: z.number().int().positive().safe().optional(), state: z.enum(["completed", "failed", "cancelled", "unknown"]), httpStatus: z.number().int().min(200).max(599), output: z.string().max(131072).optional(), data: z.record(z.string(), z.unknown()).optional(), errorCode: z.string().regex(/^[A-Z_]{1,64}$/).optional(), attemptedStages: z.number().int().min(0).max(11), completedStages: z.number().int().min(0).max(11), automaticReplay: z.literal(false), forwardingVerified: z.literal(false) }).strict()
|
|
const failureCodes = new Set(["INVALID_INPUT", "NOT_FOUND", "DESTINATION_UNAVAILABLE", "SOURCE_UNAVAILABLE", "PERMISSION_DENIED", "STATE_CONFLICT", "CANCELLED", "JOURNAL_UNKNOWN", "REPLAY_FORBIDDEN", "INVALID_ADAPTER", "INVALID_BINDING", "UPSTREAM_UNAVAILABLE", "MEASUREMENT_UNKNOWN", "RECEIPT_INVALID", "UNCLASSIFIED_FAILURE"])
|
|
const sizes = [1500, 1492, 1480, 1476, 1472, 1468, 1400, 1280, 1024, 576]
|
|
interface Stage extends Record<string, unknown> { stage_index: number; kind: string; timeout_ms: number; state: "intent" | "received"; outcome?: string }
|
|
|
|
/** Protocol parsers shared with internal legacy inspection. Parsing is not an
|
|
* execution grant, current authorization or database-source attestation. */
|
|
export function parseServerProbeJournalContext(rawContext: ServerProbeJournalContext): ServerProbeJournalContext {
|
|
const identity = identitySchema.parse(structuredClone(rawContext.identity)), context: ServerProbeJournalContext = { identity, sourceServerId: z.number().int().positive().max(2147483647).parse(rawContext.sourceServerId), ...(rawContext.destinationServerId !== undefined ? { destinationServerId: z.number().int().positive().max(2147483647).parse(rawContext.destinationServerId) } : {}), tool: toolSchema.parse(rawContext.tool) }
|
|
must((context.tool === "bandwidth") === (context.destinationServerId !== undefined))
|
|
return context
|
|
}
|
|
export function validateServerProbeJournalReceipt(context: ServerProbeJournalContext, receiptId: string, value: ServerProbeReceipt) {
|
|
const receipt = receiptSchema.parse(structuredClone(value)); counts.parse(receipt)
|
|
const json = (value: unknown, depth = 0): void => { must(depth <= 16); if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return; must(value && typeof value === "object" && (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype)); for (const child of Object.values(value)) json(child, depth + 1) }
|
|
json(receipt)
|
|
must(receipt.receiptId === receiptId && receipt.tool === context.tool && receipt.serverId === context.sourceServerId && receipt.destinationServerId === context.destinationServerId && receipt.state !== "unknown" && Buffer.byteLength(JSON.stringify(receipt)) <= 131072)
|
|
if (receipt.state === "completed") must(receipt.httpStatus === 200 && receipt.output !== undefined && receipt.data?.kind === context.tool && receipt.errorCode === undefined && receipt.attemptedStages >= 1 && receipt.attemptedStages === receipt.completedStages)
|
|
else must(receipt.httpStatus >= 400 && receipt.output === undefined && receipt.data === undefined && !!receipt.errorCode && failureCodes.has(receipt.errorCode))
|
|
return receipt
|
|
}
|
|
|
|
/** Own a fresh connection and transaction for EVERY durable method. Never use
|
|
* a caller's transaction: its rollback must not resurrect a spent attempt. */
|
|
export function createSqlServerProbeJournal(rawContext: ServerProbeJournalContext, deps: ServerProbeJournalDependencies): ServerProbeJournal {
|
|
const context = parseServerProbeJournalContext(rawContext), identity = context.identity
|
|
must(typeof deps.assertAuthority === "function")
|
|
deps.storageBoundary?.assertContext(context)
|
|
const scope = [...new Set([context.sourceServerId, ...(context.destinationServerId !== undefined ? [context.destinationServerId] : [])])], codec = deps.crypto ?? privateCrypto, now = deps.now ?? Date.now
|
|
let pinned: { receiptId: string; bindingProof: string } | undefined
|
|
const pin = (receiptId: string, bindingProof: string) => { uuid.parse(receiptId); hash.parse(bindingProof); if (pinned) must(pinned.receiptId === receiptId && pinned.bindingProof === bindingProof); else pinned = { receiptId, bindingProof }; return pinned }
|
|
const metadata = (value: ServerProbeJournalBinding) => {
|
|
must(value.ownerId === identity.ownerId && value.tool === context.tool && isDeepStrictEqual(value.serverIds, scope) && (value.transport ?? "mcp") === identity.kind)
|
|
if (identity.kind === "mcp") must(value.connectionId === identity.connectionId && value.requestId === undefined && (value.issuedAt === undefined || value.issuedAt === identity.issuedAt))
|
|
else must(value.connectionId === undefined && value.requestId === identity.requestId && value.issuedAt === identity.issuedAt)
|
|
return pin(value.receiptId, value.bindingProof)
|
|
}
|
|
const guard = async (bindingProof: string) => { must(now() < identity.expiresAt); await deps.assertAuthority(structuredClone(context), bindingProof); must(now() < identity.expiresAt) }
|
|
const transaction = async <T>(work: (sql: ProbeJournalSql) => Promise<T>, operation: "claim" | "publish" | "intent" | "received" | "read" | "quarantine" = "read", payload?: { ciphertext: string; proof: string }): Promise<T> => {
|
|
if (deps.storageBoundary) {
|
|
const locked = async (sql: ProbeJournalSql) => {
|
|
await sql.query("/* probe-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`server-probe-journal-v1:${identity.kind}:${identity.executionId}`])
|
|
await sql.query("/* probe-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`server-probe-journal-receipt-v1:${pinned!.receiptId}`])
|
|
return work(sql)
|
|
}
|
|
if (operation === "claim") return deps.storageBoundary.claim(pinned!, locked)
|
|
if (operation === "publish") { must(payload); return deps.storageBoundary.publish(pinned!, payload.ciphertext, payload.proof, locked) }
|
|
return deps.storageBoundary.transaction(pinned!, operation, locked)
|
|
}
|
|
let connection: ProbeJournalConnection
|
|
try { connection = await (deps.connections ?? ownedConnections).connect() } catch { throw new ServerProbeJournalOutcomeUnknown() }
|
|
let beginSent = false, begun = false, commitSent = false, committed = false, destroy = false
|
|
try {
|
|
beginSent = true; await connection.query("BEGIN"); begun = true
|
|
await connection.query("/* probe-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`server-probe-journal-v1:${identity.kind}:${identity.executionId}`])
|
|
await connection.query("/* probe-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`server-probe-journal-receipt-v1:${pinned!.receiptId}`])
|
|
const result = await work(connection)
|
|
commitSent = true; await connection.query("COMMIT"); committed = true
|
|
return result
|
|
} catch (error) {
|
|
if (beginSent && !begun || commitSent && !committed) { destroy = true; throw new ServerProbeJournalOutcomeUnknown() }
|
|
if (begun && !committed) { try { await connection.query("ROLLBACK") } catch { destroy = true } }
|
|
throw error instanceof ServerProbeJournalConflict ? error : new ServerProbeJournalConflict()
|
|
} finally { connection.release(destroy) }
|
|
}
|
|
const rows = async (sql: ProbeJournalSql, table: "server_probe_executions" | "server_probe_execution_quarantines") => (await sql.query(`/* probe-journal:${table} */ SELECT * FROM ${table} WHERE receipt_id=$1 OR (identity_kind=$2 AND execution_id=$3) FOR UPDATE`, [pinned!.receiptId, identity.kind, identity.executionId])).rows
|
|
const identityProof = () => codec.proof("identity", context)
|
|
const checkAnchor = (row: Record<string, unknown>) => {
|
|
must(row.receipt_id === pinned!.receiptId && row.binding_proof === pinned!.bindingProof && row.identity_kind === identity.kind && row.execution_id === identity.executionId && row.actor_id === identity.ownerId && row.authentication === (identity.kind === "mcp" ? "mcp" : identity.authentication) && row.mcp_connection_id === (identity.kind === "mcp" ? identity.connectionId : null) && row.mcp_credential_id === (identity.kind === "mcp" ? identity.credentialId : null) && row.request_id === (identity.kind === "rest" ? identity.requestId : null) && String(row.authority_issued_at) === String(identity.issuedAt) && new Date(row.authority_expires_at as string | Date).getTime() === identity.expiresAt && row.source_server_id === context.sourceServerId && row.destination_server_id === (context.destinationServerId ?? null) && row.tool === context.tool)
|
|
}
|
|
const checkQuarantine = async (row: Record<string, unknown>) => { must(row.receipt_id === pinned!.receiptId && row.binding_proof === pinned!.bindingProof && row.identity_kind === identity.kind && row.execution_id === identity.executionId && row.identity_proof === await identityProof()) }
|
|
const requireAnchor = async (sql: ProbeJournalSql, executable: boolean) => {
|
|
const quarantines = await rows(sql, "server_probe_execution_quarantines"); must(quarantines.length === 0)
|
|
const anchors = await rows(sql, "server_probe_executions"); must(anchors.length === 1); checkAnchor(anchors[0]); if (executable) must(anchors[0].state === "claimed")
|
|
return anchors[0]
|
|
}
|
|
const sqlAuthority = async (sql: ProbeJournalSql, freshClaim: boolean) => {
|
|
const servers = await sql.query("/* probe-journal:servers */ SELECT id FROM servers WHERE id=ANY($1::int[]) AND enabled=true", [scope]); must(servers.rows.length === scope.length)
|
|
if (identity.kind === "mcp") {
|
|
const owner = await sql.query(`/* probe-journal:owner */ SELECT o.id 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_credentials k ON k.connection_id=c.id
|
|
WHERE o.id=$1 AND c.id=$2 AND c.owner_id=$3 AND k.id=$4 AND k.revoked_at IS NULL AND k.expires_at>clock_timestamp()
|
|
AND c.owner_valid_until>clock_timestamp() AND c.policy->>'status'='active' AND c.policy->>'mode'<>'observer'
|
|
AND (c.policy->>'expiresAt')::timestamptz>clock_timestamp() AND c.policy#>'{scope,serverIds}' @> $5::jsonb
|
|
AND c.policy#>'{scope,operationIds}' @> to_jsonb(ARRAY[$6::text]) AND p.operation_id=$6
|
|
${freshClaim ? "AND o.state IN ('pending','running') AND p.state='executing'" : ""}`, [identity.executionId, identity.connectionId, identity.ownerId, identity.credentialId, JSON.stringify(scope), identity.operationName])
|
|
must(owner.rows.length === 1)
|
|
}
|
|
}
|
|
const stageRows = async (sql: ProbeJournalSql): Promise<Stage[]> => (await sql.query("/* probe-journal:stages */ SELECT * FROM server_probe_execution_stages WHERE receipt_id=$1 ORDER BY stage_index FOR UPDATE", [pinned!.receiptId])).rows as Stage[]
|
|
const assertStage = (prior: Stage[], kind: string, index: number, timeoutMs: number) => {
|
|
must(index === prior.length + 1 && index <= 11 && prior.every((stage, offset) => stage.stage_index === offset + 1 && stage.state === "received") && Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= (context.tool === "ping" ? 120000 : context.tool === "traceroute" ? 58000 : context.tool === "mtu" ? 25000 : context.tool === "route" ? 10000 : 30000))
|
|
if (kind === "source-dns-A") { must(["ping", "traceroute", "mtu"].includes(context.tool) && index === 1 && timeoutMs <= 10000); return }
|
|
const native = prior.filter(stage => stage.kind !== "source-dns-A")
|
|
if (context.tool === "mtu") must(kind === `native-mtu-${sizes[native.length]}` && native.length < sizes.length)
|
|
else { must(native.length === 0); const expected = { ping: "native-ping", traceroute: "native-traceroute", bandwidth: "native-bandwidth", route: "native-route-read" }; must(context.tool === "dns" ? /^manager-dns-(A|AAAA|MX|NS|TXT|CNAME|PTR)$/.test(kind) : kind === expected[context.tool]) }
|
|
}
|
|
const validateReceipt = (value: ServerProbeReceipt) => validateServerProbeJournalReceipt(context, pinned!.receiptId, value)
|
|
return {
|
|
async claim(value) {
|
|
const binding = metadata(structuredClone(value)); await guard(binding.bindingProof)
|
|
return transaction(async sql => {
|
|
const quarantines = await rows(sql, "server_probe_execution_quarantines")
|
|
if (quarantines.length) { must(quarantines.length === 1); await checkQuarantine(quarantines[0]); return "exists" }
|
|
const existing = await rows(sql, "server_probe_executions")
|
|
if (existing.length) { must(existing.length === 1); checkAnchor(existing[0]); await sqlAuthority(sql, false); await guard(binding.bindingProof); return "exists" }
|
|
await sqlAuthority(sql, true); await guard(binding.bindingProof)
|
|
const result = await sql.query(`/* probe-journal:claim */ INSERT INTO server_probe_executions(receipt_id,binding_proof,identity_kind,execution_id,actor_id,authentication,mcp_connection_id,mcp_credential_id,request_id,authority_issued_at,authority_expires_at,source_server_id,destination_server_id,tool)
|
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) ON CONFLICT DO NOTHING RETURNING receipt_id`, [binding.receiptId, binding.bindingProof, identity.kind, identity.executionId, identity.ownerId, identity.kind === "mcp" ? "mcp" : identity.authentication, identity.kind === "mcp" ? identity.connectionId : null, identity.kind === "mcp" ? identity.credentialId : null, identity.kind === "rest" ? identity.requestId : null, identity.issuedAt, new Date(identity.expiresAt), context.sourceServerId, context.destinationServerId ?? null, context.tool])
|
|
must(result.rows.length === 1); await guard(binding.bindingProof); return "claimed"
|
|
}, "claim")
|
|
},
|
|
async intent(value) {
|
|
must(pinned && value.receiptId === pinned.receiptId); await guard(pinned.bindingProof)
|
|
await transaction(async sql => {
|
|
await requireAnchor(sql, true); await sqlAuthority(sql, false)
|
|
assertStage(await stageRows(sql), value.kind, value.stageIndex, value.timeoutMs); await guard(pinned!.bindingProof)
|
|
const inserted = await sql.query("/* probe-journal:intent */ INSERT INTO server_probe_execution_stages(receipt_id,stage_index,kind,timeout_ms) VALUES($1,$2,$3,$4) RETURNING stage_index", [value.receiptId, value.stageIndex, value.kind, value.timeoutMs]); must(inserted.rows.length === 1)
|
|
}, "intent")
|
|
},
|
|
async received(value) {
|
|
must(pinned && value.receiptId === pinned.receiptId && ["received", "source-unavailable"].includes(value.outcome)); await guard(pinned.bindingProof)
|
|
await transaction(async sql => {
|
|
await requireAnchor(sql, true); await sqlAuthority(sql, false)
|
|
const stages = await stageRows(sql), stage = stages[stages.length - 1]
|
|
must(stage && stage.stage_index === value.stageIndex && stage.state === "intent" && (value.outcome !== "source-unavailable" || stage.kind === "source-dns-A")); await guard(pinned!.bindingProof)
|
|
const changed = await sql.query("/* probe-journal:received */ UPDATE server_probe_execution_stages SET state='received',outcome=$3,received_at=clock_timestamp() WHERE receipt_id=$1 AND stage_index=$2 AND state='intent' RETURNING stage_index", [value.receiptId, value.stageIndex, value.outcome]); must(changed.rows.length === 1)
|
|
}, "received")
|
|
},
|
|
async finish(value) {
|
|
must(pinned); const receipt = validateReceipt(value); await guard(pinned.bindingProof)
|
|
const envelope = JSON.stringify({ version: 1, context, bindingProof: pinned.bindingProof, receipt }), ciphertext = await codec.encrypt(envelope), digest = await codec.proof("receipt", envelope)
|
|
must(Buffer.byteLength(ciphertext) <= 262144 && hash.safeParse(digest).success)
|
|
await transaction(async sql => {
|
|
await requireAnchor(sql, true); await sqlAuthority(sql, false)
|
|
const stages = await stageRows(sql), received = stages.filter(stage => stage.state === "received").length
|
|
must(received === receipt.completedStages && receipt.attemptedStages <= stages.length && stages.length - receipt.attemptedStages <= 1)
|
|
if (receipt.state === "completed") must(received === stages.length && stages.length === receipt.attemptedStages)
|
|
await guard(pinned!.bindingProof)
|
|
const changed = deps.storageBoundary
|
|
? await sql.query("/* probe-journal:finish-stored */ UPDATE server_probe_executions SET state=$2,attempted_stages=$3,completed_stages=$4,receipt_proof=$5,finished_at=clock_timestamp() WHERE receipt_id=$1 AND state='claimed' RETURNING receipt_id", [pinned!.receiptId, receipt.state, receipt.attemptedStages, receipt.completedStages, digest])
|
|
: await sql.query("/* probe-journal:finish */ UPDATE server_probe_executions SET state=$2,attempted_stages=$3,completed_stages=$4,receipt_ciphertext=$5,receipt_proof=$6,finished_at=clock_timestamp() WHERE receipt_id=$1 AND state='claimed' RETURNING receipt_id", [pinned!.receiptId, receipt.state, receipt.attemptedStages, receipt.completedStages, ciphertext, digest]); must(changed.rows.length === 1)
|
|
}, "publish", { ciphertext, proof: digest })
|
|
},
|
|
async quarantine(value) {
|
|
const binding = metadata(structuredClone(value)); counts.parse(value)
|
|
const digest = await identityProof(), code = failureCodes.has(value.errorCode) ? value.errorCode : "UNCLASSIFIED_FAILURE"
|
|
await transaction(async sql => {
|
|
const anchors = await rows(sql, "server_probe_executions"); must(anchors.length <= 1); if (anchors.length) checkAnchor(anchors[0])
|
|
const existing = await rows(sql, "server_probe_execution_quarantines")
|
|
if (existing.length) { must(existing.length === 1); await checkQuarantine(existing[0]); return }
|
|
const result = await sql.query("/* probe-journal:quarantine */ INSERT INTO server_probe_execution_quarantines(receipt_id,binding_proof,identity_kind,execution_id,identity_proof,error_code,attempted_stages,completed_stages) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT DO NOTHING RETURNING receipt_id", [binding.receiptId, binding.bindingProof, identity.kind, identity.executionId, digest, code, value.attemptedStages, value.completedStages]); must(result.rows.length === 1)
|
|
}, "quarantine")
|
|
},
|
|
async read(receiptId, bindingProof) {
|
|
pin(receiptId, bindingProof); await guard(bindingProof)
|
|
const result = await transaction(async sql => {
|
|
const quarantines = await rows(sql, "server_probe_execution_quarantines")
|
|
if (quarantines.length) {
|
|
must(quarantines.length === 1); const row = quarantines[0]; await checkQuarantine(row)
|
|
const progress = counts.parse({ attemptedStages: row.attempted_stages, completedStages: row.completed_stages })
|
|
await guard(bindingProof)
|
|
return { receiptId, tool: context.tool, serverId: context.sourceServerId, ...(context.destinationServerId !== undefined ? { destinationServerId: context.destinationServerId } : {}), state: "unknown" as const, httpStatus: 503, errorCode: "JOURNAL_UNKNOWN", ...progress, automaticReplay: false as const, forwardingVerified: false as const }
|
|
}
|
|
const anchors = await rows(sql, "server_probe_executions"); if (!anchors.length) return undefined
|
|
must(anchors.length === 1); const row = anchors[0]; checkAnchor(row); await sqlAuthority(sql, false)
|
|
if (row.state === "claimed") return undefined
|
|
let ciphertext = row.receipt_ciphertext
|
|
if (deps.storageBoundary) {
|
|
const stored = await deps.storageBoundary.readPayload(pinned!, sql)
|
|
if (stored.kind === "expired") throw new ProbePayloadExpired()
|
|
if (stored.kind === "unavailable") throw new ProbePayloadUnavailable()
|
|
ciphertext = stored.ciphertext; must(stored.proof === row.receipt_proof)
|
|
}
|
|
must(typeof ciphertext === "string" && Buffer.byteLength(ciphertext) <= 262144 && typeof row.receipt_proof === "string")
|
|
const plaintext = await codec.decrypt(ciphertext); must(Buffer.byteLength(plaintext) <= 150000 && await codec.proof("receipt", plaintext) === row.receipt_proof)
|
|
const envelope = JSON.parse(plaintext) as { version?: unknown; context?: unknown; bindingProof?: unknown; receipt?: unknown }
|
|
must(envelope.version === 1 && isDeepStrictEqual(envelope.context, context) && envelope.bindingProof === bindingProof)
|
|
const receipt = validateReceipt(envelope.receipt as ServerProbeReceipt)
|
|
must(row.state === receipt.state && row.attempted_stages === receipt.attemptedStages && row.completed_stages === receipt.completedStages)
|
|
await guard(bindingProof); return receipt
|
|
})
|
|
await guard(bindingProof); return result
|
|
},
|
|
}
|
|
}
|