@ibgib/space-gib 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19065,7 +19065,7 @@ var KeystoneService_V1 = class _KeystoneService_V1 {
19065
19065
  }
19066
19066
  };
19067
19067
 
19068
- // ../../libs/core-gib/dist/sync/sync-peer/sync-peer-websocket-receiver/sync-websocket-peer-helpers.mjs
19068
+ // ../../libs/core-gib/dist/sync/sync-peer/sync-peer-websocket/sync-peer-websocket-receiver/sync-websocket-peer-helpers.mjs
19069
19069
  var logalot42 = GLOBAL_LOG_A_LOT2;
19070
19070
  var SESSION_KEYSTONE_POLICY = {
19071
19071
  COMMON: {
@@ -20998,6 +20998,23 @@ async function validateContextAndSagaFrame({ context }) {
20998
20998
  } else {
20999
20999
  errors.push(`context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)`);
21000
21000
  }
21001
+ if (context.sagaFrameMsg) {
21002
+ const sagaFrameMsgErrors = await validateIbGibIntrinsically({ ibGib: context.sagaFrameMsg }) ?? [];
21003
+ sagaFrameMsgErrors.forEach((x) => errors.push(x));
21004
+ if (context.sagaFrame) {
21005
+ const expectedMsgAddr = context.sagaFrame.rel8ns?.[SYNC_MSG_REL8N_NAME]?.[0];
21006
+ if (expectedMsgAddr) {
21007
+ const actualMsgAddr = getIbGibAddr({ ibGib: context.sagaFrameMsg });
21008
+ if (actualMsgAddr !== expectedMsgAddr) {
21009
+ errors.push(`context.sagaFrameMsg address (${actualMsgAddr}) does not match the stone address referenced in sagaFrame relations (${expectedMsgAddr}). (E: a983b271fcae46bbad7e82098bc24826)`);
21010
+ }
21011
+ } else {
21012
+ errors.push(`context.sagaFrame is missing the message stone relation '${SYNC_MSG_REL8N_NAME}'. (E: da872cf3a8d46dbbad89d0a68d712826)`);
21013
+ }
21014
+ }
21015
+ } else {
21016
+ errors.push(`context.sagaFrameMsg is falsy. (E: ed405a72ab0d8bbdca7b9605d8f9a26)`);
21017
+ }
21001
21018
  if (errors.length > 0) {
21002
21019
  return errors;
21003
21020
  }
@@ -21012,34 +21029,190 @@ async function validateContextAndSagaFrame({ context }) {
21012
21029
  }
21013
21030
  }
21014
21031
  }
21015
- async function authenticateContext({}) {
21016
- const lc2 = `[${authenticateContext.name}]`;
21032
+ async function authenticateContextIntrinsically({
21033
+ context,
21034
+ space
21035
+ // stageInProtocol,
21036
+ }) {
21037
+ const lc2 = `[${authenticateContextIntrinsically.name}]`;
21017
21038
  try {
21018
21039
  if (logalot53) {
21019
21040
  console.log(`${lc2} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);
21020
21041
  }
21021
- console.warn(`${lc2}[NAG] not thrown. not implemented right now after removing all identity-related code. (W: e5fad31cfb49eef198a189a82dbcf726)`);
21022
- return [];
21023
- } catch (error) {
21024
- console.error(`${lc2} ${extractErrorMsg(error)}`);
21025
- throw error;
21026
- } finally {
21027
- if (logalot53) {
21028
- console.log(`${lc2} complete.`);
21042
+ const errors = [];
21043
+ if (!context.data) {
21044
+ throw new Error(`(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)`);
21029
21045
  }
21030
- }
21031
- }
21032
- async function authorizeContext({ context, fullSagaHistory }) {
21033
- const lc2 = `[${authorizeContext.name}]`;
21034
- try {
21035
- if (logalot53) {
21036
- console.log(`${lc2} starting... (I: 48c918b41ceec0cd489ca3b8819e6826)`);
21046
+ if (!context.rel8ns) {
21047
+ throw new Error(`(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)`);
21037
21048
  }
21038
- console.error(`${lc2} NAG ERROR (NOT THROWN): not implemented. authorize business logic (v1 must have this, but later when we are working on admin vs. student)(E: bc3a78f2dab18ab64c36d055a4b50526)`);
21039
- return [];
21049
+ const { sagaFrame, signedSessionIdentity: currSessionIdentity } = context;
21050
+ if (!sagaFrame.data) {
21051
+ throw new Error(`(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)`);
21052
+ }
21053
+ if (!currSessionIdentity) {
21054
+ console.error(`${lc2}[NAG][not thrown] sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`);
21055
+ if (sagaFrame.data.sessionIdentityTjpAddr) {
21056
+ errors.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)");
21057
+ return errors;
21058
+ } else if (context.rel8ns.sessionIdentity) {
21059
+ errors.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)");
21060
+ return errors;
21061
+ } else {
21062
+ if (logalot53) {
21063
+ console.log(`${lc2} context has no signedSessionIdentity and sync saga frame doesn't state there should be session identity. So nothing further to authenticate - returning early with no authentication errors. (I: d708735f9a2899ee98f762b8a09ed826)`);
21064
+ }
21065
+ return [];
21066
+ }
21067
+ }
21068
+ const currSessionIdentityAddr = getIbGibAddr({ ibGib: currSessionIdentity });
21069
+ const prevSessionIdentityAddrs_accordingToContextRel8ns = context.rel8ns?.sessionIdentity ?? [];
21070
+ if (prevSessionIdentityAddrs_accordingToContextRel8ns.length === 0) {
21071
+ errors.push(`context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)`);
21072
+ return errors;
21073
+ }
21074
+ if (prevSessionIdentityAddrs_accordingToContextRel8ns.length > 1) {
21075
+ errors.push(`context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)`);
21076
+ return errors;
21077
+ }
21078
+ const prevSessionIdentityAddr = prevSessionIdentityAddrs_accordingToContextRel8ns[0];
21079
+ const resGetLatestAddr = await getLatestAddrs({ addrs: [prevSessionIdentityAddr], space });
21080
+ if (!resGetLatestAddr) {
21081
+ throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${space.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);
21082
+ }
21083
+ if (!resGetLatestAddr.data) {
21084
+ throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${space.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);
21085
+ }
21086
+ if (!resGetLatestAddr.data.success) {
21087
+ throw new Error(`(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)`);
21088
+ }
21089
+ const { latestAddrsMap } = resGetLatestAddr.data;
21090
+ if (!latestAddrsMap) {
21091
+ throw new Error(`(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)`);
21092
+ }
21093
+ if (Object.keys(latestAddrsMap).length !== 1) {
21094
+ throw new Error(`(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)`);
21095
+ }
21096
+ const prevSessionIdentityAddr_latest = latestAddrsMap[prevSessionIdentityAddr];
21097
+ if (!prevSessionIdentityAddr_latest) {
21098
+ errors.push(`prevSessionIdentityAddr (${prevSessionIdentityAddr}) not found in space (${space.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`);
21099
+ return errors;
21100
+ }
21101
+ if (prevSessionIdentityAddr !== prevSessionIdentityAddr_latest) {
21102
+ if (prevSessionIdentityAddr_latest === currSessionIdentityAddr) {
21103
+ } else {
21104
+ errors.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${space.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`);
21105
+ console.log(`context: ${pretty(toDto2({ ibGib: context }))}`);
21106
+ console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${prevSessionIdentityAddr}`);
21107
+ console.log(`prevSessionIdentityAddr_latest: ${prevSessionIdentityAddr_latest}`);
21108
+ console.log(`currSessionIdentity (context.signedSessionIdentity): ${pretty(toDto2({
21109
+ ibGib: {
21110
+ ib: currSessionIdentity.ib,
21111
+ gib: currSessionIdentity.gib,
21112
+ rel8ns: currSessionIdentity.rel8ns,
21113
+ data: {
21114
+ ...currSessionIdentity.data,
21115
+ challengePools: currSessionIdentity.data.challengePools.map((p) => {
21116
+ return { ...p, challenges: {} };
21117
+ })
21118
+ }
21119
+ }
21120
+ }))}`);
21121
+ console.log(`currSessionIdentityAddr: ${currSessionIdentityAddr}`);
21122
+ return errors;
21123
+ }
21124
+ }
21125
+ const resGetPrevSessionIdentity = await getFromSpace({ addr: prevSessionIdentityAddr, space });
21126
+ if (!resGetPrevSessionIdentity.success || resGetPrevSessionIdentity.ibGibs?.length !== 1) {
21127
+ errors.push(`could not fetch latest sender identity ${prevSessionIdentityAddr} from space (${space.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`);
21128
+ return errors;
21129
+ }
21130
+ const prevSessionIdentity = resGetPrevSessionIdentity.ibGibs[0];
21131
+ const sessionIdentityTjp = await getTjpIbGib({ ibGib: prevSessionIdentity, naive: true, space });
21132
+ if (!sessionIdentityTjp) {
21133
+ throw new Error(`(UNEXPECTED) couldn't get sessionIdentityTjp in space (${space.ib})? we have already gotten the identity itself in the space, so we would expect the entire timeline to exist in it. (E: 9be0382ff1c8a0e77645ea38c096f826)`);
21134
+ }
21135
+ const sessionIdentityTjpAddr = getIbGibAddr({ ibGib: sessionIdentityTjp });
21136
+ if (sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr) {
21137
+ throw new Error(`(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)`);
21138
+ }
21139
+ const sessionGenesisFrameDetails = sessionIdentityTjp.data.frameDetails;
21140
+ if (!sessionGenesisFrameDetails) {
21141
+ errors.push(`Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)`);
21142
+ return errors;
21143
+ }
21144
+ const { senderIdentityAddr, senderIdentityTjpAddr } = sessionGenesisFrameDetails;
21145
+ if (!senderIdentityAddr) {
21146
+ throw new Error(`sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)`);
21147
+ }
21148
+ if (!senderIdentityTjpAddr) {
21149
+ throw new Error(`sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)`);
21150
+ }
21151
+ const resGetLatestAddr_senderIdentity = await getLatestAddrs({ addrs: [senderIdentityTjpAddr, senderIdentityAddr], space });
21152
+ if (!resGetLatestAddr_senderIdentity) {
21153
+ throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${space.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);
21154
+ }
21155
+ if (!resGetLatestAddr_senderIdentity.data) {
21156
+ throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${space.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);
21157
+ }
21158
+ if (!resGetLatestAddr_senderIdentity.data.success) {
21159
+ throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)`);
21160
+ }
21161
+ const { latestAddrsMap: latestAddrsMap_senderIdentity } = resGetLatestAddr_senderIdentity.data;
21162
+ if (!latestAddrsMap_senderIdentity) {
21163
+ throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)`);
21164
+ }
21165
+ if (Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr) {
21166
+ throw new Error(`(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)`);
21167
+ }
21168
+ const senderIdentityTjpAddr_latest = latestAddrsMap_senderIdentity[senderIdentityTjpAddr];
21169
+ const senderIdentityAddr_latest = latestAddrsMap_senderIdentity[senderIdentityAddr];
21170
+ if (!senderIdentityAddr_latest) {
21171
+ throw new Error(`(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)`);
21172
+ }
21173
+ if (senderIdentityTjpAddr_latest !== senderIdentityAddr_latest) {
21174
+ throw new Error(`senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)`);
21175
+ }
21176
+ const resGetSenderIdentity_latest = await getFromSpace({
21177
+ addr: senderIdentityAddr_latest,
21178
+ space
21179
+ });
21180
+ if (!resGetSenderIdentity_latest.success || resGetSenderIdentity_latest.ibGibs?.length !== 1) {
21181
+ errors.push(`could not fetch latest sender identity ${prevSessionIdentityAddr} from space (${space.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`);
21182
+ return errors;
21183
+ }
21184
+ const senderIdentity_latest = resGetSenderIdentity_latest.ibGibs[0];
21185
+ if (!senderIdentity_latest.data.proofs) {
21186
+ errors.push(`Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)`);
21187
+ return errors;
21188
+ }
21189
+ const syncClaim = senderIdentity_latest.data.proofs.find((p) => p.claim.verb === KEYSTONE_VERB_SYNC)?.claim;
21190
+ if (!syncClaim) {
21191
+ errors.push(`Most recent senderIdentity has no proof whose claim.verb === ${KEYSTONE_VERB_SYNC}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`);
21192
+ return errors;
21193
+ }
21194
+ if (syncClaim.target !== sessionIdentityTjpAddr) {
21195
+ errors.push(`Most recent sender identity claim has claim.verb === ${KEYSTONE_VERB_SYNC} but DOES NOT target expected session identity addr ${prevSessionIdentityAddr}. (E: 3e7f18d99848969be8586423d5ccb826)`);
21196
+ return errors;
21197
+ }
21198
+ const keystoneSvc = new KeystoneService_V1();
21199
+ const transitionErrors = await keystoneSvc.validate({
21200
+ currentIbGib: currSessionIdentity,
21201
+ prevIbGib: prevSessionIdentity
21202
+ });
21203
+ if (transitionErrors.length > 0) {
21204
+ errors.push(`Invalid session identity transition: ${transitionErrors.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);
21205
+ }
21206
+ const contextAddr = getIbGibAddr({ ibGib: context });
21207
+ const targetsThisContext = currSessionIdentity.data?.proofs?.some((p) => p.claim.target === contextAddr);
21208
+ if (!targetsThisContext) {
21209
+ errors.push(`Session identity signature does not target current context ibgib (${contextAddr}). (E: acae68938c287178c878d1b88bebb826)`);
21210
+ }
21211
+ return errors;
21040
21212
  } catch (error) {
21041
- console.error(`${lc2} ${extractErrorMsg(error)}`);
21042
- throw error;
21213
+ const emsg = `${lc2} ${extractErrorMsg(error)}`;
21214
+ console.error(emsg);
21215
+ return [`authentication produced an error: ${emsg} (E: 45e014b82af81993d936611ca6fc4d26)`];
21043
21216
  } finally {
21044
21217
  if (logalot53) {
21045
21218
  console.log(`${lc2} complete.`);
@@ -21053,6 +21226,90 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21053
21226
  lc = `[${_SyncPeer_V1.name}]`;
21054
21227
  opts;
21055
21228
  payloadIbGibsDomainReceived$;
21229
+ currentSessionIdentity;
21230
+ get currentSessionIdentityAddr() {
21231
+ return this.currentSessionIdentity ? getIbGibAddr({ ibGib: this.currentSessionIdentity }) : void 0;
21232
+ }
21233
+ // public getSenderIdentity(): KeystoneIbGib_V1 | undefined {
21234
+ // return this.opts?.senderIdentity;
21235
+ // }
21236
+ async signContext({ contextAddr }) {
21237
+ const lc2 = `${this.lc}[${this.signContext.name}]`;
21238
+ try {
21239
+ if (!this.currentSessionIdentity) {
21240
+ return void 0;
21241
+ }
21242
+ if (!this.opts) {
21243
+ throw new Error(`opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)`);
21244
+ }
21245
+ const { fnSenderSecret, sagaId, localMetaspace, localSpace } = this.opts;
21246
+ if (!fnSenderSecret) {
21247
+ throw new Error(`fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)`);
21248
+ }
21249
+ if (!sagaId) {
21250
+ throw new Error(`sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)`);
21251
+ }
21252
+ const senderSecret = await fnSenderSecret();
21253
+ const sessionSecret = await deriveSessionSecret({ senderSecret, sagaId });
21254
+ const keystoneSvc = new KeystoneService_V1();
21255
+ const evolved = await keystoneSvc.sign({
21256
+ latestKeystone: this.currentSessionIdentity,
21257
+ masterSecret: sessionSecret,
21258
+ claim: {
21259
+ verb: KEYSTONE_VERB_SYNC,
21260
+ target: contextAddr
21261
+ },
21262
+ metaspace: localMetaspace,
21263
+ space: localSpace
21264
+ });
21265
+ this.currentSessionIdentity = evolved;
21266
+ return evolved;
21267
+ } catch (error) {
21268
+ console.error(`${lc2} ${extractErrorMsg(error)}`);
21269
+ throw error;
21270
+ }
21271
+ }
21272
+ /**
21273
+ * Evolves the session identity (S_n -> S_n+1) solving the demanded connect challenges.
21274
+ */
21275
+ async signContextConnect({ challengeUuid, demandedIds }) {
21276
+ const lc2 = `${this.lc}[${this.signContextConnect.name}]`;
21277
+ try {
21278
+ if (!this.currentSessionIdentity) {
21279
+ return void 0;
21280
+ }
21281
+ if (!this.opts) {
21282
+ throw new Error(`opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)`);
21283
+ }
21284
+ const { fnSenderSecret, sagaId, localMetaspace, localSpace } = this.opts;
21285
+ if (!fnSenderSecret) {
21286
+ throw new Error(`fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)`);
21287
+ }
21288
+ if (!sagaId) {
21289
+ throw new Error(`sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)`);
21290
+ }
21291
+ const senderSecret = await fnSenderSecret();
21292
+ const sessionSecret = await deriveSessionSecret({ senderSecret, sagaId });
21293
+ const keystoneSvc = new KeystoneService_V1();
21294
+ const evolved = await keystoneSvc.sign({
21295
+ latestKeystone: this.currentSessionIdentity,
21296
+ masterSecret: sessionSecret,
21297
+ poolId: POOL_ID_CONNECT,
21298
+ requiredChallengeIds: demandedIds,
21299
+ claim: {
21300
+ verb: KEYSTONE_VERB_CONNECT,
21301
+ target: challengeUuid
21302
+ },
21303
+ metaspace: localMetaspace,
21304
+ space: localSpace
21305
+ });
21306
+ this.currentSessionIdentity = evolved;
21307
+ return evolved;
21308
+ } catch (error) {
21309
+ console.error(`${lc2} ${extractErrorMsg(error)}`);
21310
+ throw error;
21311
+ }
21312
+ }
21056
21313
  get classname() {
21057
21314
  if (!this.data) {
21058
21315
  throw new Error(`(UNEXPECTED) this.data falsy? (E: 1ab1841e9338b54f3aa615fa37024826)`);
@@ -21124,6 +21381,11 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21124
21381
  }
21125
21382
  return void 0;
21126
21383
  }
21384
+ const senderIdentityAddr = getIbGibAddr({ ibGib: senderIdentity });
21385
+ const senderIdentityTjpAddr = getTjpAddr({ ibGib: senderIdentity });
21386
+ if (!senderIdentityTjpAddr) {
21387
+ throw new Error(`(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)`);
21388
+ }
21127
21389
  if (!sagaId) {
21128
21390
  throw new Error(`(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)`);
21129
21391
  }
@@ -21139,10 +21401,17 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21139
21401
  if (!this.opts.sessionSyncPoolConfig) {
21140
21402
  throw new Error(`(UNEXPECTED) opts.sessionSyncPoolConfig falsy? (E: dbffa810d9e7ff6079088deb5b8e7826)`);
21141
21403
  }
21404
+ const frameDetails = {
21405
+ senderIdentityAddr,
21406
+ senderIdentityTjpAddr
21407
+ };
21408
+ if (this.opts.targetAddrs) {
21409
+ frameDetails.targetAddrs = this.opts.targetAddrs;
21410
+ }
21142
21411
  const sessionIdentity = await keystoneSvc.genesis({
21143
21412
  masterSecret: sessionSecret,
21144
21413
  configs: [this.opts.sessionConnectPoolConfig, this.opts.sessionSyncPoolConfig],
21145
- frameDetails: this.opts.targetAddrs ? { targetAddrs: this.opts.targetAddrs } : void 0,
21414
+ frameDetails,
21146
21415
  metaspace: localMetaspace,
21147
21416
  space: localSpace
21148
21417
  });
@@ -21158,7 +21427,7 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21158
21427
  space: localSpace
21159
21428
  });
21160
21429
  await this.postEstablishToReceiver({ newSenderIdentity, sessionIdentity });
21161
- return sessionIdentity;
21430
+ this.currentSessionIdentity = sessionIdentity;
21162
21431
  } catch (error) {
21163
21432
  console.error(`${lc2} ${extractErrorMsg(error)}`);
21164
21433
  throw error;
@@ -21231,8 +21500,8 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21231
21500
  // if (logalot) { console.log(`${lc} complete.`); }
21232
21501
  // }
21233
21502
  // }
21234
- async authenticateValidateAuthorize({ context, fullSagaHistory }) {
21235
- const lc2 = `${this.lc}[${this.authenticateValidateAuthorize.name}]`;
21503
+ async authenticateAndValidate({ context }) {
21504
+ const lc2 = `${this.lc}[${this.authenticateAndValidate.name}]`;
21236
21505
  try {
21237
21506
  if (logalot54) {
21238
21507
  console.log(`${lc2} starting... (I: add238055cd84a222c5b8c89913af526)`);
@@ -21241,7 +21510,7 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21241
21510
  throw new Error(`(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)`);
21242
21511
  }
21243
21512
  const { localSpace } = this.opts;
21244
- const authenticationErrors = await authenticateContext({
21513
+ const authenticationErrors = await authenticateContextIntrinsically({
21245
21514
  context,
21246
21515
  space: localSpace
21247
21516
  });
@@ -21252,10 +21521,6 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21252
21521
  if (validationErrors.length > 0) {
21253
21522
  throw new Error(`invalid context received. validationErrors: ${validationErrors} (E: 8b34c875c968af29bc433138e57a7826)`);
21254
21523
  }
21255
- const authorizationErrors = await authorizeContext({ context, fullSagaHistory });
21256
- if (authorizationErrors.length > 0) {
21257
- throw new Error(`invalid context authorization. authorizationErrors: ${authorizationErrors} (E: 8ddc284a758cf10ba829334c1babb826)`);
21258
- }
21259
21524
  } catch (error) {
21260
21525
  console.error(`${lc2} ${extractErrorMsg(error)}`);
21261
21526
  throw error;
@@ -21286,24 +21551,13 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21286
21551
  if (!context.sagaFrame) {
21287
21552
  throw new Error(`context.sagaFrame falsy. (E: a33dd88aa108e2bad9e885885731ce26)`);
21288
21553
  }
21289
- const sagaHistory_beforeSend = await getFullSyncSagaHistory({
21290
- sagaIbGib: context.sagaFrame,
21291
- space: this.opts.localSpace
21292
- });
21293
- await this.authenticateValidateAuthorize({
21294
- context,
21295
- fullSagaHistory: sagaHistory_beforeSend
21296
- });
21554
+ await this.authenticateAndValidate({ context });
21297
21555
  const response = await this.sendContextRequest(context);
21298
21556
  if (response) {
21299
21557
  const sagaHistory_afterSend = await getFullSyncSagaHistory({
21300
21558
  sagaIbGib: context.sagaFrame,
21301
21559
  space: this.opts.localSpace
21302
21560
  });
21303
- await this.authenticateValidateAuthorize({
21304
- context,
21305
- fullSagaHistory: sagaHistory_afterSend
21306
- });
21307
21561
  return response;
21308
21562
  } else {
21309
21563
  if (logalot54) {
@@ -21354,7 +21608,48 @@ var SyncPeer_V1 = class _SyncPeer_V1 extends LightWitnessBase_V1 {
21354
21608
  }
21355
21609
  };
21356
21610
 
21357
- // ../../libs/core-gib/dist/sync/sync-peer/sync-peer-websocket-receiver/sync-peer-websocket-receiver-v1.mjs
21611
+ // ../../libs/core-gib/dist/sync/sync-peer/sync-peer-websocket/sync-peer-websocket-constants.mjs
21612
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_CHALLENGE_INIT = "auth-challenge-init";
21613
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_INIT = "auth-init";
21614
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_CHALLENGE = "auth-challenge";
21615
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_PROOF = "auth-proof";
21616
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_OK = "auth-ok";
21617
+ var SYNC_WEB_SOCKET_MSG_TYPE_AUTH_FAIL = "auth-fail";
21618
+ var SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME = "sync-frame";
21619
+ var SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_RESPONSE = "sync-frame-response";
21620
+ var SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_AUTHENTICATED = "sync-frame-authenticated";
21621
+ var SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_RESPONSE_AUTHENTICATED = "sync-frame-response-authenticated";
21622
+ var SYNC_WEB_SOCKET_MSG_TYPE_DOMAIN_PAYLOAD = "domain-payload";
21623
+ var SYNC_WEB_SOCKET_MSG_TYPE_SYNC_ERROR = "sync-error";
21624
+ var SyncWebSocketMsgType = {
21625
+ /** Sent by server/receiver to trigger connection authentication. */
21626
+ auth_challenge_init: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_CHALLENGE_INIT,
21627
+ /** Sent by client/sender to start the authentication handshake with the target session address. */
21628
+ auth_init: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_INIT,
21629
+ /** Sent by server/receiver with dynamic connect challenges to be solved. */
21630
+ auth_challenge: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_CHALLENGE,
21631
+ /** Sent by client/sender with proof of session keystone evolution solving challenges. */
21632
+ auth_proof: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_PROOF,
21633
+ /** Sent by server/receiver signaling successful challenge resolution and upgrade to active sync. */
21634
+ auth_ok: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_OK,
21635
+ /** Sent when authentication fails. */
21636
+ auth_fail: SYNC_WEB_SOCKET_MSG_TYPE_AUTH_FAIL,
21637
+ /** Sent by client/sender to transmit the next sync transaction context without payload ibgibs. */
21638
+ sync_frame: SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME,
21639
+ /** Sent by server/receiver responding with the next sync transaction context. */
21640
+ sync_frame_response: SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_RESPONSE,
21641
+ /** Sent by server/receiver after context is validated/authenticated to signal payload transmission. */
21642
+ sync_frame_authenticated: SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_AUTHENTICATED,
21643
+ /** Sent by client/sender after response context is validated/authenticated to signal payload transmission. */
21644
+ sync_frame_response_authenticated: SYNC_WEB_SOCKET_MSG_TYPE_SYNC_FRAME_RESPONSE_AUTHENTICATED,
21645
+ /** Sent to stream a single domain payload ibgib. */
21646
+ domain_payload: SYNC_WEB_SOCKET_MSG_TYPE_DOMAIN_PAYLOAD,
21647
+ /** Sent when a sync runtime execution error occurs. */
21648
+ sync_error: SYNC_WEB_SOCKET_MSG_TYPE_SYNC_ERROR
21649
+ };
21650
+ var SYNC_WEB_SOCKET_MSG_TYPE_VALID_VALUES = Object.values(SyncWebSocketMsgType);
21651
+
21652
+ // ../../libs/core-gib/dist/sync/sync-peer/sync-peer-websocket/sync-peer-websocket-receiver/sync-peer-websocket-receiver-v1.mjs
21358
21653
  var logalot55 = GLOBAL_LOG_A_LOT2 || true;
21359
21654
  var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends SyncPeer_V1 {
21360
21655
  lc = `[${_SyncPeerWebSocketReceiver_V1.name}]`;
@@ -21367,6 +21662,10 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21367
21662
  challengeUuid;
21368
21663
  demandedIds;
21369
21664
  sessionS_tjpAddr;
21665
+ // Runtime state variables for delayed payload streaming
21666
+ pendingContext;
21667
+ pendingPayloadAddrs;
21668
+ pendingResponsePayloadsToSend = [];
21370
21669
  constructor(initialData, initialRel8ns) {
21371
21670
  super(initialData, initialRel8ns);
21372
21671
  }
@@ -21381,13 +21680,13 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21381
21680
  try {
21382
21681
  this.challengeUuid = await getUUID();
21383
21682
  socketWrapper.send(JSON.stringify({
21384
- type: "auth-challenge-init",
21683
+ type: SyncWebSocketMsgType.auth_challenge_init,
21385
21684
  challengeUuid: this.challengeUuid
21386
21685
  }));
21387
21686
  } catch (error) {
21388
21687
  console.error(`${lc2} failed triggering challenge init: ${extractErrorMsg(error)}`);
21389
21688
  socketWrapper.send(JSON.stringify({
21390
- type: "auth-fail",
21689
+ type: SyncWebSocketMsgType.auth_fail,
21391
21690
  message: "Internal server connect error"
21392
21691
  }));
21393
21692
  }
@@ -21459,37 +21758,82 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21459
21758
  await this.handleConnectFrame(msg);
21460
21759
  return;
21461
21760
  }
21462
- if (msg.type === "domain-payload") {
21761
+ if (msg.type === SyncWebSocketMsgType.domain_payload) {
21463
21762
  const ibGib = msg.ibGib;
21464
- const tempSpace = await this.ensureLocalTempSpace();
21465
- await putInSpace({ space: tempSpace, ibGibs: [ibGib] });
21466
- } else if (msg.type === "sync-frame") {
21763
+ const validationErrors = await validateIbGibIntrinsically({ ibGib }) ?? [];
21764
+ if (validationErrors.length > 0) {
21765
+ throw new Error(`controlIbGibs invalid intrinsically. validationErrors: ${validationErrors.join("|")} (E: 5ee1787d4cc53d3d2c55f3d4f2865226)`);
21766
+ }
21767
+ if (this.pendingContext && this.pendingPayloadAddrs) {
21768
+ const addr = getIbGibAddr({ ibGib });
21769
+ if (this.pendingPayloadAddrs.has(addr)) {
21770
+ const tempSpace = await this.ensureLocalTempSpace();
21771
+ await putInSpace({ space: tempSpace, ibGibs: [ibGib] });
21772
+ this.pendingPayloadAddrs.delete(addr);
21773
+ if (this.pendingPayloadAddrs.size === 0) {
21774
+ const context = this.pendingContext;
21775
+ this.pendingContext = void 0;
21776
+ this.pendingPayloadAddrs = void 0;
21777
+ await this.executeIncomingSyncRequestAndRespond({ context });
21778
+ }
21779
+ } else {
21780
+ console.warn(`${lc2} received payload not in expected list: ${addr}`);
21781
+ }
21782
+ }
21783
+ } else if (msg.type === SyncWebSocketMsgType.sync_frame) {
21467
21784
  const context = msg.context;
21468
- const responseCtx = await this.handleIncomingSyncRequest({ context });
21469
- if (responseCtx) {
21470
- const responsePayloads = responseCtx.payloadIbGibsDomain ?? [];
21471
- for (const ibGib of responsePayloads) {
21472
- this.socketWrapper.send(JSON.stringify({
21473
- type: "domain-payload",
21474
- ibGib
21475
- }));
21785
+ const allControlIbGibs = [
21786
+ toDto2({ ibGib: context }),
21787
+ context.sagaFrame,
21788
+ context.sagaFrameMsg
21789
+ ];
21790
+ if (context.signedSessionIdentity) {
21791
+ allControlIbGibs.push(context.signedSessionIdentity);
21792
+ }
21793
+ for (const controlIbGib of allControlIbGibs) {
21794
+ const validationErrors = await validateIbGibIntrinsically({ ibGib: controlIbGib }) ?? [];
21795
+ if (validationErrors.length > 0) {
21796
+ throw new Error(`controlIbGibs invalid intrinsically. validationErrors: ${validationErrors.join("|")} (E: d40dfa87265a0b73c8ef784d1265ea26)`);
21476
21797
  }
21798
+ }
21799
+ await this.authenticateAndValidate({ context });
21800
+ for (const ibGib of allControlIbGibs) {
21801
+ await putInSpace({ space: this.opts.localSpace, ibGibs: [ibGib] });
21802
+ await registerNewIbGib({ space: this.opts.localSpace, ibGib });
21803
+ }
21804
+ const expectedPayloadAddrs = context.data?.["@payloadAddrsDomain"] || [];
21805
+ if (expectedPayloadAddrs.length > 0) {
21806
+ this.pendingContext = context;
21807
+ this.pendingPayloadAddrs = new Set(expectedPayloadAddrs);
21477
21808
  this.socketWrapper.send(JSON.stringify({
21478
- type: "sync-frame-response",
21479
- context: responseCtx
21809
+ type: SyncWebSocketMsgType.sync_frame_authenticated,
21810
+ contextAddr: getIbGibAddr({ ibGib: context })
21480
21811
  }));
21481
21812
  } else {
21482
- if (logalot55) {
21483
- console.log(`${lc2} synchronization session completed successfully.`);
21484
- }
21813
+ await this.executeIncomingSyncRequestAndRespond({ context });
21814
+ }
21815
+ } else if (msg.type === SyncWebSocketMsgType.sync_frame_response_authenticated) {
21816
+ const payloads = this.pendingResponsePayloadsToSend || [];
21817
+ this.pendingResponsePayloadsToSend = [];
21818
+ for (const ibGib of payloads) {
21819
+ this.socketWrapper.send(JSON.stringify({
21820
+ type: SyncWebSocketMsgType.domain_payload,
21821
+ ibGib
21822
+ }));
21485
21823
  }
21486
21824
  }
21487
21825
  } catch (error) {
21488
21826
  console.error(`${lc2} message frame handling failed: ${extractErrorMsg(error)}`);
21489
- this.socketWrapper?.send(JSON.stringify({
21490
- type: this.isAuthenticated ? "sync-error" : "auth-fail",
21491
- message: extractErrorMsg(error)
21492
- }));
21827
+ try {
21828
+ this.socketWrapper?.send(JSON.stringify({
21829
+ type: this.isAuthenticated ? SyncWebSocketMsgType.sync_error : SyncWebSocketMsgType.auth_fail,
21830
+ message: extractErrorMsg(error)
21831
+ }));
21832
+ } catch (nestedError) {
21833
+ console.error(`${lc2}[nested catch] failed to send error frame: ${extractErrorMsg(nestedError)}`);
21834
+ } finally {
21835
+ this.socketWrapper?.close();
21836
+ }
21493
21837
  }
21494
21838
  }
21495
21839
  /**
@@ -21499,7 +21843,7 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21499
21843
  const lc2 = `${this.lc}[${this.handleConnectFrame.name}]`;
21500
21844
  const metaspace = this.opts.localMetaspace;
21501
21845
  const space = this.opts.localSpace;
21502
- if (msg.type === "auth-init") {
21846
+ if (msg.type === SyncWebSocketMsgType.auth_init) {
21503
21847
  const { sAddr } = msg;
21504
21848
  if (logalot55) {
21505
21849
  console.log(`${lc2} auth-init for ${sAddr}`);
@@ -21514,11 +21858,11 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21514
21858
  const past = authorizedS.rel8ns?.past;
21515
21859
  this.sessionS_tjpAddr = past && past.length > 0 ? past[0] : getIbGibAddr({ ibGib: authorizedS });
21516
21860
  this.socketWrapper.send(JSON.stringify({
21517
- type: "auth-challenge",
21861
+ type: SyncWebSocketMsgType.auth_challenge,
21518
21862
  challengeUuid: this.challengeUuid,
21519
21863
  demandedIds: this.demandedIds
21520
21864
  }));
21521
- } else if (msg.type === "auth-proof") {
21865
+ } else if (msg.type === SyncWebSocketMsgType.auth_proof) {
21522
21866
  const { proofFrame } = msg;
21523
21867
  if (logalot55) {
21524
21868
  console.log(`${lc2} verifying auth-proof...`);
@@ -21538,57 +21882,54 @@ var SyncPeerWebSocketReceiver_V1 = class _SyncPeerWebSocketReceiver_V1 extends S
21538
21882
  demandedIds: this.demandedIds
21539
21883
  });
21540
21884
  await metaspace.put({ ibGibs: [proofFrame], space });
21885
+ await metaspace.registerNewIbGib({ ibGib: proofFrame, space });
21541
21886
  if (logalot55) {
21542
21887
  console.log(`${lc2} connect validation successful! Connection upgraded to active sync session.`);
21543
21888
  }
21544
21889
  this.isAuthenticated = true;
21545
21890
  this.socketWrapper.send(JSON.stringify({
21546
- type: "auth-ok"
21891
+ type: SyncWebSocketMsgType.auth_ok
21547
21892
  }));
21548
21893
  } else {
21549
21894
  throw new Error(`Unexpected message type ${msg.type} during connect phase (E: f67a0f47f8426c2b01af5bc3d0146b26)`);
21550
21895
  }
21551
21896
  }
21552
21897
  /**
21553
- * Executes the transaction turn through the local SyncSagaCoordinator.
21898
+ * Executes the incoming sync request through the local SyncSagaCoordinator and sends response.
21554
21899
  */
21555
- async handleIncomingSyncRequest({ context, payloadIbGibsControl = [] }) {
21556
- const lc2 = `${this.lc}[${this.handleIncomingSyncRequest.name}]`;
21900
+ async executeIncomingSyncRequestAndRespond({ context }) {
21901
+ const lc2 = `${this.lc}[${this.executeIncomingSyncRequestAndRespond.name}]`;
21557
21902
  try {
21558
21903
  if (logalot55) {
21559
- console.log(`${lc2} starting incoming sync turn...`);
21904
+ console.log(`${lc2} executing incoming sync turn...`);
21560
21905
  }
21561
21906
  if (!this.opts) {
21562
21907
  throw new Error(`opts not initialized. (E: 0c98186714e85b9a08bb9d98daada826)`);
21563
21908
  }
21564
21909
  const { localCoordinator, localMetaspace, localSpace } = this.opts;
21565
21910
  const localTempSpace = await this.ensureLocalTempSpace();
21566
- const allControlIbGibs = [context, ...payloadIbGibsControl];
21567
- for (const ibGib of allControlIbGibs) {
21568
- await putInSpace({ space: localSpace, ibGibs: [ibGib] });
21569
- await registerNewIbGib({ space: localSpace, ibGib });
21570
- }
21571
- const authErrors = await authenticateContext({
21572
- context,
21573
- space: localSpace
21574
- });
21575
- if (authErrors.length > 0) {
21576
- throw new Error(`Context authentication failed: ${authErrors.join(", ")} (E: 424bd9b03ff8a42df8b1a438ed393726)`);
21577
- }
21578
- if (context.payloadIbGibsDomain && context.payloadIbGibsDomain.length > 0) {
21579
- for (const ibGib of context.payloadIbGibsDomain) {
21580
- await putInSpace({ space: localTempSpace, ibGibs: [ibGib] });
21581
- }
21582
- }
21583
21911
  const responseCtx = await localCoordinator.continueSync({
21584
21912
  sagaContext: context,
21585
21913
  metaspace: localMetaspace,
21586
21914
  mySpace: localSpace,
21587
- myTempSpace: localTempSpace
21915
+ myTempSpace: localTempSpace,
21916
+ peer: this
21588
21917
  });
21589
- return responseCtx || void 0;
21918
+ if (responseCtx) {
21919
+ const responsePayloads = responseCtx.payloadIbGibsDomain ?? [];
21920
+ delete responseCtx.payloadIbGibsDomain;
21921
+ this.pendingResponsePayloadsToSend = responsePayloads;
21922
+ this.socketWrapper.send(JSON.stringify({
21923
+ type: SyncWebSocketMsgType.sync_frame_response,
21924
+ context: responseCtx
21925
+ }));
21926
+ } else {
21927
+ if (logalot55) {
21928
+ console.log(`${lc2} synchronization session completed successfully.`);
21929
+ }
21930
+ }
21590
21931
  } catch (error) {
21591
- console.error(`${lc2} handleIncomingSyncRequest turn execution failed: ${extractErrorMsg(error)}`);
21932
+ console.error(`${lc2} executeIncomingSyncRequestAndRespond failed: ${extractErrorMsg(error)}`);
21592
21933
  throw error;
21593
21934
  }
21594
21935
  }
@@ -22263,8 +22604,8 @@ function createStandardPoolConfig(opts) {
22263
22604
  }
22264
22605
 
22265
22606
  // ../../libs/core-gib/dist/sync/sync-saga-coordinator.mjs
22266
- var logalot58 = GLOBAL_LOG_A_LOT2;
22267
- var logalotControlDomain = false;
22607
+ var logalot58 = GLOBAL_LOG_A_LOT2 || true;
22608
+ var logalotControlDomain = true;
22268
22609
  var lcControlDomain = "[ControlDomain]";
22269
22610
  var SyncSagaCoordinator = class _SyncSagaCoordinator {
22270
22611
  lc = `[${_SyncSagaCoordinator.name}]`;
@@ -22369,7 +22710,7 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22369
22710
  sessionSyncPoolConfig: this.defaultSessionSyncPoolConfig(),
22370
22711
  targetAddrs
22371
22712
  });
22372
- const sessionIdentity = await peer.establishSessionIdentity();
22713
+ await peer.establishSessionIdentity();
22373
22714
  await peer.connect({ sagaId });
22374
22715
  const { initFrame, initDomainGraph } = await this.createInitFrame({
22375
22716
  sagaId,
@@ -22377,7 +22718,8 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22377
22718
  conflictStrategy,
22378
22719
  metaspace,
22379
22720
  localSpace,
22380
- tempSpace
22721
+ tempSpace,
22722
+ peer
22381
22723
  });
22382
22724
  await this.executeSagaLoop({
22383
22725
  initFrame,
@@ -22417,7 +22759,7 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22417
22759
  * @returns next context result if another round, else if commit returns
22418
22760
  * null
22419
22761
  */
22420
- async continueSync({ sagaContext, mySpace, myTempSpace, metaspace }) {
22762
+ async continueSync({ sagaContext, mySpace, myTempSpace, metaspace, peer }) {
22421
22763
  const lc2 = `${this.lc}[${this.continueSync.name}]`;
22422
22764
  try {
22423
22765
  if (logalot58) {
@@ -22447,7 +22789,10 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22447
22789
  sagaFrame: frame,
22448
22790
  localSpace: mySpace,
22449
22791
  payloadIbGibsDomain,
22450
- metaspace
22792
+ metaspace,
22793
+ sessionIdentityAddr: sagaContext.rel8ns?.sessionIdentity?.[0],
22794
+ peer,
22795
+ skipSign: true
22451
22796
  });
22452
22797
  const immediateValidationErrors = await validateContextAndSagaFrame({
22453
22798
  context: responseCtx
@@ -22523,7 +22868,9 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22523
22868
  */
22524
22869
  payloadIbGibsDomain: nextDomainIbGibs,
22525
22870
  localSpace,
22526
- metaspace
22871
+ metaspace,
22872
+ sessionIdentityAddr: peer.currentSessionIdentityAddr,
22873
+ peer
22527
22874
  });
22528
22875
  if (logalotControlDomain) {
22529
22876
  const domainAddrs = nextDomainIbGibs.map((p) => getIbGibAddr({ ibGib: p }));
@@ -22559,6 +22906,14 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22559
22906
  if (contextAndSagaFrameValidationErrors.length > 0) {
22560
22907
  throw new Error(`contextAndSagaFrameValidationErrors: ${contextAndSagaFrameValidationErrors} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);
22561
22908
  }
22909
+ const returnContextErrors = await this.validateReturnContext({
22910
+ requestCtx,
22911
+ responseCtx,
22912
+ localSpace
22913
+ });
22914
+ if (returnContextErrors.length > 0) {
22915
+ throw new Error(`validateReturnContext errors: ${returnContextErrors.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);
22916
+ }
22562
22917
  const responsePayloadAddrsDomain = responseCtx.data[SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN] || [];
22563
22918
  if (responsePayloadAddrsDomain.length > 0) {
22564
22919
  responseCtx.payloadIbGibsDomain = await this.pollForDomainPayloads({
@@ -22623,7 +22978,7 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22623
22978
  * the other ibgibs that are related to this context stone should already be
22624
22979
  * put/registered in {@link localSpace}.
22625
22980
  */
22626
- async createSyncSagaContext({ sagaFrame, payloadIbGibsDomain, metaspace, localSpace }) {
22981
+ async createSyncSagaContext({ sagaFrame, payloadIbGibsDomain, metaspace, localSpace, sessionIdentityAddr, peer, skipSign }) {
22627
22982
  const lc2 = `[${this.createSyncSagaContext.name}]`;
22628
22983
  try {
22629
22984
  if (logalot58) {
@@ -22650,6 +23005,18 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22650
23005
  const rel8ns = {
22651
23006
  sagaFrame: [getIbGibAddr({ ibGib: sagaFrame })]
22652
23007
  };
23008
+ let sessionIdentity = void 0;
23009
+ if (sessionIdentityAddr) {
23010
+ sessionIdentityAddr = await metaspace.getLatestAddr({ addr: sessionIdentityAddr, space: localSpace }) ?? sessionIdentityAddr;
23011
+ const resGet = await getFromSpace({ addr: sessionIdentityAddr, space: localSpace });
23012
+ if (resGet.success && resGet.ibGibs?.length === 1) {
23013
+ sessionIdentity = resGet.ibGibs[0];
23014
+ rel8ns.sessionIdentity = [sessionIdentityAddr];
23015
+ } else {
23016
+ debugger;
23017
+ throw new Error(`Couldn't get sessionIdentityAddr (${sessionIdentityAddr}) in space: ${localSpace.ib} (E: 5c29e80d68dbd1749866c358be093826)`);
23018
+ }
23019
+ }
22653
23020
  const ib = await getSyncSagaContextIb({ data });
22654
23021
  const contextIbGib = await Factory_V1.stone({
22655
23022
  parentPrimitiveIb: SYNC_SAGA_CONTEXT_ATOM,
@@ -22657,6 +23024,11 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22657
23024
  data,
22658
23025
  rel8ns
22659
23026
  });
23027
+ const contextAddr = getIbGibAddr({ ibGib: contextIbGib });
23028
+ let signedSessionIdentity = void 0;
23029
+ if (sessionIdentity && !skipSign) {
23030
+ signedSessionIdentity = await peer.signContext({ contextAddr });
23031
+ }
22660
23032
  await putInSpace({ ibGib: contextIbGib, space: localSpace });
22661
23033
  await registerNewIbGib({
22662
23034
  ibGib: contextIbGib,
@@ -22664,9 +23036,20 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22664
23036
  fnBroadcast: void 0
22665
23037
  });
22666
23038
  contextIbGib.sagaFrame = sagaFrame;
23039
+ const { msgStones } = await getSyncSagaFrameDependencyGraph({
23040
+ sagaIbGib: sagaFrame,
23041
+ localSpace
23042
+ });
23043
+ if (msgStones.length !== 1) {
23044
+ throw new Error(`(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)`);
23045
+ }
23046
+ contextIbGib.sagaFrameMsg = msgStones[0];
22667
23047
  if (payloadIbGibsDomain && payloadIbGibsDomain.length > 0) {
22668
23048
  contextIbGib.payloadIbGibsDomain = payloadIbGibsDomain;
22669
23049
  }
23050
+ if (signedSessionIdentity) {
23051
+ contextIbGib.signedSessionIdentity = signedSessionIdentity;
23052
+ }
22670
23053
  return contextIbGib;
22671
23054
  } catch (error) {
22672
23055
  console.error(`${lc2} ${extractErrorMsg(error)}`);
@@ -22753,7 +23136,7 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22753
23136
  * Generates the first frame containing the Knowledge Map of the Local Space.
22754
23137
  * This is sent to the Receiver to begin Gap Analysis.
22755
23138
  */
22756
- async createInitFrame({ sagaId, domainIbGibs, conflictStrategy, metaspace, localSpace, tempSpace }) {
23139
+ async createInitFrame({ sagaId, domainIbGibs, conflictStrategy, metaspace, localSpace, tempSpace, peer }) {
22757
23140
  const lc2 = `${this.lc}[${this.createInitFrame.name}]`;
22758
23141
  try {
22759
23142
  if (logalot58) {
@@ -22788,7 +23171,8 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22788
23171
  msgStones: [initStone],
22789
23172
  conflictStrategy,
22790
23173
  metaspace,
22791
- localSpace
23174
+ localSpace,
23175
+ sessionIdentity: peer.currentSessionIdentity
22792
23176
  });
22793
23177
  if (logalot58) {
22794
23178
  console.log(`${lc2} sagaFrame (init): ${pretty(sagaFrame)} (I: b3d6a8be69248f18713cc3073cb08626)`);
@@ -22803,6 +23187,39 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
22803
23187
  }
22804
23188
  }
22805
23189
  }
23190
+ /**
23191
+ * Validates that the return context received from a peer is a valid
23192
+ * continuation of the outbound context and that the session identity
23193
+ * is consistent.
23194
+ */
23195
+ async validateReturnContext({ requestCtx, responseCtx, localSpace }) {
23196
+ const lc2 = `${this.lc}[${this.validateReturnContext.name}]`;
23197
+ const errors = [];
23198
+ try {
23199
+ if (requestCtx.sagaFrame && responseCtx.sagaFrame) {
23200
+ const requestFrameAddr = getIbGibAddr({ ibGib: requestCtx.sagaFrame });
23201
+ const responseFrameAddr = getIbGibAddr({ ibGib: responseCtx.sagaFrame });
23202
+ const isContinuation = await isPastFrame({
23203
+ olderAddr: requestFrameAddr,
23204
+ newerAddr: responseFrameAddr,
23205
+ space: localSpace
23206
+ });
23207
+ if (!isContinuation) {
23208
+ errors.push(`Response saga frame (${responseFrameAddr}) is not a valid continuation of request saga frame (${requestFrameAddr}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`);
23209
+ }
23210
+ } else {
23211
+ errors.push(`Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)`);
23212
+ }
23213
+ const expectedSessionIdAddr = requestCtx.signedSessionIdentity ? getIbGibAddr({ ibGib: requestCtx.signedSessionIdentity }) : requestCtx.rel8ns?.sessionIdentity?.[0];
23214
+ const responseSessionIdAddr = responseCtx.rel8ns?.sessionIdentity?.[0];
23215
+ if (expectedSessionIdAddr !== responseSessionIdAddr) {
23216
+ errors.push(`Session identity mismatch. Expected ${expectedSessionIdAddr}, got ${responseSessionIdAddr}. (E: ab98716bca88d2243cc822187768226)`);
23217
+ }
23218
+ } catch (error) {
23219
+ errors.push(`Error during validateReturnContext: ${extractErrorMsg(error)} (E: da878e1239aa88ee27bdfca005c28226)`);
23220
+ }
23221
+ return errors;
23222
+ }
22806
23223
  /**
22807
23224
  * Helper to poll for streaming domain payloads and put them in the
22808
23225
  * local {@link tempSpace}.
@@ -24090,7 +24507,7 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
24090
24507
  /**
24091
24508
  * Evolves the saga timeline with a new frame.
24092
24509
  */
24093
- async evolveSyncSagaIbGib({ prevSagaIbGib, conflictStrategy, msgStones, localSpace, metaspace }) {
24510
+ async evolveSyncSagaIbGib({ prevSagaIbGib, conflictStrategy, msgStones, localSpace, metaspace, sessionIdentity }) {
24094
24511
  const lc2 = `${this.lc}[${this.evolveSyncSagaIbGib.name}]`;
24095
24512
  try {
24096
24513
  if (!msgStones || msgStones.length === 0) {
@@ -24148,6 +24565,13 @@ var SyncSagaCoordinator = class _SyncSagaCoordinator {
24148
24565
  isTjp: true,
24149
24566
  conflictStrategy
24150
24567
  };
24568
+ if (sessionIdentity) {
24569
+ const sessionIdentityTjpAddr = getTjpAddr({ ibGib: sessionIdentity });
24570
+ if (!sessionIdentityTjpAddr) {
24571
+ throw new Error(`(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)`);
24572
+ }
24573
+ data.sessionIdentityTjpAddr = sessionIdentityTjpAddr;
24574
+ }
24151
24575
  const ib = await getSyncIb({ data });
24152
24576
  const stoneAddrs = msgStones.map((s) => getIbGibAddr({ ibGib: s }));
24153
24577
  const rel8ns = { [SYNC_MSG_REL8N_NAME]: stoneAddrs };
@@ -24339,6 +24763,10 @@ var SyncUpgradeHandlerBase = class _SyncUpgradeHandlerBase extends ServeGibHandl
24339
24763
  },
24340
24764
  onClose(callback) {
24341
24765
  socket.on("close", callback);
24766
+ },
24767
+ close() {
24768
+ socket.write(encodeCloseFrame());
24769
+ socket.end();
24342
24770
  }
24343
24771
  };
24344
24772
  await receiverPeer.bindSocket(socketWrapper);
@@ -24351,7 +24779,9 @@ var SyncUpgradeHandlerBase = class _SyncUpgradeHandlerBase extends ServeGibHandl
24351
24779
  }
24352
24780
  async parseParamsImpl(reqCtx) {
24353
24781
  const match = reqCtx.pathname.match(this.regex);
24354
- if (!match) return void 0;
24782
+ if (!match) {
24783
+ return void 0;
24784
+ }
24355
24785
  const domainIb = decodeURIComponent(match[1]);
24356
24786
  const domainGib = decodeURIComponent(match[2]);
24357
24787
  const domainAddr = getIbGibAddr({ ib: domainIb, gib: domainGib });