/** * @module sync-peer-websocket-receiver-v1 */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../../core-constants.mjs'; import { SyncPeer_V1 } from '../../sync-peer-v1.mjs'; import { SyncSagaContextIbGib_V1 } from '../../../sync-saga-context/sync-saga-context-types.mjs'; import { authenticateContextIntrinsically } from '../../../sync-saga-context/sync-saga-context-helpers.mjs'; import { IbGibSpaceAny } from '../../../../witness/space/space-base-v1.mjs'; import { putInSpace, registerNewIbGib } from '../../../../witness/space/space-helper.mjs'; import { ConnectSyncPeerWebSocketReceiverOpts, InitializeSyncPeerWebSocketReceiverOpts, SyncPeerWebSocketReceiverData_V1, SyncPeerWebSocketReceiverRel8ns_V1, SyncPeerWebSocketReceiverIbGib_V1 } from './sync-peer-websocket-receiver-types.mjs'; import { KeystoneIbGib_V1 } from '../../../../keystone/keystone-types.mjs'; import { SyncWebSocketMsgType } from '../sync-peer-websocket-constants.mjs'; import { SESSION_KEYSTONE_POLICY, verifyConnectProof, packBinaryDomainPayload, unpackBinaryDomainPayload, chunkDomainPayloads } from './sync-websocket-peer-helpers.mjs'; import { SyncStage } from '../../../sync-constants.mjs'; import { getSyncSagaMessageFromFrame } from '../../../sync-saga-message/sync-saga-message-helpers.mjs'; import { createInMemoryTempSpace, getFullSyncSagaHistory, putInSpace_dnasThenNonDnas, getTransferredPayloadAddressesFromHistory } from '../../../sync-helpers.mjs'; import { toDto, isBinary } from '../../../../common/other/ibgib-helper.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * A platform-agnostic interface wrapping runtime-specific WebSocket stream operations. */ export interface IWebSocketWrapper { send(data: string | Uint8Array): void; onMessage(callback: (data: string | Uint8Array) => void): void; onClose(callback: () => void): void; close(): void; } /** * Platform-agnostic WebSocket Receiver Peer. * * Fully encapsulates the multi-turn cryptographic challenge connect and runtime * turn routing. */ export class SyncPeerWebSocketReceiver_V1 extends SyncPeer_V1 implements SyncPeerWebSocketReceiverIbGib_V1 { protected override lc: string = `[${SyncPeerWebSocketReceiver_V1.name}]`; override get classname(): string { return SyncPeerWebSocketReceiver_V1.name; } declare data: SyncPeerWebSocketReceiverData_V1 | undefined; declare rel8ns: SyncPeerWebSocketReceiverRel8ns_V1 | undefined; protected socketWrapper?: IWebSocketWrapper; // Connect State Machine variables protected isAuthenticated = false; protected challengeUuid?: string; protected demandedIds?: string[]; protected sessionS_tjpAddr?: string; // Runtime state variables for delayed payload streaming protected pendingContext?: SyncSagaContextIbGib_V1; protected pendingPayloadAddrs?: Set; protected pendingResponsePayloadsToSend: IbGib_V1[] = []; protected receivedPayloads: IbGib_V1[] = []; constructor( initialData: SyncPeerWebSocketReceiverData_V1, initialRel8ns?: SyncPeerWebSocketReceiverRel8ns_V1, ) { super(initialData, initialRel8ns); } /** * Wires the peer receiver to the platform-specific socket stream and * triggers the connect. */ public async bindSocket(socketWrapper: IWebSocketWrapper): Promise { const lc = `${this.lc}[${this.bindSocket.name}]`; this.socketWrapper = socketWrapper; socketWrapper.onMessage((data) => this.handleIncomingMessage(data)); socketWrapper.onClose(() => { this.cleanupLocalTempSpace().catch(err => { if (logalot) { console.warn(`${lc} onClose cleanup error: ${extractErrorMsg(err)}`); } }); }); // Immediately trigger multi-turn challenge connection try { this.challengeUuid = await getUUID(); socketWrapper.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_challenge_init, challengeUuid: this.challengeUuid })); } catch (error) { console.error(`${lc} failed triggering challenge init: ${extractErrorMsg(error)}`); socketWrapper.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_fail, message: 'Internal server connect error' })); } } protected override async preConnectCheck(opts: ConnectSyncPeerWebSocketReceiverOpts): Promise { // Handled dynamically on upgrade } protected override async connectImpl(opts: ConnectSyncPeerWebSocketReceiverOpts): Promise { // Handled dynamically on upgrade } protected override async postEstablishToReceiver(opts: { newSenderIdentity: KeystoneIbGib_V1; sessionIdentity: KeystoneIbGib_V1; }): Promise { throw new Error(`postEstablishToReceiver is not supported on Receiver Peer (E: 309f3cf8e7c813d338394f28c576da26)`); } protected override async sendContextRequest(context: SyncSagaContextIbGib_V1): Promise { throw new Error(`sendContextRequest is not supported on Receiver Peer (E: e5327ed6c64883e12ef95984f1409926)`); } /** Helper to load a Session Keystone from controlSpace */ protected async getSessionKeystone(sAddr: string): Promise { const metaspace = this.opts!.localMetaspace; const controlSpace = this.opts!.controlSpace; if (!controlSpace) { throw new Error(`controlSpace not initialized. (E: 112233445566778899aabbccddeeff26)`); } const resGet = await metaspace.get({ addrs: [sAddr], space: controlSpace }); if (resGet.success && resGet.ibGibs && resGet.ibGibs.length === 1) { return resGet.ibGibs[0] as KeystoneIbGib_V1; } throw new Error(`Session keystone not found in controlSpace: ${sAddr} (E: 42315837e3b1deb5b81072f8601e6a26)`); } protected async ensureLocalTempSpace(): Promise { const lc = `${this.lc}[${this.ensureLocalTempSpace.name}]`; try { if (!this.opts) { throw new Error(`opts not initialized. (E: c4929fb1596833a7186d119855bb7e26)`); } if (!this.opts.localTempSpace) { const uuid = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36); const now = new Date(); const dateStr = now.toISOString().slice(0, 10).replace(/-/g, ''); const tempSpaceName = `tmp_sync_recv_${dateStr}_${uuid.substring(0, 8)}`; if (this.opts.useInMemoryTempSpace) { this.opts.localTempSpace = await createInMemoryTempSpace({ name: tempSpaceName }); } else if (this.opts.localMetaspace) { const localTempSpace = await this.opts.localMetaspace.createNewLocalSpace({ opts: { allowCancel: false, spaceName: tempSpaceName, getFnPrompt: this.opts.localMetaspace.getFnPrompt!, logalot } }); if (!localTempSpace) { throw new Error(`couldn't create a temp space (E: d82461769b4bbb35df5d6a8a9c665426)`); } await localTempSpace.initialized; this.opts.localTempSpace = localTempSpace; } else { this.opts.localTempSpace = await createInMemoryTempSpace({ name: tempSpaceName }); } } return this.opts.localTempSpace; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Cleans up the ephemeral quarantine temp space created during this sync session. */ public async cleanupLocalTempSpace(): Promise { const lc = `${this.lc}[${this.cleanupLocalTempSpace.name}]`; try { if (!this.opts?.localTempSpace) { return; } const tempSpace = this.opts.localTempSpace; this.opts.localTempSpace = undefined; if (this.opts.onCleanupTempSpace) { try { await this.opts.onCleanupTempSpace(tempSpace); } catch (cleanupErr) { console.error(`${lc} onCleanupTempSpace error: ${extractErrorMsg(cleanupErr)}`); } } if (this.opts.localMetaspace && tempSpace.data?.uuid) { try { await this.opts.localMetaspace.deleteLocalUserSpace({ spaceId: tempSpace.data.uuid, deletePhysicalStorage: true, }); } catch (metaErr) { // Non-fatal if space was already unlinked or in-memory if (logalot) { console.log(`${lc} deleteLocalUserSpace note: ${extractErrorMsg(metaErr)}`); } } } } catch (error) { console.error(`${lc} cleanupLocalTempSpace failed: ${extractErrorMsg(error)}`); } } /** * Entry point for processing raw text or binary frames received over the active WebSocket connection. */ public async handleIncomingMessage(message: string | Uint8Array): Promise { const lc = `${this.lc}[${this.handleIncomingMessage.name}]`; try { if (!this.socketWrapper) { throw new Error(`WebSocket wrapper not bound to receiver peer (E: ad4c5838d1b87259586b21a89b2c7726)`); } // 1. Binary payload frame (opcode 0x2) if (typeof message !== 'string') { if (!this.isAuthenticated) { throw new Error(`Unexpected binary frame during unauthenticated connect phase (E: b9283741ac604928b812374615283726)`); } const rawBytes = message instanceof Uint8Array ? message : new Uint8Array(message); const ibGib = unpackBinaryDomainPayload(rawBytes); await this.handleIncomingDomainPayload(ibGib); return; } const msg = JSON.parse(message); if (logalot) { console.log(`${lc} received frame: ${msg.type}`); } // 2. Connect Phase Route Guard if (!this.isAuthenticated) { await this.handleConnectFrame(msg); return; /* <<<< returns early */ } // 3. Authenticated Runtime Sync Route if (msg.type === SyncWebSocketMsgType.domain_payload) { const ibGib = msg.ibGib as IbGib_V1; await this.handleIncomingDomainPayload(ibGib); } else if (msg.type === SyncWebSocketMsgType.domain_payload_batch) { const ibGibs = (msg.ibGibs || []) as IbGib_V1[]; for (const ibGib of ibGibs) { await this.handleIncomingDomainPayload(ibGib); } } else if (msg.type === SyncWebSocketMsgType.sync_frame) { const context = msg.context as SyncSagaContextIbGib_V1; // First, validate and authenticate the context const allControlIbGibs: IbGib_V1[] = [ toDto({ ibGib: context }), context.sagaFrame, context.sagaFrameMsg ]; if (context.signedSessionIdentity) { allControlIbGibs.push(context.signedSessionIdentity); } for (const controlIbGib of allControlIbGibs) { const validationErrors = await validateIbGibIntrinsically({ ibGib: controlIbGib }) ?? []; if (validationErrors.length > 0) { throw new Error(`controlIbGibs invalid intrinsically. validationErrors: ${validationErrors.join('|')} (E: d40dfa87265a0b73c8ef784d1265ea26)`); } } await this.authenticateAndValidate({ context }); // Put control ibgibs into durable controlSpace immediately for audit trail for (const ibGib of allControlIbGibs) { await putInSpace({ space: this.opts!.controlSpace, ibGibs: [ibGib] }); await registerNewIbGib({ space: this.opts!.controlSpace, ibGib }); } // Check if payloads are expected const expectedPayloadAddrs = context.data?.['@payloadAddrsDomain'] || []; if (expectedPayloadAddrs.length > 0) { // Set up wait state and request payloads this.pendingContext = context; this.pendingPayloadAddrs = new Set(expectedPayloadAddrs); this.receivedPayloads = []; this.socketWrapper.send(JSON.stringify({ type: SyncWebSocketMsgType.sync_frame_authenticated, contextAddr: getIbGibAddr({ ibGib: context }) })); } else { // No payloads expected, process immediately await this.executeIncomingSyncRequestAndRespond({ context }); } } else if (msg.type === SyncWebSocketMsgType.sync_frame_response_authenticated) { // Alice authenticated our response context, stream our payloads now const payloads = this.pendingResponsePayloadsToSend || []; this.pendingResponsePayloadsToSend = []; const chunks = chunkDomainPayloads({ payloads }); let batchIndex = 0; const totalBatches = chunks.filter(c => c.type === 'text_batch').length; for (const chunk of chunks) { if (chunk.type === 'binary_single' && chunk.binaryIbGib) { const packet = packBinaryDomainPayload(chunk.binaryIbGib); this.socketWrapper.send(packet); } else if (chunk.type === 'text_batch' && chunk.ibGibs && chunk.ibGibs.length > 0) { for (const ibGib of chunk.ibGibs) { if (ibGib.data instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(ibGib.data))) { throw new Error(`(UNEXPECTED) non-binary ibgib (${getIbGibAddr({ ibGib })}) contains Uint8Array/Buffer data! (E: a1827364bc091823bc71625344192836)`); } } this.socketWrapper.send(JSON.stringify({ type: SyncWebSocketMsgType.domain_payload_batch, batchIndex, totalBatches, itemCount: chunk.ibGibs.length, ibGibs: chunk.ibGibs })); batchIndex++; } } } else { throw new Error(`(UNEXPECTED) msg.type is ${msg.type}? not expected at this time (E: bad7c4fa1958b1976904cb884e624826)`); } } catch (error) { console.error(`${lc} message frame handling failed: ${extractErrorMsg(error)}`); try { this.socketWrapper?.send(JSON.stringify({ type: this.isAuthenticated ? SyncWebSocketMsgType.sync_error : SyncWebSocketMsgType.auth_fail, message: extractErrorMsg(error) })); } catch (nestedError) { console.error(`${lc}[nested catch] failed to send error frame: ${extractErrorMsg(nestedError)}`); } finally { this.socketWrapper?.close(); } } } /** * Processes a single incoming domain payload ibGib (either decoded from binary frame or JSON text). */ protected async handleIncomingDomainPayload(ibGib: IbGib_V1): Promise { const lc = `${this.lc}[${this.handleIncomingDomainPayload.name}]`; const validationErrors = await validateIbGibIntrinsically({ ibGib }) ?? []; if (validationErrors.length > 0) { throw new Error(`controlIbGibs invalid intrinsically. validationErrors: ${validationErrors.join('|')} (E: 5ee1787d4cc53d3d2c55f3d4f2865226)`); } const pendingPayloadAddrs = this.pendingPayloadAddrs; if (this.pendingContext && pendingPayloadAddrs) { const addr = getIbGibAddr({ ibGib }); if (pendingPayloadAddrs.has(addr)) { const tempSpace = await this.ensureLocalTempSpace(); await putInSpace_dnasThenNonDnas({ space: tempSpace, ibGibs: [ibGib] }); this.receivedPayloads.push(ibGib); pendingPayloadAddrs.delete(addr); // If all expected payloads for the pending context are received if (pendingPayloadAddrs.size === 0 && this.pendingPayloadAddrs !== undefined) { const context = this.pendingContext; context.payloadIbGibsDomain = this.receivedPayloads; this.receivedPayloads = []; this.pendingContext = undefined; this.pendingPayloadAddrs = undefined; await this.executeIncomingSyncRequestAndRespond({ context }); } } else { console.warn(`${lc} received payload not in expected list: ${addr}`); } } } /** * Handles the multi-turn cryptographic challenge connect messages. */ protected async handleConnectFrame(msg: any): Promise { const lc = `${this.lc}[${this.handleConnectFrame.name}]`; const metaspace = this.opts!.localMetaspace; const controlSpace = this.opts!.controlSpace; if (msg.type === SyncWebSocketMsgType.auth_init) { const { sAddr } = msg; if (logalot) { console.log(`${lc} auth-init for ${sAddr}`); } const authorizedS = await this.getSessionKeystone(sAddr); const connectPool = (authorizedS.data?.challengePools ?? []) .find(p => p.id === SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID); if (!connectPool) { throw new Error(`Session keystone missing "${SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID}" pool (E: 66b2a2e32db8f03168f6f2a8b746cb26)`); } // Demand random challenges const challengeIds = Object.keys(connectPool.challenges); this.demandedIds = challengeIds.sort(() => 0.5 - Math.random()).slice(0, SESSION_KEYSTONE_POLICY.CONNECT_POOL.SERVER_DEMAND_COUNT); // Resolve secure S TJP const past = authorizedS.rel8ns?.past; this.sessionS_tjpAddr = (past && past.length > 0) ? past[0] : getIbGibAddr({ ibGib: authorizedS }); this.socketWrapper!.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_challenge, challengeUuid: this.challengeUuid, demandedIds: this.demandedIds })); } else if (msg.type === SyncWebSocketMsgType.auth_proof) { const { proofFrame } = msg; if (logalot) { console.log(`${lc} verifying auth-proof...`); } if (!this.sessionS_tjpAddr) { throw new Error(`Missing active connect session TJP address (E: bf271853de61a04b6d05d6889263f826)`); } const sAddr_latest = await metaspace.getLatestAddr({ tjpAddr: this.sessionS_tjpAddr, space: controlSpace }); if (!sAddr_latest) { throw new Error(`Authorized session keystone tip not found in controlSpace (E: b8cda5cdc058903318db536f59e8e826)`); } const sKeystone_latest = await this.getSessionKeystone(sAddr_latest); // Cryptographically verify proof evolution and demand solutions await verifyConnectProof({ proofFrame, sKeystone_latest, challengeUuid: this.challengeUuid!, demandedIds: this.demandedIds! }); // Persist the newly validated evolved session keystone tip in controlSpace await metaspace.put({ ibGibs: [proofFrame], space: controlSpace }); await metaspace.registerNewIbGib({ ibGib: proofFrame, space: controlSpace }); if (logalot) { console.log(`${lc} connect validation successful! Connection upgraded to active sync session.`); } this.isAuthenticated = true; this.socketWrapper!.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_ok })); } else { throw new Error(`Unexpected message type ${msg.type} during connect phase (E: f67a0f47f8426c2b01af5bc3d0146b26)`); } } /** * Executes the incoming sync request through the local SyncSagaCoordinator and sends response. */ protected async executeIncomingSyncRequestAndRespond({ context }: { context: SyncSagaContextIbGib_V1; }): Promise { const lc = `${this.lc}[${this.executeIncomingSyncRequestAndRespond.name}]`; try { if (logalot) { console.log(`${lc} executing incoming sync turn...`); } if (!this.opts) { throw new Error(`opts not initialized. (E: 0c98186714e85b9a08bb9d98daada826)`); } const { localCoordinator, localMetaspace, controlSpace, domainSpace } = this.opts; const localTempSpace = await this.ensureLocalTempSpace(); const responseCtx = await localCoordinator.continueSync({ sagaContext: context, metaspace: localMetaspace, controlSpace, domainSpace, myTempSpace: localTempSpace, peer: this, }); if (responseCtx) { const responsePayloads = responseCtx.payloadIbGibsDomain ?? []; delete responseCtx.payloadIbGibsDomain; // Save payloads to stream once authenticated by Alice this.pendingResponsePayloadsToSend = responsePayloads; this.socketWrapper!.send(JSON.stringify({ type: SyncWebSocketMsgType.sync_frame_response, context: responseCtx })); } // Check if this turn completed the saga (commit stage or saga finished) let isCommit = false; let finalFrame: any = undefined; if (responseCtx?.sagaFrame) { try { const msg = await getSyncSagaMessageFromFrame({ frameIbGib: responseCtx.sagaFrame, space: controlSpace, }); if (msg?.data?.stage === SyncStage.commit) { isCommit = true; finalFrame = responseCtx.sagaFrame; } } catch (err) { // Not a commit frame or unable to read message stone } } else if (!responseCtx) { if (logalot) { console.log(`${lc} synchronization session completed successfully.`); } isCommit = true; finalFrame = context.sagaFrame; } if (isCommit && this.opts?.onSyncComplete) { try { let transferredAddrs: string[] | undefined = undefined; if (finalFrame) { try { const sagaHistory = await getFullSyncSagaHistory({ sagaIbGib: finalFrame, controlSpace, }); transferredAddrs = getTransferredPayloadAddressesFromHistory({ sagaHistory, }); if (logalot) { console.log(`${lc} onSyncComplete extracted ${transferredAddrs?.length ?? 0} transferredAddrs from saga history.`); } } catch (histErr) { console.error(`${lc} failed getting full saga history for onSyncComplete: ${extractErrorMsg(histErr)}`); } } await this.opts.onSyncComplete({ context: responseCtx ?? context, controlSpace, domainSpace, metaspace: localMetaspace, transferredAddrs, }); } catch (hookErr) { console.error(`${lc} onSyncComplete hook failed: ${extractErrorMsg(hookErr)}`); } } if (isCommit) { await this.cleanupLocalTempSpace(); } } catch (error) { console.error(`${lc} executeIncomingSyncRequestAndRespond failed: ${extractErrorMsg(error)}`); throw error; } } }