/** Explicit offline owner operation. Never imported by startup, MCP or native * transport. Seals an already installed EMPTY control store; does not enroll * routers, create keys/roles/schema, or certify control-provider rollback. */ import { createHash, createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto" import { constants } from "node:fs" import { link, lstat, open, realpath } from "node:fs/promises" import { dirname, isAbsolute, resolve } from "node:path" import { Pool, type PoolClient } from "pg" import { z } from "zod" import { assertBandwidthControlRuntimeRole } from "./bandwidth-control-role.js" import { bandwidthControlEndpointSha256, bandwidthControlSchemaSourceSha256, canonicalBandwidthControlRecord, createConfiguredBandwidthControlSource, observeBandwidthControlCatalog, readBandwidthControlFile, type BandwidthControlRecord, } from "./bandwidth-control-source.js" export const bandwidthControlProvisionConfigSchema=z.object({ ownerDatabaseUrl:z.string().min(1),databaseUrl:z.string().min(1),applicationDatabaseUrl:z.string().min(1), attestationFile:z.string().min(1),trustKeyFile:z.string().min(1),trustKeySha256:z.string().regex(/^[a-f0-9]{64}$/), eventKeyFile:z.string().min(1),issuerPrivateKeyFile:z.string().min(1),attestationRef:z.string().trim().min(30).max(2000), }).strict() export class BandwidthControlProvisionError extends Error { readonly code="BANDWIDTH_CONTROL_PROVISION_UNCONFIRMED" constructor(){super("Выдача привязки control source не подтверждена; проверьте pending-файл и запись источника до повторной операции")} } const sha=(value:Buffer|string)=>createHash("sha256").update(value).digest("hex") async function syncParent(path:string){ const directory=dirname(path) if(await realpath(directory)!==directory)throw new BandwidthControlProvisionError() const handle=await open(directory,constants.O_RDONLY|(constants.O_DIRECTORY??0)|(constants.O_NOFOLLOW??0)) try{if(!(await handle.stat()).isDirectory())throw new BandwidthControlProvisionError();await handle.sync()}finally{await handle.close()} } /** Existing pending/final files are never overwritten or removed. If COMMIT or * publication is uncertain, the operator must reconcile the original signed * record with the immutable identity. This function never invents a recovery * generation and never releases occupancy. */ export async function sealEmptyBandwidthControlSource(input:unknown):Promise>{ let owner:Pool|undefined,runtime:Pool|undefined,client:PoolClient|undefined let eventKey:Buffer|undefined,privateBytes:Buffer|undefined let transaction=false,commitStarted=false,ownerFailed=false const deadline=Date.now()+15000 const live=()=>{if(ownerFailed||Date.now()>=deadline)throw new BandwidthControlProvisionError()} const timer=setTimeout(()=>{client?.release(true);client=undefined},15000) try{ const config=bandwidthControlProvisionConfigSchema.parse(input) const paths=[config.attestationFile,config.trustKeyFile,config.eventKeyFile,config.issuerPrivateKeyFile] if(paths.some(path=>!isAbsolute(path)||resolve(path)!==path)||new Set(paths).size!==paths.length)throw new Error() // Constructor validates separate app/control DB and fixed pinned file config // before owner I/O. It performs no connection or automatic enrollment. const validation=createConfiguredBandwidthControlSource(config);await validation.close() for(const path of [config.attestationFile,config.attestationFile+".pending"]){ try{await lstat(path);throw new BandwidthControlProvisionError()} catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error} } // A platform/filesystem without durable directory flush cannot issue this // binding. In particular do not silently weaken this on Windows/EPERM. await syncParent(config.attestationFile);live() const target=new URL(config.databaseUrl),ownerUrl=new URL(config.ownerDatabaseUrl) const runtimeRole=decodeURIComponent(target.username),ownerRole=decodeURIComponent(ownerUrl.username) const databaseName=decodeURIComponent(target.pathname.slice(1)) if(!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(ownerRole)||ownerRole===runtimeRole)throw new Error() // Password and owner username are the only allowed connection differences. const ownerTarget=new URL(ownerUrl);ownerTarget.username=target.username;ownerTarget.password=target.password if(bandwidthControlEndpointSha256(ownerTarget.toString())!==bandwidthControlEndpointSha256(target.toString()))throw new Error() const publicBytes=await readBandwidthControlFile(config.trustKeyFile,16384,live) const publicKey=createPublicKey(publicBytes) if(publicKey.asymmetricKeyType!=="ed25519"||sha(publicKey.export({type:"spki",format:"der"}))!==config.trustKeySha256)throw new Error() privateBytes=await readBandwidthControlFile(config.issuerPrivateKeyFile,16384,live) const privateKey=createPrivateKey(privateBytes) if(privateKey.asymmetricKeyType!=="ed25519"||!createPublicKey(privateKey).export({type:"spki",format:"der"}).equals(publicKey.export({type:"spki",format:"der"})))throw new Error() eventKey=await readBandwidthControlFile(config.eventKeyFile,32,live);if(eventKey.length!==32)throw new Error() owner=new Pool({connectionString:config.ownerDatabaseUrl,max:1,connectionTimeoutMillis:3000,query_timeout:5000,options:"-c search_path=pg_catalog"}) runtime=new Pool({connectionString:config.databaseUrl,max:1,connectionTimeoutMillis:3000,query_timeout:5000,options:"-c search_path=pg_catalog"}) owner.on("error",()=>{});runtime.on("error",()=>{}) client=await owner.connect();client.on("error",()=>{ownerFailed=true});live() await client.query("BEGIN");transaction=true await client.query("SET LOCAL statement_timeout='5s'") await client.query("SET LOCAL lock_timeout='2s'") await client.query("SET LOCAL synchronous_commit=on") await client.query("LOCK TABLE mmapp_control.bandwidth_attempts,mmapp_control.bandwidth_node_occupancy,mmapp_control.bandwidth_attempt_events,mmapp_control.bandwidth_source_identity IN SHARE ROW EXCLUSIVE MODE") const facts=(await client.query(`SELECT d.oid::pg_catalog.int8 AS oid,d.datname,r.rolname AS owner, SESSION_USER AS session_role,CURRENT_USER AS current_role, r.rolsuper OR r.rolcreatedb OR r.rolcreaterole OR r.rolreplication OR r.rolbypassrls AS unsafe_owner FROM pg_catalog.pg_database d JOIN pg_catalog.pg_roles r ON r.oid=d.datdba WHERE d.datname=pg_catalog.current_database()`)).rows if(facts.length!==1||facts[0].datname!==databaseName||facts[0].owner!==ownerRole||facts[0].session_role!==ownerRole||facts[0].current_role!==ownerRole||facts[0].unsafe_owner!==false)throw new Error() const state=(await client.query(`SELECT EXISTS(SELECT 1 FROM mmapp_control.bandwidth_attempts) OR EXISTS(SELECT 1 FROM mmapp_control.bandwidth_node_occupancy) OR EXISTS(SELECT 1 FROM mmapp_control.bandwidth_attempt_events) OR EXISTS(SELECT 1 FROM mmapp_control.bandwidth_source_identity) AS occupied`)).rows if(state.length!==1||state[0].occupied!==false)throw new Error() await assertBandwidthControlRuntimeRole(runtime,{databaseName,runtimeRole,ownerRole},live) const record:BandwidthControlRecord={format:"mmapp-bandwidth-control-source-v1",installationId:randomUUID(),controlGeneration:randomUUID(), databaseName,databaseOid:Number(facts[0].oid),runtimeRole,ownerRole,endpointSha256:bandwidthControlEndpointSha256(config.databaseUrl), schemaSourceSha256:bandwidthControlSchemaSourceSha256(),catalogSha256:await observeBandwidthControlCatalog(runtime,live), eventKeySha256:sha(eventKey),attestationRef:config.attestationRef} const bytes=Buffer.from(canonicalBandwidthControlRecord(record)),pending=config.attestationFile+".pending" const envelope=JSON.stringify({format:"mmapp-bandwidth-control-envelope-v1",payload:bytes.toString("base64url"),signature:sign(null,bytes,privateKey).toString("base64url")}) // wx is the durable attempt marker. Never truncate it on rerun. Publishing // also uses a no-replace hard link, so an existing attestation is untouched. const file=await open(pending,"wx",0o600) try{await file.writeFile(envelope);await file.sync()}finally{await file.close()} await syncParent(pending) live() await client.query("INSERT INTO mmapp_control.bandwidth_source_identity(id,installation_id,control_generation,attestation_sha256,event_key_sha256) VALUES(1,$1,$2,$3,$4)",[record.installationId,record.controlGeneration,sha(bytes),record.eventKeySha256]) live();commitStarted=true;await client.query("COMMIT");transaction=false;live() client.release();client=undefined const checked=createConfiguredBandwidthControlSource({...config,attestationFile:pending}) try{await checked.identity({deadlineAt:Math.min(deadline,Date.now()+10000)})}finally{await checked.close()} live();await link(pending,config.attestationFile);await syncParent(config.attestationFile);live() return Object.freeze(record) }catch{ if(transaction&&!commitStarted&&client)try{await client.query("ROLLBACK")}catch{/* Destroy below; no retry. */} throw new BandwidthControlProvisionError() }finally{ clearTimeout(timer);eventKey?.fill(0);privateBytes?.fill(0);client?.release(true) await Promise.allSettled([owner?.end(),runtime?.end()]) } }