/** One bounded MVCC snapshot of the ORIGINAL v1 registry identity. No new lease, * supplied SQL, readiness assertion, cache, retry or native authority. The same * pure original role/catalog validators and unchanged signed catalog digest. */ import { z } from "zod" import { BANDWIDTH_NODE_REGISTRY_ROLE_SQL, captureBandwidthNodeRegistryRoleExpected, validateBandwidthNodeRegistryRuntimeRoleRows } from "./bandwidth-node-registry-role.js" import { BANDWIDTH_NODE_REGISTRY_CATALOG_SQL, validateBandwidthNodeRegistryCatalogRows } from "./bandwidth-node-registry-catalog.js" export interface BandwidthNodeIdentitySql { query(text:string,values?:unknown[]):Promise<{rows:Record[]}> } const hash=z.string().regex(/^[a-f0-9]{64}$/) const expectedSchema=z.object({databaseName:z.string(),runtimeRole:z.string(),ownerRole:z.string(),installationId:z.string().uuid(),issuerKeySha256:hash,quiescenceProof:hash,registryCatalogSha256:hash}).strict() export type BandwidthNodeIdentityExpected=z.infer export class BandwidthNodeIdentityRefused extends Error { readonly code="BANDWIDTH_NODE_IDENTITY_REFUSED" constructor(){super("Bandwidth v1 node registry identity refused")} } function fail():never{throw new BandwidthNodeIdentityRefused()} const plain=(v:unknown):v is Record=>!!v&&typeof v==="object"&&Object.getPrototypeOf(v)===Object.prototype const fields=["databaseName","runtimeRole","ownerRole","installationId","issuerKeySha256","quiescenceProof","registryCatalogSha256"] as const /** Original scalar expectations are copied before the first asynchronous SQL; * caller getters, serializers, symbols and later mutations cannot select pins. */ function capture(expected:BandwidthNodeIdentityExpected):Readonly{ if(!plain(expected)||Reflect.ownKeys(expected).length!==fields.length)fail() const descriptors=Object.getOwnPropertyDescriptors(expected) if(Object.keys(descriptors).sort().join(",")!==[...fields].sort().join(",")||Object.values(descriptors).some(field=>!("value"in field)||!field.enumerable))fail() let parsed:BandwidthNodeIdentityExpected try{parsed=expectedSchema.parse(Object.fromEntries(fields.map(name=>[name,descriptors[name].value])));captureBandwidthNodeRegistryRoleExpected({databaseName:parsed.databaseName,runtimeRole:parsed.runtimeRole,ownerRole:parsed.ownerRole})}catch{return fail()} return Object.freeze(parsed) } type Kind="role"|"catalog"|"authority" const limits:Record={role:1,catalog:230,authority:1} /** Exact old role SQL, strict 22-trigger v1 catalog SQL and authority share one * command snapshot. No new catalog, pin format, DDL, cache or source identity. */ export const BANDWIDTH_NODE_IDENTITY_SQL=`/* bandwidth-node:identity */ WITH node_role AS MATERIALIZED (${BANDWIDTH_NODE_REGISTRY_ROLE_SQL}), node_catalog AS MATERIALIZED (${BANDWIDTH_NODE_REGISTRY_CATALOG_SQL}), authority AS MATERIALIZED ( SELECT installation_id::pg_catalog.text,issuer_key_sha256,quiescence_proof,status FROM mmapp_control.bandwidth_node_authority WHERE id=1 LIMIT 2), bundled AS ( SELECT 'role'::pg_catalog.text AS kind,pg_catalog.to_jsonb(r)::pg_catalog.text AS raw_json FROM node_role r UNION ALL SELECT 'catalog',pg_catalog.to_jsonb(r)::pg_catalog.text FROM node_catalog r UNION ALL SELECT 'authority',pg_catalog.to_jsonb(r)::pg_catalog.text FROM authority r), metered AS ( SELECT kind,raw_json,pg_catalog.row_number() OVER(ORDER BY kind COLLATE "C",raw_json COLLATE "C") AS row_order, pg_catalog.count(*) OVER() AS row_count,pg_catalog.sum(pg_catalog.octet_length(raw_json)) OVER() AS total_bytes FROM bundled) SELECT kind,row_order::pg_catalog.text AS row_order, CASE WHEN row_count<=232 AND total_bytes<=4194304 AND pg_catalog.octet_length(raw_json)<=131200 THEN raw_json END AS raw_json FROM metered ORDER BY metered.row_order LIMIT 233` /** Pure counterpart for captured rows. Component validators retain their own * tighter structural/byte bounds and the original exact signed digest. */ export function validateBandwidthNodeIdentityRows(rows:unknown,expected:BandwidthNodeIdentityExpected):void{ const captured=capture(expected) if(!Array.isArray(rows)||rows.length>232)fail() const found:Record[]>={role:[],catalog:[],authority:[]} const ordinals=new Set();let bytes=0 for(const row of rows){ if(!plain(row)||Object.keys(row).sort().join(",")!=="kind,raw_json,row_order"||typeof row.kind!=="string"||!Object.hasOwn(found,row.kind)||typeof row.raw_json!=="string"||typeof row.row_order!=="string"||!/^[1-9][0-9]{0,2}$/.test(row.row_order))fail() const ordinal=Number(row.row_order);if(ordinal>rows.length||ordinals.has(ordinal))fail();ordinals.add(ordinal) const size=Buffer.byteLength(row.raw_json);bytes+=size;if(size>131200||bytes>4194304)fail() let value:unknown;try{value=JSON.parse(row.raw_json)}catch{return fail()};if(!plain(value))fail() const kind=row.kind as Kind;found[kind].push(value);if(found[kind].length>limits[kind])fail() } try{ const role={databaseName:captured.databaseName,runtimeRole:captured.runtimeRole,ownerRole:captured.ownerRole} validateBandwidthNodeRegistryRuntimeRoleRows(found.role,role) if(validateBandwidthNodeRegistryCatalogRows(found.catalog)!==captured.registryCatalogSha256)fail() if(found.authority.length!==1)fail() const authority=found.authority[0] if(Object.keys(authority).sort().join(",")!=="installation_id,issuer_key_sha256,quiescence_proof,status"||authority.installation_id!==captured.installationId||authority.issuer_key_sha256!==captured.issuerKeySha256||authority.quiescence_proof!==captured.quiescenceProof||authority.status!=="active")fail() }catch{return fail()} } export async function assertBandwidthNodeIdentity(sql:BandwidthNodeIdentitySql,expected:BandwidthNodeIdentityExpected,live:()=>void):Promise{ const captured=capture(expected) live();let result:{rows:Record[]} try{result=await sql.query(BANDWIDTH_NODE_IDENTITY_SQL,[captured.databaseName,captured.runtimeRole,captured.ownerRole])}catch{live();return fail()} live();validateBandwidthNodeIdentityRows(result?.rows,captured);live() }