/** * @module sync-websocket-peer-helpers * * Reusable, isomorphic pure validation helper functions and policies for the * WebSocket Sync Peer connect process. */ import { HashAlgorithm, extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr, getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs'; import { validateIbGibAddr, validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs'; import { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs'; import { IbGib_V1, IbGibRel8ns_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../../core-constants.mjs'; import { KeystoneReplenishStrategy, KeystoneChallengeType, KeystoneIbGib_V1, KeystoneSolution, KeystoneChallenge, KEYSTONE_CLAIM_TYPE_CHANGE_PASSWORD, KEYSTONE_CLAIM_TYPE_ADD_POOL, KEYSTONE_CLAIM_TYPE_REMOVE_POOL, KEYSTONE_CLAIM_TYPE_REPLACE_POOL } from '../../../../keystone/keystone-types.mjs'; import { parseKeystoneIb, validateKeystoneIb } from '../../../../keystone/keystone-helpers.mjs'; import { KeystoneStrategyFactory } from '../../../../keystone/strategy/keystone-strategy-factory.mjs'; import { KeystoneService_V1 } from '../../../../keystone/keystone-service-v1.mjs'; import { IbGibSpaceAny } from '../../../../witness/space/space-base-v1.mjs'; import { MetaspaceService } from '../../../../witness/space/metaspace/metaspace-types.mjs'; import { POOL_ID_CONNECT, KEYSTONE_VERB_CONNECT, KEYSTONE_VERB_SYNC, KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_AUTHOR } from '../../../../keystone/keystone-constants.mjs'; import { getTjpAddr, isBinary } from '../../../../common/other/ibgib-helper.mjs'; const logalot = GLOBAL_LOG_A_LOT /** * Standard configuration defaults for the Ephemeral Session Keystone. */ export const SESSION_KEYSTONE_POLICY = { COMMON: { ALGO: HashAlgorithm.sha_256, TYPE: KeystoneChallengeType.hash_reveal_v1, ROUNDS: 2, REPLENISH: KeystoneReplenishStrategy.topUp, }, CONNECT_POOL: { ID: POOL_ID_CONNECT, VERB: KEYSTONE_VERB_CONNECT, SIZE: 10, SELECT_SEQUENTIALLY: 2, SELECT_RANDOMLY: 2, TARGET_BINDING_COUNT: 0, SERVER_DEMAND_COUNT: 3, } } as const; /** * Resolves the deterministic dynamic upfront pre-filter challenge. */ export function getConnectChallenge(keystone: KeystoneIbGib_V1): { challengeId: string; challenge: KeystoneChallenge; } { const lc = `[${getConnectChallenge.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 3c791af2f978a00a087dfdde90884826)`); } const connectPool = (keystone.data?.challengePools ?? []).find( (p) => p.id === SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID ); if (!connectPool) { throw new Error(`Keystone missing "${SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`); } const challengeIds = Object.keys(connectPool.challenges).sort(); if (challengeIds.length === 0) { throw new Error(`Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)`); } const challengeId = challengeIds[0]; const challenge = connectPool.challenges[challengeId]; return { challengeId, challenge }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates the upfront solution against the session keystone's first connect * challenge. */ export async function checkConnectSolution( keystone: KeystoneIbGib_V1, solutionValue: string ): Promise { const lc = `[${checkConnectSolution.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 166aa101e109194556e6b99575945826)`); } const connectPool = (keystone.data?.challengePools ?? []).find( (p) => p.id === SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID ); if (!connectPool) { return false; } const { challengeId, challenge } = getConnectChallenge(keystone); const strategy = KeystoneStrategyFactory.create({ config: connectPool.config }); const solution: KeystoneSolution = { type: 'hash-reveal-v1', challengeId, poolId: SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID, value: solutionValue }; return await strategy.validateSolution({ solution, challenge }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates the upfront connect parameter solutions before socket connection upgrades. */ export async function validateUpfrontConnect({ sAddr, solution, space, metaspace, }: { sAddr: string; solution: string; space: IbGibSpaceAny; metaspace: MetaspaceService; }): Promise<{ sAddr_tjp: string; authorizedS: KeystoneIbGib_V1 }> { const lc = `[${validateUpfrontConnect.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 7c21ecaf0b7f59347882bc18d8245826)`); } // 1. Initial address sanity check const addrErrors = validateIbGibAddr({ addr: sAddr }) ?? []; if (addrErrors.length > 0) { throw new Error(`Invalid sAddr: ${addrErrors.join(', ')} (E: 9a80cea03308ddab721eec08ffe0e826)`); } const { ib } = getIbAndGib({ ibGibAddr: sAddr }); parseKeystoneIb({ ib }); // 2. Fetch session keystone from storage const resGet = await metaspace.get({ addrs: [sAddr], space }); if (!resGet.success || !resGet.ibGibs || resGet.ibGibs.length !== 1) { throw new Error(`Session keystone not found in space: ${sAddr} (E: d381a8269328dbe6b8a9e4f86c2a3626)`); } const authorizedS = resGet.ibGibs[0] as KeystoneIbGib_V1; // 3. Cryptographically check dynamic solution const isValid = await checkConnectSolution(authorizedS, solution); if (!isValid) { throw new Error(`Upfront connect solution verification failed (E: 67c5b17968b8829058925d8808d09826)`); } // 4. Resolve secure TJP const past = authorizedS.rel8ns?.past; const sAddr_tjp = (past && past.length > 0) ? past[0] : getIbGibAddr({ ibGib: authorizedS }); return { sAddr_tjp, authorizedS }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Verifies the multi-turn evolved Keystone challenge proof frame. */ export async function verifyConnectProof({ proofFrame, sKeystone_latest, challengeUuid, demandedIds, }: { proofFrame: KeystoneIbGib_V1; sKeystone_latest: KeystoneIbGib_V1; challengeUuid: string; demandedIds: string[]; }): Promise { const lc = `[${verifyConnectProof.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 4500528dabb80aeb98dabf886d6b2826)`); } // 1. Validate evolution structure intrinsically const keystoneService = new KeystoneService_V1(); const validationErrors = await keystoneService.validate({ prevIbGib: sKeystone_latest, currentIbGib: proofFrame, }); if (validationErrors && validationErrors.length > 0) { throw new Error(`Proof validation failed: ${validationErrors.join(', ')} (E: e70278c90dc475a2d80d0ad8bbf1a826)`); } // 2. Validate connect target signature const proofs = proofFrame.data.proofs ?? []; const proof = proofs.find(p => p.claim?.verb === SESSION_KEYSTONE_POLICY.CONNECT_POOL.VERB); if (!proof || proof.claim?.target !== challengeUuid) { throw new Error(`Proof target mismatch or missing connect claim (E: e897bba1bb6161b418a630c1e30c5726)`); } // 3. Verify client successfully solved all demanded challenges const solvedIds = new Set(proof.solutions?.map(s => s.challengeId) ?? []); const missingIds = demandedIds.filter(id => !solvedIds.has(id)); if (missingIds.length > 0) { throw new Error(`Proof is missing demanded solutions: ${missingIds.join(', ')} (E: 161329081aff00f1a8e4cf9330a62326)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Isomorphic pure function to intrinsically validate, persist, and register * posted keystones. Shared between REST API and sync websocket receiver peers. */ export async function validateAndRegisterPostKeystones({ ibGibs, metaspace, space }: { ibGibs: any[]; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `[${validateAndRegisterPostKeystones.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: aae81e3412c8c87bc8f3e227d81be826)`); } // 1. Intrinsic Validation for (const ibGib of ibGibs) { const errors = await validateIbGibIntrinsically({ ibGib }); if (errors && errors.length > 0) { throw new Error(`Intrinsic validation failed for ${getIbGibAddr({ ibGib })}: ${errors.join(', ')} (E: 4162884c53183b58b3caaa48c26be826)`); } } // 2. Keystone-specific checks & Registration for (const ibGib of ibGibs) { if (ibGib.ib?.startsWith('keystone')) { // Registration handles genesis vs evolution internally via metastones await metaspace.registerNewIbGib({ ibGib, space }); } } // 3. Persistence await metaspace.put({ ibGibs, space }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Isomorphic pure function to validate a keystone evolution transition and * related S session keystones, and persist them to metaspace. Shared across * REST API evolve handlers and future socket evolution channels. */ export async function validateAndRegisterEvolveKeystone({ domainAddr, keystoneIbGib, relatedKeystoneIbGibs = [], metaspace, space }: { /** * Address of the root parent domain identity keystone. */ domainAddr: string; /** * The main evolved keystone frame being synchronized. */ keystoneIbGib: KeystoneIbGib_V1; /** * Array of other keystone frames related to this evolution. * Distinction in intent: * 1. Ephemeral Session Keystones: Temporary keystones generated to verify * WebSocket connection sessions (under 'sync' claims, targeted via * claim.target = sAddr). * 2. Persistent Delegate Keystones: Long-lived sub-keystones registered in * the parent's `delegates` dictionary that are evolved concurrently * (e.g., during 'manage' password changes). */ relatedKeystoneIbGibs?: IbGib_V1[]; /** * The MetaspaceService instance. */ metaspace: MetaspaceService; /** * The active storage space. */ space: IbGibSpaceAny; }): Promise { const lc = `[${validateAndRegisterEvolveKeystone.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 42b826a690881cd5a8fe520cbdfad826)`); } // 1. Intrinsic hash validation on primary keystone const intrinsicErrors = await validateIbGibIntrinsically({ ibGib: keystoneIbGib }); if (intrinsicErrors && intrinsicErrors.length > 0) { throw new Error(`Intrinsic keystone validation failed: ${intrinsicErrors.join(', ')} (E: 38ea984585edc6ee88d2a698c7895826)`); } // 2. Proofs & Verb extraction const proofs = keystoneIbGib.data?.proofs ?? []; if (proofs.length === 0) { throw new Error('No proofs found in evolved keystone data (E: c09ca224636f2fcad05aed7a31a251ff)'); } if (proofs.length !== 1) { throw new Error(`evolving keystone with proofs.length !== 1? (E: 14e058a34964dcd7181395382cc60826)`); } const claim = proofs[0].claim; if (!claim) { throw new Error(`proof.claim is falsy (E: 54be88be2c975ef18e571a4286928826)`); } const verb = claim.verb; if (!verb) { throw new Error(`claim.verb is falsy (E: 92cf38af58db2cd90e7132b8940fe326)`); } // 3. Load latest root Domain Identity tip in space const keystoneService = new KeystoneService_V1(); let parentKeystone: KeystoneIbGib_V1; try { parentKeystone = await keystoneService.getLatestKeystone({ addr: domainAddr, metaspace, space }); } catch (error) { throw new Error(`Could not retrieve root Domain Identity tip for ${domainAddr}: ${extractErrorMsg(error)} (E: b73ed8aeb0d837d248718b487345d326)`); } const parentTjpAddr = getTjpAddr({ ibGib: parentKeystone }); const incomingTjpAddr = getTjpAddr({ ibGib: keystoneIbGib }); if (!incomingTjpAddr) { throw new Error(`Incoming keystone does not have a TJP address (E: 7bea0998a23d3243e7fe9da65a4f5c49)`); } const isDelegate = incomingTjpAddr !== parentTjpAddr; // 4. Primary Verb Branching switch (verb) { case KEYSTONE_VERB_MANAGE: await validateManageEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space }); break; case KEYSTONE_VERB_SYNC: await validateSyncEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space }); break; case KEYSTONE_VERB_AUTHOR: await validateAuthorEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space }); break; default: throw new Error(`Unsupported keystone evolution verb: ${verb} (E: eca4681b05486d1f784c0cb815ef9926)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates and registers a keystone evolution authorized by a 'manage' verb claim. * * ## Assumptions (ATOW 07/2026) * - The primary Domain Identity evolution step is authorized by a single proof. * - Sub-verb details (`claim.details?.type`) specify the structural management operation * (e.g. 'change-password', 'add-pool', 'remove-pool'). * - Under 'change-password', relatedKeystoneIbGibs contains outward delegate keystones being * registered or evolved concurrently. * - Delegates evolve independently by design, so `delegateInfo.delegateAddr` in the parent keystone * captures historical registration context. Active delegate tip resolution queries the space via * `keystoneService.getLatestKeystone({ addr: delegateTjpAddr, metaspace, space })`. */ async function validateManageEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space, }: { keystoneIbGib: KeystoneIbGib_V1; relatedKeystoneIbGibs: IbGib_V1[]; parentKeystone: KeystoneIbGib_V1; isDelegate: boolean; domainAddr: IbGibAddr; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `[validateManageEvolveKeystone]`; const keystoneService = new KeystoneService_V1(); // 1. Validate parent Domain Identity keystone transition from current tip in space const transitionErrors = await keystoneService.validate({ currentIbGib: keystoneIbGib, prevIbGib: parentKeystone }); if (transitionErrors && transitionErrors.length > 0) { throw new Error(`Parent Domain Identity evolution validation failed: ${transitionErrors.join(', ')} (E: 5212f8492ac839953842631834bcd826)`); } const proof = keystoneIbGib.data?.proofs?.[0]; const claim = proof?.claim; const claimType = claim?.details?.type; const prevDelegates = parentKeystone.data?.delegates ?? {}; const currDelegates = keystoneIbGib.data?.delegates ?? {}; // 2. Sub-verb branching based on claim details type switch (claimType) { case KEYSTONE_CLAIM_TYPE_CHANGE_PASSWORD: case KEYSTONE_CLAIM_TYPE_ADD_POOL: case KEYSTONE_CLAIM_TYPE_REMOVE_POOL: case KEYSTONE_CLAIM_TYPE_REPLACE_POOL: default: // Validate all related delegate keystones provided in cargo for (const related of relatedKeystoneIbGibs) { const ibIsValid = await validateKeystoneIb({ ib: related.ib }); if (!ibIsValid) { throw new Error(`Invalid related keystone ibgib. related.ib (${related.ib}) is not a valid keystone ib. (E: 89dff2f48fa8c33b449081e2478c6826)`); } const relatedTjp = getTjpAddr({ ibGib: related }); if (!relatedTjp) { throw new Error(`Related keystone in relatedKeystoneIbGibs is missing a TJP address (E: 2fe5a68438e288ab4e86c90d81d142826)`); } const relatedAddr = getIbGibAddr({ ibGib: related }); // Assert it is registered under the current delegates map of the parent const delegateInfo = currDelegates[relatedTjp]; if (!delegateInfo) { throw new Error(`Related keystone (${relatedTjp}) is not a registered delegate under parent Domain Identity (E: 3fe5a68438e288ab4e86c90d81d142826)`); } const delegateIsNewlyRegistered = !prevDelegates[relatedTjp]; if (delegateIsNewlyRegistered) { const delegateKeystone = related as KeystoneIbGib_V1; const delegatePrimaryTjpAddr = delegateKeystone.data?.frameDetails?.primaryTjpAddr; const parentPrimaryTjpAddr = getTjpAddr({ ibGib: parentKeystone }); if (delegatePrimaryTjpAddr !== parentPrimaryTjpAddr) { throw new Error(`Newly registered delegate keystone (${relatedAddr}) has primaryTjpAddr mismatch. Expected ${parentPrimaryTjpAddr}, got ${delegatePrimaryTjpAddr}. (E: 5cdd0dee42d7d437ef6af698150cfe26)`); } if (delegateKeystone.data?.n !== 0) { throw new Error(`Newly registered delegate keystone (${relatedAddr}) has data.n !== 0 (${delegateKeystone.data?.n}). Registering non-genesis delegate keystones is not supported at this time. (E: 4cdd0dee42d7d437ef6af698150cfe26)`); } const genesisErrors = await keystoneService.validateGenesisKeystone({ keystoneIbGib: delegateKeystone }); if (genesisErrors && genesisErrors.length > 0) { throw new Error(`Genesis validation failed for new delegate keystone ${relatedAddr}: ${genesisErrors.join(', ')} (E: d8afdc1dbed48c000455b35585dc26826)`); } } else { // Transition/Evolution validation against the delegate's active tip in space let prevDelegateTip: KeystoneIbGib_V1 | undefined; try { prevDelegateTip = await keystoneService.getLatestKeystone({ addr: relatedTjp, metaspace, space }); } catch (err) { throw new Error(`Could not find previous delegate tip for ${relatedTjp} in space: ${extractErrorMsg(err)} (E: 5fe5a68438e288ab4e86c90d81d142826)`); } const evolutionErrors = await keystoneService.validate({ currentIbGib: related as KeystoneIbGib_V1, prevIbGib: prevDelegateTip }); if (evolutionErrors && evolutionErrors.length > 0) { throw new Error(`Evolution transition validation failed for delegate keystone ${relatedAddr}: ${evolutionErrors.join(', ')} (E: 6fe5a68438e288ab4e86c90d81d142826)`); } } } break; } // Persist parent and related keystones await metaspace.put({ ibGibs: [keystoneIbGib, ...relatedKeystoneIbGibs], space }); await metaspace.registerNewIbGib({ ibGib: keystoneIbGib, space }); for (const related of relatedKeystoneIbGibs) { if (related.ib?.startsWith('keystone')) { await metaspace.registerNewIbGib({ ibGib: related, space }); } } } /** * Validates and registers a sync delegate keystone evolution and its associated session keystone. * * ## Assumptions (ATOW 07/2026) * - The evolving keystone must be an authorized outward delegate (Root Domain Identity cannot sync directly). * - The claim verb is 'sync'. * - relatedKeystoneIbGibs contains the newly created session keystone (S^Stjp) target address specified in claim.target. */ async function validateSyncEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space, }: { keystoneIbGib: KeystoneIbGib_V1; relatedKeystoneIbGibs: IbGib_V1[]; parentKeystone: KeystoneIbGib_V1; isDelegate: boolean; domainAddr: IbGibAddr; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `[validateSyncEvolveKeystone]`; const keystoneService = new KeystoneService_V1(); if (!isDelegate) { throw new Error(`Root Domain Identity (${domainAddr}) is not allowed to sync directly. A delegate must be used. (E: 30cbb6acf7a8b258180f081c5a5fed95)`); } const incomingTjpAddr = getTjpAddr({ ibGib: keystoneIbGib }); if (!incomingTjpAddr) { throw new Error(`Incoming delegate keystone missing TJP address (E: cb14567d70383c6085b49848351849ab)`); } // Verify delegate is registered under root Domain Identity const delegateInfo = parentKeystone.data?.delegates?.[incomingTjpAddr]; if (!delegateInfo) { throw new Error(`Incoming delegate keystone (${incomingTjpAddr}) is not registered under parent Domain Identity (E: 07410e9e255c06721f8e202e073084b3)`); } // Verify delegate is authorized for sync and has truthy spaceId const allowedVerbs = delegateInfo.allowedVerbs ?? []; const isSyncDelegate = (delegateInfo as any).role === 'sync-delegate' || allowedVerbs.includes('sync') || allowedVerbs.includes(KEYSTONE_VERB_SYNC); if (!allowedVerbs.includes(KEYSTONE_VERB_SYNC) && !isSyncDelegate) { throw new Error(`Incoming delegate keystone is not authorized for sync. Allowed verbs: ${allowedVerbs.join(', ')} (E: 25f3a7317d7835ed9312279c027b16ae)`); } const delegateSpaceId = delegateInfo.spaceId || (delegateInfo as any).details?.spaceId; if (isSyncDelegate && !delegateSpaceId) { throw new Error(`Sync delegate (${incomingTjpAddr}) is missing required spaceId (E: 7648c45ca937ae2ce3521988d7537ab7)`); } // Load delegate's previous tip from space using keystoneService.getLatestKeystone if it exists let prevDelegateTip: KeystoneIbGib_V1 | undefined; try { prevDelegateTip = await keystoneService.getLatestKeystone({ addr: incomingTjpAddr, metaspace, space }); } catch (err) { // No previous tip found in space yet; will validate graph below } if (prevDelegateTip) { const validationErrors = await keystoneService.validate({ currentIbGib: keystoneIbGib, prevIbGib: prevDelegateTip, }); if (validationErrors && validationErrors.length > 0) { throw new Error(`Sync delegate keystone evolution validation failed: ${validationErrors.join(', ')} (E: 5212f8492ac839953842631834bcd827)`); } } else { throw new Error(`Previous tip for sync delegate (${incomingTjpAddr}) not found in space. Sync delegate must be registered under parent Domain Identity and evolve lock-step a single frame at a time. (E: a00fb5bf3e1a2f7c125b7b5c4bd049c9)`); } const proof = keystoneIbGib.data?.proofs?.[0]; const claim = proof?.claim; const sAddr = claim?.target; if (!sAddr) { throw new Error('No target address found in sync claim'); } // Validate S^Stjp (session keystone ibgib) from relatedKeystoneIbGibs const sIbGib = relatedKeystoneIbGibs.find(ibGib => getIbGibAddr({ ibGib }) === sAddr) as KeystoneIbGib_V1 | undefined; if (!sIbGib) { throw new Error(`Session keystone ${sAddr} must be provided in relatedKeystoneIbGibs (E: fe5a68438e288ab4e86c90d81d142826)`); } const sIntrinsicErrors = await validateIbGibIntrinsically({ ibGib: sIbGib }); if (sIntrinsicErrors && sIntrinsicErrors.length > 0) { throw new Error(`Intrinsic validation failed for S^Stjp: ${sIntrinsicErrors.join(', ')} (E: 802d8350c3cccbd7184dd43866c05526)`); } const sGenesisErrors = await keystoneService.validateGenesisKeystone({ keystoneIbGib: sIbGib }); if (sGenesisErrors && sGenesisErrors.length > 0) { throw new Error(`Genesis validation failed for S^Stjp: ${sGenesisErrors.join(', ')} (E: 8afdc1dbed48c000455b35585dc26826)`); } // Persist and Register both I and S await metaspace.put({ ibGibs: [keystoneIbGib, sIbGib], space }); await metaspace.registerNewIbGib({ ibGib: keystoneIbGib, space }); await metaspace.registerNewIbGib({ ibGib: sIbGib, space }); } /** * Validates a transition from prevTip to targetKeystone, supporting single-step * (n -> n+1) or multi-step (n -> n+k) transitions via intermediate frames in relatedKeystones. */ async function validateKeystoneTransitionChain({ keystoneService, targetKeystone, prevTip, relatedKeystones = [], }: { keystoneService: KeystoneService_V1; targetKeystone: KeystoneIbGib_V1; prevTip: KeystoneIbGib_V1; relatedKeystones?: IbGib_V1[]; }): Promise { const prevN = prevTip.data?.n ?? 0; const targetN = targetKeystone.data?.n ?? 0; if (targetN <= prevN) { throw new Error(`Target keystone frame (n: ${targetN}) is not newer than previous tip in space (n: ${prevN}). (E: 7f1908bcae482716b9cb4819d4218826)`); } if (targetN === prevN + 1) { // Direct single-step evolution const validationErrors = await keystoneService.validate({ currentIbGib: targetKeystone, prevIbGib: prevTip, }); if (validationErrors && validationErrors.length > 0) { throw new Error(`Single-step keystone evolution validation failed: ${validationErrors.join(', ')} (E: 5212f8492ac839953842631834bcd827)`); } return; } // Multi-step evolution (n -> n+k): collect and sort intermediate frames const targetTjp = getTjpAddr({ ibGib: targetKeystone }); const intermediateFrames = relatedKeystones .filter(x => (x as any).data?.n !== undefined && getTjpAddr({ ibGib: x }) === targetTjp) .sort((a, b) => ((a as any).data.n) - ((b as any).data.n)) as KeystoneIbGib_V1[]; let currentPrev = prevTip; const fullChain = [...intermediateFrames, targetKeystone]; for (const frame of fullChain) { const frameN = frame.data?.n ?? 0; const currentPrevN = currentPrev.data?.n ?? 0; if (frameN !== currentPrevN + 1) { throw new Error(`Gap in keystone evolution chain: expected n = ${currentPrevN + 1}, found n = ${frameN}. Intermediate frames missing. (E: 81ba829104efca89110294bcf8419926)`); } const stepErrors = await keystoneService.validate({ currentIbGib: frame, prevIbGib: currentPrev, }); if (stepErrors && stepErrors.length > 0) { throw new Error(`Keystone evolution validation failed at step n = ${frameN}: ${stepErrors.join(', ')} (E: 99ba10284cfeb9102847192837bcda26)`); } currentPrev = frame; } } /** * Validates and registers an author delegate keystone evolution. */ async function validateAuthorEvolveKeystone({ keystoneIbGib, relatedKeystoneIbGibs, parentKeystone, isDelegate, domainAddr, metaspace, space, }: { keystoneIbGib: KeystoneIbGib_V1; relatedKeystoneIbGibs: IbGib_V1[]; parentKeystone: KeystoneIbGib_V1; isDelegate: boolean; domainAddr: IbGibAddr; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `[validateAuthorEvolveKeystone]`; const keystoneService = new KeystoneService_V1(); if (!isDelegate) { throw new Error(`Root Domain Identity (${domainAddr}) is not allowed to author commits directly. An author delegate must be used. (E: 55552f5f4632a226a6f4d57899443693)`); } const incomingTjpAddr = getTjpAddr({ ibGib: keystoneIbGib }); if (!incomingTjpAddr) { throw new Error(`Incoming author delegate keystone missing TJP address (E: 9dc7f59d1970bf3b228086a65947be65)`); } // Verify delegate is registered under root Domain Identity const delegateInfo = parentKeystone.data?.delegates?.[incomingTjpAddr]; if (!delegateInfo) { throw new Error(`Incoming delegate keystone (${incomingTjpAddr}) is not registered under parent Domain Identity (E: 67d6b5cd6c5be01d8f7ba086039bacb8)`); } // Verify delegate is authorized for author const allowedVerbs = delegateInfo.allowedVerbs ?? []; const isAuthorDelegate = (delegateInfo as any).role === 'author-delegate' || allowedVerbs.includes('author') || allowedVerbs.includes(KEYSTONE_VERB_AUTHOR); if (!allowedVerbs.includes(KEYSTONE_VERB_AUTHOR) && !isAuthorDelegate) { throw new Error(`Incoming delegate keystone is not authorized for authoring commits. Allowed verbs: ${allowedVerbs.join(', ')} (E: 1fd45bf4b14996e44b65da82353aca3f)`); } // Load delegate's previous tip from space using keystoneService.getLatestKeystone if it exists let prevDelegateTip: KeystoneIbGib_V1 | undefined; try { prevDelegateTip = await keystoneService.getLatestKeystone({ addr: incomingTjpAddr, metaspace, space }); } catch (err) { // No previous tip found in space yet; will validate graph below } if (prevDelegateTip) { await validateKeystoneTransitionChain({ keystoneService, targetKeystone: keystoneIbGib, prevTip: prevDelegateTip, relatedKeystones: relatedKeystoneIbGibs, }); } else { const validationErrors = await keystoneService.validateKeystoneGraph({ keystoneIbGib, getLatest: false, invalidIfMoreRecentKeystoneFoundInSpace: false, space }); if (validationErrors && validationErrors.length > 0) { throw new Error(`Author delegate keystone graph validation failed: ${validationErrors.join(', ')} (E: 2507d83bb88f834723e3f500103b3703)`); } } // Sort all author frames sequentially in ascending chronological order (data.n) const targetTjp = incomingTjpAddr; const authorFramesToPersist = [ ...relatedKeystoneIbGibs.filter(x => getTjpAddr({ ibGib: x }) === targetTjp), keystoneIbGib ].sort((a, b) => ((a as any).data?.n ?? 0) - ((b as any).data?.n ?? 0)); // Persist and register each keystone frame sequentially in ascending order await metaspace.put({ ibGibs: authorFramesToPersist, space }); for (const frame of authorFramesToPersist) { if (frame.ib?.startsWith('keystone')) { await metaspace.registerNewIbGib({ ibGib: frame, space }); } } } /** * Packages a binary ibGib into a length-prefixed binary packet for direct WebSocket transmission: * [4-byte meta JSON length (Big-Endian UInt32)][metadata JSON (UTF-8)][raw binary payload bytes] */ export function packBinaryDomainPayload(ibGib: IbGib_V1): Uint8Array { if (!isBinary({ ibGib })) { throw new Error(`packBinaryDomainPayload called on non-binary ibgib: ${ibGib.ib} (E: a928371bfca04899b827e8a918237126)`); } if (!(ibGib.data instanceof Uint8Array) && !(typeof Buffer !== 'undefined' && Buffer.isBuffer(ibGib.data))) { throw new Error(`isBinary ibgib data must be Uint8Array or Buffer: ${ibGib.ib} (E: f1829374abc09182bc83716253449126)`); } if (!ibGib.gib) { throw new Error(`packBinaryDomainPayload requires ibGib to have a gib: ${ibGib.ib} (E: 8fbc1829037482910385718293049182)`); } const meta: { ib: string; gib: string; rel8ns?: IbGibRel8ns_V1 } = { ib: ibGib.ib, gib: ibGib.gib, }; if (ibGib.rel8ns && Object.keys(ibGib.rel8ns).length > 0) { meta.rel8ns = ibGib.rel8ns; } const metaBytes = new TextEncoder().encode(JSON.stringify(meta)); const rawBytes = ibGib.data instanceof Uint8Array ? ibGib.data : new Uint8Array((ibGib.data as Buffer).buffer, (ibGib.data as Buffer).byteOffset, (ibGib.data as Buffer).byteLength); const packet = new Uint8Array(4 + metaBytes.length + rawBytes.length); const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength); view.setUint32(0, metaBytes.length, false); // big-endian packet.set(metaBytes, 4); packet.set(rawBytes, 4 + metaBytes.length); return packet; } /** * Reconstitutes an IbGib_V1 from a length-prefixed binary packet received over WebSocket: * [4-byte meta JSON length (Big-Endian UInt32)][metadata JSON (UTF-8)][raw binary payload bytes] */ export function unpackBinaryDomainPayload(packet: Uint8Array): IbGib_V1 { if (packet.byteLength < 4) { throw new Error(`Binary domain payload packet too short: ${packet.byteLength} bytes (E: d8271635ab09182bc716253441928326)`); } const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength); const metaLen = view.getUint32(0, false); if (packet.byteLength < 4 + metaLen) { throw new Error(`Binary domain payload packet truncated: length ${packet.byteLength} < 4 + metaLen ${metaLen} (E: e9182736bc8271635449182736152426)`); } const metaBytes = packet.subarray(4, 4 + metaLen); const metaStr = new TextDecoder('utf-8').decode(metaBytes); const meta = JSON.parse(metaStr) as { ib: string; gib: string; rel8ns?: IbGibRel8ns_V1 }; const rawData = packet.subarray(4 + metaLen); const ibGib: IbGib_V1 = { ib: meta.ib, gib: meta.gib, data: rawData, }; if (meta.rel8ns && Object.keys(meta.rel8ns).length > 0) { ibGib.rel8ns = meta.rel8ns; } return ibGib; } /** * Default threshold constants for domain payload batching: * - Up to 50 ibgibs per batch * - Up to 2 MB total serialized payload per batch */ export const DEFAULT_SYNC_BATCH_MAX_ITEMS = 50; export const DEFAULT_SYNC_BATCH_MAX_BYTES = 2 * 1024 * 1024; // 2MB export interface DomainPayloadChunk { type: 'text_batch' | 'binary_single'; ibGibs?: IbGib_V1[]; binaryIbGib?: IbGib_V1; } /** * Splits an array of domain ibgibs into transmission chunks: * - Group text/JSON ibgibs into batches of up to maxItems or maxBytes * - Send binary stones individually via opcode 0x2 */ export function chunkDomainPayloads({ payloads, maxItems = DEFAULT_SYNC_BATCH_MAX_ITEMS, maxBytes = DEFAULT_SYNC_BATCH_MAX_BYTES }: { payloads: IbGib_V1[]; maxItems?: number; maxBytes?: number; }): DomainPayloadChunk[] { const chunks: DomainPayloadChunk[] = []; let currentBatch: IbGib_V1[] = []; let currentBatchBytes = 0; function flushCurrentBatch(): void { if (currentBatch.length > 0) { chunks.push({ type: 'text_batch', ibGibs: currentBatch, }); currentBatch = []; currentBatchBytes = 0; } } for (const ibGib of payloads) { if (isBinary({ ibGib })) { flushCurrentBatch(); chunks.push({ type: 'binary_single', binaryIbGib: ibGib, }); } else { // Rough estimate of serialized size let dataLen = 0; if (typeof ibGib.data === 'string') { dataLen = (ibGib.data as string).length; } else if (ibGib.data !== undefined && ibGib.data !== null) { try { dataLen = JSON.stringify(ibGib.data).length; } catch { dataLen = 100; } } const estBytes = (ibGib.ib?.length || 0) + (ibGib.gib?.length || 0) + dataLen; if (currentBatch.length >= maxItems || (currentBatchBytes + estBytes > maxBytes && currentBatch.length > 0)) { flushCurrentBatch(); } currentBatch.push(ibGib); currentBatchBytes += estBytes; } } flushCurrentBatch(); return chunks; }