/** * @module sync-withid.establish.respec * * Phase 1 — `establishSessionIdentity` (Pre-Connect) * * Goal: Get `I^Itjp` onto the domain provider, generate `S^Stjp` locally, * evolve `I → I1` with a `sync` claim targeting `S^Stjp`, and post both * `I1` and `S` to the provider. Verify both keystones are in the appropriate * durable spaces at the right times. * * `senderCoordinator.sync(...)` IS called — we are not mocking. We expect it * may throw at first. We examine side-effects (keystone presence in durable * spaces) rather than end-to-end correctness. As phases succeed and sync no * longer throws, assertions will be adjusted accordingly. * * @see libs/core-gib/src/sync/docs/security.md — Implementation Plan, Phase 1A */ import { respecfully, ifWeMight, iReckon, ifWe } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs'; const maam = `[${import.meta.url}]`, sir = maam; import { clone, delay, extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../core-constants.mjs'; import { SyncSagaCoordinator } from './sync-saga-coordinator.mjs'; import { getFromSpace } from '../witness/space/space-helper.mjs'; import { Metaspace_Innerspace } from '../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace.mjs'; import { InnerSpace_V1 } from '../witness/space/inner-space/inner-space-v1.mjs'; import { SyncPeerInnerspace_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-v1.mjs'; import { DEFAULT_INNER_SPACE_DATA_V1 } from '../witness/space/inner-space/inner-space-types.mjs'; import { SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-constants.mjs'; import { KeystoneService_V1 } from '../keystone/keystone-service-v1.mjs'; import { KeystoneIbGib_V1 } from '../keystone/keystone-types.mjs'; import { KEYSTONE_VERB_SYNC, POOL_ID_SYNC, POOL_ID_CONNECT, KEYSTONE_VERB_CONNECT } from '../keystone/keystone-constants.mjs'; import { createStandardPoolConfig } from '../keystone/keystone-config-builder.mjs'; import { KeystoneReplenishStrategy } from '../keystone/keystone-types.mjs'; import { SyncConflictStrategy } from './sync-constants.mjs'; import { IbGibAddr, TransformResult } from '@ibgib/ts-gib/dist/types.mjs'; import { IbGibSpaceAny } from '../witness/space/space-base-v1.mjs'; import { MetaspaceService } from '../witness/space/metaspace/metaspace-types.mjs'; import { getIdentity_throwIfUndefined } from '../keystone/keystone-helpers.mjs'; import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs'; import { fork } from '@ibgib/ts-gib/dist/V1/transforms/fork.mjs'; import { SYNC_SPACE_MODES, createSyncTestSpaces, verifySyncControlAndDomainSpaces } from './sync-respec-helper.mjs'; const logalot = GLOBAL_LOG_A_LOT; const lc = sir; const SENDER_SECRET = 'test-sender-secret-phase1'; const SESSION_CONNECT_POOL_CONFIG = createStandardPoolConfig({ id: POOL_ID_CONNECT, salt: 'session-connect-salt-phase1', verbs: [KEYSTONE_VERB_CONNECT], size: 10, sequential: 1, random: 1, targetBinding: 2, replenishStrategy: KeystoneReplenishStrategy.deleteAll, }); const SESSION_SYNC_POOL_CONFIG = createStandardPoolConfig({ id: POOL_ID_SYNC, salt: 'session-sync-salt-phase1', verbs: [KEYSTONE_VERB_SYNC], size: 200, sequential: 1, random: 1, targetBinding: 2, replenishStrategy: KeystoneReplenishStrategy.topUp, }); const SENDER_IDENTITY_SYNC_POOL_CONFIG = createStandardPoolConfig({ id: POOL_ID_SYNC, salt: 'senderidentitysyncsaltphase1', verbs: [KEYSTONE_VERB_SYNC], size: 200, sequential: 1, random: 1, targetBinding: 2, replenishStrategy: KeystoneReplenishStrategy.topUp, }); await respecfully(sir, `Test Phase 1: establishSessionIdentity`, async () => { for (const spaceMode of SYNC_SPACE_MODES) { await respecfully(sir, `establishSessionIdentity [${spaceMode}]`, async () => { const metaspace = new Metaspace_Innerspace(undefined); await metaspace.initialize({ getFnAlert: () => async ({ title, msg }) => { console.log(`[Alert] ${title}: ${msg}`); }, getFnPrompt: () => async ({ title, msg }) => { console.log(`[Prompt] ${title}: ${msg}`); return ''; }, getFnPromptPassword: () => async (title, msg) => { console.log(`[PromptPwd] ${title}: ${msg}`); return null; }, }); while (!metaspace.initialized) { await delay(10); } const defaultLocalUserSpace = await metaspace.getLocalUserSpace({ lock: false }); await defaultLocalUserSpace!.initialized; const { sourceControlSpace, sourceDomainSpace, destControlSpace, destDomainSpace, } = await createSyncTestSpaces({ spaceMode, prefix: 'establish' }); const senderCoordinator = new SyncSagaCoordinator(); const receiverCoordinator = new SyncSagaCoordinator(); async function newTestIbGib_stone({ ib = 'test', data }: { ib: string, data?: any }): Promise { const stone = await Factory_V1.stone({ parentPrimitiveIb: ib.split(' ').at(0) ?? 'test', ib, data, uuid: true, }); return stone; } async function newTestPeer(): Promise { const peer = new SyncPeerInnerspace_V1(clone(SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1)); await peer.initialized; await peer.initializeOpts({ sagaId: '', localMetaspace: metaspace, controlSpace: sourceControlSpace, domainSpace: sourceDomainSpace, receiverControlSpace: destControlSpace, receiverDomainSpace: destDomainSpace, receiverCoordinator, receiverMetaspace: metaspace, }); return peer; } const keystoneSvc = new KeystoneService_V1(); const senderIdentity = await keystoneSvc.genesis({ masterSecret: SENDER_SECRET, configs: [SENDER_IDENTITY_SYNC_POOL_CONFIG], metaspace, space: sourceControlSpace, }); if (logalot) { console.log(`${lc} senderIdentity genesis addr: ${getIbGibAddr({ ibGib: senderIdentity })}`); } await metaspace.put({ ibGib: senderIdentity, space: destControlSpace }); await metaspace.registerNewIbGib({ ibGib: senderIdentity, space: destControlSpace }); let xStone!: IbGib_V1; let xStoneAddr!: IbGibAddr; try { if (logalot) { console.log(`${lc}[Step 2] starting... (I: 1aa5643dd8d46fcdd87d48b8be550826)`); } xStone = await newTestIbGib_stone({ ib: 'test' }); xStoneAddr = getIbGibAddr({ ibGib: xStone }); await metaspace.put({ ibGib: xStone, space: sourceDomainSpace }); await metaspace.registerNewIbGib({ ibGib: xStone, space: sourceDomainSpace }); const syncSaga = await senderCoordinator.sync({ domainIbGibs: [xStone], senderIdentityInfo: { senderIdentity, senderDomainAddr: getIbGibAddr({ ibGib: senderIdentity }), }, fnSenderSecret: async () => { return SENDER_SECRET }, peer: await newTestPeer(), controlSpace: sourceControlSpace, domainSpace: sourceDomainSpace, metaspace, conflictStrategy: SyncConflictStrategy.optimisticWithLCS, }); await syncSaga.done; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); } finally { if (logalot) { console.log(`${lc}[Step 2] complete.`); } } let newSenderIdentityAddr: IbGibAddr | undefined; let newSenderIdentity: KeystoneIbGib_V1 | undefined; await ifWe(sir, 'newSenderIdentity created and stored in sourceControlSpace', async () => { newSenderIdentityAddr = await metaspace.getLatestAddr({ ibGib: senderIdentity, space: sourceControlSpace, }); if (!newSenderIdentityAddr) { throw new Error(`newSenderIdentity not found in space (${sourceControlSpace.ib}). this should have been evolved and stored during sync (E: a5a798bf8ba467cbc87595dcc2b36726)`); } newSenderIdentity = await getIdentity_throwIfUndefined({ addr: newSenderIdentityAddr, metaspace, space: sourceControlSpace, }); iReckon(sir, newSenderIdentity).asTo('newSenderIdentity is truthy').isGonnaBeTruthy(); const syncProof = newSenderIdentity?.data?.proofs?.find(p => p.claim?.verb === KEYSTONE_VERB_SYNC); iReckon(sir, syncProof).asTo('I1 has a sync-verb proof/claim').isGonnaBeTruthy(); iReckon(sir, syncProof?.claim?.target).asTo('sync claim has a target (S^Stjp)').isGonnaBeTruthy(); }); if (!newSenderIdentity) { throw new Error(`(UNEXPECTED) newSenderIdentity falsy? should have thrown before this if falsy. (E: 7a3d92e6160409de149eaf6802365126)`); } const sessionIdentityTjpAddr = newSenderIdentity.data.proofs .find(p => p.claim.verb === KEYSTONE_VERB_SYNC)?.claim.target; if (!sessionIdentityTjpAddr) { throw new Error(`(UNEXPECTED) sessionIdentityTjpAddr falsy? (E: c53583b07a78837de84a59388b6ff826)`); } let sessionIdentity: KeystoneIbGib_V1 | undefined; await ifWe(sir, 'creates sessionIdentity genesis (S) locally — exists in sourceControlSpace', async () => { sessionIdentity = await getIdentity_throwIfUndefined({ addr: sessionIdentityTjpAddr, metaspace, space: sourceControlSpace, }); iReckon(sir, sessionIdentity).asTo('sessionIdentity is truthy').isGonnaBeTruthy(); }); if (!sessionIdentity) { throw new Error(`(UNEXPECTED) sessionIdentity falsy? (E: e1fa06009df535f3c848e6ca8b0bd326)`); } await ifWe(sir, 'Session identity S has expected state', async () => { if (!sessionIdentity || !sessionIdentity.data) { throw new Error(`(UNEXPECTED) sessionIdentity/data falsy? (E: dd229f4e44489a54488768157a393926)`); } const sPools = sessionIdentity.data.challengePools; iReckon(sir, sPools).asTo('S has challengePools').isGonnaBeTruthy(); const hasConnectPool = sPools?.some(p => p.id === POOL_ID_CONNECT); const hasSyncPool = sPools?.some(p => p.id === POOL_ID_SYNC); iReckon(sir, hasConnectPool).asTo('S has connect pool').isGonnaBeTrue(); iReckon(sir, hasSyncPool).asTo('S has sync pool').isGonnaBeTrue(); const sProofs = sessionIdentity.data.proofs; iReckon(sir, sProofs).asTo('S has proofs array').isGonnaBeTruthy(); iReckon(sir, sProofs.length === 0).asTo('S has 0 proofs on genesis').isGonnaBeTrue(); const targetAddrs = sessionIdentity.data.frameDetails?.targetAddrs; iReckon(sir, targetAddrs).asTo('S has targetAddrs array in frameDetails').isGonnaBeTruthy(); iReckon(sir, targetAddrs?.includes(xStoneAddr)).asTo('S targetAddrs contains the domain being synced (xStoneAddr)').isGonnaBeTrue(); }); await ifWe(sir, 'I, I1 and S all exist in destControlSpace (receiver)', async () => { const senderIdentityAddr = getIbGibAddr({ ibGib: senderIdentity! }); await getIdentity_throwIfUndefined({ addr: senderIdentityAddr, metaspace, space: destControlSpace }); iReckon(sir, true).asTo('I (original) exists in destControlSpace').isGonnaBeTrue(); if (!newSenderIdentityAddr) { throw new Error(`newSenderIdentity not found in space (${sourceControlSpace.ib}). this should have been evolved and stored during sync (E: b626885071885b38d87853189f25c826)`); } await getIdentity_throwIfUndefined({ addr: newSenderIdentityAddr, metaspace, space: destControlSpace }); iReckon(sir, true).asTo('I1 (evolved) exists in destControlSpace').isGonnaBeTrue(); await getIdentity_throwIfUndefined({ addr: sessionIdentityTjpAddr, metaspace, space: destControlSpace }); iReckon(sir, true).asTo('S (sessionIdentity) exists in destControlSpace').isGonnaBeTrue(); }); await verifySyncControlAndDomainSpaces({ sir, spaceMode, senderCoordinator, sourceControlSpace, sourceDomainSpace, destControlSpace, destDomainSpace, domainIbGibs: [xStone], }); }); } });