@floegence/flowersec-core 6.1.0 → 7.1.0

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.
Files changed (713) hide show
  1. package/README.md +101 -170
  2. package/THIRD_PARTY_NOTICES.md +10 -3075
  3. package/dist/browser/connectSessionV3.d.ts +44 -0
  4. package/dist/browser/connectSessionV3.js +261 -0
  5. package/dist/browser/directWebSocketProfileV1.d.ts +14 -0
  6. package/dist/browser/directWebSocketProfileV1.js +71 -0
  7. package/dist/browser/httpDirectV1.d.ts +30 -0
  8. package/dist/browser/httpDirectV1.js +52 -0
  9. package/dist/browser/index.d.ts +10 -15
  10. package/dist/browser/index.js +4 -5
  11. package/dist/browser/privateLoopbackV1.d.ts +30 -0
  12. package/dist/browser/privateLoopbackV1.js +70 -0
  13. package/dist/cli.d.ts +1 -24
  14. package/dist/cli.js +129 -91
  15. package/dist/cliSpendMarker.js +8 -0
  16. package/dist/defaults.d.ts +23 -1
  17. package/dist/defaults.js +23 -1
  18. package/dist/facade.d.ts +21 -104
  19. package/dist/facade.js +8 -45
  20. package/dist/framing/jsonframe.d.ts +21 -0
  21. package/dist/framing/jsonframe.js +107 -0
  22. package/dist/node/acceptor.d.ts +1 -0
  23. package/dist/node/acceptor.js +1 -0
  24. package/dist/node/acceptorV3.d.ts +70 -0
  25. package/dist/node/acceptorV3.js +296 -0
  26. package/dist/node/byteStreamDuplex.d.ts +4 -0
  27. package/dist/node/byteStreamDuplex.js +69 -0
  28. package/dist/node/connectSessionV3.d.ts +33 -0
  29. package/dist/node/connectSessionV3.js +99 -0
  30. package/dist/node/connectionPath.d.ts +0 -2
  31. package/dist/node/connectionPath.js +0 -18
  32. package/dist/node/index.d.ts +16 -52
  33. package/dist/node/index.js +6 -24
  34. package/dist/node/listenerIngress.d.ts +5 -0
  35. package/dist/node/listenerIngress.js +12 -0
  36. package/dist/node/nativeTransportAddon.d.ts +138 -0
  37. package/dist/node/nativeTransportAddon.js +233 -0
  38. package/dist/node/proxyServer.d.ts +4 -30
  39. package/dist/node/proxyServer.js +169 -600
  40. package/dist/node/rawQuicAdapterV3.d.ts +11 -0
  41. package/dist/node/rawQuicAdapterV3.js +83 -0
  42. package/dist/node/rawQuicServerV3.d.ts +36 -0
  43. package/dist/node/rawQuicServerV3.js +64 -0
  44. package/dist/node/runtimeAuthorizationV3.d.ts +41 -0
  45. package/dist/node/runtimeAuthorizationV3.js +156 -0
  46. package/dist/node/tunnelRuntimeV3.d.ts +60 -0
  47. package/dist/node/tunnelRuntimeV3.js +838 -0
  48. package/dist/node/webSocketServerV3.d.ts +28 -0
  49. package/dist/node/webSocketServerV3.js +223 -0
  50. package/dist/proxy/fetch.d.ts +2 -3
  51. package/dist/proxy/fetch.js +29 -96
  52. package/dist/proxy/index.d.ts +1 -5
  53. package/dist/proxy/index.js +0 -2
  54. package/dist/proxy/integration.d.ts +8 -12
  55. package/dist/proxy/integration.js +16 -23
  56. package/dist/proxy/policy.d.ts +0 -5
  57. package/dist/proxy/policy.js +22 -60
  58. package/dist/proxy/runtime.d.ts +1 -3
  59. package/dist/proxy/runtime.js +186 -404
  60. package/dist/proxy/scope.js +2 -2
  61. package/dist/proxy/serviceWorker.d.ts +0 -3
  62. package/dist/proxy/serviceWorker.js +176 -634
  63. package/dist/proxy/serviceWorkerRuntime.js +1 -26
  64. package/dist/proxy/stream.d.ts +6 -17
  65. package/dist/proxy/stream.js +40 -9
  66. package/dist/proxy/types.d.ts +11 -50
  67. package/dist/proxy/windowBridge.d.ts +3 -11
  68. package/dist/proxy/windowBridge.js +31 -70
  69. package/dist/proxy/wsPatch.js +26 -34
  70. package/dist/public/contract.d.ts +74 -1
  71. package/dist/public/contract.js +8 -0
  72. package/dist/public/sessionHandlers.d.ts +47 -0
  73. package/dist/public/sessionHandlers.js +151 -0
  74. package/dist/public/streamHandlers.d.ts +20 -0
  75. package/dist/public/streamHandlers.js +127 -0
  76. package/dist/public/streamMetadata.d.ts +2 -34
  77. package/dist/public/streamMetadata.js +13 -206
  78. package/dist/rpc/client.d.ts +34 -0
  79. package/dist/rpc/client.js +244 -0
  80. package/dist/rpc/server.d.ts +59 -0
  81. package/dist/rpc/server.js +255 -0
  82. package/dist/rpc/validate.d.ts +4 -0
  83. package/dist/{application/rpcJSON.js → rpc/validate.js} +1 -1
  84. package/dist/rpc/wire.d.ts +15 -0
  85. package/dist/v3/admissionError.d.ts +4 -0
  86. package/dist/v3/admissionError.js +8 -0
  87. package/dist/v3/artifact.d.ts +145 -0
  88. package/dist/v3/artifact.js +1180 -0
  89. package/dist/v3/artifactLease.d.ts +19 -0
  90. package/dist/v3/artifactLease.js +128 -0
  91. package/dist/v3/browserRuntime.d.ts +37 -0
  92. package/dist/v3/browserRuntime.js +197 -0
  93. package/dist/v3/browserSessionRuntime.d.ts +2 -0
  94. package/dist/v3/browserSessionRuntime.js +21 -0
  95. package/dist/v3/capability.d.ts +32 -0
  96. package/dist/v3/capability.js +345 -0
  97. package/dist/v3/carrier.d.ts +86 -0
  98. package/dist/v3/carrier.js +414 -0
  99. package/dist/v3/connectionController.d.ts +101 -0
  100. package/dist/v3/connectionController.js +888 -0
  101. package/dist/v3/contract.d.ts +70 -0
  102. package/dist/v3/contract.js +3 -0
  103. package/dist/v3/controller.d.ts +45 -0
  104. package/dist/v3/controller.js +316 -0
  105. package/dist/v3/handshake.d.ts +81 -0
  106. package/dist/v3/handshake.js +471 -0
  107. package/dist/v3/jcs.d.ts +6 -0
  108. package/dist/v3/jcs.js +69 -0
  109. package/dist/v3/jsonPreflight.d.ts +1 -0
  110. package/dist/v3/jsonPreflight.js +251 -0
  111. package/dist/v3/nodeRuntime.d.ts +43 -0
  112. package/dist/v3/nodeRuntime.js +437 -0
  113. package/dist/v3/nodeSessionRuntime.d.ts +2 -0
  114. package/dist/v3/nodeSessionRuntime.js +13 -0
  115. package/dist/v3/protocol.d.ts +100 -0
  116. package/dist/v3/protocol.js +715 -0
  117. package/dist/v3/publicApi.d.ts +12 -0
  118. package/dist/v3/publicApi.js +46 -0
  119. package/dist/v3/publicSession.js +316 -0
  120. package/dist/v3/runtimeAdapters.d.ts +9 -0
  121. package/dist/v3/runtimeAdapters.js +109 -0
  122. package/dist/v3/security.d.ts +36 -0
  123. package/dist/v3/security.js +113 -0
  124. package/dist/v3/serverAdmission.d.ts +42 -0
  125. package/dist/v3/serverAdmission.js +242 -0
  126. package/dist/v3/session.d.ts +339 -0
  127. package/dist/v3/session.js +2399 -0
  128. package/dist/v3/sessionConnector.d.ts +46 -0
  129. package/dist/v3/sessionConnector.js +534 -0
  130. package/dist/v3/streamLifetimeLedger.d.ts +32 -0
  131. package/dist/v3/streamLifetimeLedger.js +146 -0
  132. package/dist/v3/streamMetadata.js +7 -0
  133. package/dist/v3/transportConstants.d.ts +56 -0
  134. package/dist/v3/transportConstants.js +59 -0
  135. package/dist/v3/tunnelIngress.d.ts +8 -0
  136. package/dist/v3/tunnelIngress.js +21 -0
  137. package/dist/v3/unreliableMessage.d.ts +44 -0
  138. package/dist/v3/unreliableMessage.js +287 -0
  139. package/dist/v3/webSocketCarrier.d.ts +33 -0
  140. package/dist/v3/webSocketCarrier.js +380 -0
  141. package/dist/v3/webTransportCarrier.d.ts +27 -0
  142. package/dist/v3/webTransportCarrier.js +580 -0
  143. package/dist/vendor/tr46.js +17 -23
  144. package/dist/ws-client/binaryTransport.d.ts +65 -0
  145. package/dist/ws-client/binaryTransport.js +348 -0
  146. package/dist/yamux/byteReader.d.ts +13 -0
  147. package/dist/yamux/byteReader.js +81 -0
  148. package/dist/yamux/constants.d.ts +10 -0
  149. package/dist/yamux/constants.js +14 -0
  150. package/dist/yamux/errors.d.ts +15 -0
  151. package/dist/yamux/errors.js +34 -0
  152. package/dist/yamux/header.d.ts +20 -0
  153. package/dist/yamux/header.js +30 -0
  154. package/dist/yamux/session.d.ts +81 -0
  155. package/dist/yamux/session.js +401 -0
  156. package/dist/yamux/stream.d.ts +42 -0
  157. package/dist/yamux/stream.js +307 -0
  158. package/package.json +23 -22
  159. package/sbom/cyclonedx.json +55 -773
  160. package/sbom/spdx.json +60 -577
  161. package/dist/application/rpcJSON.d.ts +0 -15
  162. package/dist/browser/clientV4.d.ts +0 -61
  163. package/dist/browser/clientV4.js +0 -179
  164. package/dist/browser/indexedDBPoolV4.d.ts +0 -101
  165. package/dist/browser/indexedDBPoolV4.js +0 -634
  166. package/dist/browser/liveHTTPSV4.d.ts +0 -35
  167. package/dist/browser/liveHTTPSV4.js +0 -162
  168. package/dist/browser/localBrowserBridge.d.ts +0 -20
  169. package/dist/browser/localBrowserBridge.js +0 -82
  170. package/dist/browser/poolServerAllow.d.ts +0 -21
  171. package/dist/browser/poolServerAllow.js +0 -151
  172. package/dist/browser/webTransportPositionsV4.d.ts +0 -16
  173. package/dist/browser/webTransportPositionsV4.js +0 -75
  174. package/dist/browser/webTransportStreamV4.d.ts +0 -36
  175. package/dist/browser/webTransportStreamV4.js +0 -370
  176. package/dist/browser/webTransportV4.d.ts +0 -126
  177. package/dist/browser/webTransportV4.js +0 -627
  178. package/dist/browser/wssV4.d.ts +0 -69
  179. package/dist/browser/wssV4.js +0 -339
  180. package/dist/generated/brotliWorker.d.ts +0 -1
  181. package/dist/generated/brotliWorker.js +0 -3
  182. package/dist/generated/idna151.d.ts +0 -2
  183. package/dist/generated/idna151.js +0 -38
  184. package/dist/generated/normalization151.d.ts +0 -5
  185. package/dist/generated/normalization151.js +0 -878
  186. package/dist/generated/sqliteWorkers.d.ts +0 -2
  187. package/dist/generated/sqliteWorkers.js +0 -3
  188. package/dist/generated/transportV4APIResults.d.ts +0 -145
  189. package/dist/generated/transportV4APIResults.js +0 -52
  190. package/dist/generated/transportV4Registry.d.ts +0 -3758
  191. package/dist/generated/transportV4Registry.js +0 -29
  192. package/dist/interop/browserRunner.d.ts +0 -72
  193. package/dist/interop/browserRunner.js +0 -354
  194. package/dist/interop/currentClock.d.ts +0 -3
  195. package/dist/interop/currentClock.js +0 -39
  196. package/dist/interop/currentContracts.d.ts +0 -6
  197. package/dist/interop/currentContracts.js +0 -14
  198. package/dist/interop/currentNativeTunnel.d.ts +0 -31
  199. package/dist/interop/currentNativeTunnel.js +0 -185
  200. package/dist/interop/currentParity.d.ts +0 -68
  201. package/dist/interop/currentParity.js +0 -392
  202. package/dist/interop/currentPeer.d.ts +0 -252
  203. package/dist/interop/currentPeer.js +0 -677
  204. package/dist/interop/currentRegisteredTunnelPeer.d.ts +0 -37
  205. package/dist/interop/currentRegisteredTunnelPeer.js +0 -93
  206. package/dist/interop/currentRelayPeer.d.ts +0 -131
  207. package/dist/interop/currentRelayPeer.js +0 -263
  208. package/dist/interop/currentServer.d.ts +0 -44
  209. package/dist/interop/currentServer.js +0 -299
  210. package/dist/interop/currentTLSPin.d.ts +0 -9
  211. package/dist/interop/currentTLSPin.js +0 -44
  212. package/dist/interop/currentTunnelMaterial.d.ts +0 -34
  213. package/dist/interop/currentTunnelMaterial.js +0 -100
  214. package/dist/interop/httpApplicationPeer.d.ts +0 -15
  215. package/dist/interop/httpApplicationPeer.js +0 -167
  216. package/dist/interop/invalidProofPeer.d.ts +0 -8
  217. package/dist/interop/invalidProofPeer.js +0 -106
  218. package/dist/interop/proxyServerPeer.js +0 -49
  219. package/dist/interop/serverParityPeer.d.ts +0 -101
  220. package/dist/interop/serverParityPeer.js +0 -609
  221. package/dist/node/acceptorCurrent.d.ts +0 -55
  222. package/dist/node/acceptorCurrent.js +0 -286
  223. package/dist/node/admissionRecord.d.ts +0 -23
  224. package/dist/node/admissionRecord.js +0 -178
  225. package/dist/node/clientV4.d.ts +0 -59
  226. package/dist/node/clientV4.js +0 -197
  227. package/dist/node/endpointDialer.d.ts +0 -70
  228. package/dist/node/endpointDialer.js +0 -231
  229. package/dist/node/endpointListener.d.ts +0 -48
  230. package/dist/node/endpointListener.js +0 -403
  231. package/dist/node/endpointTransport.d.ts +0 -7
  232. package/dist/node/endpointTransport.js +0 -18
  233. package/dist/node/grantIssuerCurrent.d.ts +0 -64
  234. package/dist/node/grantIssuerCurrent.js +0 -355
  235. package/dist/node/liveHTTPSV4.d.ts +0 -28
  236. package/dist/node/liveHTTPSV4.js +0 -298
  237. package/dist/node/liveTunnelAuthorityCurrent.d.ts +0 -153
  238. package/dist/node/liveTunnelAuthorityCurrent.js +0 -590
  239. package/dist/node/nativeDuplexBridgeV4.d.ts +0 -41
  240. package/dist/node/nativeDuplexBridgeV4.js +0 -494
  241. package/dist/node/nativeTransportCurrent.d.ts +0 -196
  242. package/dist/node/nativeTransportCurrent.js +0 -37
  243. package/dist/node/poolServerAllow.d.ts +0 -33
  244. package/dist/node/poolServerAllow.js +0 -277
  245. package/dist/node/proxyCredentials.d.ts +0 -67
  246. package/dist/node/proxyCredentials.js +0 -364
  247. package/dist/node/proxyNetwork.d.ts +0 -18
  248. package/dist/node/proxyNetwork.js +0 -213
  249. package/dist/node/rawQUICCurrent.d.ts +0 -139
  250. package/dist/node/rawQUICCurrent.js +0 -1177
  251. package/dist/node/registeredLiveTunnelControl.d.ts +0 -74
  252. package/dist/node/registeredLiveTunnelControl.js +0 -865
  253. package/dist/node/registeredPoolTunnelAuthority.d.ts +0 -50
  254. package/dist/node/registeredPoolTunnelAuthority.js +0 -305
  255. package/dist/node/registeredTunnelControl.d.ts +0 -189
  256. package/dist/node/registeredTunnelControl.js +0 -1007
  257. package/dist/node/registeredWinnerContinuation.d.ts +0 -26
  258. package/dist/node/registeredWinnerContinuation.js +0 -83
  259. package/dist/node/relayNativePair.d.ts +0 -62
  260. package/dist/node/relayNativePair.js +0 -737
  261. package/dist/node/relayRecord.d.ts +0 -57
  262. package/dist/node/relayRecord.js +0 -275
  263. package/dist/node/serveRawQUIC.d.ts +0 -58
  264. package/dist/node/serveRawQUIC.js +0 -331
  265. package/dist/node/serveWSS.d.ts +0 -58
  266. package/dist/node/serveWSS.js +0 -309
  267. package/dist/node/sqliteAdmission.d.ts +0 -100
  268. package/dist/node/sqliteAdmission.js +0 -1185
  269. package/dist/node/sqliteExecutionContentV4.d.ts +0 -63
  270. package/dist/node/sqliteExecutionContentV4.js +0 -251
  271. package/dist/node/sqliteExecutionV4.d.ts +0 -114
  272. package/dist/node/sqliteExecutionV4.js +0 -1052
  273. package/dist/node/sqliteFormat.d.ts +0 -20
  274. package/dist/node/sqliteFormat.js +0 -72
  275. package/dist/node/sqliteInspectionV4.d.ts +0 -7
  276. package/dist/node/sqliteInspectionV4.js +0 -47
  277. package/dist/node/sqliteNativeV4.d.ts +0 -3
  278. package/dist/node/sqliteNativeV4.js +0 -16
  279. package/dist/node/sqlitePoolV4.d.ts +0 -41
  280. package/dist/node/sqlitePoolV4.js +0 -282
  281. package/dist/node/sqlitePoolWorkerProgramV4.js +0 -411
  282. package/dist/node/sqlitePoolWorkerV4.d.ts +0 -67
  283. package/dist/node/sqlitePoolWorkerV4.js +0 -206
  284. package/dist/node/sqliteV4.d.ts +0 -82
  285. package/dist/node/sqliteV4.js +0 -166
  286. package/dist/node/sqliteWorkerProgramV4.js +0 -175
  287. package/dist/node/sqliteWorkerV4.d.ts +0 -47
  288. package/dist/node/sqliteWorkerV4.js +0 -142
  289. package/dist/node/streamDuplexV4.d.ts +0 -33
  290. package/dist/node/streamDuplexV4.js +0 -359
  291. package/dist/node/tunnelListenerPreparation.d.ts +0 -37
  292. package/dist/node/tunnelListenerPreparation.js +0 -162
  293. package/dist/node/tunnelRuntime.d.ts +0 -124
  294. package/dist/node/tunnelRuntime.js +0 -1205
  295. package/dist/node/webTransportCurrent.d.ts +0 -24
  296. package/dist/node/webTransportCurrent.js +0 -12
  297. package/dist/node/wssV4.d.ts +0 -99
  298. package/dist/node/wssV4.js +0 -846
  299. package/dist/proxy/admission.d.ts +0 -21
  300. package/dist/proxy/admission.js +0 -126
  301. package/dist/proxy/brotliBody.d.ts +0 -10
  302. package/dist/proxy/brotliBody.js +0 -85
  303. package/dist/proxy/credentialControl.d.ts +0 -30
  304. package/dist/proxy/credentialControl.js +0 -86
  305. package/dist/proxy/currentStream.d.ts +0 -24
  306. package/dist/proxy/currentStream.js +0 -158
  307. package/dist/proxy/headers.d.ts +0 -8
  308. package/dist/proxy/headers.js +0 -63
  309. package/dist/proxy/publicationOwner.d.ts +0 -10
  310. package/dist/proxy/publicationOwner.js +0 -130
  311. package/dist/proxy/requestAssociation.d.ts +0 -11
  312. package/dist/proxy/requestAssociation.js +0 -8
  313. package/dist/proxy/surface.d.ts +0 -45
  314. package/dist/proxy/surface.js +0 -384
  315. package/dist/proxy/wire.d.ts +0 -11
  316. package/dist/proxy/wire.js +0 -214
  317. package/dist/public/streamKind.d.ts +0 -3
  318. package/dist/public/streamKind.js +0 -19
  319. package/dist/testSupport/tlsFixture.d.ts +0 -2
  320. package/dist/testSupport/tlsFixture.js +0 -8
  321. package/dist/v4/admissionOffer.d.ts +0 -8
  322. package/dist/v4/admissionOffer.js +0 -1
  323. package/dist/v4/checkpoint.d.ts +0 -23
  324. package/dist/v4/checkpoint.js +0 -16
  325. package/dist/v4/clientServices.d.ts +0 -35
  326. package/dist/v4/clientServices.js +0 -11
  327. package/dist/v4/connectionDiagnostic.d.ts +0 -42
  328. package/dist/v4/connectionDiagnostic.js +0 -45
  329. package/dist/v4/connectionRequirements.d.ts +0 -5
  330. package/dist/v4/connectionRequirements.js +0 -34
  331. package/dist/v4/controller.d.ts +0 -122
  332. package/dist/v4/controller.js +0 -1161
  333. package/dist/v4/controllerNotifications.d.ts +0 -81
  334. package/dist/v4/controllerNotifications.js +0 -610
  335. package/dist/v4/diagnostics.d.ts +0 -44
  336. package/dist/v4/diagnostics.js +0 -9
  337. package/dist/v4/drain.d.ts +0 -39
  338. package/dist/v4/drain.js +0 -80
  339. package/dist/v4/duplexBridge.d.ts +0 -53
  340. package/dist/v4/duplexBridge.js +0 -446
  341. package/dist/v4/entrypoints.d.ts +0 -20
  342. package/dist/v4/entrypoints.js +0 -50
  343. package/dist/v4/eventSource.d.ts +0 -34
  344. package/dist/v4/eventSource.js +0 -28
  345. package/dist/v4/handlerPlan.d.ts +0 -53
  346. package/dist/v4/handlerPlan.js +0 -129
  347. package/dist/v4/liveness.d.ts +0 -20
  348. package/dist/v4/liveness.js +0 -10
  349. package/dist/v4/localReport.d.ts +0 -17
  350. package/dist/v4/localReport.js +0 -10
  351. package/dist/v4/messageDefinition.d.ts +0 -66
  352. package/dist/v4/messageDefinition.js +0 -109
  353. package/dist/v4/messageStream.d.ts +0 -89
  354. package/dist/v4/messageStream.js +0 -1375
  355. package/dist/v4/notificationOperation.d.ts +0 -30
  356. package/dist/v4/notificationOperation.js +0 -31
  357. package/dist/v4/notificationSubscription.d.ts +0 -47
  358. package/dist/v4/notificationSubscription.js +0 -24
  359. package/dist/v4/operationReference.d.ts +0 -28
  360. package/dist/v4/operationReference.js +0 -61
  361. package/dist/v4/operationReferenceCodec.d.ts +0 -20
  362. package/dist/v4/operationReferenceCodec.js +0 -129
  363. package/dist/v4/operationReferenceStore.d.ts +0 -90
  364. package/dist/v4/operationReferenceStore.js +0 -272
  365. package/dist/v4/operationResultRead.d.ts +0 -26
  366. package/dist/v4/operationResultRead.js +0 -24
  367. package/dist/v4/poolControl.d.ts +0 -11
  368. package/dist/v4/poolControl.js +0 -50
  369. package/dist/v4/poolSource.d.ts +0 -93
  370. package/dist/v4/poolSource.js +0 -900
  371. package/dist/v4/profileDHReference.d.ts +0 -2
  372. package/dist/v4/profileDHReference.js +0 -42
  373. package/dist/v4/public.d.ts +0 -232
  374. package/dist/v4/public.js +0 -632
  375. package/dist/v4/responsePublication.d.ts +0 -48
  376. package/dist/v4/responsePublication.js +0 -227
  377. package/dist/v4/resume.d.ts +0 -17
  378. package/dist/v4/resume.js +0 -15
  379. package/dist/v4/runtime/applicationExecutor.d.ts +0 -190
  380. package/dist/v4/runtime/applicationExecutor.js +0 -759
  381. package/dist/v4/runtime/applicationHeader.d.ts +0 -61
  382. package/dist/v4/runtime/applicationHeader.js +0 -222
  383. package/dist/v4/runtime/canonicalText.d.ts +0 -8
  384. package/dist/v4/runtime/canonicalText.js +0 -142
  385. package/dist/v4/runtime/cbor.d.ts +0 -92
  386. package/dist/v4/runtime/cbor.js +0 -728
  387. package/dist/v4/runtime/cborWriter.d.ts +0 -18
  388. package/dist/v4/runtime/cborWriter.js +0 -59
  389. package/dist/v4/runtime/checkpointToken.d.ts +0 -41
  390. package/dist/v4/runtime/checkpointToken.js +0 -61
  391. package/dist/v4/runtime/clientAdmission.d.ts +0 -40
  392. package/dist/v4/runtime/clientAdmission.js +0 -378
  393. package/dist/v4/runtime/clientSessionSpec.d.ts +0 -45
  394. package/dist/v4/runtime/clientSessionSpec.js +0 -91
  395. package/dist/v4/runtime/clock.d.ts +0 -80
  396. package/dist/v4/runtime/clock.js +0 -284
  397. package/dist/v4/runtime/connectionFacts.d.ts +0 -23
  398. package/dist/v4/runtime/connectionFacts.js +0 -106
  399. package/dist/v4/runtime/contractAcceptance.d.ts +0 -20
  400. package/dist/v4/runtime/contractAcceptance.js +0 -91
  401. package/dist/v4/runtime/contractQuery.d.ts +0 -57
  402. package/dist/v4/runtime/contractQuery.js +0 -265
  403. package/dist/v4/runtime/contractQueryAccess.d.ts +0 -25
  404. package/dist/v4/runtime/contractQueryAccess.js +0 -117
  405. package/dist/v4/runtime/contractQueryAcquisition.d.ts +0 -83
  406. package/dist/v4/runtime/contractQueryAcquisition.js +0 -572
  407. package/dist/v4/runtime/contractQueryClient.d.ts +0 -70
  408. package/dist/v4/runtime/contractQueryClient.js +0 -411
  409. package/dist/v4/runtime/contractQueryCodecs.d.ts +0 -20
  410. package/dist/v4/runtime/contractQueryCodecs.js +0 -71
  411. package/dist/v4/runtime/contractQueryExchange.d.ts +0 -36
  412. package/dist/v4/runtime/contractQueryExchange.js +0 -160
  413. package/dist/v4/runtime/contractQueryService.d.ts +0 -42
  414. package/dist/v4/runtime/contractQueryService.js +0 -572
  415. package/dist/v4/runtime/contractQuerySession.d.ts +0 -38
  416. package/dist/v4/runtime/contractQuerySession.js +0 -158
  417. package/dist/v4/runtime/contractRoutes.d.ts +0 -87
  418. package/dist/v4/runtime/contractRoutes.js +0 -396
  419. package/dist/v4/runtime/contractSnapshotReader.d.ts +0 -59
  420. package/dist/v4/runtime/contractSnapshotReader.js +0 -418
  421. package/dist/v4/runtime/contractSnapshotWriter.d.ts +0 -32
  422. package/dist/v4/runtime/contractSnapshotWriter.js +0 -208
  423. package/dist/v4/runtime/controllerServiceSource.d.ts +0 -23
  424. package/dist/v4/runtime/controllerServiceSource.js +0 -109
  425. package/dist/v4/runtime/controllerUnaryRoute.d.ts +0 -28
  426. package/dist/v4/runtime/controllerUnaryRoute.js +0 -1
  427. package/dist/v4/runtime/credentialNamespace.d.ts +0 -143
  428. package/dist/v4/runtime/credentialNamespace.js +0 -1286
  429. package/dist/v4/runtime/credentialSupport.d.ts +0 -60
  430. package/dist/v4/runtime/credentialSupport.js +0 -294
  431. package/dist/v4/runtime/credentialVerifier.d.ts +0 -404
  432. package/dist/v4/runtime/credentialVerifier.js +0 -1443
  433. package/dist/v4/runtime/cryptoUsage.d.ts +0 -135
  434. package/dist/v4/runtime/cryptoUsage.js +0 -552
  435. package/dist/v4/runtime/deadline.d.ts +0 -31
  436. package/dist/v4/runtime/deadline.js +0 -188
  437. package/dist/v4/runtime/diagnosticCounters.d.ts +0 -15
  438. package/dist/v4/runtime/diagnosticCounters.js +0 -78
  439. package/dist/v4/runtime/diagnosticObservation.d.ts +0 -25
  440. package/dist/v4/runtime/diagnosticObservation.js +0 -67
  441. package/dist/v4/runtime/diagnosticSink.d.ts +0 -16
  442. package/dist/v4/runtime/diagnosticSink.js +0 -320
  443. package/dist/v4/runtime/ed25519.d.ts +0 -1
  444. package/dist/v4/runtime/ed25519.js +0 -34
  445. package/dist/v4/runtime/endpointHop.d.ts +0 -12
  446. package/dist/v4/runtime/endpointHop.js +0 -26
  447. package/dist/v4/runtime/envelope.d.ts +0 -66
  448. package/dist/v4/runtime/envelope.js +0 -275
  449. package/dist/v4/runtime/environment.d.ts +0 -277
  450. package/dist/v4/runtime/environment.js +0 -1913
  451. package/dist/v4/runtime/executionManagementChannel.d.ts +0 -27
  452. package/dist/v4/runtime/executionManagementChannel.js +0 -733
  453. package/dist/v4/runtime/executionManagementCodec.d.ts +0 -84
  454. package/dist/v4/runtime/executionManagementCodec.js +0 -127
  455. package/dist/v4/runtime/executionStorage.d.ts +0 -71
  456. package/dist/v4/runtime/executionStorage.js +0 -10
  457. package/dist/v4/runtime/fixedDiagnosticExecutor.d.ts +0 -34
  458. package/dist/v4/runtime/fixedDiagnosticExecutor.js +0 -149
  459. package/dist/v4/runtime/fixedManagementExecutor.d.ts +0 -21
  460. package/dist/v4/runtime/fixedManagementExecutor.js +0 -153
  461. package/dist/v4/runtime/fixedQueryExecutor.d.ts +0 -46
  462. package/dist/v4/runtime/fixedQueryExecutor.js +0 -311
  463. package/dist/v4/runtime/grantDigest.d.ts +0 -9
  464. package/dist/v4/runtime/grantDigest.js +0 -31
  465. package/dist/v4/runtime/hopAuthentication.d.ts +0 -51
  466. package/dist/v4/runtime/hopAuthentication.js +0 -392
  467. package/dist/v4/runtime/host.d.ts +0 -15
  468. package/dist/v4/runtime/host.js +0 -332
  469. package/dist/v4/runtime/initializerWorkload.d.ts +0 -38
  470. package/dist/v4/runtime/initializerWorkload.js +0 -164
  471. package/dist/v4/runtime/lifecycle.d.ts +0 -5
  472. package/dist/v4/runtime/lifecycle.js +0 -17
  473. package/dist/v4/runtime/liveAuthorization.d.ts +0 -42
  474. package/dist/v4/runtime/liveAuthorization.js +0 -133
  475. package/dist/v4/runtime/liveAuthorizationWire.d.ts +0 -8
  476. package/dist/v4/runtime/liveAuthorizationWire.js +0 -31
  477. package/dist/v4/runtime/liveCarrierPreparation.d.ts +0 -9
  478. package/dist/v4/runtime/liveCarrierPreparation.js +0 -27
  479. package/dist/v4/runtime/liveness.d.ts +0 -37
  480. package/dist/v4/runtime/liveness.js +0 -319
  481. package/dist/v4/runtime/maintenancePositions.d.ts +0 -29
  482. package/dist/v4/runtime/maintenancePositions.js +0 -152
  483. package/dist/v4/runtime/messageCodec.d.ts +0 -20
  484. package/dist/v4/runtime/messageCodec.js +0 -192
  485. package/dist/v4/runtime/namespaceContinuity.d.ts +0 -20
  486. package/dist/v4/runtime/namespaceContinuity.js +0 -176
  487. package/dist/v4/runtime/nativeCandidates.d.ts +0 -18
  488. package/dist/v4/runtime/nativeCandidates.js +0 -109
  489. package/dist/v4/runtime/nativeFailure.d.ts +0 -10
  490. package/dist/v4/runtime/nativeFailure.js +0 -32
  491. package/dist/v4/runtime/nativeFrame.d.ts +0 -47
  492. package/dist/v4/runtime/nativeFrame.js +0 -318
  493. package/dist/v4/runtime/nativeIngress.d.ts +0 -30
  494. package/dist/v4/runtime/nativeIngress.js +0 -177
  495. package/dist/v4/runtime/nativePositions.d.ts +0 -24
  496. package/dist/v4/runtime/nativePositions.js +0 -131
  497. package/dist/v4/runtime/nativeProviderPositions.d.ts +0 -16
  498. package/dist/v4/runtime/nativeProviderPositions.js +0 -75
  499. package/dist/v4/runtime/nativeSend.d.ts +0 -15
  500. package/dist/v4/runtime/nativeSend.js +0 -57
  501. package/dist/v4/runtime/noiseHandshake.d.ts +0 -70
  502. package/dist/v4/runtime/noiseHandshake.js +0 -373
  503. package/dist/v4/runtime/noiseWasmBinary.d.ts +0 -2
  504. package/dist/v4/runtime/noiseWasmBinary.js +0 -3
  505. package/dist/v4/runtime/notifyChannel.d.ts +0 -37
  506. package/dist/v4/runtime/notifyChannel.js +0 -277
  507. package/dist/v4/runtime/notifyDispatch.d.ts +0 -108
  508. package/dist/v4/runtime/notifyDispatch.js +0 -717
  509. package/dist/v4/runtime/notifyExecution.d.ts +0 -18
  510. package/dist/v4/runtime/notifyExecution.js +0 -59
  511. package/dist/v4/runtime/notifyPreparation.d.ts +0 -70
  512. package/dist/v4/runtime/notifyPreparation.js +0 -465
  513. package/dist/v4/runtime/openAdmission.d.ts +0 -125
  514. package/dist/v4/runtime/openAdmission.js +0 -810
  515. package/dist/v4/runtime/peerOpenPreparation.d.ts +0 -18
  516. package/dist/v4/runtime/peerOpenPreparation.js +0 -61
  517. package/dist/v4/runtime/poolJournal.d.ts +0 -18
  518. package/dist/v4/runtime/poolJournal.js +0 -14
  519. package/dist/v4/runtime/poolJournalStorage.d.ts +0 -4
  520. package/dist/v4/runtime/poolJournalStorage.js +0 -172
  521. package/dist/v4/runtime/poolRecord.d.ts +0 -9
  522. package/dist/v4/runtime/poolRecord.js +0 -23
  523. package/dist/v4/runtime/poolRecordStorage.d.ts +0 -10
  524. package/dist/v4/runtime/poolRecordStorage.js +0 -216
  525. package/dist/v4/runtime/poolServerAllow.d.ts +0 -49
  526. package/dist/v4/runtime/poolServerAllow.js +0 -38
  527. package/dist/v4/runtime/poolSpend.d.ts +0 -20
  528. package/dist/v4/runtime/poolSpend.js +0 -4
  529. package/dist/v4/runtime/queryRenewalPosition.d.ts +0 -59
  530. package/dist/v4/runtime/queryRenewalPosition.js +0 -220
  531. package/dist/v4/runtime/random.d.ts +0 -15
  532. package/dist/v4/runtime/random.js +0 -71
  533. package/dist/v4/runtime/rawStreamPreparation.d.ts +0 -40
  534. package/dist/v4/runtime/rawStreamPreparation.js +0 -125
  535. package/dist/v4/runtime/receiveDirection.d.ts +0 -135
  536. package/dist/v4/runtime/receiveDirection.js +0 -957
  537. package/dist/v4/runtime/receiveWorkspace.d.ts +0 -19
  538. package/dist/v4/runtime/receiveWorkspace.js +0 -82
  539. package/dist/v4/runtime/record.d.ts +0 -7
  540. package/dist/v4/runtime/record.js +0 -173
  541. package/dist/v4/runtime/recordCrypto.d.ts +0 -121
  542. package/dist/v4/runtime/recordCrypto.js +0 -633
  543. package/dist/v4/runtime/recordWorkspace.d.ts +0 -17
  544. package/dist/v4/runtime/recordWorkspace.js +0 -69
  545. package/dist/v4/runtime/registeredCarrierPreparation.d.ts +0 -17
  546. package/dist/v4/runtime/registeredCarrierPreparation.js +0 -191
  547. package/dist/v4/runtime/rekey.d.ts +0 -40
  548. package/dist/v4/runtime/rekey.js +0 -362
  549. package/dist/v4/runtime/relayCredentials.d.ts +0 -126
  550. package/dist/v4/runtime/relayCredentials.js +0 -349
  551. package/dist/v4/runtime/replayWindow.d.ts +0 -6
  552. package/dist/v4/runtime/replayWindow.js +0 -59
  553. package/dist/v4/runtime/resources.d.ts +0 -200
  554. package/dist/v4/runtime/resources.js +0 -1236
  555. package/dist/v4/runtime/resumeCodec.d.ts +0 -44
  556. package/dist/v4/runtime/resumeCodec.js +0 -192
  557. package/dist/v4/runtime/resumeStream.d.ts +0 -23
  558. package/dist/v4/runtime/resumeStream.js +0 -23
  559. package/dist/v4/runtime/rpcApplication.d.ts +0 -234
  560. package/dist/v4/runtime/rpcApplication.js +0 -2170
  561. package/dist/v4/runtime/rpcApplicationServices.d.ts +0 -18
  562. package/dist/v4/runtime/rpcApplicationServices.js +0 -62
  563. package/dist/v4/runtime/rpcCallCapacity.d.ts +0 -62
  564. package/dist/v4/runtime/rpcCallCapacity.js +0 -289
  565. package/dist/v4/runtime/rpcChannel.d.ts +0 -58
  566. package/dist/v4/runtime/rpcChannel.js +0 -334
  567. package/dist/v4/runtime/rpcCompletion.d.ts +0 -42
  568. package/dist/v4/runtime/rpcCompletion.js +0 -152
  569. package/dist/v4/runtime/rpcEventSource.d.ts +0 -27
  570. package/dist/v4/runtime/rpcEventSource.js +0 -201
  571. package/dist/v4/runtime/rpcFragment.d.ts +0 -42
  572. package/dist/v4/runtime/rpcFragment.js +0 -227
  573. package/dist/v4/runtime/rpcInput.d.ts +0 -41
  574. package/dist/v4/runtime/rpcInput.js +0 -137
  575. package/dist/v4/runtime/rpcNetwork.d.ts +0 -143
  576. package/dist/v4/runtime/rpcNetwork.js +0 -652
  577. package/dist/v4/runtime/rpcOutputInterest.d.ts +0 -20
  578. package/dist/v4/runtime/rpcOutputInterest.js +0 -106
  579. package/dist/v4/runtime/rpcPayload.d.ts +0 -24
  580. package/dist/v4/runtime/rpcPayload.js +0 -82
  581. package/dist/v4/runtime/rpcPreacceptedStreams.d.ts +0 -46
  582. package/dist/v4/runtime/rpcPreacceptedStreams.js +0 -406
  583. package/dist/v4/runtime/rpcPublisher.d.ts +0 -49
  584. package/dist/v4/runtime/rpcPublisher.js +0 -406
  585. package/dist/v4/runtime/rpcReceiver.d.ts +0 -40
  586. package/dist/v4/runtime/rpcReceiver.js +0 -255
  587. package/dist/v4/runtime/rpcResumeDispatch.d.ts +0 -46
  588. package/dist/v4/runtime/rpcResumeDispatch.js +0 -266
  589. package/dist/v4/runtime/rpcStream.d.ts +0 -14
  590. package/dist/v4/runtime/rpcStream.js +0 -12
  591. package/dist/v4/runtime/rpcStreamMessages.d.ts +0 -53
  592. package/dist/v4/runtime/rpcStreamMessages.js +0 -428
  593. package/dist/v4/runtime/rpcStreamPreparation.d.ts +0 -21
  594. package/dist/v4/runtime/rpcStreamPreparation.js +0 -110
  595. package/dist/v4/runtime/rpcStreamingDispatch.d.ts +0 -26
  596. package/dist/v4/runtime/rpcStreamingDispatch.js +0 -607
  597. package/dist/v4/runtime/rpcStreamingExchange.d.ts +0 -91
  598. package/dist/v4/runtime/rpcStreamingExchange.js +0 -812
  599. package/dist/v4/runtime/rpcUnaryCall.d.ts +0 -16
  600. package/dist/v4/runtime/rpcUnaryCall.js +0 -152
  601. package/dist/v4/runtime/rpcUnaryDispatch.d.ts +0 -34
  602. package/dist/v4/runtime/rpcUnaryDispatch.js +0 -569
  603. package/dist/v4/runtime/rpcUnaryExchange.d.ts +0 -127
  604. package/dist/v4/runtime/rpcUnaryExchange.js +0 -1042
  605. package/dist/v4/runtime/rpcUnaryPreparation.d.ts +0 -102
  606. package/dist/v4/runtime/rpcUnaryPreparation.js +0 -736
  607. package/dist/v4/runtime/rpcUnaryRegistration.d.ts +0 -33
  608. package/dist/v4/runtime/rpcUnaryRegistration.js +0 -113
  609. package/dist/v4/runtime/rpcUnaryResultRecipient.d.ts +0 -21
  610. package/dist/v4/runtime/rpcUnaryResultRecipient.js +0 -57
  611. package/dist/v4/runtime/schema.d.ts +0 -26
  612. package/dist/v4/runtime/schema.js +0 -668
  613. package/dist/v4/runtime/schemaRegistry.d.ts +0 -128
  614. package/dist/v4/runtime/schemaRegistry.js +0 -74
  615. package/dist/v4/runtime/sendBudget.d.ts +0 -10
  616. package/dist/v4/runtime/sendBudget.js +0 -46
  617. package/dist/v4/runtime/serveGroup.d.ts +0 -73
  618. package/dist/v4/runtime/serveGroup.js +0 -589
  619. package/dist/v4/runtime/serverAdmission.d.ts +0 -33
  620. package/dist/v4/runtime/serverAdmission.js +0 -342
  621. package/dist/v4/runtime/serverAdmissionAuthority.d.ts +0 -23
  622. package/dist/v4/runtime/serverAdmissionAuthority.js +0 -5
  623. package/dist/v4/runtime/serverSessionSpec.d.ts +0 -9
  624. package/dist/v4/runtime/serverSessionSpec.js +0 -12
  625. package/dist/v4/runtime/serviceBinding.d.ts +0 -128
  626. package/dist/v4/runtime/serviceBinding.js +0 -1435
  627. package/dist/v4/runtime/serviceBindingConfig.d.ts +0 -72
  628. package/dist/v4/runtime/serviceBindingConfig.js +0 -85
  629. package/dist/v4/runtime/serviceBindingPool.d.ts +0 -58
  630. package/dist/v4/runtime/serviceBindingPool.js +0 -327
  631. package/dist/v4/runtime/serviceContract.d.ts +0 -111
  632. package/dist/v4/runtime/serviceContract.js +0 -588
  633. package/dist/v4/runtime/serviceInputs.d.ts +0 -30
  634. package/dist/v4/runtime/serviceInputs.js +0 -201
  635. package/dist/v4/runtime/serviceOfferPlan.d.ts +0 -81
  636. package/dist/v4/runtime/serviceOfferPlan.js +0 -335
  637. package/dist/v4/runtime/serviceOfferScheduler.d.ts +0 -12
  638. package/dist/v4/runtime/serviceOfferScheduler.js +0 -201
  639. package/dist/v4/runtime/serviceOfferWork.d.ts +0 -25
  640. package/dist/v4/runtime/serviceOfferWork.js +0 -1
  641. package/dist/v4/runtime/session.d.ts +0 -411
  642. package/dist/v4/runtime/session.js +0 -6369
  643. package/dist/v4/runtime/sessionActivity.d.ts +0 -19
  644. package/dist/v4/runtime/sessionActivity.js +0 -97
  645. package/dist/v4/runtime/sessionAdmission.d.ts +0 -93
  646. package/dist/v4/runtime/sessionAdmission.js +0 -498
  647. package/dist/v4/runtime/sessionCleanup.d.ts +0 -47
  648. package/dist/v4/runtime/sessionCleanup.js +0 -268
  649. package/dist/v4/runtime/sessionKeyPreparation.d.ts +0 -19
  650. package/dist/v4/runtime/sessionKeyPreparation.js +0 -50
  651. package/dist/v4/runtime/signedMap.d.ts +0 -68
  652. package/dist/v4/runtime/signedMap.js +0 -425
  653. package/dist/v4/runtime/streamAdapter.d.ts +0 -113
  654. package/dist/v4/runtime/streamAdapter.js +0 -62
  655. package/dist/v4/runtime/streamData.d.ts +0 -11
  656. package/dist/v4/runtime/streamData.js +0 -50
  657. package/dist/v4/runtime/streamOpenPreparation.d.ts +0 -23
  658. package/dist/v4/runtime/streamOpenPreparation.js +0 -77
  659. package/dist/v4/runtime/streamRegistration.d.ts +0 -87
  660. package/dist/v4/runtime/streamRegistration.js +0 -296
  661. package/dist/v4/runtime/taskObservation.d.ts +0 -1
  662. package/dist/v4/runtime/taskObservation.js +0 -48
  663. package/dist/v4/runtime/timeArithmetic.d.ts +0 -29
  664. package/dist/v4/runtime/timeArithmetic.js +0 -107
  665. package/dist/v4/runtime/unreliable.d.ts +0 -76
  666. package/dist/v4/runtime/unreliable.js +0 -473
  667. package/dist/v4/runtime/volatileExecutions.d.ts +0 -128
  668. package/dist/v4/runtime/volatileExecutions.js +0 -792
  669. package/dist/v4/runtime/wireRegistry.d.ts +0 -52
  670. package/dist/v4/runtime/wireRegistry.js +0 -29
  671. package/dist/v4/runtime/writeRequest.d.ts +0 -42
  672. package/dist/v4/runtime/writeRequest.js +0 -237
  673. package/dist/v4/serve.d.ts +0 -107
  674. package/dist/v4/serve.js +0 -80
  675. package/dist/v4/serviceClient.d.ts +0 -92
  676. package/dist/v4/serviceClient.js +0 -323
  677. package/dist/v4/serviceDefinition.d.ts +0 -138
  678. package/dist/v4/serviceDefinition.js +0 -150
  679. package/dist/v4/serviceDependencies.d.ts +0 -66
  680. package/dist/v4/serviceDependencies.js +0 -250
  681. package/dist/v4/serviceFactory.d.ts +0 -31
  682. package/dist/v4/serviceFactory.js +0 -157
  683. package/dist/v4/serviceHandlers.d.ts +0 -55
  684. package/dist/v4/serviceHandlers.js +0 -15
  685. package/dist/v4/serviceMembers.d.ts +0 -4
  686. package/dist/v4/serviceMembers.js +0 -12
  687. package/dist/v4/staticServiceContracts.d.ts +0 -43
  688. package/dist/v4/staticServiceContracts.js +0 -161
  689. package/dist/v4/storageFormat.d.ts +0 -16
  690. package/dist/v4/storageFormat.js +0 -5
  691. package/dist/v4/streamContent.d.ts +0 -30
  692. package/dist/v4/streamContent.js +0 -29
  693. package/dist/v4/streamHandlers.d.ts +0 -61
  694. package/dist/v4/streamHandlers.js +0 -16
  695. package/dist/v4/streamingOperation.d.ts +0 -64
  696. package/dist/v4/streamingOperation.js +0 -141
  697. package/dist/v4/strictEd25519Reference.d.ts +0 -2
  698. package/dist/v4/strictEd25519Reference.js +0 -37
  699. package/dist/v4/testSupport/cbor.d.ts +0 -124
  700. package/dist/v4/testSupport/cbor.js +0 -230
  701. package/dist/v4/testSupport/credentials.d.ts +0 -55
  702. package/dist/v4/testSupport/credentials.js +0 -111
  703. package/dist/v4/testSupport/unicode.d.ts +0 -19
  704. package/dist/v4/testSupport/unicode.js +0 -112
  705. package/dist/v4/unaryOperation.d.ts +0 -59
  706. package/dist/v4/unaryOperation.js +0 -80
  707. package/dist/v4/unreliable.d.ts +0 -26
  708. package/dist/v4/unreliable.js +0 -10
  709. package/dist/v4/webStreams.d.ts +0 -30
  710. package/dist/v4/webStreams.js +0 -377
  711. /package/dist/{interop/proxyServerPeer.d.ts → rpc/wire.js} +0 -0
  712. /package/dist/{node/sqlitePoolWorkerProgramV4.d.ts → v3/publicSession.d.ts} +0 -0
  713. /package/dist/{node/sqliteWorkerProgramV4.d.ts → v3/streamMetadata.d.ts} +0 -0
@@ -0,0 +1,2399 @@
1
+ import { RpcClient } from "../rpc/client.js";
2
+ import { RpcRouter, RpcServer } from "../rpc/server.js";
3
+ import { CarrierError } from "./carrier.js";
4
+ import { FLOWERSEC_V3_PROFILE } from "./transportConstants.js";
5
+ import { computeClientConfirmV3, computeHandshakeH0V3, computeHandshakeH1V3, computeHandshakeH2V3, computeHandshakeH3V3, computeServerConfirmV3, computeSharedSecretV3, decodeClientFinishedV3, decodeClientInitV3, decodeHandshakeFrameV3, decodeServerFinishedV3, deriveHandshakePRKV3, deriveSessionPRKV3, encodeClientFinishedCoreV3, encodeClientFinishedV3, encodeClientInitV3, encodeControlPrefaceV3, encodeServerFinishedCoreV3, encodeServerFinishedV3, generateEphemeralKeyV3, parseControlPrefaceV3, validateClientInitV3, validateServerFinishedV3, } from "./handshake.js";
6
+ import { DirectionV3, InnerTypeV3, computeValidatedFSS3HashV3Internal, computeValidatedOpenHashV3Internal, computeSetupMAC, decodeInnerRecordV3, decodeOpenACKV3, decodeOpenPayload, decodeOpenRejectV3, decodeRecordHeader, decodeSetupPrefaceV3, decodeStreamKeyUpdateACKV3, deriveControlMaterial, deriveEpochZero, deriveEpochRoots, deriveNextEpoch, deriveStreamMaterial, encodeOpenACKV3, encodeOpenPayloadFromMetadataV3Internal, encodeOpenRejectV3, encodeSetupPreface, encodeStreamKeyUpdateACKV3, openRecordWithRawHeaderV3Internal, sealRecordWireV3Internal, verifySetupMAC, } from "./protocol.js";
7
+ import { StreamLifetimeLedgerV3, StreamLifetimeLedgerV3Error, maxLogicalStreamIDV3, } from "./streamLifetimeLedger.js";
8
+ import { UNRELIABLE_MESSAGES_FEATURE_V3, UNRELIABLE_MESSAGE_WIRE_BYTES_V3, createInternalUnreliableMessageChannelV3, } from "./unreliableMessage.js";
9
+ const decoder = new TextDecoder();
10
+ const MAX_DATA_BYTES = 16_384;
11
+ const MAX_BUFFERED_STREAM_BYTES = 4 * 1024 * 1024;
12
+ const RESERVED_RPC_KIND = "flowersec.rpc.v5";
13
+ const DEFAULT_IDLE_TIMEOUT_MS = 60_000;
14
+ const DEFAULT_CLOSE_TIMEOUT_MS = 2_000;
15
+ const DEFAULT_CONTROL_CONFIRM_TIMEOUT_MS = 2_000;
16
+ const MAX_UINT32 = 0xffffffff;
17
+ const MAX_UINT64 = (1n << 64n) - 1n;
18
+ export class SessionV3Error extends Error {
19
+ code;
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.code = code;
23
+ this.name = "SessionV3Error";
24
+ }
25
+ }
26
+ class SessionRpcPeerV3 {
27
+ createClient;
28
+ inbound;
29
+ outbound;
30
+ terminalError;
31
+ constructor(createClient, inbound) {
32
+ this.createClient = createClient;
33
+ this.inbound = inbound;
34
+ }
35
+ call(typeId, payload, signal) {
36
+ if (signal?.aborted)
37
+ return Promise.reject(abortReason(signal));
38
+ if (this.terminalError !== undefined)
39
+ return Promise.reject(this.terminalError);
40
+ return (this.outbound ??= this.createClient()).call(typeId, payload, signal);
41
+ }
42
+ notify(typeId, payload, signal) {
43
+ if (signal?.aborted)
44
+ return Promise.reject(abortReason(signal));
45
+ if (this.terminalError !== undefined)
46
+ return Promise.reject(this.terminalError);
47
+ return (this.outbound ??= this.createClient()).notify(typeId, payload, signal);
48
+ }
49
+ onNotify(typeId, handler) {
50
+ return this.inbound.onNotify(typeId, handler);
51
+ }
52
+ close(reason = new SessionV3Error("closed", "RPC peer closed")) {
53
+ if (this.terminalError !== undefined)
54
+ return;
55
+ this.terminalError = reason;
56
+ this.outbound?.close(reason);
57
+ }
58
+ async waitStopped() { await this.outbound?.waitStopped(); }
59
+ }
60
+ export async function establishSessionV3(carrier, config, options = {}) {
61
+ validateConfig(carrier, config);
62
+ const establishDeadline = createSessionDeadline(config.deadlines, "establish");
63
+ const establishSignal = combineSignals(options.signal, establishDeadline.signal);
64
+ throwIfAborted(establishSignal.signal);
65
+ let control;
66
+ try {
67
+ control = config.role === "client"
68
+ ? await carrier.openStream(signalOptions(establishSignal.signal))
69
+ : await carrier.acceptStream(signalOptions(establishSignal.signal));
70
+ const reader = new ExactReader(control);
71
+ const localFeatures = supportedFeatures(carrier.unreliableDatagrams);
72
+ const material = config.role === "client"
73
+ ? await clientHandshake(control, reader, config, localFeatures, establishSignal.signal)
74
+ : await serverHandshake(control, reader, config, localFeatures, establishSignal.signal);
75
+ const session = new SessionV3(carrier, control, reader, config, material);
76
+ session.start();
77
+ return session;
78
+ }
79
+ catch (error) {
80
+ control?.abort(asError(error));
81
+ carrier.abort({ code: 6, reason: "handshake failed" });
82
+ if (error instanceof SessionV3Error)
83
+ throw error;
84
+ throw new SessionV3Error("handshake", `Flowersec v5 handshake failed: ${errorMessage(error)}`);
85
+ }
86
+ finally {
87
+ establishSignal.cancel();
88
+ establishDeadline.cancel();
89
+ }
90
+ }
91
+ export class SessionV3 {
92
+ carrier;
93
+ control;
94
+ controlReader;
95
+ path;
96
+ endpointInstanceId;
97
+ rpc;
98
+ termination;
99
+ unreliableMessages;
100
+ terminalError;
101
+ role;
102
+ sendDirection;
103
+ receiveDirection;
104
+ h3;
105
+ sendRoots = new Map();
106
+ receiveRoots = new Map();
107
+ sendEpoch = 0;
108
+ receiveEpoch = 0;
109
+ controlSendEpoch = 0;
110
+ controlSendSequence = 0n;
111
+ controlSendKey;
112
+ controlReceiveEpoch = 0;
113
+ controlReceiveSequence = 0n;
114
+ controlReceiveKey;
115
+ controlWriteTail = Promise.resolve();
116
+ controlTerminalSealed = false;
117
+ nextLogicalID;
118
+ receivedGoAway = false;
119
+ receivedGoAwayLastAccepted = 0n;
120
+ receivedGoAwayReason = 0;
121
+ sentGoAway = false;
122
+ sentGoAwayLastAccepted = 0n;
123
+ sentGoAwayReason = 0;
124
+ closePromise;
125
+ lifecycle = "opening";
126
+ sentSessionClose = false;
127
+ sessionCloseCommitted = false;
128
+ peerCloseReceived = false;
129
+ tunnelRPCStop;
130
+ finishingTunnelCarrier = false;
131
+ peerCloseOrTermination = deferred();
132
+ streams = new Map();
133
+ releasedStreams = new Map();
134
+ releasedStreamCleanup = releasedStreamCleanup(this.releasedStreams);
135
+ peerLedger;
136
+ outboundLedger;
137
+ incoming = new AsyncQueue();
138
+ outboundPermits;
139
+ inboundPermits;
140
+ pings = new Map();
141
+ backgroundTasks = new Set();
142
+ nextPing = 1n;
143
+ rpcServer;
144
+ rekeyTail = Promise.resolve();
145
+ nextTransition = 1n;
146
+ receiveTransition = 0n;
147
+ pendingSessionRekey;
148
+ lastSessionRekeyACK;
149
+ preparingSendEpoch;
150
+ pendingReceiveEpoch;
151
+ openFrozen = false;
152
+ openGate = deferred();
153
+ outboundFrontierChanged = deferred();
154
+ activeInboundResponders = 0;
155
+ localResponderFrozen = false;
156
+ peerResponderFrozen = false;
157
+ responderChanged = deferred();
158
+ idleWatchdogStarted = false;
159
+ idleDeadlineMs;
160
+ idleTimerCancel;
161
+ terminationState = deferred();
162
+ terminationController = new AbortController();
163
+ suite;
164
+ runtime;
165
+ deadlines;
166
+ idleTimeoutMs;
167
+ closeTimeoutMs;
168
+ rpcRouter;
169
+ rpcServerOptions;
170
+ constructor(carrier, control, controlReader, config, material) {
171
+ this.carrier = carrier;
172
+ this.control = control;
173
+ this.controlReader = controlReader;
174
+ this.path = config.path;
175
+ this.suite = config.suite;
176
+ this.runtime = config.runtime;
177
+ this.deadlines = config.deadlines;
178
+ this.idleTimeoutMs = sessionIdleTimeoutMs(config);
179
+ this.closeTimeoutMs = sessionCloseTimeoutMs(config);
180
+ this.termination = this.terminationState.promise;
181
+ this.endpointInstanceId = config.path === "tunnel" ? config.expectedPeerEndpointInstanceID : undefined;
182
+ this.role = config.role === "client" ? 1 : 2;
183
+ this.sendDirection = this.role === 1 ? DirectionV3.ClientToServer : DirectionV3.ServerToClient;
184
+ this.receiveDirection = this.role === 1 ? DirectionV3.ServerToClient : DirectionV3.ClientToServer;
185
+ this.nextLogicalID = this.role === 1 ? 1n : 2n;
186
+ this.peerLedger = new StreamLifetimeLedgerV3(this.role === 1 ? 2 : 1);
187
+ this.outboundLedger = new StreamLifetimeLedgerV3(this.role);
188
+ this.h3 = material.h3.slice();
189
+ this.sendRoots.set(0, deriveEpochZero(material.sessionPRK, this.sendDirection));
190
+ this.receiveRoots.set(0, deriveEpochZero(material.sessionPRK, this.receiveDirection));
191
+ this.unreliableMessages = (material.selectedFeatures & UNRELIABLE_MESSAGES_FEATURE_V3) !== 0
192
+ ? createInternalUnreliableMessageChannelV3({
193
+ transport: requireUnreliableDatagrams(carrier),
194
+ suite: this.suite,
195
+ h3: this.h3,
196
+ sendDirection: this.sendDirection,
197
+ receiveDirection: this.receiveDirection,
198
+ currentSendEpoch: () => ({
199
+ epoch: this.sendEpoch,
200
+ epochSecret: this.rootForSend(this.sendEpoch).epochSecret,
201
+ }),
202
+ receiveEpochSecret: (epoch) => epoch <= this.receiveEpoch && epoch + 1 >= this.receiveEpoch
203
+ ? this.receiveRoots.get(epoch)?.epochSecret
204
+ : undefined,
205
+ onProtocolFailure: () => this.fail(protocolError("previous protocol unreliable frame")),
206
+ })
207
+ : undefined;
208
+ this.outboundPermits = new AsyncSemaphore(config.maxInboundStreams);
209
+ this.inboundPermits = new AsyncSemaphore(config.maxInboundStreams);
210
+ this.rpcRouter = config.rpcRouter ?? new RpcRouter();
211
+ this.rpcServerOptions = config.rpcServerOptions;
212
+ this.rpc = new SessionRpcPeerV3(this.createRpcClient.bind(this), this.rpcRouter);
213
+ }
214
+ createRpcClient() {
215
+ let opened;
216
+ let reader;
217
+ const stream = () => opened ??= this.openLogicalStream(RESERVED_RPC_KIND, { signal: this.terminationController.signal }, true);
218
+ return new RpcClient(async (length) => (reader ??= new ExactReader(await stream())).readExactly(length), async (payload, signal) => { await (await raceAbort(stream(), signal)).writeRpcFrame(payload, signal); }, { onTerminal: (error) => this.fail(error), ...this.rpcServerOptions });
219
+ }
220
+ async openStream(kind, options = {}) {
221
+ if (kind === RESERVED_RPC_KIND)
222
+ throw new SessionV3Error("open_rejected", "reserved RPC stream kind");
223
+ return await this.openLogicalStream(kind, options, false);
224
+ }
225
+ async acceptStream(options = {}) {
226
+ this.assertOpen();
227
+ return await this.incoming.shift(options.signal);
228
+ }
229
+ async probeLiveness(options = {}) {
230
+ this.assertOpen();
231
+ throwIfAborted(options.signal);
232
+ const nonce = this.nextPing++;
233
+ const pending = deferred();
234
+ this.pings.set(nonce, pending);
235
+ const started = this.runtime.monotonicMilliseconds();
236
+ try {
237
+ await this.sendControl(InnerTypeV3.Ping, u64(nonce), options.signal);
238
+ await raceAbort(pending.promise, options.signal);
239
+ return Math.max(0, this.runtime.monotonicMilliseconds() - started);
240
+ }
241
+ finally {
242
+ this.pings.delete(nonce);
243
+ }
244
+ }
245
+ async rekey(options = {}) {
246
+ const callerCancellation = canonicalCallerCancellation(options.signal);
247
+ try {
248
+ this.assertOpen();
249
+ throwIfAborted(callerCancellation.signal);
250
+ const task = this.rekeyTail.then(async () => {
251
+ throwIfAborted(callerCancellation.signal);
252
+ await this.rekeyOnce({ signal: callerCancellation.signal });
253
+ });
254
+ this.rekeyTail = task.catch(() => undefined);
255
+ await raceAbort(task, callerCancellation.signal);
256
+ }
257
+ finally {
258
+ callerCancellation.cancel();
259
+ }
260
+ }
261
+ close() {
262
+ if (this.closePromise === undefined) {
263
+ this.beginClosing();
264
+ this.closePromise = this.closeOnce();
265
+ }
266
+ return this.closePromise;
267
+ }
268
+ start() {
269
+ if (this.lifecycle !== "opening")
270
+ return;
271
+ this.lifecycle = "open";
272
+ this.startIdleWatchdog();
273
+ this.trackBackground(this.controlLoop());
274
+ this.trackBackground(this.acceptCarrierLoop());
275
+ this.trackBackground(this.carrier.waitTermination().then(() => this.carrierEnded(new CarrierError("closed", "carrier session terminated")), (error) => this.carrierEnded(asError(error))));
276
+ }
277
+ carrierEnded(error) {
278
+ if (this.finishingTunnelCarrier)
279
+ return;
280
+ this.fail(error, false);
281
+ }
282
+ rootForSend(epoch) {
283
+ const roots = this.sendRoots.get(epoch);
284
+ if (roots === undefined)
285
+ throw protocolError("missing send epoch roots");
286
+ return roots;
287
+ }
288
+ rootForReceive(epoch) {
289
+ const roots = this.receiveRoots.get(epoch);
290
+ if (roots === undefined)
291
+ throw protocolError("missing receive epoch roots");
292
+ return roots;
293
+ }
294
+ hasReceiveRoots(epoch) {
295
+ return this.receiveRoots.has(epoch);
296
+ }
297
+ installReceiveRoots(epoch, roots) {
298
+ const existing = this.receiveRoots.get(epoch);
299
+ if (existing !== undefined && !bytesEqual(existing.epochSecret, roots.epochSecret)) {
300
+ throw protocolError("conflicting receive epoch roots");
301
+ }
302
+ this.receiveRoots.set(epoch, roots);
303
+ }
304
+ transcriptHash() {
305
+ return this.h3;
306
+ }
307
+ receiveDirectionValue() {
308
+ return this.receiveDirection;
309
+ }
310
+ terminationSignal() {
311
+ return this.terminationController.signal;
312
+ }
313
+ async sendStreamRecord(stream, type, payload, signal) {
314
+ this.assertOpen();
315
+ const roots = this.rootForSend(stream.sendEpoch);
316
+ const material = stream.sendMaterial(roots, this.h3, this.sendDirection);
317
+ const wire = sealRecordWireV3Internal(this.suite, material, this.h3, stream.id, this.sendDirection, stream.sendEpoch, stream.sendSequence, type, payload);
318
+ stream.sendSequence += 1n;
319
+ await writeAll(stream.carrier, wire, signal);
320
+ this.markAuthenticatedActivity();
321
+ }
322
+ async readStreamRecord(stream) {
323
+ const rawHeader = await stream.reader.readExactly(24);
324
+ const header = decodeRecordHeader(rawHeader);
325
+ const priorACK = stream.priorACK !== undefined &&
326
+ header.epoch === stream.priorACK.epoch && header.sequence === stream.priorACK.sequence;
327
+ if (!priorACK && (header.epoch !== stream.receiveEpoch || header.sequence !== stream.receiveSequence)) {
328
+ throw protocolError("unexpected stream epoch or sequence");
329
+ }
330
+ const roots = this.rootForReceive(header.epoch);
331
+ const material = stream.receiveMaterial(roots, this.h3, this.receiveDirection, header.epoch);
332
+ const ciphertext = await stream.reader.readExactly(header.ciphertextLength, undefined, true);
333
+ const inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, stream.id, this.receiveDirection, header, rawHeader, ciphertext));
334
+ if (priorACK) {
335
+ if (inner.type !== InnerTypeV3.StreamKeyUpdateACK)
336
+ throw protocolError("late old-epoch record is not rekey ACK");
337
+ stream.priorACK = undefined;
338
+ stream.pruneReceiveMaterials();
339
+ this.cleanupEpochRoots();
340
+ }
341
+ else {
342
+ stream.receiveSequence += 1n;
343
+ }
344
+ this.markAuthenticatedActivity();
345
+ return { ...inner, header };
346
+ }
347
+ async localReset(stream, error) {
348
+ if (!stream.markTerminal(error))
349
+ return;
350
+ this.releaseStream(stream);
351
+ let controlConfirmed = false;
352
+ try {
353
+ if (await this.sendControlCleanup(InnerTypeV3.StreamReset, idReason(stream.id, 6))) {
354
+ this.commitLocalReset(stream.id);
355
+ if (stream.hasRemoteFIN())
356
+ controlConfirmed = await this.confirmControlDelivery();
357
+ }
358
+ }
359
+ catch (cause) {
360
+ this.fail(asError(cause));
361
+ }
362
+ if (controlConfirmed) {
363
+ await stream.carrier.closeWrite().catch(async () => await stream.carrier.reset().catch(() => undefined));
364
+ }
365
+ else {
366
+ await stream.carrier.reset().catch(() => undefined);
367
+ }
368
+ }
369
+ releaseStream(stream) {
370
+ stream.wipeRecordMaterials();
371
+ if (stream.terminalError !== undefined) {
372
+ this.releasedStreams.delete(stream.id);
373
+ this.releasedStreamCleanup.unregister(stream);
374
+ }
375
+ if (this.streams.get(stream.id) !== stream)
376
+ return;
377
+ this.streams.delete(stream.id);
378
+ if (stream.terminalError === undefined) {
379
+ this.releasedStreams.set(stream.id, new WeakRef(stream));
380
+ this.releasedStreamCleanup.register(stream, stream.id, stream);
381
+ }
382
+ stream.releasePermit();
383
+ this.cleanupEpochRoots();
384
+ }
385
+ async confirmControlDelivery() {
386
+ if (this.lifecycle !== "open" || this.controlTerminalSealed)
387
+ return false;
388
+ const nonce = this.nextPing++;
389
+ const pending = deferred();
390
+ this.pings.set(nonce, pending);
391
+ try {
392
+ await this.sendControl(InnerTypeV3.Ping, u64(nonce));
393
+ return await resolveWithin(pending.promise, DEFAULT_CONTROL_CONFIRM_TIMEOUT_MS);
394
+ }
395
+ finally {
396
+ this.pings.delete(nonce);
397
+ }
398
+ }
399
+ async openLogicalStream(kind, options, internal) {
400
+ this.assertOpen();
401
+ throwIfAborted(options.signal);
402
+ await this.waitOpenGate(options.signal);
403
+ const releasePermit = internal ? () => undefined : await this.outboundPermits.acquire(options.signal);
404
+ let stream;
405
+ let carrierStream;
406
+ let id;
407
+ let ledgerAllocated = false;
408
+ try {
409
+ this.assertOpen();
410
+ await this.waitOpenGate(options.signal);
411
+ if (this.sentGoAway || this.receivedGoAway)
412
+ throw new SessionV3Error("going_away", "session is going away");
413
+ id = this.nextLogicalID;
414
+ if (id > maxLogicalStreamIDV3(this.role)) {
415
+ await this.sendGoAway(5);
416
+ throw new SessionV3Error("resource_exhausted", "logical stream lifetime ledger exhausted");
417
+ }
418
+ this.nextLogicalID += 2n;
419
+ const setupAction = this.outboundLedger.validFSS3(id);
420
+ ledgerAllocated = true;
421
+ if (setupAction === "reset") {
422
+ this.notifyOutboundFrontierChanged();
423
+ throw new SessionV3Error("closed", "logical stream identity was already reset by peer");
424
+ }
425
+ carrierStream = await this.carrier.openStream(options);
426
+ if (!this.localOpeningAllowedAfterGoAway(id)) {
427
+ throw new SessionV3Error("going_away", "logical stream is beyond the peer GOAWAY boundary");
428
+ }
429
+ const roots = this.rootForSend(this.sendEpoch);
430
+ const unsigned = {
431
+ openerRole: this.role,
432
+ logicalStreamID: id,
433
+ initialSendEpoch: this.sendEpoch,
434
+ setupMAC: new Uint8Array(32),
435
+ };
436
+ const prefaceRaw = encodeSetupPreface({
437
+ ...unsigned,
438
+ setupMAC: computeSetupMAC(roots.setupRoot, this.h3, unsigned),
439
+ });
440
+ await writeAll(carrierStream, prefaceRaw, options.signal);
441
+ if (!this.localOpeningAllowedAfterGoAway(id)) {
442
+ throw new SessionV3Error("going_away", "logical stream is beyond the peer GOAWAY boundary");
443
+ }
444
+ const openRaw = encodeOpenPayloadFromMetadataV3Internal({
445
+ logicalStreamID: id,
446
+ fss3Hash: computeValidatedFSS3HashV3Internal(prefaceRaw),
447
+ kind,
448
+ metadata: options.metadata ?? {},
449
+ });
450
+ stream = new EncryptedStreamV3(this, carrierStream, id, kind, this.sendEpoch, this.receiveEpoch, releasePermit);
451
+ this.streams.set(id, stream);
452
+ stream.setOpenHash(computeValidatedOpenHashV3Internal(openRaw));
453
+ await stream.send(InnerTypeV3.Open, openRaw, options.signal);
454
+ stream.startPump();
455
+ await raceAbort(stream.opened.promise, options.signal);
456
+ if (!this.localOpeningAllowedAfterGoAway(id)) {
457
+ throw new SessionV3Error("going_away", "logical stream is beyond the peer GOAWAY boundary");
458
+ }
459
+ return stream;
460
+ }
461
+ catch (error) {
462
+ if (stream !== undefined)
463
+ await this.localReset(stream, asError(error));
464
+ else {
465
+ await carrierStream?.reset().catch(() => undefined);
466
+ if (id !== undefined && ledgerAllocated) {
467
+ await this.commitOutboundReset(id).catch((cause) => this.fail(asError(cause)));
468
+ }
469
+ releasePermit();
470
+ }
471
+ throw error;
472
+ }
473
+ }
474
+ async acceptCarrierLoop() {
475
+ try {
476
+ while (this.lifecycle === "open") {
477
+ const carrierStream = await this.carrier.acceptStream();
478
+ this.trackBackground(this.acceptCarrierStream(carrierStream).catch(async (error) => {
479
+ if (error instanceof StreamLifetimeLedgerV3Error && error.code === "duplicate") {
480
+ this.fail(protocolError(error.message));
481
+ }
482
+ await carrierStream.reset().catch(() => undefined);
483
+ }));
484
+ }
485
+ }
486
+ catch (error) {
487
+ if (this.finishingTunnelCarrier && error instanceof CarrierError && error.code === "closed")
488
+ return;
489
+ if (this.lifecycle !== "closed")
490
+ this.fail(asError(error));
491
+ }
492
+ }
493
+ async acceptCarrierStream(carrierStream) {
494
+ let responderHeld = false;
495
+ let ledgerID;
496
+ try {
497
+ this.assertOpen();
498
+ await this.enterInboundResponder();
499
+ responderHeld = true;
500
+ const reader = new ExactReader(carrierStream);
501
+ let prefaceRaw;
502
+ let preface;
503
+ prefaceRaw = await reader.readExactly(56);
504
+ preface = decodeSetupPrefaceV3(prefaceRaw);
505
+ const peerRole = this.role === 1 ? 2 : 1;
506
+ if (preface.openerRole !== peerRole || preface.initialSendEpoch !== this.receiveEpoch) {
507
+ await carrierStream.reset().catch(() => undefined);
508
+ return;
509
+ }
510
+ const receiveRoots = this.rootForReceive(preface.initialSendEpoch);
511
+ if (!verifySetupMAC(receiveRoots.setupRoot, this.h3, preface) || !this.acceptsPeerStreamAfterGoAway(preface.logicalStreamID)) {
512
+ await carrierStream.reset().catch(() => undefined);
513
+ return;
514
+ }
515
+ let setupAction;
516
+ try {
517
+ setupAction = this.peerLedger.validFSS3(preface.logicalStreamID);
518
+ }
519
+ catch (error) {
520
+ if (error instanceof StreamLifetimeLedgerV3Error && error.code === "duplicate")
521
+ throw error;
522
+ await carrierStream.reset().catch(() => undefined);
523
+ return;
524
+ }
525
+ if (setupAction === "reset") {
526
+ await carrierStream.reset().catch(() => undefined);
527
+ return;
528
+ }
529
+ ledgerID = preface.logicalStreamID;
530
+ await this.acceptCarrierStreamAfterFSS3(carrierStream, reader, prefaceRaw, preface);
531
+ }
532
+ catch (error) {
533
+ if (ledgerID !== undefined)
534
+ await this.resetInboundBeforeDelivery(ledgerID, carrierStream);
535
+ else
536
+ await carrierStream.reset().catch(() => undefined);
537
+ if (error instanceof StreamLifetimeLedgerV3Error && error.code === "duplicate")
538
+ throw error;
539
+ }
540
+ finally {
541
+ if (responderHeld)
542
+ this.leaveInboundResponder();
543
+ }
544
+ }
545
+ async acceptCarrierStreamAfterFSS3(carrierStream, reader, prefaceRaw, preface) {
546
+ this.assertOpen();
547
+ const temporary = new EncryptedStreamV3(this, carrierStream, preface.logicalStreamID, "", this.sendEpoch, preface.initialSendEpoch, () => undefined, reader);
548
+ let stream;
549
+ try {
550
+ const first = await this.readStreamRecord(temporary);
551
+ if (first.type !== InnerTypeV3.Open)
552
+ throw protocolError("OPEN must be first");
553
+ const open = decodeOpenPayload(first.payload);
554
+ const openHash = computeValidatedOpenHashV3Internal(first.payload);
555
+ if (open.logicalStreamID !== preface.logicalStreamID ||
556
+ !bytesEqual(open.fss3Hash, computeValidatedFSS3HashV3Internal(prefaceRaw))) {
557
+ throw protocolError("OPEN binding mismatch");
558
+ }
559
+ this.peerLedger.validOpen(preface.logicalStreamID);
560
+ const internalRPC = open.kind === RESERVED_RPC_KIND;
561
+ if (internalRPC && decoder.decode(open.metadata) !== "{}") {
562
+ await temporary.send(InnerTypeV3.OpenReject, encodeOpenRejectV3(openHash, 4));
563
+ temporary.wipeRecordMaterials();
564
+ await carrierStream.closeWrite();
565
+ return;
566
+ }
567
+ const releasePermit = internalRPC ? () => undefined : this.inboundPermits.tryAcquire();
568
+ if (releasePermit === undefined) {
569
+ await temporary.send(InnerTypeV3.OpenReject, encodeOpenRejectV3(openHash, 2));
570
+ temporary.wipeRecordMaterials();
571
+ await carrierStream.closeWrite();
572
+ return;
573
+ }
574
+ stream = new EncryptedStreamV3(this, carrierStream, preface.logicalStreamID, open.kind, this.sendEpoch, preface.initialSendEpoch, releasePermit, reader);
575
+ this.assertOpen();
576
+ stream.receiveSequence = temporary.receiveSequence;
577
+ temporary.transferReceiveMaterialsTo(stream);
578
+ this.streams.set(stream.id, stream);
579
+ await stream.send(InnerTypeV3.OpenACK, encodeOpenACKV3(openHash));
580
+ stream.markOpen();
581
+ stream.startPump();
582
+ if (!this.acceptsPeerStreamAfterGoAway(stream.id)) {
583
+ await this.localReset(stream, new SessionV3Error("going_away", "peer stream exceeds the sent GOAWAY boundary"));
584
+ return;
585
+ }
586
+ if (internalRPC) {
587
+ if (this.tunnelRPCStop !== undefined || this.lifecycle === "closed")
588
+ return;
589
+ if (this.rpcServer !== undefined) {
590
+ await this.localReset(stream, protocolError("duplicate reserved RPC stream"));
591
+ return;
592
+ }
593
+ const rpcStream = stream;
594
+ const rpcReader = new ExactReader(rpcStream);
595
+ const server = new RpcServer({
596
+ readExactly: async (length) => await rpcReader.readExactly(length),
597
+ write: async (payload) => { await rpcStream.writeRpcFrame(payload); },
598
+ close: reason => { if (reason !== this.tunnelRPCStop)
599
+ return rpcStream.reset(); },
600
+ }, this.rpcServerOptions, this.rpcRouter);
601
+ this.rpcServer = server;
602
+ this.trackBackground(server.serve(this.terminationController.signal).catch((error) => {
603
+ if (this.lifecycle !== "closed" && error !== this.tunnelRPCStop)
604
+ this.fail(asError(error));
605
+ }).finally(() => {
606
+ this.rpcServer = "stopped";
607
+ return server.waitHandlers();
608
+ }));
609
+ return;
610
+ }
611
+ this.incoming.push({
612
+ id: stream.id,
613
+ kind: stream.kind,
614
+ metadata: decodeMetadata(open.metadata),
615
+ stream,
616
+ });
617
+ }
618
+ catch (error) {
619
+ if (stream !== undefined) {
620
+ stream.markTerminal(asError(error));
621
+ this.releaseStream(stream);
622
+ }
623
+ throw error;
624
+ }
625
+ finally {
626
+ temporary.wipeRecordMaterials();
627
+ }
628
+ }
629
+ async resetInboundBeforeDelivery(id, carrierStream) {
630
+ await carrierStream.reset().catch(() => undefined);
631
+ try {
632
+ if (await this.sendControlCleanup(InnerTypeV3.StreamReset, idReason(id, 3))) {
633
+ this.peerLedger.localResetCommitted(id);
634
+ }
635
+ }
636
+ catch (error) {
637
+ this.fail(asError(error));
638
+ }
639
+ }
640
+ async sendControl(type, payload, signal) {
641
+ if (this.controlTerminalSealed) {
642
+ throw this.terminalError ?? new SessionV3Error("closed", "Flowersec v5 control stream is sealed");
643
+ }
644
+ const task = this.controlWriteTail.then(async () => {
645
+ if (this.lifecycle === "closed")
646
+ throw this.terminalError ?? new SessionV3Error("closed", "Flowersec v5 session closed");
647
+ await this.writeControl(type, payload, signal);
648
+ });
649
+ this.controlWriteTail = task.catch(() => undefined);
650
+ if (signal === undefined)
651
+ await task;
652
+ else
653
+ await raceAbort(task, signal);
654
+ }
655
+ async sendControlResponse(type, payload, publish) {
656
+ if (this.lifecycle !== "open" || this.controlTerminalSealed)
657
+ return false;
658
+ const task = this.controlWriteTail.then(async () => {
659
+ if (this.lifecycle !== "open" || this.controlTerminalSealed)
660
+ return false;
661
+ publish?.();
662
+ await this.writeControl(type, payload);
663
+ return true;
664
+ });
665
+ this.controlWriteTail = task.then(() => undefined, () => undefined);
666
+ return await task;
667
+ }
668
+ async sendControlCleanup(type, payload) {
669
+ if (this.controlTerminalSealed || this.lifecycle === "closed")
670
+ return false;
671
+ const task = this.controlWriteTail.then(async () => {
672
+ if (this.lifecycle === "closed")
673
+ return false;
674
+ await this.writeControl(type, payload);
675
+ return true;
676
+ });
677
+ this.controlWriteTail = task.then(() => undefined, () => undefined);
678
+ return await task;
679
+ }
680
+ sendTerminalControl(reason) {
681
+ if (this.controlTerminalSealed)
682
+ return this.controlWriteTail;
683
+ this.controlTerminalSealed = true;
684
+ const task = this.controlWriteTail.then(async () => {
685
+ if (this.lifecycle === "closed")
686
+ throw this.terminalError ?? new SessionV3Error("closed", "Flowersec v5 session closed");
687
+ if (!this.sentGoAway) {
688
+ this.sentGoAway = true;
689
+ this.sentGoAwayLastAccepted = this.peerLedger.frontier;
690
+ this.sentGoAwayReason = reason;
691
+ }
692
+ await this.writeControl(InnerTypeV3.GoAway, idReason(this.sentGoAwayLastAccepted, this.sentGoAwayReason));
693
+ if (!this.sentSessionClose) {
694
+ this.sentSessionClose = true;
695
+ await this.writeControl(InnerTypeV3.SessionClose, Uint8Array.of(0, reason));
696
+ this.sessionCloseCommitted = true;
697
+ }
698
+ if (this.path !== "tunnel")
699
+ await this.control.closeWrite();
700
+ });
701
+ this.controlWriteTail = task.catch(() => undefined);
702
+ return task;
703
+ }
704
+ async writeControl(type, payload, signal) {
705
+ const material = this.controlSendKey ??= deriveControlRecordKey(this.rootForSend(this.controlSendEpoch), this.h3, this.sendDirection, this.controlSendEpoch);
706
+ const wire = sealRecordWireV3Internal(this.suite, material, this.h3, 0n, this.sendDirection, this.controlSendEpoch, this.controlSendSequence, type, payload);
707
+ this.controlSendSequence += 1n;
708
+ await writeAll(this.control, wire, signal);
709
+ this.markAuthenticatedActivity();
710
+ }
711
+ async readControl() {
712
+ const rawHeader = await this.controlReader.readExactly(24);
713
+ const header = decodeRecordHeader(rawHeader);
714
+ const cutover = header.epoch === this.controlReceiveEpoch + 1 &&
715
+ header.epoch <= this.receiveEpoch && header.sequence === 0n;
716
+ if (!cutover && (header.epoch !== this.controlReceiveEpoch || header.sequence !== this.controlReceiveSequence)) {
717
+ throw protocolError("unexpected control epoch or sequence");
718
+ }
719
+ const ciphertext = await this.controlReader.readExactly(header.ciphertextLength, undefined, true);
720
+ const material = (!cutover ? this.controlReceiveKey : undefined) ?? deriveControlRecordKey(this.rootForReceive(header.epoch), this.h3, this.receiveDirection, header.epoch);
721
+ let inner;
722
+ try {
723
+ inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, 0n, this.receiveDirection, header, rawHeader, ciphertext));
724
+ }
725
+ catch (error) {
726
+ wipeRecordKey(material);
727
+ throw error;
728
+ }
729
+ if (cutover) {
730
+ wipeRecordKey(this.controlReceiveKey);
731
+ this.controlReceiveEpoch = header.epoch;
732
+ this.controlReceiveSequence = 1n;
733
+ this.cleanupEpochRoots();
734
+ }
735
+ else {
736
+ this.controlReceiveSequence += 1n;
737
+ }
738
+ this.controlReceiveKey = material;
739
+ this.markAuthenticatedActivity();
740
+ return inner;
741
+ }
742
+ async controlLoop() {
743
+ try {
744
+ while (this.lifecycle !== "closed") {
745
+ const record = await this.readControl();
746
+ switch (record.type) {
747
+ case InnerTypeV3.Ping:
748
+ await this.sendControlResponse(InnerTypeV3.Pong, record.payload);
749
+ break;
750
+ case InnerTypeV3.Pong:
751
+ this.pings.get(readU64(record.payload))?.resolve();
752
+ break;
753
+ case InnerTypeV3.StreamReset: {
754
+ const { id, reason } = parseIDReason(record.payload);
755
+ if (id === 0n || reason === 0)
756
+ throw protocolError("invalid STREAM_RESET");
757
+ const stream = this.streams.get(id);
758
+ if (stream !== undefined) {
759
+ stream.peerReset(new SessionV3Error("stream_reset", "logical stream reset by peer"));
760
+ }
761
+ else {
762
+ const released = this.releasedStreams.get(id);
763
+ if (released !== undefined) {
764
+ this.releasedStreams.delete(id);
765
+ const releasedStream = released.deref();
766
+ if (releasedStream !== undefined) {
767
+ this.releasedStreamCleanup.unregister(releasedStream);
768
+ releasedStream.markTerminal(new SessionV3Error("stream_reset", "logical stream reset by peer"));
769
+ }
770
+ }
771
+ }
772
+ if (this.isLocalLogicalID(id)) {
773
+ this.outboundLedger.peerReset(id);
774
+ this.notifyOutboundFrontierChanged();
775
+ }
776
+ else {
777
+ this.peerLedger.peerReset(id);
778
+ }
779
+ break;
780
+ }
781
+ case InnerTypeV3.SessionKeyUpdate:
782
+ await this.receiveSessionRekey(record.payload);
783
+ break;
784
+ case InnerTypeV3.SessionKeyUpdateACK:
785
+ this.receiveSessionRekeyACK(record.payload);
786
+ break;
787
+ case InnerTypeV3.GoAway:
788
+ await this.receiveGoAway(record.payload);
789
+ break;
790
+ case InnerTypeV3.SessionClose:
791
+ if (record.payload.length !== 2 || readU16(record.payload, 0) === 0) {
792
+ throw protocolError("invalid SESSION_CLOSE");
793
+ }
794
+ this.peerCloseReceived = true;
795
+ this.peerCloseOrTermination.resolve();
796
+ void this.close().catch(error => this.fail(asError(error)));
797
+ return;
798
+ default:
799
+ throw protocolError(`unexpected control type ${record.type}`);
800
+ }
801
+ }
802
+ }
803
+ catch (error) {
804
+ if (this.lifecycle !== "closed")
805
+ this.fail(asError(error));
806
+ }
807
+ }
808
+ async closeOnce() {
809
+ if (this.lifecycle === "closed") {
810
+ await this.waitStopped();
811
+ return;
812
+ }
813
+ const closed = new SessionV3Error("closed", "Flowersec v5 session closed");
814
+ const terminal = this.sendTerminalControl(1);
815
+ const work = (async () => {
816
+ try {
817
+ await terminal;
818
+ }
819
+ catch (error) {
820
+ this.fail(asError(error));
821
+ return;
822
+ }
823
+ await this.peerCloseOrTermination.promise;
824
+ if (this.lifecycle === "closed")
825
+ return;
826
+ if (this.path === "tunnel") {
827
+ this.tunnelRPCStop = closed;
828
+ if (this.rpcServer instanceof RpcServer)
829
+ this.rpcServer.close(closed);
830
+ if (this.role === 2)
831
+ await this.control.closeWrite();
832
+ await this.controlReader.readEOF();
833
+ if (this.terminalError !== undefined)
834
+ return;
835
+ this.finishingTunnelCarrier = true;
836
+ if (this.role === 1) {
837
+ await this.control.closeWrite();
838
+ if (await this.carrier.waitRemoteSessionClose?.() !== true) {
839
+ throw protocolError("missing normal tunnel carrier close");
840
+ }
841
+ }
842
+ else {
843
+ await this.carrier.close({ code: 1, reason: "session closed" });
844
+ }
845
+ this.fail(closed, false);
846
+ return;
847
+ }
848
+ this.fail(closed, false);
849
+ await this.carrier.close({ code: 1, reason: "session closed" }).catch(() => undefined);
850
+ })().catch(error => this.fail(asError(error)));
851
+ if (!await settleWithin(work, this.closeTimeoutMs)) {
852
+ this.fail(new SessionV3Error("timeout", "session close deadline exceeded"), false);
853
+ this.carrier.abort({ code: 6, reason: "session close deadline exceeded" });
854
+ }
855
+ this.fail(closed, false);
856
+ // Close is the barrier for every workflow the session owns. A caller may
857
+ // already have stopped observing a committed rekey, but its internal task
858
+ // must release all gates before Close returns.
859
+ await Promise.allSettled([work, this.waitStopped()]);
860
+ }
861
+ async waitStopped() {
862
+ await Promise.allSettled([this.rpc.waitStopped(), this.rekeyTail, this.controlWriteTail]);
863
+ while (this.backgroundTasks.size)
864
+ await Promise.allSettled([...this.backgroundTasks]);
865
+ }
866
+ async waitTermination() {
867
+ return await this.termination;
868
+ }
869
+ runtimeInventory() {
870
+ let streams = 0, residual = 0;
871
+ for (const stream of this.streams.values())
872
+ if (stream.kind !== RESERVED_RPC_KIND)
873
+ streams++;
874
+ for (const entry of this.releasedStreams.values()) {
875
+ const stream = entry.deref();
876
+ if (stream && stream.kind !== RESERVED_RPC_KIND)
877
+ residual++;
878
+ }
879
+ return { active: this.lifecycle === "open", streams, residual };
880
+ }
881
+ async rekeyOnce(options) {
882
+ this.assertOpen();
883
+ throwIfAborted(options.signal);
884
+ this.openFrozen = true;
885
+ this.openGate = deferred();
886
+ let committed = false;
887
+ const prepareDeadline = createSessionDeadline(this.deadlines, "rekey_prepare");
888
+ const prepareSignal = combineSignals(options.signal, prepareDeadline.signal);
889
+ let completionDeadline;
890
+ let completionSignal;
891
+ let respondersFrozen = false;
892
+ try {
893
+ const currentEpoch = this.sendEpoch;
894
+ if (currentEpoch === MAX_UINT32) {
895
+ await this.rejectExhaustedRekey("session epoch exhausted", prepareSignal.signal, options.signal);
896
+ }
897
+ if (this.nextTransition < 1n || this.nextTransition > MAX_UINT64) {
898
+ await this.rejectExhaustedRekey("session transition exhausted", prepareSignal.signal, options.signal);
899
+ }
900
+ await this.freezeInboundResponders(false, prepareSignal.signal);
901
+ respondersFrozen = true;
902
+ const nextEpoch = currentEpoch + 1;
903
+ const currentRoots = this.rootForSend(currentEpoch);
904
+ const nextRoots = deriveEpochRoots(deriveNextEpoch(currentRoots.rekeyRoot, this.h3, this.sendDirection, nextEpoch));
905
+ this.sendRoots.set(nextEpoch, nextRoots);
906
+ this.preparingSendEpoch = nextEpoch;
907
+ const watermark = this.nextLogicalID > 2n ? this.nextLogicalID - 2n : 0n;
908
+ await this.waitOutboundFrontier(watermark, prepareSignal.signal);
909
+ // Do not consume a transition id until preparation has completed and
910
+ // the caller has not cancelled the operation.
911
+ throwIfAborted(prepareSignal.signal);
912
+ prepareSignal.cancel();
913
+ prepareDeadline.cancel();
914
+ completionDeadline = createSessionDeadline(this.deadlines, "rekey_completion");
915
+ // Once preparation has committed, caller cancellation only cancels the
916
+ // caller's wait (the outer rekey() race), while this operation continues
917
+ // under its bounded completion deadline.
918
+ completionSignal = combineSignals(completionDeadline.signal);
919
+ committed = true;
920
+ throwIfAborted(completionSignal.signal);
921
+ const transition = this.nextTransition;
922
+ this.nextTransition = transition === MAX_UINT64 ? 0n : transition + 1n;
923
+ const payload = concat(u64(transition), u32(nextEpoch), u64(watermark));
924
+ const active = [...this.streams.values()].filter((stream) => stream.canRekeySend());
925
+ const updates = active.map((stream) => stream.startSendRekey(transition, nextEpoch));
926
+ await Promise.all(updates.map(async (update) => await raceAbort(update.armed.promise, completionSignal.signal)));
927
+ const pending = {
928
+ payload,
929
+ epoch: nextEpoch,
930
+ acknowledged: deferred(),
931
+ committed: { value: false },
932
+ };
933
+ this.pendingSessionRekey = pending;
934
+ this.preparingSendEpoch = undefined;
935
+ await Promise.all([
936
+ this.sendControl(InnerTypeV3.SessionKeyUpdate, payload, completionSignal.signal),
937
+ raceAbort(pending.acknowledged.promise, completionSignal.signal),
938
+ ]);
939
+ await Promise.all(updates.map(async (update) => await raceAbort(update.done.promise, completionSignal.signal)));
940
+ if (this.pendingSessionRekey === pending)
941
+ this.pendingSessionRekey = undefined;
942
+ this.cleanupEpochRoots();
943
+ }
944
+ catch (error) {
945
+ const failure = asError(error);
946
+ if (committed) {
947
+ this.fail(failure);
948
+ if (failure instanceof SessionV3Error && failure.code === "closed")
949
+ throw failure;
950
+ const message = failure instanceof SessionV3Error && failure.code === "timeout"
951
+ ? "Flowersec v5 rekey completion deadline exceeded"
952
+ : "Flowersec v5 rekey completion failed";
953
+ throw new SessionV3Error("rekey_failed", message);
954
+ }
955
+ if (failure instanceof SessionV3Error && failure.code === "timeout") {
956
+ throw new SessionV3Error("rekey_failed", "Flowersec v5 rekey preparation deadline exceeded");
957
+ }
958
+ throw error;
959
+ }
960
+ finally {
961
+ prepareSignal.cancel();
962
+ prepareDeadline.cancel();
963
+ completionSignal?.cancel();
964
+ completionDeadline?.cancel();
965
+ this.openFrozen = false;
966
+ this.openGate.resolve();
967
+ if (respondersFrozen)
968
+ this.unfreezeInboundResponders(false);
969
+ this.preparingSendEpoch = undefined;
970
+ this.cleanupEpochRoots();
971
+ }
972
+ }
973
+ async rejectExhaustedRekey(message, signal, callerSignal) {
974
+ try {
975
+ await this.sendGoAway(5, signal);
976
+ }
977
+ catch (error) {
978
+ const failure = asError(error);
979
+ this.fail(failure);
980
+ if (failure instanceof SessionV3Error && failure.code === "aborted" && callerSignal?.aborted === true) {
981
+ throw abortedError();
982
+ }
983
+ if (failure instanceof SessionV3Error && failure.code === "timeout") {
984
+ throw new SessionV3Error("rekey_failed", "exhaustion GOAWAY preparation deadline exceeded");
985
+ }
986
+ }
987
+ throw new SessionV3Error("resource_exhausted", message);
988
+ }
989
+ async receiveSessionRekey(payload) {
990
+ this.validateSessionRekeySequence(payload);
991
+ const completionDeadline = createSessionDeadline(this.deadlines, "rekey_completion");
992
+ let respondersFrozen = false;
993
+ try {
994
+ await this.freezeInboundResponders(true, completionDeadline.signal);
995
+ respondersFrozen = true;
996
+ await this.receiveSessionRekeyBeforeDeadline(payload, completionDeadline.signal);
997
+ }
998
+ finally {
999
+ if (respondersFrozen)
1000
+ this.unfreezeInboundResponders(true);
1001
+ completionDeadline.cancel();
1002
+ }
1003
+ }
1004
+ async enterInboundResponder() {
1005
+ while (this.localResponderFrozen || this.peerResponderFrozen) {
1006
+ this.assertOpen();
1007
+ await this.responderChanged.promise;
1008
+ }
1009
+ this.assertOpen();
1010
+ this.activeInboundResponders++;
1011
+ this.notifyResponderChanged();
1012
+ }
1013
+ leaveInboundResponder() {
1014
+ if (this.activeInboundResponders === 0)
1015
+ return;
1016
+ this.activeInboundResponders--;
1017
+ this.notifyResponderChanged();
1018
+ }
1019
+ async freezeInboundResponders(peer, signal) {
1020
+ if (peer)
1021
+ this.peerResponderFrozen = true;
1022
+ else
1023
+ this.localResponderFrozen = true;
1024
+ this.notifyResponderChanged();
1025
+ try {
1026
+ while (this.activeInboundResponders !== 0) {
1027
+ await raceAbort(this.responderChanged.promise, signal);
1028
+ this.assertOpen();
1029
+ }
1030
+ }
1031
+ catch (error) {
1032
+ this.unfreezeInboundResponders(peer);
1033
+ throw error;
1034
+ }
1035
+ }
1036
+ unfreezeInboundResponders(peer) {
1037
+ if (peer)
1038
+ this.peerResponderFrozen = false;
1039
+ else
1040
+ this.localResponderFrozen = false;
1041
+ this.notifyResponderChanged();
1042
+ }
1043
+ notifyResponderChanged() {
1044
+ this.responderChanged.resolve();
1045
+ this.responderChanged = deferred();
1046
+ }
1047
+ async receiveSessionRekeyBeforeDeadline(payload, signal) {
1048
+ throwIfAborted(signal);
1049
+ this.validateSessionRekeySequence(payload);
1050
+ const transition = readU64(payload);
1051
+ const nextEpoch = readU32(payload, 8);
1052
+ const watermark = readU64At(payload, 12);
1053
+ if (watermark !== this.peerLedger.frontier)
1054
+ throw protocolError("SESSION_KEY_UPDATE watermark mismatch");
1055
+ this.pendingReceiveEpoch = nextEpoch;
1056
+ const current = this.rootForReceive(this.receiveEpoch);
1057
+ if (!this.receiveRoots.has(nextEpoch)) {
1058
+ this.receiveRoots.set(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.h3, this.receiveDirection, nextEpoch)));
1059
+ }
1060
+ const streams = [...this.streams.values()];
1061
+ await Promise.all(streams.map(async (stream) => await stream.waitReceiveRekey(transition, nextEpoch, signal)));
1062
+ const acknowledged = await raceAbort(this.sendControlResponse(InnerTypeV3.SessionKeyUpdateACK, payload, () => {
1063
+ this.receiveEpoch = nextEpoch;
1064
+ this.receiveTransition = transition;
1065
+ this.pendingReceiveEpoch = undefined;
1066
+ for (const stream of streams)
1067
+ stream.publishReceiveRekey(transition, nextEpoch);
1068
+ this.cleanupEpochRoots();
1069
+ }), signal);
1070
+ if (!acknowledged) {
1071
+ this.pendingReceiveEpoch = undefined;
1072
+ this.cleanupEpochRoots();
1073
+ return;
1074
+ }
1075
+ throwIfAborted(signal);
1076
+ }
1077
+ validateSessionRekeySequence(payload) {
1078
+ if (payload.length !== 20)
1079
+ throw protocolError("invalid SESSION_KEY_UPDATE");
1080
+ const transition = readU64(payload);
1081
+ const nextEpoch = readU32(payload, 8);
1082
+ if (this.receiveTransition >= MAX_UINT64 || this.receiveEpoch >= MAX_UINT32 ||
1083
+ transition !== this.receiveTransition + 1n || nextEpoch !== this.receiveEpoch + 1) {
1084
+ throw protocolError("invalid SESSION_KEY_UPDATE");
1085
+ }
1086
+ }
1087
+ receiveSessionRekeyACK(payload) {
1088
+ if (this.lastSessionRekeyACK !== undefined && bytesEqual(payload, this.lastSessionRekeyACK))
1089
+ return;
1090
+ const pending = this.pendingSessionRekey;
1091
+ if (pending === undefined) {
1092
+ throw protocolError("unexpected SESSION_KEY_UPDATE_ACK");
1093
+ }
1094
+ if (!bytesEqual(payload, pending.payload))
1095
+ throw protocolError("unexpected SESSION_KEY_UPDATE_ACK");
1096
+ if (pending.committed.value)
1097
+ return;
1098
+ pending.committed.value = true;
1099
+ this.sendEpoch = pending.epoch;
1100
+ wipeRecordKey(this.controlSendKey);
1101
+ this.controlSendKey = undefined;
1102
+ this.controlSendEpoch = pending.epoch;
1103
+ this.controlSendSequence = 0n;
1104
+ this.lastSessionRekeyACK = payload.slice();
1105
+ pending.acknowledged.resolve();
1106
+ this.cleanupEpochRoots();
1107
+ }
1108
+ async waitOpenGate(signal) {
1109
+ while (this.openFrozen)
1110
+ await raceAbort(this.openGate.promise, signal);
1111
+ }
1112
+ resolveOutboundOpen(id) {
1113
+ this.outboundLedger.validOpen(id);
1114
+ this.notifyOutboundFrontierChanged();
1115
+ }
1116
+ async waitOutboundFrontier(watermark, signal) {
1117
+ while (this.outboundLedger.frontier !== watermark) {
1118
+ if (this.outboundLedger.frontier > watermark)
1119
+ throw protocolError("outbound frontier exceeded watermark");
1120
+ await raceAbort(this.outboundFrontierChanged.promise, signal);
1121
+ }
1122
+ }
1123
+ async commitOutboundReset(id) {
1124
+ if (await this.sendControlCleanup(InnerTypeV3.StreamReset, idReason(id, 6))) {
1125
+ this.outboundLedger.localResetCommitted(id);
1126
+ this.notifyOutboundFrontierChanged();
1127
+ }
1128
+ }
1129
+ commitLocalReset(id) {
1130
+ if (this.isLocalLogicalID(id)) {
1131
+ this.outboundLedger.localResetCommitted(id);
1132
+ this.notifyOutboundFrontierChanged();
1133
+ return;
1134
+ }
1135
+ this.peerLedger.localResetCommitted(id);
1136
+ }
1137
+ notifyOutboundFrontierChanged() {
1138
+ this.outboundFrontierChanged.resolve();
1139
+ this.outboundFrontierChanged = deferred();
1140
+ }
1141
+ isLocalLogicalID(id) {
1142
+ return id > 0n && (this.role === 1 ? (id & 1n) === 1n : (id & 1n) === 0n);
1143
+ }
1144
+ localOpenHighWatermark() {
1145
+ const first = this.role === 1 ? 1n : 2n;
1146
+ return this.nextLogicalID === first ? 0n : this.nextLogicalID - 2n;
1147
+ }
1148
+ validGoAwayBoundary(lastAccepted) {
1149
+ if (lastAccepted === 0n)
1150
+ return true;
1151
+ return this.isLocalLogicalID(lastAccepted) && lastAccepted <= this.localOpenHighWatermark();
1152
+ }
1153
+ async sendGoAway(reason, signal) {
1154
+ if (!Number.isInteger(reason) || reason < 1 || reason > 0xffff)
1155
+ throw protocolError("invalid GOAWAY reason");
1156
+ if (this.sentGoAway) {
1157
+ if (this.sentGoAwayReason !== reason)
1158
+ throw protocolError("conflicting local GOAWAY reason");
1159
+ return;
1160
+ }
1161
+ const lastAccepted = this.peerLedger.frontier;
1162
+ this.sentGoAway = true;
1163
+ this.sentGoAwayLastAccepted = lastAccepted;
1164
+ this.sentGoAwayReason = reason;
1165
+ await this.sendControl(InnerTypeV3.GoAway, idReason(lastAccepted, reason), signal);
1166
+ }
1167
+ async receiveGoAway(payload) {
1168
+ const { id: lastAccepted, reason } = parseIDReason(payload);
1169
+ if (reason === 0 || !this.validGoAwayBoundary(lastAccepted))
1170
+ throw protocolError("invalid GOAWAY boundary");
1171
+ if (this.receivedGoAway) {
1172
+ if (this.receivedGoAwayLastAccepted !== lastAccepted || this.receivedGoAwayReason !== reason) {
1173
+ throw protocolError("conflicting GOAWAY");
1174
+ }
1175
+ return;
1176
+ }
1177
+ this.receivedGoAway = true;
1178
+ this.receivedGoAwayLastAccepted = lastAccepted;
1179
+ this.receivedGoAwayReason = reason;
1180
+ const excluded = [...this.streams.values()].filter((stream) => this.isLocalLogicalID(stream.id) && stream.id > lastAccepted);
1181
+ for (const stream of excluded) {
1182
+ this.trackBackground(this.localReset(stream, new SessionV3Error("going_away", "logical stream exceeds peer GOAWAY boundary")));
1183
+ }
1184
+ }
1185
+ trackBackground(task) {
1186
+ this.backgroundTasks.add(task);
1187
+ void task.catch((error) => {
1188
+ if (this.lifecycle !== "closed")
1189
+ this.fail(asError(error));
1190
+ }).finally(() => this.backgroundTasks.delete(task));
1191
+ }
1192
+ localOpeningAllowedAfterGoAway(id) {
1193
+ return !this.receivedGoAway || id <= this.receivedGoAwayLastAccepted;
1194
+ }
1195
+ acceptsPeerStreamAfterGoAway(id) {
1196
+ return !this.sentGoAway || id <= this.sentGoAwayLastAccepted;
1197
+ }
1198
+ cleanupEpochRoots() {
1199
+ const sendInUse = new Set([this.sendEpoch, this.controlSendEpoch]);
1200
+ const receiveInUse = new Set([this.receiveEpoch, this.controlReceiveEpoch]);
1201
+ if (this.preparingSendEpoch !== undefined)
1202
+ sendInUse.add(this.preparingSendEpoch);
1203
+ if (this.pendingReceiveEpoch !== undefined)
1204
+ receiveInUse.add(this.pendingReceiveEpoch);
1205
+ if (this.pendingSessionRekey !== undefined)
1206
+ sendInUse.add(this.pendingSessionRekey.epoch);
1207
+ for (const stream of this.streams.values()) {
1208
+ for (const epoch of stream.sendEpochsInUse())
1209
+ sendInUse.add(epoch);
1210
+ for (const epoch of stream.receiveEpochsInUse())
1211
+ receiveInUse.add(epoch);
1212
+ }
1213
+ this.cleanupRootMap(this.sendRoots, sendInUse);
1214
+ this.cleanupRootMap(this.receiveRoots, receiveInUse);
1215
+ }
1216
+ streamEpochStateChanged() {
1217
+ this.cleanupEpochRoots();
1218
+ }
1219
+ cleanupRootMap(roots, inUse) {
1220
+ for (const [epoch, value] of roots) {
1221
+ if (inUse.has(epoch))
1222
+ continue;
1223
+ wipeEpochRoots(value);
1224
+ roots.delete(epoch);
1225
+ }
1226
+ }
1227
+ wipeAllRoots() {
1228
+ wipeRecordKey(this.controlSendKey);
1229
+ wipeRecordKey(this.controlReceiveKey);
1230
+ this.controlSendKey = undefined;
1231
+ this.controlReceiveKey = undefined;
1232
+ for (const roots of this.sendRoots.values())
1233
+ wipeEpochRoots(roots);
1234
+ for (const roots of this.receiveRoots.values())
1235
+ wipeEpochRoots(roots);
1236
+ this.sendRoots.clear();
1237
+ this.receiveRoots.clear();
1238
+ }
1239
+ startIdleWatchdog() {
1240
+ this.idleWatchdogStarted = true;
1241
+ this.markAuthenticatedActivity();
1242
+ }
1243
+ markAuthenticatedActivity() {
1244
+ if (!this.idleWatchdogStarted || this.lifecycle !== "open")
1245
+ return;
1246
+ if (this.idleTimeoutMs === 0)
1247
+ return;
1248
+ this.idleDeadlineMs = this.runtime.monotonicMilliseconds() + this.idleTimeoutMs;
1249
+ if (this.idleTimerCancel !== undefined)
1250
+ return;
1251
+ this.scheduleIdleWatchdog();
1252
+ }
1253
+ scheduleIdleWatchdog() {
1254
+ const deadlineMs = this.idleDeadlineMs;
1255
+ if (deadlineMs === undefined || this.lifecycle !== "open")
1256
+ return;
1257
+ const remainingMs = Math.max(0, deadlineMs - this.runtime.monotonicMilliseconds());
1258
+ this.idleTimerCancel = scheduleLongTimeout(() => {
1259
+ this.idleTimerCancel = undefined;
1260
+ if (this.lifecycle !== "open" || this.idleDeadlineMs === undefined)
1261
+ return;
1262
+ if (this.runtime.monotonicMilliseconds() < this.idleDeadlineMs) {
1263
+ this.scheduleIdleWatchdog();
1264
+ return;
1265
+ }
1266
+ this.fail(new SessionV3Error("timeout", "Flowersec v5 session idle timeout exceeded"));
1267
+ }, remainingMs);
1268
+ }
1269
+ fail(error, abortCarrier = true) {
1270
+ if (this.lifecycle === "closed")
1271
+ return;
1272
+ if (this.path === "tunnel" && ((error instanceof CarrierError && error.code === "closed") ||
1273
+ (error instanceof SessionV3Error && error.code === "closed" && abortCarrier))) {
1274
+ error = protocolError("tunnel closed before the terminal exchange completed");
1275
+ }
1276
+ this.terminationController.abort(error);
1277
+ this.controlTerminalSealed = true;
1278
+ this.beginClosing(error);
1279
+ const pendingSessionRekey = this.pendingSessionRekey;
1280
+ this.pendingSessionRekey = undefined;
1281
+ pendingSessionRekey?.acknowledged.reject(error);
1282
+ const normalPeerCarrierClose = this.sessionCloseCommitted && error instanceof CarrierError && error.code === "closed";
1283
+ this.peerCloseOrTermination.resolve();
1284
+ this.terminalError = error;
1285
+ this.lifecycle = "closed";
1286
+ this.terminationState.resolve({ error, ...(this.peerCloseReceived && { peerCloseReceived: true }) });
1287
+ this.idleTimerCancel?.();
1288
+ this.idleTimerCancel = undefined;
1289
+ this.idleDeadlineMs = undefined;
1290
+ this.incoming.fail(error);
1291
+ this.outboundPermits.fail(error);
1292
+ this.inboundPermits.fail(error);
1293
+ this.notifyResponderChanged();
1294
+ for (const ping of this.pings.values())
1295
+ ping.reject(error);
1296
+ this.pings.clear();
1297
+ for (const stream of [...this.streams.values()])
1298
+ stream.peerReset(error);
1299
+ for (const released of this.releasedStreams.values()) {
1300
+ const stream = released.deref();
1301
+ if (stream !== undefined)
1302
+ this.releasedStreamCleanup.unregister(stream);
1303
+ }
1304
+ this.releasedStreams.clear();
1305
+ this.wipeAllRoots();
1306
+ this.h3.fill(0);
1307
+ if (abortCarrier && !normalPeerCarrierClose)
1308
+ this.carrier.abort({ code: 6, reason: "session terminated" });
1309
+ }
1310
+ assertOpen() {
1311
+ if (this.lifecycle === "open")
1312
+ return;
1313
+ if (this.terminalError !== undefined)
1314
+ throw this.terminalError;
1315
+ throw new SessionV3Error("closed", "Flowersec v5 session closed");
1316
+ }
1317
+ beginClosing(reason = new SessionV3Error("closed", "Flowersec v5 session closed")) {
1318
+ if (this.lifecycle === "opening" || this.lifecycle === "open") {
1319
+ this.lifecycle = "closing";
1320
+ this.rpc.close(reason);
1321
+ }
1322
+ }
1323
+ }
1324
+ class EncryptedStreamV3 {
1325
+ session;
1326
+ carrier;
1327
+ id;
1328
+ kind;
1329
+ sendEpoch;
1330
+ receiveEpoch;
1331
+ permitRelease;
1332
+ reader;
1333
+ opened = deferred();
1334
+ data = new ByteQueue(MAX_BUFFERED_STREAM_BYTES);
1335
+ terminalError;
1336
+ sendSequence = 0n;
1337
+ receiveSequence = 0n;
1338
+ priorACK;
1339
+ sendTail = Promise.resolve();
1340
+ localFIN = false;
1341
+ remoteFIN = false;
1342
+ pumpStarted = false;
1343
+ permitReleased = false;
1344
+ closeWriteTask;
1345
+ pendingFIN;
1346
+ pendingSendRekey;
1347
+ lastSendRekeyACK;
1348
+ receiveRekey;
1349
+ sendMaterials = new Map();
1350
+ receiveMaterials = new Map();
1351
+ receiveRekeyChanged = deferred();
1352
+ constructor(session, carrier, id, kind, sendEpoch, receiveEpoch, permitRelease, reader) {
1353
+ this.session = session;
1354
+ this.carrier = carrier;
1355
+ this.id = id;
1356
+ this.kind = kind;
1357
+ this.sendEpoch = sendEpoch;
1358
+ this.receiveEpoch = receiveEpoch;
1359
+ this.permitRelease = permitRelease;
1360
+ this.reader = reader ?? new ExactReader(carrier);
1361
+ }
1362
+ async read(options = {}) {
1363
+ if (this.terminalError !== undefined)
1364
+ throw this.terminalError;
1365
+ return await this.data.read(options.signal);
1366
+ }
1367
+ async write(payload, options = {}) {
1368
+ if (!(payload instanceof Uint8Array))
1369
+ throw new TypeError("stream write requires Uint8Array");
1370
+ throwIfAborted(options.signal);
1371
+ return await this.writeBytes(new Uint8Array(payload), options.signal, false);
1372
+ }
1373
+ /** The frame encoder owns these bytes until the sequenced write completes. */
1374
+ async writeRpcFrame(payload, signal) {
1375
+ return await this.writeBytes(payload, signal, true);
1376
+ }
1377
+ async writeBytes(payload, signal, rpcFrame) {
1378
+ if (payload.length === 0)
1379
+ return 0;
1380
+ throwIfAborted(signal);
1381
+ await raceAbort(this.opened.promise, signal);
1382
+ await this.waitSendRekey(signal);
1383
+ if (this.localFIN)
1384
+ throw new SessionV3Error("closed", "write after FIN");
1385
+ if (this.terminalError !== undefined)
1386
+ throw this.terminalError;
1387
+ await this.enqueueSend(async () => {
1388
+ throwIfAborted(signal);
1389
+ if (this.localFIN)
1390
+ throw new SessionV3Error("closed", "write after FIN");
1391
+ const writeSignal = rpcFrame ? this.session.terminationSignal() : signal;
1392
+ try {
1393
+ for (let offset = 0; offset < payload.length; offset += MAX_DATA_BYTES) {
1394
+ throwIfAborted(writeSignal);
1395
+ await this.session.sendStreamRecord(this, InnerTypeV3.Data, payload.subarray(offset, offset + MAX_DATA_BYTES), writeSignal);
1396
+ }
1397
+ }
1398
+ catch (error) {
1399
+ const normalized = asError(error);
1400
+ void this.session.localReset(this, normalized);
1401
+ throw normalized;
1402
+ }
1403
+ });
1404
+ return payload.length;
1405
+ }
1406
+ async closeWrite() {
1407
+ await this.opened.promise;
1408
+ await this.waitSendRekey();
1409
+ if (this.localFIN)
1410
+ return;
1411
+ if (this.terminalError !== undefined)
1412
+ throw this.terminalError;
1413
+ if (this.closeWriteTask === undefined) {
1414
+ const pending = new AbortController();
1415
+ this.pendingFIN = pending;
1416
+ this.closeWriteTask = this.enqueueSend(async () => {
1417
+ await this.session.sendStreamRecord(this, InnerTypeV3.FIN, new Uint8Array());
1418
+ throwIfAborted(pending.signal);
1419
+ await this.carrier.closeWrite();
1420
+ throwIfAborted(pending.signal);
1421
+ this.localFIN = true;
1422
+ this.releaseIfClean();
1423
+ }, pending.signal).catch((error) => {
1424
+ const normalized = this.terminalError ?? asError(error);
1425
+ void this.session.localReset(this, normalized);
1426
+ throw normalized;
1427
+ }).finally(() => { this.pendingFIN = undefined; });
1428
+ }
1429
+ await this.closeWriteTask;
1430
+ }
1431
+ async reset() {
1432
+ await this.session.localReset(this, new SessionV3Error("stream_reset", "logical stream reset"));
1433
+ }
1434
+ async close() {
1435
+ await this.reset();
1436
+ }
1437
+ send(type, payload, signal) {
1438
+ return this.enqueueSend(async () => await this.session.sendStreamRecord(this, type, payload, signal));
1439
+ }
1440
+ canRekeySend() {
1441
+ return this.terminalError === undefined && this.opened.settled && !this.localFIN;
1442
+ }
1443
+ hasRemoteFIN() {
1444
+ return this.remoteFIN;
1445
+ }
1446
+ startSendRekey(transition, epoch) {
1447
+ if (this.pendingSendRekey !== undefined)
1448
+ throw protocolError("overlapping stream rekey");
1449
+ const pending = { transition, epoch, armed: deferred(), done: deferred() };
1450
+ this.pendingSendRekey = pending;
1451
+ void this.enqueueSend(async () => {
1452
+ await this.session.sendStreamRecord(this, InnerTypeV3.StreamKeyUpdate, concat(u64(transition), u32(epoch)));
1453
+ pending.armed.resolve();
1454
+ }).catch((error) => {
1455
+ pending.armed.reject(error);
1456
+ pending.done.reject(error);
1457
+ void this.session.localReset(this, asError(error));
1458
+ });
1459
+ return pending;
1460
+ }
1461
+ async waitReceiveRekey(transition, epoch, signal) {
1462
+ throwIfAborted(signal);
1463
+ if (this.terminalError !== undefined || this.remoteFIN)
1464
+ return;
1465
+ while (true) {
1466
+ const pending = this.receiveRekey;
1467
+ if (pending !== undefined) {
1468
+ if (pending.transition !== transition || pending.epoch !== epoch)
1469
+ throw protocolError("stream rekey mismatch");
1470
+ await raceAbort(pending.acknowledged.promise, signal);
1471
+ return;
1472
+ }
1473
+ await raceAbort(this.receiveRekeyChanged.promise, signal);
1474
+ if (this.terminalError !== undefined || this.remoteFIN)
1475
+ return;
1476
+ }
1477
+ }
1478
+ publishReceiveRekey(transition, epoch) {
1479
+ if (this.receiveRekey?.transition === transition && this.receiveRekey.epoch === epoch) {
1480
+ this.receiveRekey = undefined;
1481
+ }
1482
+ }
1483
+ notifyReceiveRekeyChanged() {
1484
+ const changed = this.receiveRekeyChanged;
1485
+ this.receiveRekeyChanged = deferred();
1486
+ changed.resolve();
1487
+ }
1488
+ startPump() {
1489
+ if (this.pumpStarted)
1490
+ return;
1491
+ this.pumpStarted = true;
1492
+ this.session.trackBackground(this.pump());
1493
+ }
1494
+ markOpen() {
1495
+ this.opened.resolve();
1496
+ }
1497
+ markTerminal(error) {
1498
+ if (this.terminalError !== undefined)
1499
+ return false;
1500
+ this.terminalError = error;
1501
+ this.pendingFIN?.abort(error);
1502
+ const pendingSendRekey = this.pendingSendRekey;
1503
+ this.pendingSendRekey = undefined;
1504
+ pendingSendRekey?.armed.reject(error);
1505
+ pendingSendRekey?.done.reject(error);
1506
+ this.notifyReceiveRekeyChanged();
1507
+ this.opened.reject(error);
1508
+ this.data.fail(error);
1509
+ return true;
1510
+ }
1511
+ peerReset(error) {
1512
+ if (!this.markTerminal(error))
1513
+ return;
1514
+ this.carrier.abort(error);
1515
+ this.session.releaseStream(this);
1516
+ }
1517
+ carrierReset() {
1518
+ if (!this.markTerminal(new SessionV3Error("stream_reset", "logical stream reset by peer")))
1519
+ return;
1520
+ this.session.releaseStream(this);
1521
+ }
1522
+ abort(error = new SessionV3Error("closed", "logical stream aborted")) {
1523
+ this.peerReset(error);
1524
+ }
1525
+ releasePermit() {
1526
+ if (this.permitReleased)
1527
+ return;
1528
+ this.permitReleased = true;
1529
+ this.permitRelease();
1530
+ }
1531
+ sendMaterial(roots, h3, direction) {
1532
+ let material = this.sendMaterials.get(this.sendEpoch);
1533
+ if (material === undefined) {
1534
+ material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, this.sendEpoch);
1535
+ this.sendMaterials.set(this.sendEpoch, material);
1536
+ }
1537
+ return material;
1538
+ }
1539
+ receiveMaterial(roots, h3, direction, epoch) {
1540
+ let material = this.receiveMaterials.get(epoch);
1541
+ if (material === undefined) {
1542
+ material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, epoch);
1543
+ this.receiveMaterials.set(epoch, material);
1544
+ }
1545
+ return material;
1546
+ }
1547
+ pruneReceiveMaterials() {
1548
+ pruneRecordMaterials(this.receiveMaterials, new Set([this.receiveEpoch]));
1549
+ }
1550
+ wipeRecordMaterials() {
1551
+ pruneRecordMaterials(this.sendMaterials, new Set());
1552
+ pruneRecordMaterials(this.receiveMaterials, new Set());
1553
+ }
1554
+ transferReceiveMaterialsTo(destination) {
1555
+ if (destination.receiveMaterials.size !== 0)
1556
+ throw protocolError("receive material destination is not empty");
1557
+ for (const [epoch, material] of this.receiveMaterials)
1558
+ destination.receiveMaterials.set(epoch, material);
1559
+ this.receiveMaterials.clear();
1560
+ }
1561
+ async pump() {
1562
+ try {
1563
+ while (this.terminalError === undefined) {
1564
+ const record = await this.session.readStreamRecord(this);
1565
+ if (!this.opened.settled) {
1566
+ if (record.type === InnerTypeV3.OpenACK) {
1567
+ const got = decodeOpenACKV3(record.payload);
1568
+ if (!bytesEqual(got, this.openedHash()))
1569
+ throw protocolError("OPEN ACK hash mismatch");
1570
+ this.session.resolveOutboundOpen(this.id);
1571
+ this.markOpen();
1572
+ continue;
1573
+ }
1574
+ if (record.type === InnerTypeV3.OpenReject) {
1575
+ const reject = decodeOpenRejectV3(record.payload);
1576
+ if (!bytesEqual(reject.openHash, this.openedHash()))
1577
+ throw protocolError("OPEN REJECT hash mismatch");
1578
+ this.session.resolveOutboundOpen(this.id);
1579
+ const error = new SessionV3Error("open_rejected", `logical stream rejected (${reject.reason})`);
1580
+ this.markTerminal(error);
1581
+ this.session.releaseStream(this);
1582
+ await this.carrier.closeWrite().catch(() => undefined);
1583
+ return;
1584
+ }
1585
+ throw protocolError("expected OPEN ACK or REJECT");
1586
+ }
1587
+ switch (record.type) {
1588
+ case InnerTypeV3.Data:
1589
+ if (this.remoteFIN)
1590
+ throw protocolError("DATA after FIN");
1591
+ await this.data.waitForCapacity(record.payload.length);
1592
+ this.data.push(record.payload);
1593
+ break;
1594
+ case InnerTypeV3.FIN:
1595
+ if (this.remoteFIN)
1596
+ throw protocolError("duplicate FIN");
1597
+ await this.reader.readEOF();
1598
+ this.remoteFIN = true;
1599
+ this.data.close();
1600
+ this.releaseIfClean();
1601
+ return;
1602
+ case InnerTypeV3.StreamKeyUpdate:
1603
+ await this.receiveStreamKeyUpdate(record.payload, record.header);
1604
+ break;
1605
+ case InnerTypeV3.StreamKeyUpdateACK:
1606
+ this.receiveStreamKeyUpdateACK(record.payload);
1607
+ break;
1608
+ default:
1609
+ throw protocolError(`unexpected stream type ${record.type}`);
1610
+ }
1611
+ }
1612
+ }
1613
+ catch (error) {
1614
+ const normalized = asError(error);
1615
+ if (normalized instanceof CarrierError && normalized.code === "reset") {
1616
+ this.carrierReset();
1617
+ return;
1618
+ }
1619
+ await this.session.localReset(this, normalized);
1620
+ }
1621
+ }
1622
+ openedHash() {
1623
+ const value = this.openHash;
1624
+ if (value === undefined)
1625
+ throw protocolError("missing OPEN hash");
1626
+ return value;
1627
+ }
1628
+ setOpenHash(value) {
1629
+ this.openHash = value.slice();
1630
+ }
1631
+ enqueueSend(operation, signal) {
1632
+ const queued = this.sendTail.then(async () => {
1633
+ if (this.terminalError !== undefined)
1634
+ throw this.terminalError;
1635
+ await operation();
1636
+ });
1637
+ const task = signal === undefined ? queued : raceAbort(queued, signal);
1638
+ this.sendTail = task.catch(() => undefined);
1639
+ return task;
1640
+ }
1641
+ async waitSendRekey(signal) {
1642
+ while (this.pendingSendRekey !== undefined) {
1643
+ await raceAbort(this.pendingSendRekey.done.promise, signal);
1644
+ }
1645
+ }
1646
+ async receiveStreamKeyUpdate(payload, header) {
1647
+ if (payload.length !== 12 || this.receiveRekey !== undefined)
1648
+ throw protocolError("invalid STREAM_KEY_UPDATE");
1649
+ const transition = readU64(payload);
1650
+ const nextEpoch = readU32(payload, 8);
1651
+ if (transition === 0n || nextEpoch !== this.receiveEpoch + 1)
1652
+ throw protocolError("invalid stream rekey transition");
1653
+ const current = this.session.rootForReceive(this.receiveEpoch);
1654
+ if (!this.session.hasReceiveRoots(nextEpoch)) {
1655
+ this.session.installReceiveRoots(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.session.transcriptHash(), this.session.receiveDirectionValue(), nextEpoch)));
1656
+ }
1657
+ if (this.pendingSendRekey?.transition === transition && this.pendingSendRekey.epoch === nextEpoch) {
1658
+ this.priorACK = { epoch: header.epoch, sequence: this.receiveSequence };
1659
+ }
1660
+ this.receiveEpoch = nextEpoch;
1661
+ this.receiveSequence = 0n;
1662
+ pruneRecordMaterials(this.receiveMaterials, new Set(this.priorACK === undefined ? [nextEpoch] : [header.epoch, nextEpoch]));
1663
+ const pending = { transition, epoch: nextEpoch, acknowledged: deferred() };
1664
+ this.receiveRekey = pending;
1665
+ this.notifyReceiveRekeyChanged();
1666
+ await this.send(InnerTypeV3.StreamKeyUpdateACK, encodeStreamKeyUpdateACKV3({
1667
+ logicalStreamID: this.id,
1668
+ transition,
1669
+ epoch: nextEpoch,
1670
+ }), this.session.terminationSignal());
1671
+ pending.acknowledged.resolve();
1672
+ }
1673
+ receiveStreamKeyUpdateACK(payload) {
1674
+ const decoded = decodeStreamKeyUpdateACKV3(payload);
1675
+ if (decoded.logicalStreamID !== this.id)
1676
+ throw protocolError("invalid STREAM_KEY_UPDATE_ACK");
1677
+ const { transition, epoch } = decoded;
1678
+ if (this.lastSendRekeyACK?.transition === transition && this.lastSendRekeyACK.epoch === epoch)
1679
+ return;
1680
+ const pending = this.pendingSendRekey;
1681
+ if (pending === undefined) {
1682
+ throw protocolError("unexpected STREAM_KEY_UPDATE_ACK");
1683
+ }
1684
+ if (pending.transition !== transition || pending.epoch !== epoch)
1685
+ throw protocolError("unexpected STREAM_KEY_UPDATE_ACK");
1686
+ this.sendEpoch = epoch;
1687
+ this.sendSequence = 0n;
1688
+ pruneRecordMaterials(this.sendMaterials, new Set([epoch]));
1689
+ this.pendingSendRekey = undefined;
1690
+ this.lastSendRekeyACK = { transition, epoch };
1691
+ pending.done.resolve();
1692
+ this.session.streamEpochStateChanged();
1693
+ }
1694
+ sendEpochsInUse() {
1695
+ return this.pendingSendRekey === undefined ? [this.sendEpoch] : [this.sendEpoch, this.pendingSendRekey.epoch];
1696
+ }
1697
+ receiveEpochsInUse() {
1698
+ const epochs = new Set([this.receiveEpoch]);
1699
+ if (this.priorACK !== undefined)
1700
+ epochs.add(this.priorACK.epoch);
1701
+ if (this.receiveRekey !== undefined)
1702
+ epochs.add(this.receiveRekey.epoch);
1703
+ return [...epochs];
1704
+ }
1705
+ releaseIfClean() {
1706
+ if (!this.localFIN || !this.remoteFIN || this.terminalError !== undefined)
1707
+ return;
1708
+ this.session.releaseStream(this);
1709
+ }
1710
+ }
1711
+ async function clientHandshake(control, reader, config, offeredFeatures, signal) {
1712
+ const key = generateEphemeralKeyV3(config.suite, (length) => config.runtime.entropy(length));
1713
+ const controlPreface = encodeControlPrefaceV3();
1714
+ const initRaw = encodeClientInitV3({
1715
+ profile: FLOWERSEC_V3_PROFILE,
1716
+ channelID: config.channelID,
1717
+ sessionContractHash: config.sessionContractHash,
1718
+ clientRole: 1,
1719
+ suite: config.suite,
1720
+ clientEphemeralPublic: key.publicKey,
1721
+ nonceC: sessionRandomBytes(config, 32),
1722
+ selectedFeatures: offeredFeatures,
1723
+ maxInboundStreams: config.maxInboundStreams,
1724
+ clientAdmissionBinding: config.localAdmissionBinding,
1725
+ clientEndpointInstanceID: config.localEndpointInstanceID,
1726
+ });
1727
+ await writeAll(control, controlPreface, signal);
1728
+ await writeAll(control, initRaw, signal);
1729
+ const serverRaw = await readHandshakeFrame(reader, signal);
1730
+ const server = decodeServerFinishedV3(serverRaw, config.suite);
1731
+ validateServerFinishedV3(server, expectations(config, false));
1732
+ if ((server.core.selectedFeatures & ~offeredFeatures) !== 0) {
1733
+ throw protocolError("server selected an unoffered feature");
1734
+ }
1735
+ const shared = computeSharedSecretV3(config.suite, key.privateKey, server.core.serverEphemeralPublic);
1736
+ const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1737
+ const h0 = computeHandshakeH0V3(controlPreface, initRaw);
1738
+ const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(server.core, config.suite));
1739
+ if (!bytesEqual(server.serverConfirm, computeServerConfirmV3(handshakePRK, h1))) {
1740
+ throw protocolError("server confirm mismatch");
1741
+ }
1742
+ const clientCore = encodeClientFinishedCoreV3(server.core.handshakeID);
1743
+ const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore);
1744
+ const clientRaw = encodeClientFinishedV3({
1745
+ handshakeID: server.core.handshakeID,
1746
+ clientConfirm: computeClientConfirmV3(handshakePRK, h2),
1747
+ });
1748
+ await writeAll(control, clientRaw, signal);
1749
+ const h3 = computeHandshakeH3V3(h2, clientRaw);
1750
+ return {
1751
+ h3,
1752
+ sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1753
+ selectedFeatures: server.core.selectedFeatures,
1754
+ };
1755
+ }
1756
+ async function serverHandshake(control, reader, config, localFeatures, signal) {
1757
+ const controlPreface = await reader.readExactly(16, signal);
1758
+ parseControlPrefaceV3(controlPreface);
1759
+ const clientRaw = await readHandshakeFrame(reader, signal);
1760
+ const client = decodeClientInitV3(clientRaw);
1761
+ validateClientInitV3(client, expectations(config, true));
1762
+ const key = generateEphemeralKeyV3(config.suite, (length) => config.runtime.entropy(length));
1763
+ const shared = computeSharedSecretV3(config.suite, key.privateKey, client.clientEphemeralPublic);
1764
+ const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1765
+ const core = {
1766
+ suite: config.suite,
1767
+ handshakeID: sessionRandomBytes(config, 16),
1768
+ serverEphemeralPublic: key.publicKey,
1769
+ nonceS: sessionRandomBytes(config, 32),
1770
+ sessionContractHash: config.sessionContractHash,
1771
+ selectedFeatures: client.selectedFeatures & localFeatures,
1772
+ maxInboundStreams: config.maxInboundStreams,
1773
+ serverAdmissionBinding: config.localAdmissionBinding,
1774
+ serverEndpointInstanceID: config.localEndpointInstanceID,
1775
+ };
1776
+ const h0 = computeHandshakeH0V3(controlPreface, clientRaw);
1777
+ const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(core, config.suite));
1778
+ const serverRaw = encodeServerFinishedV3({
1779
+ core,
1780
+ serverConfirm: computeServerConfirmV3(handshakePRK, h1),
1781
+ }, config.suite);
1782
+ await writeAll(control, serverRaw, signal);
1783
+ const clientFinishedRaw = await readHandshakeFrame(reader, signal);
1784
+ const clientFinished = decodeClientFinishedV3(clientFinishedRaw);
1785
+ if (!bytesEqual(clientFinished.handshakeID, core.handshakeID))
1786
+ throw protocolError("handshake ID mismatch");
1787
+ const clientCore = encodeClientFinishedCoreV3(clientFinished.handshakeID);
1788
+ const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore);
1789
+ if (!bytesEqual(clientFinished.clientConfirm, computeClientConfirmV3(handshakePRK, h2))) {
1790
+ throw protocolError("client confirm mismatch");
1791
+ }
1792
+ const h3 = computeHandshakeH3V3(h2, clientFinishedRaw);
1793
+ return {
1794
+ h3,
1795
+ sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1796
+ selectedFeatures: core.selectedFeatures,
1797
+ };
1798
+ }
1799
+ function expectations(config, peerIsClient) {
1800
+ return {
1801
+ path: config.path,
1802
+ channelID: peerIsClient ? config.channelID : "",
1803
+ sessionContractHash: config.sessionContractHash,
1804
+ suite: config.suite,
1805
+ maxInboundStreams: config.maxInboundStreams,
1806
+ admissionBinding: config.peerAdmissionBinding,
1807
+ expectedEndpointInstanceID: config.expectedPeerEndpointInstanceID,
1808
+ };
1809
+ }
1810
+ async function readHandshakeFrame(reader, signal) {
1811
+ const header = await reader.readExactly(12, signal);
1812
+ const length = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8, false);
1813
+ if (length < 1 || length > 8_192)
1814
+ throw protocolError("invalid handshake payload length");
1815
+ const raw = concat(header, await reader.readExactly(length, signal));
1816
+ decodeHandshakeFrameV3(raw);
1817
+ return raw;
1818
+ }
1819
+ class ExactReader {
1820
+ stream;
1821
+ remaining;
1822
+ constructor(stream) {
1823
+ this.stream = stream;
1824
+ }
1825
+ async readExactly(length, signal, borrowWholeCiphertext = false) {
1826
+ let out;
1827
+ let written = 0;
1828
+ while (written < length) {
1829
+ const chunk = this.remaining ?? await this.stream.read(signal === undefined ? {} : { signal });
1830
+ if (chunk === null)
1831
+ throw new SessionV3Error("closed", "unexpected carrier EOF");
1832
+ if (chunk.length === 0)
1833
+ continue;
1834
+ if (borrowWholeCiphertext && written === 0 && chunk.length === length && chunk.buffer instanceof ArrayBuffer) {
1835
+ this.remaining = undefined;
1836
+ return chunk;
1837
+ }
1838
+ const take = Math.min(length - written, chunk.length);
1839
+ out ??= new Uint8Array(length);
1840
+ out.set(chunk.subarray(0, take), written);
1841
+ written += take;
1842
+ this.remaining = take === chunk.length ? undefined : chunk.subarray(take);
1843
+ }
1844
+ return out ?? new Uint8Array(0);
1845
+ }
1846
+ async readEOF(signal) {
1847
+ if (this.remaining !== undefined)
1848
+ throw protocolError("trailing carrier bytes after logical FIN");
1849
+ while (true) {
1850
+ const chunk = await this.stream.read(signal === undefined ? {} : { signal });
1851
+ if (chunk === null)
1852
+ return;
1853
+ if (chunk.length !== 0)
1854
+ throw protocolError("trailing carrier bytes after logical FIN");
1855
+ }
1856
+ }
1857
+ }
1858
+ class ByteQueue {
1859
+ limit;
1860
+ chunks = [];
1861
+ head = 0;
1862
+ bytes = 0;
1863
+ closed = false;
1864
+ error;
1865
+ waiters = new Set();
1866
+ capacityWaiters = new Set();
1867
+ constructor(limit) {
1868
+ this.limit = limit;
1869
+ }
1870
+ push(chunk) {
1871
+ if (this.closed || this.error !== undefined)
1872
+ throw protocolError("DATA after terminal stream state");
1873
+ if (this.bytes + chunk.length > this.limit)
1874
+ throw new SessionV3Error("resource_exhausted", "stream receive buffer exceeded");
1875
+ this.chunks.push(chunk);
1876
+ this.bytes += chunk.length;
1877
+ this.wake();
1878
+ }
1879
+ close() {
1880
+ this.closed = true;
1881
+ this.wake();
1882
+ }
1883
+ fail(error) {
1884
+ if (this.error !== undefined)
1885
+ return;
1886
+ this.error = error;
1887
+ this.chunks.length = 0;
1888
+ this.head = 0;
1889
+ this.bytes = 0;
1890
+ this.wake(error);
1891
+ this.wakeCapacity(error);
1892
+ }
1893
+ async waitForCapacity(required) {
1894
+ if (!Number.isInteger(required) || required < 0 || required > this.limit) {
1895
+ throw new RangeError("invalid stream receive capacity request");
1896
+ }
1897
+ while (this.bytes + required > this.limit) {
1898
+ if (this.error !== undefined)
1899
+ throw this.error;
1900
+ if (this.closed)
1901
+ return;
1902
+ const waiter = deferred();
1903
+ this.capacityWaiters.add(waiter);
1904
+ try {
1905
+ await waiter.promise;
1906
+ }
1907
+ finally {
1908
+ this.capacityWaiters.delete(waiter);
1909
+ }
1910
+ }
1911
+ }
1912
+ async read(signal) {
1913
+ while (true) {
1914
+ if (this.error !== undefined)
1915
+ throw this.error;
1916
+ if (this.head < this.chunks.length) {
1917
+ const chunk = this.chunks[this.head];
1918
+ this.chunks[this.head++] = undefined;
1919
+ this.bytes -= chunk.length;
1920
+ this.wakeCapacity();
1921
+ if (this.head === this.chunks.length) {
1922
+ this.chunks.length = 0;
1923
+ this.head = 0;
1924
+ }
1925
+ else if (this.head > 1_024 && this.head * 2 > this.chunks.length) {
1926
+ this.chunks.splice(0, this.head);
1927
+ this.head = 0;
1928
+ }
1929
+ return chunk;
1930
+ }
1931
+ if (this.closed)
1932
+ return null;
1933
+ const waiter = deferred();
1934
+ this.waiters.add(waiter);
1935
+ try {
1936
+ await raceAbort(waiter.promise, signal);
1937
+ }
1938
+ finally {
1939
+ this.waiters.delete(waiter);
1940
+ }
1941
+ }
1942
+ }
1943
+ wake(error) {
1944
+ for (const waiter of [...this.waiters])
1945
+ error === undefined ? waiter.resolve() : waiter.reject(error);
1946
+ this.waiters.clear();
1947
+ }
1948
+ wakeCapacity(error) {
1949
+ for (const waiter of [...this.capacityWaiters])
1950
+ error === undefined ? waiter.resolve() : waiter.reject(error);
1951
+ this.capacityWaiters.clear();
1952
+ }
1953
+ }
1954
+ class AsyncSemaphore {
1955
+ available;
1956
+ waiters = new Set();
1957
+ error;
1958
+ constructor(count) { this.available = count; }
1959
+ async acquire(signal) {
1960
+ if (this.error !== undefined)
1961
+ throw this.error;
1962
+ if (this.available > 0) {
1963
+ this.available--;
1964
+ return this.releaser();
1965
+ }
1966
+ return await new Promise((resolve, reject) => {
1967
+ let settled = false;
1968
+ const cleanup = () => {
1969
+ this.waiters.delete(waiter);
1970
+ signal?.removeEventListener("abort", abort);
1971
+ };
1972
+ const waiter = {
1973
+ deliver: (release) => {
1974
+ if (settled) {
1975
+ release();
1976
+ return false;
1977
+ }
1978
+ settled = true;
1979
+ cleanup();
1980
+ resolve(release);
1981
+ return true;
1982
+ },
1983
+ fail: (error) => {
1984
+ if (settled)
1985
+ return;
1986
+ settled = true;
1987
+ cleanup();
1988
+ reject(error);
1989
+ },
1990
+ };
1991
+ const abort = () => waiter.fail(abortReason(signal));
1992
+ this.waiters.add(waiter);
1993
+ signal?.addEventListener("abort", abort, { once: true });
1994
+ if (signal?.aborted === true)
1995
+ abort();
1996
+ });
1997
+ }
1998
+ tryAcquire() {
1999
+ if (this.error !== undefined || this.available === 0)
2000
+ return undefined;
2001
+ this.available--;
2002
+ return this.releaser();
2003
+ }
2004
+ fail(error) {
2005
+ this.error = error;
2006
+ for (const waiter of [...this.waiters])
2007
+ waiter.fail(error);
2008
+ }
2009
+ releaser() {
2010
+ let released = false;
2011
+ return () => {
2012
+ if (released)
2013
+ return;
2014
+ released = true;
2015
+ const waiter = this.waiters.values().next().value;
2016
+ if (waiter === undefined)
2017
+ this.available++;
2018
+ else
2019
+ waiter.deliver(this.releaser());
2020
+ };
2021
+ }
2022
+ }
2023
+ class AsyncQueue {
2024
+ values = [];
2025
+ waiters = new Set();
2026
+ error;
2027
+ push(value) {
2028
+ if (this.error !== undefined)
2029
+ return;
2030
+ const waiter = this.waiters.values().next().value;
2031
+ if (waiter === undefined || !waiter.deliver(value))
2032
+ this.values.push(value);
2033
+ }
2034
+ async shift(signal) {
2035
+ if (this.error !== undefined)
2036
+ throw this.error;
2037
+ const value = this.values.shift();
2038
+ if (value !== undefined)
2039
+ return value;
2040
+ return await new Promise((resolve, reject) => {
2041
+ let settled = false;
2042
+ const cleanup = () => {
2043
+ this.waiters.delete(waiter);
2044
+ signal?.removeEventListener("abort", abort);
2045
+ };
2046
+ const waiter = {
2047
+ deliver: (next) => {
2048
+ if (settled)
2049
+ return false;
2050
+ settled = true;
2051
+ cleanup();
2052
+ resolve(next);
2053
+ return true;
2054
+ },
2055
+ fail: (error) => {
2056
+ if (settled)
2057
+ return;
2058
+ settled = true;
2059
+ cleanup();
2060
+ reject(error);
2061
+ },
2062
+ };
2063
+ const abort = () => waiter.fail(abortReason(signal));
2064
+ this.waiters.add(waiter);
2065
+ signal?.addEventListener("abort", abort, { once: true });
2066
+ if (signal?.aborted === true)
2067
+ abort();
2068
+ });
2069
+ }
2070
+ fail(error) {
2071
+ this.error = error;
2072
+ this.values.length = 0;
2073
+ for (const waiter of [...this.waiters])
2074
+ waiter.fail(error);
2075
+ }
2076
+ }
2077
+ function deferred() {
2078
+ let resolvePromise;
2079
+ let rejectPromise;
2080
+ let settled = false;
2081
+ const promise = new Promise((resolve, reject) => {
2082
+ resolvePromise = resolve;
2083
+ rejectPromise = reject;
2084
+ });
2085
+ return {
2086
+ promise,
2087
+ resolve: (value) => { if (!settled) {
2088
+ settled = true;
2089
+ resolvePromise(value);
2090
+ } },
2091
+ reject: (reason) => { if (!settled) {
2092
+ settled = true;
2093
+ rejectPromise(reason);
2094
+ } },
2095
+ get settled() { return settled; },
2096
+ };
2097
+ }
2098
+ function validateConfig(carrier, config) {
2099
+ if (config.runtime === undefined ||
2100
+ typeof config.runtime.entropy !== "function" ||
2101
+ typeof config.runtime.monotonicMilliseconds !== "function") {
2102
+ throw new SessionV3Error("handshake", "session protocol runtime is required");
2103
+ }
2104
+ if (carrier.path !== config.path || (config.role !== "client" && config.role !== "server")) {
2105
+ throw new SessionV3Error("handshake", "invalid session carrier/config binding");
2106
+ }
2107
+ if (!Number.isInteger(config.maxInboundStreams) || config.maxInboundStreams < 1 || config.maxInboundStreams > 128) {
2108
+ throw new SessionV3Error("handshake", "invalid maxInboundStreams");
2109
+ }
2110
+ if (carrier.inboundBidirectionalStreamCapacity !== config.maxInboundStreams + 2) {
2111
+ throw new SessionV3Error("handshake", "carrier inbound bidirectional stream capacity mismatch");
2112
+ }
2113
+ sessionIdleTimeoutMs(config);
2114
+ sessionCloseTimeoutMs(config);
2115
+ for (const [name, value] of [
2116
+ ["session contract hash", config.sessionContractHash],
2117
+ ["PSK", config.psk],
2118
+ ["local admission binding", config.localAdmissionBinding],
2119
+ ["peer admission binding", config.peerAdmissionBinding],
2120
+ ]) {
2121
+ if (value.length !== 32)
2122
+ throw new SessionV3Error("handshake", `${name} must be 32 bytes`);
2123
+ }
2124
+ if (config.path === "direct") {
2125
+ if (config.localEndpointInstanceID !== "" || config.expectedPeerEndpointInstanceID !== "") {
2126
+ throw new SessionV3Error("handshake", "direct session endpoint IDs must be empty");
2127
+ }
2128
+ }
2129
+ else if (config.localEndpointInstanceID === "" || config.expectedPeerEndpointInstanceID === "") {
2130
+ throw new SessionV3Error("handshake", "tunnel session endpoint IDs are required");
2131
+ }
2132
+ }
2133
+ function supportedFeatures(datagrams) {
2134
+ return datagrams !== undefined && datagrams.maxDatagramSize >= UNRELIABLE_MESSAGE_WIRE_BYTES_V3
2135
+ ? UNRELIABLE_MESSAGES_FEATURE_V3
2136
+ : 0;
2137
+ }
2138
+ function requireUnreliableDatagrams(carrier) {
2139
+ const datagrams = carrier.unreliableDatagrams;
2140
+ if (datagrams === undefined || datagrams.maxDatagramSize < UNRELIABLE_MESSAGE_WIRE_BYTES_V3) {
2141
+ throw new SessionV3Error("handshake", "negotiated unreliable messages require native DATAGRAM support");
2142
+ }
2143
+ return datagrams;
2144
+ }
2145
+ function decodeMetadata(raw) {
2146
+ return JSON.parse(decoder.decode(raw));
2147
+ }
2148
+ async function writeAll(stream, value, signal) {
2149
+ let offset = 0;
2150
+ while (offset < value.length) {
2151
+ throwIfAborted(signal);
2152
+ const written = await stream.write(value.subarray(offset), signal === undefined ? {} : { signal });
2153
+ if (written < 1 || written > value.length - offset)
2154
+ throw protocolError("short carrier write");
2155
+ offset += written;
2156
+ }
2157
+ }
2158
+ async function settleWithin(promise, timeoutMs) {
2159
+ return await new Promise((resolve) => {
2160
+ const timer = setTimeout(() => resolve(false), timeoutMs);
2161
+ void promise.then(() => { clearTimeout(timer); resolve(true); }, () => { clearTimeout(timer); resolve(true); });
2162
+ });
2163
+ }
2164
+ async function resolveWithin(promise, timeoutMs) {
2165
+ return await new Promise((resolve) => {
2166
+ const timer = setTimeout(() => resolve(false), timeoutMs);
2167
+ void promise.then(() => { clearTimeout(timer); resolve(true); }, () => { clearTimeout(timer); resolve(false); });
2168
+ });
2169
+ }
2170
+ function sessionIdleTimeoutMs(config) {
2171
+ const timeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
2172
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) {
2173
+ throw new RangeError("idleTimeoutMs must be a non-negative integer");
2174
+ }
2175
+ return timeoutMs;
2176
+ }
2177
+ function sessionCloseTimeoutMs(config) {
2178
+ const timeoutMs = config.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
2179
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) {
2180
+ throw new RangeError("closeTimeoutMs must be an integer from 1 to 60000");
2181
+ }
2182
+ return timeoutMs;
2183
+ }
2184
+ function sessionRandomBytes(config, length) {
2185
+ const output = config.runtime.entropy(length);
2186
+ if (!(output instanceof Uint8Array) || output.length !== length) {
2187
+ throw new SessionV3Error("handshake", `session entropy must return exactly ${length} bytes`);
2188
+ }
2189
+ return output.slice();
2190
+ }
2191
+ function idReason(id, reason) {
2192
+ return concat(u64(id), Uint8Array.of((reason >>> 8) & 0xff, reason & 0xff));
2193
+ }
2194
+ function parseIDReason(payload) {
2195
+ if (payload.length !== 10)
2196
+ throw protocolError("invalid ID/reason payload");
2197
+ return { id: readU64(payload), reason: readU16(payload, 8) };
2198
+ }
2199
+ function u64(value) {
2200
+ if (typeof value !== "bigint" || value < 0n || value > MAX_UINT64) {
2201
+ throw new RangeError("uint64 value is out of range");
2202
+ }
2203
+ const out = new Uint8Array(8);
2204
+ new DataView(out.buffer).setBigUint64(0, value, false);
2205
+ return out;
2206
+ }
2207
+ function u32(value) {
2208
+ if (!Number.isInteger(value) || value < 0 || value > MAX_UINT32) {
2209
+ throw new RangeError("uint32 value is out of range");
2210
+ }
2211
+ const out = new Uint8Array(4);
2212
+ new DataView(out.buffer).setUint32(0, value, false);
2213
+ return out;
2214
+ }
2215
+ function readU64(value) {
2216
+ if (value.length < 8)
2217
+ throw protocolError("truncated uint64");
2218
+ return new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64(0, false);
2219
+ }
2220
+ function readU64At(value, offset) {
2221
+ if (value.length < offset + 8)
2222
+ throw protocolError("truncated uint64");
2223
+ return new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64(offset, false);
2224
+ }
2225
+ function readU32(value, offset) {
2226
+ if (value.length < offset + 4)
2227
+ throw protocolError("truncated uint32");
2228
+ return new DataView(value.buffer, value.byteOffset, value.byteLength).getUint32(offset, false);
2229
+ }
2230
+ function readU16(value, offset) {
2231
+ if (value.length < offset + 2)
2232
+ throw protocolError("truncated uint16");
2233
+ return new DataView(value.buffer, value.byteOffset, value.byteLength).getUint16(offset, false);
2234
+ }
2235
+ function concat(...values) {
2236
+ const out = new Uint8Array(values.reduce((sum, value) => sum + value.length, 0));
2237
+ let offset = 0;
2238
+ for (const value of values) {
2239
+ out.set(value, offset);
2240
+ offset += value.length;
2241
+ }
2242
+ return out;
2243
+ }
2244
+ function bytesEqual(left, right) {
2245
+ if (left.length !== right.length)
2246
+ return false;
2247
+ let difference = 0;
2248
+ for (let index = 0; index < left.length; index++)
2249
+ difference |= left[index] ^ right[index];
2250
+ return difference === 0;
2251
+ }
2252
+ function deriveControlRecordKey(roots, h3, direction, epoch) {
2253
+ const { secret, recordKey, noncePrefix } = deriveControlMaterial(roots.controlRoot, h3, direction, epoch);
2254
+ secret.fill(0);
2255
+ return { recordKey, noncePrefix };
2256
+ }
2257
+ function wipeRecordKey(material) {
2258
+ material?.recordKey.fill(0);
2259
+ material?.noncePrefix.fill(0);
2260
+ }
2261
+ function wipeEpochRoots(roots) {
2262
+ roots.epochSecret.fill(0);
2263
+ roots.controlRoot.fill(0);
2264
+ roots.streamRoot.fill(0);
2265
+ roots.setupRoot.fill(0);
2266
+ roots.rekeyRoot.fill(0);
2267
+ }
2268
+ function pruneRecordMaterials(materials, retained) {
2269
+ for (const [epoch, material] of materials) {
2270
+ if (retained.has(epoch))
2271
+ continue;
2272
+ material.secret.fill(0);
2273
+ wipeRecordKey(material);
2274
+ materials.delete(epoch);
2275
+ }
2276
+ }
2277
+ async function raceAbort(promise, signal) {
2278
+ if (signal === undefined)
2279
+ return await promise;
2280
+ throwIfAborted(signal);
2281
+ return await new Promise((resolve, reject) => {
2282
+ const abort = () => reject(abortReason(signal));
2283
+ signal.addEventListener("abort", abort, { once: true });
2284
+ void promise.then((value) => { signal.removeEventListener("abort", abort); resolve(value); }, (error) => { signal.removeEventListener("abort", abort); reject(error); });
2285
+ });
2286
+ }
2287
+ function throwIfAborted(signal) {
2288
+ if (signal?.aborted === true)
2289
+ throw abortReason(signal);
2290
+ }
2291
+ function abortedError() {
2292
+ return new SessionV3Error("aborted", "operation aborted");
2293
+ }
2294
+ function abortReason(signal) {
2295
+ return signal.reason instanceof Error ? signal.reason : abortedError();
2296
+ }
2297
+ function releasedStreamCleanup(streams) {
2298
+ return new FinalizationRegistry((id) => {
2299
+ const stream = streams.get(id);
2300
+ if (stream !== undefined && stream.deref() === undefined)
2301
+ streams.delete(id);
2302
+ });
2303
+ }
2304
+ function createSessionDeadline(deadlines, phase) {
2305
+ const timeoutMs = phase === "establish"
2306
+ ? deadlines?.establishTimeoutMs ?? 30_000
2307
+ : phase === "rekey_prepare"
2308
+ ? deadlines?.rekeyPrepareTimeoutMs ?? 10_000
2309
+ : deadlines?.rekeyCompletionTimeoutMs ?? 30_000;
2310
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
2311
+ throw new RangeError(`${phase} timeout must be positive`);
2312
+ return (deadlines?.factory ?? defaultDeadlineFactory)(timeoutMs, phase);
2313
+ }
2314
+ function defaultDeadlineFactory(timeoutMs, phase) {
2315
+ const controller = new AbortController();
2316
+ const cancelTimer = scheduleLongTimeout(() => {
2317
+ controller.abort(new SessionV3Error("timeout", `${phase} deadline exceeded`));
2318
+ }, timeoutMs);
2319
+ return {
2320
+ signal: controller.signal,
2321
+ cancel: cancelTimer,
2322
+ };
2323
+ }
2324
+ const MAX_NATIVE_TIMEOUT_MS = 2_147_483_647;
2325
+ // Node and browsers clamp setTimeout delays above a signed 32-bit integer.
2326
+ // Keep the public timeout range intact by scheduling the remaining duration in
2327
+ // bounded segments against a monotonic wall-clock deadline.
2328
+ function scheduleLongTimeout(callback, timeoutMs) {
2329
+ const clock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
2330
+ const deadline = clock() + timeoutMs;
2331
+ let timer;
2332
+ let canceled = false;
2333
+ const schedule = () => {
2334
+ if (canceled)
2335
+ return;
2336
+ const remaining = deadline - clock();
2337
+ if (remaining <= 0) {
2338
+ callback();
2339
+ return;
2340
+ }
2341
+ timer = setTimeout(schedule, Math.min(remaining, MAX_NATIVE_TIMEOUT_MS));
2342
+ };
2343
+ schedule();
2344
+ return () => {
2345
+ canceled = true;
2346
+ if (timer !== undefined)
2347
+ clearTimeout(timer);
2348
+ };
2349
+ }
2350
+ function combineSignals(...signals) {
2351
+ const controller = new AbortController();
2352
+ const cleanups = [];
2353
+ const abortFrom = (signal) => {
2354
+ if (!controller.signal.aborted)
2355
+ controller.abort(abortReason(signal));
2356
+ };
2357
+ for (const signal of signals) {
2358
+ if (signal === undefined)
2359
+ continue;
2360
+ const abort = () => abortFrom(signal);
2361
+ signal.addEventListener("abort", abort, { once: true });
2362
+ cleanups.push(() => signal.removeEventListener("abort", abort));
2363
+ if (signal.aborted)
2364
+ abortFrom(signal);
2365
+ }
2366
+ return {
2367
+ signal: controller.signal,
2368
+ cancel: () => { for (const cleanup of cleanups.splice(0))
2369
+ cleanup(); },
2370
+ };
2371
+ }
2372
+ function canonicalCallerCancellation(signal) {
2373
+ const controller = new AbortController();
2374
+ if (signal === undefined)
2375
+ return { signal: controller.signal, cancel: () => undefined };
2376
+ const abort = () => {
2377
+ if (!controller.signal.aborted)
2378
+ controller.abort(abortedError());
2379
+ };
2380
+ signal.addEventListener("abort", abort, { once: true });
2381
+ if (signal.aborted)
2382
+ abort();
2383
+ return {
2384
+ signal: controller.signal,
2385
+ cancel: () => signal.removeEventListener("abort", abort),
2386
+ };
2387
+ }
2388
+ function signalOptions(signal) {
2389
+ return signal === undefined ? {} : { signal };
2390
+ }
2391
+ function protocolError(message) {
2392
+ return new SessionV3Error("protocol", message);
2393
+ }
2394
+ function asError(error) {
2395
+ return error instanceof Error ? error : new Error(String(error));
2396
+ }
2397
+ function errorMessage(error) {
2398
+ return error instanceof Error ? error.message : String(error);
2399
+ }