58 lines
4.1 KiB
TypeScript
58 lines
4.1 KiB
TypeScript
import type { PoolClient } from "pg"
|
|
import { z } from "zod"
|
|
import { fingerprint, McpError, privateFingerprinterExisting } from "./security.js"
|
|
import type { RoutingSwitchLedgerEntry } from "./routing-switch-ledger-contract.js"
|
|
import { readRoutingChargeJournal } from "./routing-charge-journal.js"
|
|
import { stageRoutingChargeWitness } from "./routing-reservation-transaction.js"
|
|
|
|
const action = "routing.charge.admitted"
|
|
const uuid = z.string().uuid(), digest = z.string().regex(/^[a-f0-9]{64}$/)
|
|
const anchor = z.object({ revision: z.literal(1), profileId: uuid, connectionId: uuid, ownerId: z.string().min(1).max(1000),
|
|
sourceOperationId: uuid, allocationId: uuid, kind: z.enum(["forward", "manual-inverse", "reserved"]),
|
|
bindingDigest: digest, createdAt: z.string().datetime() }).strict()
|
|
const envelope = z.object({ anchor, mac: digest }).strict()
|
|
type Anchor = z.infer<typeof anchor>
|
|
const signer = () => privateFingerprinterExisting("routing-charge-audit-v1")
|
|
const fail = () => new McpError("STATE_CONFLICT", "Учёт переключений не совпал с журналом допуска", 409)
|
|
|
|
/** Run on the same transaction that creates the charge. No authority is issued. */
|
|
export async function recordRoutingChargeAnchor(db: PoolClient,
|
|
input: Omit<Anchor, "revision" | "bindingDigest"> & { bindingProof: string }, deadline: number) {
|
|
const { bindingProof, ...fields } = input
|
|
const binding = anchor.parse({ ...fields, revision: 1, bindingDigest: fingerprint(bindingProof) })
|
|
const mac = (await signer())(fingerprint(binding))
|
|
const result = await db.query(`INSERT INTO mcp_audit (actor_id,action,connection_id,payload,created_at)
|
|
VALUES ($1,$2,$3,$4::jsonb,$5)`, [binding.ownerId, action, binding.connectionId, JSON.stringify({ anchor: binding, mac }), binding.createdAt])
|
|
if (result.rowCount !== 1) throw fail()
|
|
stageRoutingChargeWitness(db, binding.profileId, { allocationId: binding.allocationId, createdAt: binding.createdAt, auditMac: mac }, deadline)
|
|
}
|
|
|
|
/** The surviving audit is an independent witness of recent charges. Earlier
|
|
* charges remain readable without an audit anchor. */
|
|
export async function assertRoutingChargeAudit(db: PoolClient, profileId: string, owner: { id: string; owner_id: string }, now: number,
|
|
entries: readonly RoutingSwitchLedgerEntry[]) {
|
|
const { rows } = await db.query(`SELECT actor_id,created_at,
|
|
CASE WHEN octet_length(payload::text)<=4096 THEN payload END AS payload
|
|
FROM mcp_audit WHERE action='${action}' AND connection_id=$1 AND payload->'anchor'->>'profileId'=$2 AND created_at>$3
|
|
ORDER BY created_at,id LIMIT 12`, [owner.id, profileId, new Date(now - 3600000)])
|
|
if (rows.length > 11) throw fail()
|
|
const witnesses = await readRoutingChargeJournal(profileId, now)
|
|
if (!rows.length && !witnesses.length) return
|
|
const sign = await signer(), seen = new Map<string, string>()
|
|
for (const row of rows) {
|
|
const parsed = envelope.safeParse(row.payload)
|
|
if (!parsed.success) throw fail()
|
|
const { anchor: binding, mac } = parsed.data
|
|
if (binding.profileId !== profileId || binding.connectionId !== owner.id || binding.ownerId !== owner.owner_id ||
|
|
row.actor_id !== binding.ownerId || !(row.created_at instanceof Date) || row.created_at.getTime() !== Date.parse(binding.createdAt) ||
|
|
row.created_at.getTime() > now || mac !== sign(fingerprint(binding)) || seen.has(binding.allocationId)) throw fail()
|
|
seen.set(binding.allocationId, mac)
|
|
const expected = binding.kind === "reserved" ? ["forward", "inverse"] : [binding.kind === "forward" ? "forward" : "inverse"]
|
|
const matching = entries.filter(entry => entry.allocationId === binding.allocationId)
|
|
if (matching.length !== expected.length || expected.some(lane => !matching.some(entry => entry.lane === lane)) ||
|
|
matching.some(entry => entry.profileId !== profileId || entry.sourceOperationId !== binding.sourceOperationId ||
|
|
entry.createdAt !== binding.createdAt || fingerprint(entry.sourceIdentity) !== binding.bindingDigest)) throw fail()
|
|
}
|
|
if (witnesses.some(witness => seen.get(witness.allocationId) !== witness.auditMac)) throw fail()
|
|
}
|