/** * @module sync-peer-websocket-sender-v1 */ import { extractErrorMsg } 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 { KeystoneIbGib_V1 } from '../../../../keystone/keystone-types.mjs'; import { KeystoneService_V1 } from '../../../../keystone/keystone-service-v1.mjs'; import { KeystoneStrategyFactory } from '../../../../keystone/strategy/keystone-strategy-factory.mjs'; import { deriveSessionSecret } from '../../../sync-helpers.mjs'; import { SyncPeer_V1 } from '../../sync-peer-v1.mjs'; import { SyncSagaContextIbGib_V1 } from '../../../sync-saga-context/sync-saga-context-types.mjs'; import { validateContextAndSagaFrame } from '../../../sync-saga-context/sync-saga-context-helpers.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../../core-constants.mjs'; import { ConnectSyncPeerWebSocketSenderOpts, InitializeSyncPeerWebSocketSenderOpts, SyncPeerWebSocketSenderData_V1, SyncPeerWebSocketSenderRel8ns_V1, SyncPeerWebSocketSenderIbGib_V1 } from './sync-peer-websocket-sender-types.mjs'; import { SESSION_KEYSTONE_POLICY, getConnectChallenge, packBinaryDomainPayload, unpackBinaryDomainPayload, chunkDomainPayloads } from '../sync-peer-websocket-receiver/sync-websocket-peer-helpers.mjs'; import { SyncWebSocketMsgType, isSyncWebSocketMsgType, SYNC_WEB_SOCKET_MSG_TYPE_VALID_VALUES } from '../sync-peer-websocket-constants.mjs'; import { toDto, isBinary } from '../../../../common/other/ibgib-helper.mjs'; import { putInSpace, registerNewIbGib } from '../../../../witness/space/space-helper.mjs'; /** * helper in creating compile-time safety that we're handling all message types. */ function assertUnreachable(x: never): never { throw new Error(`Unhandled message type: ${x} (E: e928a3f82cd7469a98ef1bc248a3f826)`); } const logalot = GLOBAL_LOG_A_LOT; /** * WebSocket Sender Peer implementation running in browser/native environment. */ export class SyncPeerWebSocketSender_V1 extends SyncPeer_V1 implements SyncPeerWebSocketSenderIbGib_V1 { protected override lc: string = `[${SyncPeerWebSocketSender_V1.name}]`; override get classname(): string { return SyncPeerWebSocketSender_V1.name; } public get isSocketOpen(): boolean { return this.ws !== undefined && this.ws.readyState === WebSocket.OPEN; } declare data: SyncPeerWebSocketSenderData_V1 | undefined; declare rel8ns: SyncPeerWebSocketSenderRel8ns_V1 | undefined; protected ws?: WebSocket; protected activeResolve?: (value: SyncSagaContextIbGib_V1 | undefined) => void; protected activeReject?: (reason: any) => void; protected pendingPayloadsToSend: IbGib_V1[] = []; protected handshakeMessageListener?: (event: MessageEvent) => Promise; constructor( initialData: SyncPeerWebSocketSenderData_V1, initialRel8ns?: SyncPeerWebSocketSenderRel8ns_V1, ) { super(initialData, initialRel8ns); } protected override async preConnectCheck(opts: ConnectSyncPeerWebSocketSenderOpts): Promise { const lc = `${this.lc}[${this.preConnectCheck.name}]`; if (!this.data?.wsUrl) { throw new Error(`Missing wsUrl in peer data (E: 144c6ddf53980554cf08fa0896bd9826)`); } if (!this.data?.httpEvolveUrl) { throw new Error(`Missing httpEvolveUrl in peer data (E: 53425c1a13f829b8e8a55c2cea3a4a26)`); } } /** * Submits the evolved master identity (I1) and new session keystone (S) to the server's HTTP registry. */ protected override async postEstablishToReceiver({ newSenderIdentity, sessionIdentity, }: { newSenderIdentity: KeystoneIbGib_V1; sessionIdentity: KeystoneIbGib_V1; }): Promise { const lc = `${this.lc}[${this.postEstablishToReceiver.name}]`; try { if (logalot) { console.log(`${lc} posting evolved keystones to ${this.data!.httpEvolveUrl}...`); } if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)`); } if (!this.data.httpEvolveUrl) { throw new Error(`(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)`); } const response = await fetch(this.data.httpEvolveUrl, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ keystoneIbGib: newSenderIdentity, relatedKeystoneIbGibs: [sessionIdentity] }), }); if (!response.ok) { const data = await response.json().catch(() => ({})); const errorMsg = data.message || data.error || 'Unknown error'; throw new Error(`HTTP ${response.status} evolution post rejected. errorMsg: ${errorMsg} (E: e8a478291b88d05c68cf6b385684b826)`); } if (logalot) { console.log(`${lc} evolve post accepted by server.`); } } catch (error) { console.error(`${lc} establish post failed: ${extractErrorMsg(error)}`); throw error; } } /** * Establishes the stateful WebSocket connection and performs the multi-turn cryptographic challenge connect. */ protected override async connectImpl(opts: ConnectSyncPeerWebSocketSenderOpts): Promise { const lc = `${this.lc}[${this.connectImpl.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } const { senderIdentity, fnSenderSecret, sagaId } = this.opts!; if (!senderIdentity || !fnSenderSecret || !sagaId) { throw new Error(`Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)`); } // 1. Solve upfront pre-filter solution const senderSecret = await fnSenderSecret(); const sessionSecret = await deriveSessionSecret({ senderSecret, sagaId }); // Use the session keystone S established immediately prior in establishSessionIdentity() const sessionS = this.currentSessionIdentity; if (!sessionS) { throw new Error(`currentSessionIdentity falsy. establishSessionIdentity() must be called before connect() (E: 225607318bef485d7821f82de97b6826)`); } const targetSAddr = getIbGibAddr({ ibGib: sessionS }); // Solve dynamic upfront picket-fence challenge const connectPool = (sessionS.data?.challengePools ?? []) .find(p => p.id === SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID); if (!connectPool) { throw new Error(`Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)`); } const { challengeId } = getConnectChallenge(sessionS); const strategy = KeystoneStrategyFactory.create({ config: connectPool.config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: sessionSecret }); const solution = await strategy.generateSolution({ poolSecret, poolId: SESSION_KEYSTONE_POLICY.CONNECT_POOL.ID, challengeId }); // 2. Open WebSocket connection let baseWsUrl = this.data!.wsUrl; const coords = this.opts?.destinationSpaceCoords ?? this.data?.destinationSpaceCoords; if (coords) { const coordsPath = `/${encodeURIComponent(coords.cosmosName)}/${encodeURIComponent(coords.galaxyName)}/${encodeURIComponent(coords.branchName)}`; if (!baseWsUrl.includes(coordsPath)) { baseWsUrl = baseWsUrl.replace(/\/+$/, '') + coordsPath; } } let wsUrl = `${baseWsUrl}?sAddr=${encodeURIComponent(targetSAddr)}&solution=${encodeURIComponent(solution.value)}`; if (coords?.spaceId) { wsUrl += `&spaceId=${encodeURIComponent(coords.spaceId)}`; } if (logalot) { console.log(`${lc} connecting to WebSocket: ${wsUrl}`); } const ws = new WebSocket(wsUrl); ws.binaryType = 'arraybuffer'; this.ws = ws; return new Promise((resolve, reject) => { let isResolved = false; ws.addEventListener('open', () => { if (logalot) { console.log(`${lc} WebSocket opened. Awaiting challenge...`); } }); this.handshakeMessageListener = async (ev) => { try { const msg = JSON.parse(ev.data); if (logalot) { console.log(`${lc} received handshake frame: ${msg.type}`); } const msgType = msg.type; if (!isSyncWebSocketMsgType(msgType)) { const validTypes = SYNC_WEB_SOCKET_MSG_TYPE_VALID_VALUES.join(', '); throw new Error(`Unknown message type '${msgType}' received during connection handshake. Valid types are: ${validTypes} (E: 9e88934c7c8be758fcd921a3a6e0c021)`); } switch (msgType) { case SyncWebSocketMsgType.auth_challenge_init: await this.handleHandshakeAuthChallengeInit(ws, targetSAddr); break; case SyncWebSocketMsgType.auth_challenge: await this.handleHandshakeAuthChallenge(ws, msg, sessionS, sessionSecret); break; case SyncWebSocketMsgType.auth_ok: isResolved = true; this.handleHandshakeAuthOk(ws, resolve); break; case SyncWebSocketMsgType.auth_fail: this.handleHandshakeAuthFail(msg, reject); break; case SyncWebSocketMsgType.sync_error: this.handleHandshakeSyncError(msg, reject); break; // Protocol violations / unexpected messages during connection handshake case SyncWebSocketMsgType.auth_init: case SyncWebSocketMsgType.auth_proof: case SyncWebSocketMsgType.sync_frame: case SyncWebSocketMsgType.sync_frame_response: case SyncWebSocketMsgType.sync_frame_authenticated: case SyncWebSocketMsgType.sync_frame_response_authenticated: case SyncWebSocketMsgType.domain_payload: case SyncWebSocketMsgType.domain_payload_batch: throw new Error(`Unexpected message type '${msgType}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`); default: assertUnreachable(msgType); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); reject(error); } }; ws.addEventListener('message', this.handshakeMessageListener); ws.addEventListener('close', (event) => { if (!isResolved) { this.disconnect(); reject(new Error(`WebSocket closed before connect completed (code: ${event.code})`)); } }); ws.addEventListener('error', (err) => { if (!isResolved) { this.disconnect(); reject(new Error(`WebSocket connection error`)); } }); }); } catch (error) { console.error(`${lc} connect failed: ${extractErrorMsg(error)}`); throw error; } } /** * Cleanly closes the socket and removes the handshake message listener. * * LOGS AND SWALLOWS ERRORS, DOES NOT THROW */ public disconnect(): void { const lc = `${this.lc}[${this.disconnect.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`); } if (this.ws) { if (this.handshakeMessageListener) { this.ws.removeEventListener('message', this.handshakeMessageListener); this.handshakeMessageListener = undefined; } try { this.ws.close(); } catch (error) { console.error(`${lc} failed to close websocket: ${extractErrorMsg(error)}`); } this.ws = undefined; } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); // throw error; // disconnect does NOT rethrow } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Handles synchronizing messages and evolved context frames during active transaction turns. */ protected async handleRuntimeMessage(event: MessageEvent): Promise { const lc = `${this.lc}[${this.handleRuntimeMessage.name}]`; try { // Check if binary frame (ArrayBuffer / Uint8Array / Buffer) if (typeof event.data !== 'string') { const rawBytes = event.data instanceof Uint8Array ? event.data : new Uint8Array(event.data); const payload = unpackBinaryDomainPayload(rawBytes); this.payloadIbGibsDomainReceived$.next(payload); return; } const msg = JSON.parse(event.data); if (logalot) { console.log(`${lc} received runtime frame: ${msg.type}`); } const msgType = msg.type; if (!isSyncWebSocketMsgType(msgType)) { const validTypes = SYNC_WEB_SOCKET_MSG_TYPE_VALID_VALUES.join(', '); throw new Error(`Unknown message type '${msgType}' received during active sync saga loop. Valid types are: ${validTypes} (E: 066444bcb2f1177352583d9752f28305)`); } switch (msgType) { case SyncWebSocketMsgType.sync_frame_response: await this.handleRuntimeSyncFrameResponse(msg); break; case SyncWebSocketMsgType.sync_frame_authenticated: this.handleRuntimeSyncFrameAuthenticated(); break; case SyncWebSocketMsgType.domain_payload: this.handleRuntimeDomainPayload(msg); break; case SyncWebSocketMsgType.domain_payload_batch: this.handleRuntimeDomainPayloadBatch(msg); break; case SyncWebSocketMsgType.sync_error: this.handleRuntimeSyncError(msg); break; // Handshake messages / unexpected messages during active sync saga loop case SyncWebSocketMsgType.auth_challenge_init: case SyncWebSocketMsgType.auth_init: case SyncWebSocketMsgType.auth_challenge: case SyncWebSocketMsgType.auth_proof: case SyncWebSocketMsgType.auth_ok: case SyncWebSocketMsgType.auth_fail: case SyncWebSocketMsgType.sync_frame: case SyncWebSocketMsgType.sync_frame_response_authenticated: throw new Error(`Unexpected message type '${msgType}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`); default: assertUnreachable(msgType); } } catch (error) { console.error(`${lc} failed parsing/handling runtime frame: ${extractErrorMsg(error)}`); this.disconnect(); if (this.activeReject) { const reject = this.activeReject; this.activeResolve = undefined; this.activeReject = undefined; reject(error); } } } protected async handleHandshakeAuthChallengeInit(ws: WebSocket, targetSAddr: string): Promise { ws.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_init, sAddr: targetSAddr })); } protected async handleHandshakeAuthChallenge( ws: WebSocket, msg: any, sessionS: KeystoneIbGib_V1, sessionSecret: string ): Promise { const { challengeUuid, demandedIds } = msg; if (logalot) { console.log(`${this.lc} solving demanded challenges: ${demandedIds.join(', ')}`); } const proofFrame = await this.signContextConnect({ challengeUuid, demandedIds }); if (!proofFrame) { throw new Error(`Failed to sign connect challenge proof (E: e1aaa83c0580e6384c39a81a6268fd83)`); } ws.send(JSON.stringify({ type: SyncWebSocketMsgType.auth_proof, proofFrame })); } protected handleHandshakeAuthOk(ws: WebSocket, resolve: () => void): void { if (logalot) { console.log(`${this.lc} WebSocket connect SUCCESS!`); } if (this.handshakeMessageListener) { ws.removeEventListener('message', this.handshakeMessageListener); this.handshakeMessageListener = undefined; } ws.addEventListener('message', (event) => this.handleRuntimeMessage(event)); resolve(); } protected handleHandshakeAuthFail(msg: any, reject: (err: Error) => void): void { this.disconnect(); reject(new Error(`Handshake auth failed: ${msg.message || 'Unknown fail reason'} (E: f380b271a2be498db257bc8209fa8926)`)); } protected handleHandshakeSyncError(msg: any, reject: (err: Error) => void): void { this.disconnect(); reject(new Error(`Handshake sync error: ${msg.message || msg.error || 'Unknown sync error'} (E: f9208a01fe434cbbad83f210ea8f3426)`)); } protected async handleRuntimeSyncFrameResponse(msg: any): Promise { const responseContext = msg.context as SyncSagaContextIbGib_V1; const validationErrors = await validateContextAndSagaFrame({ context: responseContext }); if (validationErrors.length > 0) { throw new Error(`Invalid response context received: ${validationErrors.join(', ')} (E: d7b5a283cf4c43ba8659c803800cf826)`); } // Put response control ibgibs into durable space immediately const allControlIbGibs: IbGib_V1[] = [ toDto({ ibGib: responseContext }), responseContext.sagaFrame, responseContext.sagaFrameMsg! ]; if (responseContext.signedSessionIdentity) { allControlIbGibs.push(responseContext.signedSessionIdentity); } const { controlSpace } = this.opts!; for (const ibGib of allControlIbGibs) { await putInSpace({ space: controlSpace, ibGibs: [ibGib] }); await registerNewIbGib({ space: controlSpace, ibGib }); } const expectedPayloadAddrs = responseContext.data?.['@payloadAddrsDomain'] || []; if (expectedPayloadAddrs.length > 0) { this.ws!.send(JSON.stringify({ type: SyncWebSocketMsgType.sync_frame_response_authenticated, contextAddr: getIbGibAddr({ ibGib: responseContext }) })); } if (this.activeResolve) { const resolve = this.activeResolve; this.activeResolve = undefined; this.activeReject = undefined; resolve(responseContext); } } protected handleRuntimeSyncFrameAuthenticated(): void { const payloads = this.pendingPayloadsToSend || []; this.pendingPayloadsToSend = []; 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.ws!.send(packet as any); } else if (chunk.type === 'text_batch' && chunk.ibGibs && chunk.ibGibs.length > 0) { // Verify all ibgibs are valid text objects 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: ba53a06053387bbe4e3c968eabc1e68a)`); } } this.ws!.send(JSON.stringify({ type: SyncWebSocketMsgType.domain_payload_batch, batchIndex, totalBatches, itemCount: chunk.ibGibs.length, ibGibs: chunk.ibGibs })); batchIndex++; } } } protected handleRuntimeDomainPayload(msg: any): void { const payload = msg.ibGib as IbGib_V1; this.payloadIbGibsDomainReceived$.next(payload); } protected handleRuntimeDomainPayloadBatch(msg: any): void { const ibGibs = (msg.ibGibs || []) as IbGib_V1[]; for (const ibGib of ibGibs) { this.payloadIbGibsDomainReceived$.next(ibGib); } } protected handleRuntimeSyncError(msg: any): void { const errorDetail = msg.message || msg.error || 'Unknown sync runtime error'; const error = new Error(`Sync runtime error from receiver: ${errorDetail} (E: e983bc1c828d447fa0581da2b8004f26)`); if (this.activeReject) { const reject = this.activeReject; this.activeResolve = undefined; this.activeReject = undefined; reject(error); } else { throw error; } } /** * Serializes the transaction context and payload down the active WebSocket connection. */ protected override async sendContextRequest(context: SyncSagaContextIbGib_V1): Promise { const lc = `${this.lc}[${this.sendContextRequest.name}]`; try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { throw new Error(`WebSocket is not connected or open (E: 2979923231b882c5d6529e88b3f16826)`); } // 1. Separate payloads to send later const domainPayloads = context.payloadIbGibsDomain ?? []; this.pendingPayloadsToSend = [...domainPayloads]; // 2. Clone context without payloads for transport const contextToSend = { ...context }; delete contextToSend.payloadIbGibsDomain; // 3. Transmit the synchronizing transaction context return new Promise((resolve, reject) => { this.activeResolve = resolve; this.activeReject = reject; this.ws!.send(JSON.stringify({ type: SyncWebSocketMsgType.sync_frame, context: contextToSend })); }); } catch (error) { console.error(`${lc} sendContextRequest failed: ${extractErrorMsg(error)}`); throw error; } } }