Files
MikrotikManager/backend/src/services/bandwidth-node-registry-catalog.ts
T

293 lines
27 KiB
TypeScript

import { createHash } from "node:crypto"
import { BANDWIDTH_ADMISSION_PROPOSAL_DDL } from "./bandwidth-admission-schema.js"
import { BANDWIDTH_NODE_REGISTRY_DDL } from "./bandwidth-node-registry-schema.js"
import { observeBandwidthExternalNodeRegistryCatalog,validateBandwidthExternalNodeRegistryCatalogRows } from "./bandwidth-external-node-registry-catalog.js"
/** Fixed component verification plus a canonical observation digest. No default
* I/O, DDL, role assertion, readiness or generation issuance. Constraint/index
* definitions are captured for the fixed issuer's signed pin; their structural
* checks below are not a general proof of arbitrary SQL expression equivalence.
* The core truncate function referenced by registry guards is independently
* checked against the core literal here, including its owner/path/signature. */
export interface BandwidthNodeRegistryCatalogSql { query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> }
export class BandwidthNodeRegistryCatalogRefused extends Error {
readonly code = "BANDWIDTH_NODE_REGISTRY_CATALOG_REFUSED"
constructor() { super("Bandwidth node registry catalog refused") }
}
type Row = Record<string, unknown>
const tableNames = ["bandwidth_node_authority", "bandwidth_nodes", "bandwidth_node_aliases", "bandwidth_node_events"] as const
const functionNames = ["bandwidth_node_authority_guard", "bandwidth_node_immutable_guard", "bandwidth_node_alias_guard", "bandwidth_node_event_guard", "bandwidth_node_alias_consistency_guard", "bandwidth_admission_reject_truncate"] as const
const normalizeBody = (value: string) => value.replace(/\r\n?/g, "\n").trim()
function expectedBodies(): Map<string, string> {
const found = new Map<string, string>()
for (const ddl of [BANDWIDTH_ADMISSION_PROPOSAL_DDL, BANDWIDTH_NODE_REGISTRY_DDL]) {
for (const match of ddl.matchAll(/CREATE FUNCTION mmapp_control\.([a-z_]+)\([\s\S]*?\)\s+RETURNS\s+(?:boolean|trigger)[\s\S]*?\bAS\s+\$body\$([\s\S]*?)\$body\$;/g)) {
if (!functionNames.includes(match[1] as typeof functionNames[number])) continue
if (found.has(match[1])) refuse()
found.set(match[1], normalizeBody(match[2]))
}
}
if (found.size !== functionNames.length || functionNames.some(name => !found.has(name))) refuse()
return found
}
const sections = { namespace: 1, tables: 4, columns: 26, functions: 6, triggers: 22, constraints: 80, indexes: 9, rules: 0, policies: 0 } as const
export const BANDWIDTH_NODE_REGISTRY_CATALOG_SQL = `WITH component AS (
SELECT c.* FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
WHERE n.nspname='mmapp_control' AND c.relname=ANY(ARRAY['bandwidth_node_authority','bandwidth_nodes','bandwidth_node_aliases','bandwidth_node_events'])
), catalog AS MATERIALIZED (
SELECT 'namespace'::text AS section,pg_catalog.to_jsonb(q)::text AS raw_json FROM (
SELECT n.nspname::text AS name,o.rolname::text AS owner FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_roles o ON o.oid=n.nspowner WHERE n.nspname='mmapp_control' LIMIT 2) q
UNION ALL SELECT 'tables',pg_catalog.to_jsonb(q)::text FROM (
SELECT c.relname::text AS name,o.rolname::text AS owner,c.relkind::text AS kind,c.relpersistence::text AS persistence,
c.relrowsecurity AS row_security,c.relforcerowsecurity AS force_row_security,c.relispartition AS is_partition,c.relreplident::text AS replica_identity,c.reloptions AS options,
EXISTS(SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid=c.oid) AS has_parent,EXISTS(SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhparent=c.oid) AS has_children,
c.reloftype<>0 AS typed_table,(SELECT am.amname::text FROM pg_catalog.pg_am am WHERE am.oid=c.relam) AS access_method
FROM component c JOIN pg_catalog.pg_roles o ON o.oid=c.relowner ORDER BY c.relname LIMIT 5) q
UNION ALL SELECT 'columns',pg_catalog.to_jsonb(q)::text FROM (
SELECT c.relname::text AS table_name,a.attnum::integer AS position,a.attname::text AS name,tn.nspname::text AS type_namespace,t.typname::text AS type_name,
a.attnotnull AS not_null,a.attidentity::text AS identity,a.attgenerated::text AS generated,
cn.nspname::text AS collation_namespace,co.collname::text AS collation_name,
pg_catalog.pg_get_expr(d.adbin,d.adrelid,true) AS default_expr
FROM component c JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid AND a.attnum>0
JOIN pg_catalog.pg_type t ON t.oid=a.atttypid JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
LEFT JOIN pg_catalog.pg_collation co ON co.oid=a.attcollation LEFT JOIN pg_catalog.pg_namespace cn ON cn.oid=co.collnamespace
LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum
WHERE NOT a.attisdropped ORDER BY c.relname,a.attnum LIMIT 27) q
UNION ALL SELECT 'functions',pg_catalog.to_jsonb(q)::text FROM (
SELECT p.proname::text AS name,o.rolname::text AS owner,l.lanname::text AS language,p.prosrc AS body,p.prosecdef AS security_definer,
p.proisstrict AS strict,p.provolatile::text AS volatility,p.proleakproof AS leakproof,p.prokind::text AS kind,
p.proparallel::text AS parallel,p.pronargdefaults::integer AS argument_defaults,p.provariadic<>0 AS variadic,p.proconfig AS config,
p.proretset AS returns_set,p.prosupport<>0 AS has_support,p.proallargtypes IS NULL AND p.proargmodes IS NULL AS input_only,p.proargnames AS argument_names,
rt.typname::text AS return_type,rn.nspname::text AS return_namespace,
ARRAY(SELECT t.typname::text FROM pg_catalog.unnest(p.proargtypes::oid[]) WITH ORDINALITY a(type_oid,position) JOIN pg_catalog.pg_type t ON t.oid=a.type_oid ORDER BY a.position) AS argument_types,
ARRAY(SELECT n.nspname::text FROM pg_catalog.unnest(p.proargtypes::oid[]) WITH ORDINALITY a(type_oid,position) JOIN pg_catalog.pg_type t ON t.oid=a.type_oid JOIN pg_catalog.pg_namespace n ON n.oid=t.typnamespace ORDER BY a.position) AS argument_namespaces
FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace JOIN pg_catalog.pg_language l ON l.oid=p.prolang
JOIN pg_catalog.pg_roles o ON o.oid=p.proowner JOIN pg_catalog.pg_type rt ON rt.oid=p.prorettype JOIN pg_catalog.pg_namespace rn ON rn.oid=rt.typnamespace
WHERE n.nspname='mmapp_control' AND p.proname=ANY(ARRAY['bandwidth_node_authority_guard','bandwidth_node_immutable_guard','bandwidth_node_alias_guard','bandwidth_node_event_guard','bandwidth_node_alias_consistency_guard','bandwidth_admission_reject_truncate'])
ORDER BY p.proname,p.oid LIMIT 7) q
UNION ALL SELECT 'triggers',pg_catalog.to_jsonb(q)::text FROM (
SELECT c.relname::text AS table_name,CASE WHEN t.tgisinternal THEN NULL ELSE t.tgname::text END AS name,t.tgisinternal AS internal,
t.tgtype::integer AS type,t.tgenabled::text AS enabled,t.tgdeferrable AS deferrable,t.tginitdeferred AS initially_deferred,
t.tgconstraint<>0 AS is_constraint,con.conname::text AS constraint_name,
pn.nspname::text AS function_namespace,p.proname::text AS function_name,t.tgnargs::integer AS argument_count,
pg_catalog.encode(t.tgargs,'hex') AS arguments,t.tgattr::text AS columns,pg_catalog.pg_get_expr(t.tgqual,t.tgrelid,true) AS condition,
t.tgoldtable::text AS old_table,t.tgnewtable::text AS new_table
FROM component c JOIN pg_catalog.pg_trigger t ON t.tgrelid=c.oid JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
JOIN pg_catalog.pg_namespace pn ON pn.oid=p.pronamespace LEFT JOIN pg_catalog.pg_constraint con ON con.oid=t.tgconstraint
ORDER BY c.relname,t.tgname LIMIT 23) q
UNION ALL SELECT 'constraints',pg_catalog.to_jsonb(q)::text FROM (
SELECT c.relname::text AS table_name,k.conname::text AS name,k.contype::text AS type,k.convalidated AS validated,k.condeferrable AS deferrable,k.condeferred AS initially_deferred,
ARRAY(SELECT a.attname::text FROM pg_catalog.unnest(k.conkey) WITH ORDINALITY x(attnum,position) JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid AND a.attnum=x.attnum ORDER BY x.position) AS keys,
fn.nspname::text AS foreign_namespace,fc.relname::text AS foreign_table,
ARRAY(SELECT a.attname::text FROM pg_catalog.unnest(k.confkey) WITH ORDINALITY x(attnum,position) JOIN pg_catalog.pg_attribute a ON a.attrelid=k.confrelid AND a.attnum=x.attnum ORDER BY x.position) AS foreign_keys,
k.confupdtype::text AS update_action,k.confdeltype::text AS delete_action,k.confmatchtype::text AS match_type,
pg_catalog.pg_get_constraintdef(k.oid,true) AS definition
FROM component c JOIN pg_catalog.pg_constraint k ON k.conrelid=c.oid
LEFT JOIN pg_catalog.pg_class fc ON fc.oid=k.confrelid LEFT JOIN pg_catalog.pg_namespace fn ON fn.oid=fc.relnamespace
ORDER BY c.relname,k.conname LIMIT 81) q
UNION ALL SELECT 'indexes',pg_catalog.to_jsonb(q)::text FROM (
SELECT c.relname::text AS table_name,ic.relname::text AS name,i.indisunique AS unique,i.indisprimary AS primary,i.indisvalid AS valid,i.indisready AS ready,i.indislive AS live,
i.indnkeyatts::integer AS key_count,i.indnatts::integer AS attribute_count,am.amname::text AS method,
ARRAY(SELECT a.attname::text FROM pg_catalog.unnest(i.indkey::smallint[]) WITH ORDINALITY x(attnum,position) LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid AND a.attnum=x.attnum ORDER BY x.position) AS keys,
ARRAY(SELECT co.collname::text FROM pg_catalog.unnest(i.indcollation::oid[]) WITH ORDINALITY x(collation_oid,position) LEFT JOIN pg_catalog.pg_collation co ON co.oid=x.collation_oid ORDER BY x.position) AS collations,
ARRAY(SELECT n.nspname::text FROM pg_catalog.unnest(i.indcollation::oid[]) WITH ORDINALITY x(collation_oid,position) LEFT JOIN pg_catalog.pg_collation co ON co.oid=x.collation_oid LEFT JOIN pg_catalog.pg_namespace n ON n.oid=co.collnamespace ORDER BY x.position) AS collation_namespaces,
ARRAY(SELECT op.opcname::text FROM pg_catalog.unnest(i.indclass::oid[]) WITH ORDINALITY x(class_oid,position) JOIN pg_catalog.pg_opclass op ON op.oid=x.class_oid ORDER BY x.position) AS operator_classes,
ARRAY(SELECT n.nspname::text FROM pg_catalog.unnest(i.indclass::oid[]) WITH ORDINALITY x(class_oid,position) JOIN pg_catalog.pg_opclass op ON op.oid=x.class_oid JOIN pg_catalog.pg_namespace n ON n.oid=op.opcnamespace ORDER BY x.position) AS operator_class_namespaces,
i.indoption::text AS options,pg_catalog.pg_get_expr(i.indexprs,i.indrelid,true) AS expressions,pg_catalog.pg_get_expr(i.indpred,i.indrelid,true) AS predicate,
pg_catalog.pg_get_indexdef(i.indexrelid) AS definition
FROM component c JOIN pg_catalog.pg_index i ON i.indrelid=c.oid JOIN pg_catalog.pg_class ic ON ic.oid=i.indexrelid JOIN pg_catalog.pg_am am ON am.oid=ic.relam
ORDER BY c.relname,ic.relname LIMIT 10) q
UNION ALL SELECT 'rules',pg_catalog.to_jsonb(q)::text FROM (SELECT c.relname::text AS table_name,r.rulename::text AS name FROM component c JOIN pg_catalog.pg_rewrite r ON r.ev_class=c.oid LIMIT 1) q
UNION ALL SELECT 'policies',pg_catalog.to_jsonb(q)::text FROM (SELECT c.relname::text AS table_name,p.polname::text AS name FROM component c JOIN pg_catalog.pg_policy p ON p.polrelid=c.oid LIMIT 1) q
), metered AS (
SELECT section,raw_json,pg_catalog.sum(pg_catalog.octet_length(raw_json)) OVER(ORDER BY section,raw_json) AS bytes FROM catalog
) SELECT section,CASE WHEN pg_catalog.octet_length(raw_json)<=65536 AND bytes<=1048576 THEN raw_json END AS raw_json FROM metered ORDER BY section,raw_json`
function refuse(): never { throw new BandwidthNodeRegistryCatalogRefused() }
const plain = (value: unknown): value is Row => !!value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype
const arrayEqual = (value: unknown, expected: unknown[]) => Array.isArray(value) && JSON.stringify(value) === JSON.stringify(expected)
function canonical(value: unknown): string {
if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"
if (plain(value)) return "{" + Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => JSON.stringify(key) + ":" + canonical(item)).join(",") + "}"
return JSON.stringify(value)
}
type Column = [name: string, type: string, notNull: boolean, defaultExpr?: string]
const text = (name: string, notNull = true): Column => [name, "text", notNull]
const columns: Record<typeof tableNames[number], Column[]> = {
bandwidth_node_authority: [["id","int4",true],["installation_id","uuid",true],text("issuer_key_sha256"),text("quiescence_proof"),text("status"),["created_at","timestamptz",true,"clock_timestamp()"]],
bandwidth_nodes: [["node_id","uuid",true],text("claim_proof"),text("enrollment_mac"),["created_at","timestamptz",true,"clock_timestamp()"]],
bandwidth_node_aliases: [["server_id","int8",true],["incarnation","uuid",true],["node_id","uuid",true],text("status"),text("record_mac"),["created_at","timestamptz",true,"clock_timestamp()"]],
bandwidth_node_events: [["event_id","uuid",true],["server_id","int8",true],["incarnation","uuid",true],["node_id","uuid",true],text("kind"),text("old_status",false),text("new_status"),text("authority_proof"),text("event_mac"),["created_at","timestamptz",true,"clock_timestamp()"]],
}
const triggers: Record<string, [table: string, fn: string, type: number, deferred: boolean]> = {
bandwidth_node_authority_guard: ["bandwidth_node_authority","bandwidth_node_authority_guard",31,false],
bandwidth_node_immutable_guard: ["bandwidth_nodes","bandwidth_node_immutable_guard",27,false],
bandwidth_node_alias_guard: ["bandwidth_node_aliases","bandwidth_node_alias_guard",31,false],
bandwidth_node_event_guard: ["bandwidth_node_events","bandwidth_node_event_guard",31,false],
bandwidth_node_authority_no_truncate: ["bandwidth_node_authority","bandwidth_admission_reject_truncate",34,false],
bandwidth_nodes_no_truncate: ["bandwidth_nodes","bandwidth_admission_reject_truncate",34,false],
bandwidth_node_aliases_no_truncate: ["bandwidth_node_aliases","bandwidth_admission_reject_truncate",34,false],
bandwidth_node_events_no_truncate: ["bandwidth_node_events","bandwidth_admission_reject_truncate",34,false],
bandwidth_node_alias_consistency: ["bandwidth_node_aliases","bandwidth_node_alias_consistency_guard",29,true],
bandwidth_node_event_consistency: ["bandwidth_node_events","bandwidth_node_alias_consistency_guard",29,true],
}
export const BANDWIDTH_PEER_MANAGED_REGISTRY_CATALOG_SQL = BANDWIDTH_NODE_REGISTRY_CATALOG_SQL.replace("ORDER BY c.relname,t.tgname LIMIT 23", "ORDER BY c.relname,t.tgname LIMIT 27")
export const BANDWIDTH_PEER_REGISTRY_INCOMING_SQL = `SELECT c.relname::text AS table_name,k.conname::text AS constraint_name
FROM pg_catalog.pg_constraint k
JOIN pg_catalog.pg_class c ON c.oid=k.conrelid
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
JOIN pg_catalog.pg_class target ON target.oid=k.confrelid
JOIN pg_catalog.pg_namespace tn ON tn.oid=target.relnamespace
WHERE n.nspname='mmapp_control' AND c.relname=ANY(ARRAY['bandwidth_external_node_aliases','bandwidth_external_node_events'])
AND k.contype='f' AND tn.nspname='mmapp_control' AND target.relname='bandwidth_nodes'
ORDER BY c.relname,k.conname LIMIT 3`
export async function observeBandwidthNodeRegistryCatalog(sql: BandwidthNodeRegistryCatalogSql, live: () => void): Promise<string> {
return observeManagedCatalog(sql, live)
}
/** Explicit v2 component: verify the complete external footprint, including its
* four inbound node FK triggers, then retain those exact triggers in the
* managed catalog proof as well. A v1 observer/pin is deliberately unchanged. */
export async function observeBandwidthPeerRegistryCatalog(sql: BandwidthNodeRegistryCatalogSql, live: () => void): Promise<string> {
live()
const external = await observeBandwidthExternalNodeRegistryCatalog(sql, live)
live()
const result = await sql.query(BANDWIDTH_PEER_REGISTRY_INCOMING_SQL, [])
live()
const incoming = incomingNodeTriggers(result.rows)
const managed = await observeManagedCatalog(sql, live, incoming)
live()
return createHash("sha256").update(canonical({ format: "mmapp-bandwidth-peer-registry-catalog-v2", managed, external })).digest("hex")
}
function incomingNodeTriggers(rows: unknown): string[] {
if (!Array.isArray(rows) || rows.length !== 2) refuse()
const names = rows.map(row => {
if (!plain(row) || Object.keys(row).sort().join(",") !== "constraint_name,table_name"
|| typeof row.constraint_name !== "string" || !row.constraint_name || row.constraint_name.length > 63
|| !["bandwidth_external_node_aliases", "bandwidth_external_node_events"].includes(String(row.table_name))) refuse()
return { table: row.table_name as string, name: row.constraint_name }
})
if (new Set(names.map(row => row.table)).size !== 2) refuse()
const incoming = names.flatMap(row => [`bandwidth_nodes:${row.name}:RI_FKey_restrict_del:9`, `bandwidth_nodes:${row.name}:RI_FKey_restrict_upd:17`])
return incoming
}
export function validateBandwidthPeerRegistryCatalogRows(managedRows: unknown, externalRows: unknown, incomingRows: unknown): string {
const external = validateBandwidthExternalNodeRegistryCatalogRows(externalRows)
const incoming = incomingNodeTriggers(incomingRows)
const managed = validateBandwidthNodeRegistryCatalogRows(managedRows, incoming)
return createHash("sha256").update(canonical({ format: "mmapp-bandwidth-peer-registry-catalog-v2", managed, external })).digest("hex")
}
async function observeManagedCatalog(sql: BandwidthNodeRegistryCatalogSql, live: () => void, incoming: readonly string[] = []): Promise<string> {
live()
let result: { rows: Row[] }
const statement = incoming.length ? BANDWIDTH_PEER_MANAGED_REGISTRY_CATALOG_SQL : BANDWIDTH_NODE_REGISTRY_CATALOG_SQL
try { result = await sql.query(statement, []) } catch { live(); refuse() }
live()
return validateBandwidthNodeRegistryCatalogRows(result.rows, incoming)
}
/** Default remains the strict v1 footprint. V2 incoming identities must be
* derived from the same captured external FK rows by the combined validator. */
export function validateBandwidthNodeRegistryCatalogRows(rows: unknown, incoming: readonly string[] = []): string {
const limits = { ...sections, triggers: sections.triggers + incoming.length }
const bodies = expectedBodies()
if (!Array.isArray(rows) || rows.length > 230 + incoming.length) refuse()
const found = Object.fromEntries(Object.keys(sections).map(key => [key, [] as Row[]])) as unknown as Record<keyof typeof sections, Row[]>
let bytes = 0
for (const item of rows) {
if (!plain(item) || Object.keys(item).sort().join(",") !== "raw_json,section" || typeof item.section !== "string" || !Object.hasOwn(sections,item.section) || typeof item.raw_json !== "string") refuse()
bytes += Buffer.byteLength(item.raw_json)
if (Buffer.byteLength(item.raw_json)>65536 || bytes>1048576) refuse()
let parsed: unknown
try { parsed = JSON.parse(item.raw_json) } catch { refuse() }
if (!plain(parsed)) refuse()
const section = item.section as keyof typeof sections
found[section].push(parsed)
if (found[section].length>limits[section]) refuse()
}
if (found.namespace.length!==1 || found.namespace[0].name!=="mmapp_control" || typeof found.namespace[0].owner!=="string") refuse()
if (found.tables.length!==4 || new Set(found.tables.map(row=>row.name)).size!==4) refuse()
for (const row of found.tables) if (!tableNames.includes(row.name as typeof tableNames[number]) || row.owner!==found.namespace[0].owner || row.kind!=="r" || row.persistence!=="p" || row.row_security!==false || row.force_row_security!==false || row.is_partition!==false || row.replica_identity!=="d" || row.options!==null || row.has_parent!==false || row.has_children!==false || row.typed_table!==false || row.access_method!=="heap") refuse()
if (found.columns.length!==26) refuse()
for (const table of tableNames) {
const actual = found.columns.filter(row=>row.table_name===table).sort((a,b)=>Number(a.position)-Number(b.position))
if (actual.length!==columns[table].length) refuse()
for (const [index,expected] of columns[table].entries()) {
const row=actual[index],collation=expected[1]==="text"?"C":null
const defaultExpr=row.default_expr==="pg_catalog.clock_timestamp()"?"clock_timestamp()":row.default_expr
if (row.position!==index+1 || row.name!==expected[0] || row.type_namespace!=="pg_catalog" || row.type_name!==expected[1] || row.not_null!==expected[2] || row.identity!=="" || row.generated!=="" || row.collation_name!==collation || row.collation_namespace!==(collation?"pg_catalog":null) || defaultExpr!==(expected[3]??null)) refuse()
row.default_expr=defaultExpr
}
}
if (found.functions.length!==6 || new Set(found.functions.map(row=>row.name)).size!==6) refuse()
for (const row of found.functions) {
const args: string[]=[]
if (typeof row.name!=="string" || !bodies.has(row.name) || typeof row.body!=="string" || normalizeBody(row.body)!==bodies.get(row.name)
|| row.owner!==found.namespace[0].owner || row.language!=="plpgsql" || row.return_namespace!=="pg_catalog" || row.return_type!=="trigger"
|| row.security_definer!==false || row.strict!==false || row.volatility!=="v" || row.leakproof!==false || row.kind!=="f" || row.parallel!=="u" || row.argument_defaults!==0 || row.variadic!==false
|| row.returns_set!==false || row.has_support!==false || row.input_only!==true || row.argument_names!==null
|| !arrayEqual(row.argument_types,args) || !arrayEqual(row.argument_namespaces,args.map(()=>"pg_catalog"))
|| !Array.isArray(row.config) || row.config.length!==1 || typeof row.config[0]!=="string" || row.config[0].replace(/\s/g,"")!=="search_path=pg_catalog,mmapp_control") refuse()
row.body=normalizeBody(row.body)
row.config=["search_path=pg_catalog,mmapp_control"]
}
const userTriggers=found.triggers.filter(row=>row.internal===false),internal=found.triggers.filter(row=>row.internal===true)
if (userTriggers.length!==10 || internal.length!==12+incoming.length || new Set(userTriggers.map(row=>row.name)).size!==10) refuse()
for (const row of found.triggers) {
if (row.argument_count!==0 || row.arguments!=="" || row.columns!=="" || row.condition!==null || row.old_table!==null || row.new_table!==null) refuse()
if (row.internal===false) {
const expected=typeof row.name==="string"?triggers[row.name]:undefined
if (!expected || row.table_name!==expected[0] || row.function_namespace!=="mmapp_control" || row.function_name!==expected[1] || row.type!==expected[2] || row.enabled!=="A" || row.deferrable!==expected[3] || row.initially_deferred!==expected[3] || row.is_constraint!==expected[3] || row.constraint_name!==(expected[3]?row.name:null)) refuse()
} else if (row.internal!==true || row.name!==null || row.function_namespace!=="pg_catalog" || !["RI_FKey_check_ins","RI_FKey_check_upd","RI_FKey_restrict_del","RI_FKey_restrict_upd"].includes(String(row.function_name)) || row.enabled!=="O" || row.is_constraint!==true || row.deferrable!==false || row.initially_deferred!==false) refuse()
}
const checkCounts: Record<string,number>={bandwidth_node_authority:4,bandwidth_nodes:2,bandwidth_node_aliases:3,bandwidth_node_events:6}
const keySpecs: Record<string,string[]>={bandwidth_node_authority:["p:id"],bandwidth_nodes:["p:node_id","u:claim_proof"],bandwidth_node_aliases:["p:server_id","u:incarnation","f:node_id"],bandwidth_node_events:["p:event_id","u:server_id,kind","f:server_id","f:node_id"]}
for (const table of tableNames) {
const actual=found.constraints.filter(row=>row.table_name===table),keys:string[]=[]
if (actual.filter(row=>row.type==="c").length!==checkCounts[table]) refuse()
for (const row of actual) {
if (typeof row.name!=="string" || typeof row.definition!=="string" || !row.definition || row.validated!==true || !Array.isArray(row.keys) || !["p","u","f","c","n","t"].includes(String(row.type))) refuse()
if (row.type==="t") { if (row.deferrable!==true || row.initially_deferred!==true || !Object.hasOwn(triggers,row.name)) refuse() }
else if (row.deferrable!==false || row.initially_deferred!==false) refuse()
if (["p","u","f"].includes(String(row.type))) keys.push(row.type+":"+row.keys.join(","))
if (row.type==="f") {
const target=arrayEqual(row.keys,["node_id"])?"bandwidth_nodes":table==="bandwidth_node_events"&&arrayEqual(row.keys,["server_id"])?"bandwidth_node_aliases":undefined
if (!target || row.foreign_namespace!=="mmapp_control" || row.foreign_table!==target || !arrayEqual(row.foreign_keys,row.keys) || row.update_action!=="r" || row.delete_action!=="r" || row.match_type!=="s") refuse()
}
const constraintKeys=row.keys
if (row.type==="n" && (constraintKeys.length!==1 || !columns[table].some(column=>column[0]===constraintKeys[0]&&column[2]))) refuse()
}
if (!arrayEqual(keys.sort(),keySpecs[table].sort())) refuse()
}
if (found.constraints.some(row=>!tableNames.includes(row.table_name as typeof tableNames[number]))) refuse()
const expectedInternal:string[]=[...incoming]
for (const fk of found.constraints.filter(row=>row.type==="f")) {
expectedInternal.push(`${fk.table_name}:${fk.name}:RI_FKey_check_ins:5`,`${fk.table_name}:${fk.name}:RI_FKey_check_upd:17`,`${fk.foreign_table}:${fk.name}:RI_FKey_restrict_del:9`,`${fk.foreign_table}:${fk.name}:RI_FKey_restrict_upd:17`)
}
if (!arrayEqual(internal.map(row=>`${row.table_name}:${row.constraint_name}:${row.function_name}:${row.type}`).sort(),expectedInternal.sort())) refuse()
if (!arrayEqual(found.constraints.filter(row=>row.type==="t").map(row=>row.table_name+":"+row.name).sort(),userTriggers.filter(row=>row.is_constraint===true).map(row=>row.table_name+":"+row.name).sort())) refuse()
const indexSpecs: Record<string,string[]>={bandwidth_node_authority:["p:id"],bandwidth_nodes:["p:node_id","u:claim_proof"],bandwidth_node_aliases:["p:server_id","u:incarnation","i:node_id"],bandwidth_node_events:["p:event_id","u:server_id,kind","i:node_id"]}
if (found.indexes.length!==9) refuse()
for (const table of tableNames) {
const actual=found.indexes.filter(row=>row.table_name===table),keys:string[]=[]
for (const row of actual) {
if (!Array.isArray(row.keys) || !row.keys.length || typeof row.name!=="string" || typeof row.unique!=="boolean" || typeof row.primary!=="boolean" || row.primary&&!row.unique || row.key_count!==row.keys.length || row.attribute_count!==row.keys.length || row.valid!==true || row.ready!==true || row.live!==true || row.method!=="btree" || row.expressions!==null || row.predicate!==null || row.options!==row.keys.map(()=>"0").join(" ") || typeof row.definition!=="string") refuse()
const expectedColumns=row.keys.map(name=>columns[table].find(column=>column[0]===name))
if (expectedColumns.some(column=>!column) || !arrayEqual(row.collations,expectedColumns.map(column=>column![1]==="text"?"C":null)) || !arrayEqual(row.collation_namespaces,expectedColumns.map(column=>column![1]==="text"?"pg_catalog":null)) || !arrayEqual(row.operator_classes,expectedColumns.map(column=>column![1]==="uuid"?"uuid_ops":column![1]==="int4"?"int4_ops":column![1]==="int8"?"int8_ops":"text_ops")) || !arrayEqual(row.operator_class_namespaces,expectedColumns.map(()=>"pg_catalog"))) refuse()
keys.push((row.primary===true?"p":row.unique===true?"u":"i")+":"+row.keys.join(","))
}
if (!arrayEqual(keys.sort(),indexSpecs[table].sort())) refuse()
}
// Sort semantic rows independently of SQL transport order. No physical OID or
// volatile statistics enter the digest; internal trigger names contain OIDs
// and are deliberately represented by their structural/function identity.
const snapshot=Object.fromEntries(Object.entries(found).map(([section,rows])=>[section,rows.map(canonical).sort()]))
return createHash("sha256").update(canonical(snapshot)).digest("hex")
}