@openllmsh/sdk 2.10.12-alpha.1 → 2.10.12-alpha.2

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 (634) hide show
  1. package/README.md +27 -7
  2. package/dist/client/chat.d.ts +38 -0
  3. package/dist/client/chat.js +77 -0
  4. package/dist/client/devices.d.ts +70 -0
  5. package/dist/client/devices.js +172 -0
  6. package/dist/client/http.d.ts +24 -0
  7. package/dist/client/http.js +34 -0
  8. package/dist/client/index.d.ts +43 -0
  9. package/dist/client/index.js +57 -0
  10. package/dist/client/relay-mux.d.ts +71 -0
  11. package/dist/client/relay-mux.js +394 -0
  12. package/dist/client/types.d.ts +47 -0
  13. package/dist/client/types.js +5 -0
  14. package/dist/client/vault.d.ts +68 -0
  15. package/dist/client/vault.js +113 -0
  16. package/dist/connect/chat.d.ts +24 -0
  17. package/dist/connect/chat.js +25 -0
  18. package/dist/connect/client.d.ts +50 -0
  19. package/dist/connect/client.js +141 -0
  20. package/dist/connect/config.d.ts +22 -0
  21. package/dist/connect/config.js +22 -0
  22. package/dist/connect/errors.d.ts +32 -0
  23. package/dist/connect/errors.js +85 -0
  24. package/{connect/index.ts → dist/connect/index.d.ts} +7 -7
  25. package/dist/connect/index.js +23 -0
  26. package/dist/connect/oauth.d.ts +51 -0
  27. package/dist/connect/oauth.js +150 -0
  28. package/dist/connect/routes.d.ts +38 -0
  29. package/dist/connect/routes.js +175 -0
  30. package/dist/connect/store.d.ts +26 -0
  31. package/dist/connect/store.js +65 -0
  32. package/dist/mcp/handle.d.ts +6 -0
  33. package/dist/mcp/handle.js +6 -0
  34. package/dist/mcp/index.d.ts +15 -0
  35. package/dist/mcp/index.js +10 -0
  36. package/dist/mcp/server.d.ts +84 -0
  37. package/dist/mcp/server.js +168 -0
  38. package/dist/mcp/tools/marketplace.d.ts +94 -0
  39. package/dist/mcp/tools/marketplace.js +303 -0
  40. package/dist/mcp/tools/memory-client.d.ts +109 -0
  41. package/dist/mcp/tools/memory-client.js +200 -0
  42. package/dist/mcp/tools/memory-config.d.ts +29 -0
  43. package/dist/mcp/tools/memory-config.js +12 -0
  44. package/dist/mcp/tools/memory.d.ts +92 -0
  45. package/dist/mcp/tools/memory.js +312 -0
  46. package/dist/mcp/tools/model-priority.d.ts +16 -0
  47. package/dist/mcp/tools/model-priority.js +87 -0
  48. package/dist/mcp/tools/openllm.d.ts +75 -0
  49. package/dist/mcp/tools/openllm.js +715 -0
  50. package/dist/mcp/types.d.ts +25 -0
  51. package/dist/mcp/types.js +7 -0
  52. package/dist/openapi/call.d.ts +26 -0
  53. package/dist/openapi/call.js +56 -0
  54. package/dist/openapi/index.d.ts +2 -0
  55. package/dist/openapi/index.js +2 -0
  56. package/dist/openapi/openapi.json +80213 -0
  57. package/dist/openapi/operations.d.ts +14 -0
  58. package/dist/openapi/operations.js +2060 -0
  59. package/dist/protocol/access.d.ts +81 -0
  60. package/dist/protocol/access.js +125 -0
  61. package/dist/protocol/agent-prompt-text.d.ts +15 -0
  62. package/{protocol/agent-prompt-text.ts → dist/protocol/agent-prompt-text.js} +9 -14
  63. package/dist/protocol/agent.d.ts +1487 -0
  64. package/dist/protocol/agent.js +787 -0
  65. package/dist/protocol/api-key-syntax.d.ts +58 -0
  66. package/dist/protocol/api-key-syntax.js +73 -0
  67. package/dist/protocol/audio.d.ts +18 -0
  68. package/dist/protocol/audio.js +21 -0
  69. package/dist/protocol/auth.d.ts +126 -0
  70. package/dist/protocol/auth.js +119 -0
  71. package/dist/protocol/changelog.d.ts +69 -0
  72. package/dist/protocol/changelog.js +107 -0
  73. package/dist/protocol/chat.d.ts +789 -0
  74. package/dist/protocol/chat.js +394 -0
  75. package/dist/protocol/client-registry.d.ts +151 -0
  76. package/dist/protocol/client-registry.js +238 -0
  77. package/dist/protocol/config.d.ts +508 -0
  78. package/dist/protocol/config.js +289 -0
  79. package/dist/protocol/control-channel.d.ts +102 -0
  80. package/{protocol/control-channel.ts → dist/protocol/control-channel.js} +33 -61
  81. package/dist/protocol/cooldown-reason.d.ts +30 -0
  82. package/dist/protocol/cooldown-reason.js +44 -0
  83. package/dist/protocol/cost.d.ts +9 -0
  84. package/dist/protocol/cost.js +8 -0
  85. package/dist/protocol/daemon-port.d.ts +2 -0
  86. package/dist/protocol/daemon-port.js +28 -0
  87. package/dist/protocol/daemon.d.ts +2034 -0
  88. package/dist/protocol/daemon.js +1286 -0
  89. package/dist/protocol/default-chains.d.ts +15 -0
  90. package/dist/protocol/default-chains.js +21 -0
  91. package/dist/protocol/device-state.d.ts +223 -0
  92. package/dist/protocol/device-state.js +52 -0
  93. package/dist/protocol/doctor-report-local.d.ts +105 -0
  94. package/{protocol/doctor-report-local.ts → dist/protocol/doctor-report-local.js} +92 -196
  95. package/dist/protocol/doctor-report-policy.d.ts +62 -0
  96. package/{protocol/doctor-report-policy.ts → dist/protocol/doctor-report-policy.js} +23 -76
  97. package/dist/protocol/doctor-report.d.ts +406 -0
  98. package/dist/protocol/doctor-report.js +645 -0
  99. package/dist/protocol/errors.d.ts +17 -0
  100. package/dist/protocol/errors.js +10 -0
  101. package/dist/protocol/execution-selection.d.ts +92 -0
  102. package/{protocol/execution-selection.ts → dist/protocol/execution-selection.js} +38 -63
  103. package/dist/protocol/hop-grant.d.ts +28 -0
  104. package/{protocol/hop-grant.ts → dist/protocol/hop-grant.js} +7 -13
  105. package/dist/protocol/image-edit-parse.d.ts +25 -0
  106. package/dist/protocol/image-edit-parse.js +196 -0
  107. package/dist/protocol/images.d.ts +288 -0
  108. package/dist/protocol/images.js +229 -0
  109. package/dist/protocol/index.d.ts +69 -0
  110. package/dist/protocol/index.js +74 -0
  111. package/dist/protocol/inference-headers.d.ts +3 -0
  112. package/dist/protocol/keepalive.d.ts +36 -0
  113. package/dist/protocol/keepalive.js +51 -0
  114. package/dist/protocol/local-auth.d.ts +125 -0
  115. package/dist/protocol/local-auth.js +227 -0
  116. package/dist/protocol/local-device-control.d.ts +108 -0
  117. package/{protocol/local-device-control.ts → dist/protocol/local-device-control.js} +40 -70
  118. package/dist/protocol/local-provider.d.ts +105 -0
  119. package/dist/protocol/local-provider.js +213 -0
  120. package/dist/protocol/local-session.d.ts +70 -0
  121. package/dist/protocol/local-session.js +87 -0
  122. package/dist/protocol/marketplace.d.ts +190 -0
  123. package/dist/protocol/marketplace.js +140 -0
  124. package/{protocol/media-attempt.ts → dist/protocol/media-attempt.d.ts} +11 -50
  125. package/dist/protocol/media-attempt.js +50 -0
  126. package/dist/protocol/media-bytes.d.ts +8 -0
  127. package/dist/protocol/media-bytes.js +21 -0
  128. package/dist/protocol/media-default.d.ts +56 -0
  129. package/dist/protocol/media-default.js +302 -0
  130. package/{protocol/media-dimensions.ts → dist/protocol/media-dimensions.d.ts} +11 -78
  131. package/dist/protocol/media-dimensions.js +90 -0
  132. package/dist/protocol/media-input.d.ts +20 -0
  133. package/dist/protocol/media-input.js +29 -0
  134. package/dist/protocol/media-model.d.ts +77 -0
  135. package/dist/protocol/media-model.js +89 -0
  136. package/{protocol/media-option-issue.ts → dist/protocol/media-option-issue.d.ts} +25 -53
  137. package/dist/protocol/media-option-issue.js +50 -0
  138. package/dist/protocol/media-types.d.ts +14 -0
  139. package/dist/protocol/media-types.js +61 -0
  140. package/dist/protocol/model-match.d.ts +254 -0
  141. package/dist/protocol/model-match.js +760 -0
  142. package/dist/protocol/model-settings.d.ts +153 -0
  143. package/dist/protocol/model-settings.js +246 -0
  144. package/dist/protocol/models.d.ts +1065 -0
  145. package/dist/protocol/models.js +638 -0
  146. package/dist/protocol/mux.d.ts +350 -0
  147. package/dist/protocol/mux.js +595 -0
  148. package/{protocol/plan-surface.ts → dist/protocol/plan-surface.d.ts} +12 -26
  149. package/dist/protocol/plan-surface.js +39 -0
  150. package/dist/protocol/provider-models.d.ts +8 -0
  151. package/{protocol/provider-models.ts → dist/protocol/provider-models.js} +7 -9
  152. package/dist/protocol/provider-status.d.ts +59 -0
  153. package/dist/protocol/provider-status.js +142 -0
  154. package/dist/protocol/provider-tier.d.ts +34 -0
  155. package/{protocol/provider-tier.ts → dist/protocol/provider-tier.js} +9 -34
  156. package/dist/protocol/provider-usage.d.ts +230 -0
  157. package/dist/protocol/provider-usage.js +214 -0
  158. package/dist/protocol/providers.d.ts +2496 -0
  159. package/dist/protocol/providers.js +723 -0
  160. package/dist/protocol/public-usage-index.d.ts +449 -0
  161. package/dist/protocol/public-usage-index.js +279 -0
  162. package/dist/protocol/realtime-generated.d.ts +29 -0
  163. package/{protocol/realtime-generated.ts → dist/protocol/realtime-generated.js} +3 -5
  164. package/dist/protocol/realtime.d.ts +241 -0
  165. package/{protocol/realtime.ts → dist/protocol/realtime.js} +88 -155
  166. package/dist/protocol/registry-pointer.d.ts +24 -0
  167. package/dist/protocol/registry-pointer.js +78 -0
  168. package/dist/protocol/relay.d.ts +1152 -0
  169. package/{protocol/relay.ts → dist/protocol/relay.js} +237 -370
  170. package/dist/protocol/replay-session.d.ts +4 -0
  171. package/{protocol/replay-session.ts → dist/protocol/replay-session.js} +1 -8
  172. package/dist/protocol/responses.d.ts +303 -0
  173. package/dist/protocol/responses.js +240 -0
  174. package/dist/protocol/semver.d.ts +59 -0
  175. package/dist/protocol/semver.js +171 -0
  176. package/{protocol/setup-mode.ts → dist/protocol/setup-mode.d.ts} +4 -12
  177. package/dist/protocol/setup-mode.js +18 -0
  178. package/dist/protocol/sha256-hex.d.ts +2 -0
  179. package/dist/protocol/sha256-hex.js +93 -0
  180. package/dist/protocol/stats.d.ts +711 -0
  181. package/dist/protocol/stats.js +353 -0
  182. package/dist/protocol/streaming.d.ts +16 -0
  183. package/dist/protocol/streaming.js +15 -0
  184. package/{protocol/subscription-daemon-floors.ts → dist/protocol/subscription-daemon-floors.d.ts} +8 -14
  185. package/dist/protocol/subscription-daemon-floors.js +4 -0
  186. package/dist/protocol/subscription-provider-compat.d.ts +44 -0
  187. package/dist/protocol/subscription-provider-compat.js +67 -0
  188. package/dist/protocol/subscription-provider.d.ts +15 -0
  189. package/dist/protocol/subscription-provider.js +17 -0
  190. package/dist/protocol/team-grant.d.ts +14 -0
  191. package/{protocol/team-grant.ts → dist/protocol/team-grant.js} +0 -3
  192. package/dist/protocol/team-shareable.d.ts +6 -0
  193. package/{protocol/team-shareable.ts → dist/protocol/team-shareable.js} +29 -33
  194. package/dist/protocol/transcription-encoding.d.ts +25 -0
  195. package/dist/protocol/transcription-encoding.js +47 -0
  196. package/{protocol/url-locality-dns.ts → dist/protocol/url-locality-dns.d.ts} +1 -23
  197. package/dist/protocol/url-locality-dns.js +33 -0
  198. package/dist/protocol/url-locality.d.ts +45 -0
  199. package/dist/protocol/url-locality.js +288 -0
  200. package/dist/protocol/usage-snapshots.d.ts +8 -0
  201. package/{protocol/usage-snapshots.ts → dist/protocol/usage-snapshots.js} +1 -2
  202. package/dist/protocol/vendor-cli-install.d.ts +20 -0
  203. package/{protocol/vendor-cli-install.ts → dist/protocol/vendor-cli-install.js} +10 -15
  204. package/dist/protocol/video-job-plan.d.ts +18 -0
  205. package/dist/protocol/video-job-plan.js +44 -0
  206. package/dist/protocol/videos.d.ts +107 -0
  207. package/dist/protocol/videos.js +154 -0
  208. package/dist/tunnel/channel-envelope.d.ts +53 -0
  209. package/dist/tunnel/channel-envelope.js +100 -0
  210. package/dist/tunnel/codec.d.ts +71 -0
  211. package/dist/tunnel/codec.js +151 -0
  212. package/dist/tunnel/device-anchor.d.ts +62 -0
  213. package/dist/tunnel/device-anchor.js +168 -0
  214. package/dist/tunnel/device-control.d.ts +50 -0
  215. package/dist/tunnel/device-control.js +88 -0
  216. package/dist/tunnel/device-grant.d.ts +91 -0
  217. package/dist/tunnel/device-grant.js +105 -0
  218. package/dist/tunnel/fleet.d.ts +28 -0
  219. package/dist/tunnel/fleet.js +41 -0
  220. package/dist/tunnel/index.d.ts +22 -0
  221. package/dist/tunnel/index.js +22 -0
  222. package/dist/tunnel/mux.d.ts +64 -0
  223. package/dist/tunnel/mux.js +449 -0
  224. package/dist/tunnel/peer-link.d.ts +88 -0
  225. package/dist/tunnel/peer-link.js +271 -0
  226. package/dist/tunnel/rtc-auth.d.ts +159 -0
  227. package/dist/tunnel/rtc-auth.js +340 -0
  228. package/dist/tunnel/rtc-duplex.d.ts +52 -0
  229. package/dist/tunnel/rtc-duplex.js +148 -0
  230. package/dist/tunnel/rtc-ice.d.ts +55 -0
  231. package/dist/tunnel/rtc-ice.js +100 -0
  232. package/dist/tunnel/secure.d.ts +179 -0
  233. package/dist/tunnel/secure.js +936 -0
  234. package/dist/tunnel/stream-reset-error.d.ts +6 -0
  235. package/dist/tunnel/stream-reset-error.js +9 -0
  236. package/dist/tunnel/streams.d.ts +244 -0
  237. package/dist/tunnel/streams.js +1071 -0
  238. package/dist/tunnel/team-grant.d.ts +90 -0
  239. package/dist/tunnel/team-grant.js +226 -0
  240. package/dist/tunnel/wire-bytes.d.ts +32 -0
  241. package/dist/tunnel/wire-bytes.js +90 -0
  242. package/dist/vault/api-key.d.ts +71 -0
  243. package/dist/vault/api-key.js +130 -0
  244. package/{vault/argon2.ts → dist/vault/argon2.d.ts} +18 -53
  245. package/dist/vault/argon2.js +82 -0
  246. package/dist/vault/cli-auth-seal.d.ts +35 -0
  247. package/dist/vault/cli-auth-seal.js +78 -0
  248. package/dist/vault/cred-seal.d.ts +18 -0
  249. package/dist/vault/cred-seal.js +86 -0
  250. package/dist/vault/credential.d.ts +21 -0
  251. package/dist/vault/credential.js +26 -0
  252. package/dist/vault/crypto.d.ts +51 -0
  253. package/dist/vault/crypto.js +156 -0
  254. package/dist/vault/daemon-attest.d.ts +68 -0
  255. package/dist/vault/daemon-attest.js +147 -0
  256. package/dist/vault/derive.d.ts +34 -0
  257. package/dist/vault/derive.js +84 -0
  258. package/dist/vault/device-access.d.ts +17 -0
  259. package/dist/vault/device-access.js +77 -0
  260. package/dist/vault/device-anchor.d.ts +42 -0
  261. package/dist/vault/device-anchor.js +90 -0
  262. package/dist/vault/device-control.d.ts +80 -0
  263. package/{vault/device-control.ts → dist/vault/device-control.js} +46 -104
  264. package/dist/vault/handoff.d.ts +102 -0
  265. package/dist/vault/handoff.js +236 -0
  266. package/dist/vault/index.d.ts +21 -0
  267. package/dist/vault/index.js +21 -0
  268. package/dist/vault/passkey.d.ts +82 -0
  269. package/{vault/passkey.ts → dist/vault/passkey.js} +63 -153
  270. package/dist/vault/phrase.d.ts +40 -0
  271. package/{vault/phrase.ts → dist/vault/phrase.js} +17 -23
  272. package/dist/vault/pin.d.ts +46 -0
  273. package/dist/vault/pin.js +92 -0
  274. package/dist/vault/public-key-seal.d.ts +17 -0
  275. package/dist/vault/public-key-seal.js +59 -0
  276. package/dist/vault/seed.d.ts +96 -0
  277. package/dist/vault/seed.js +179 -0
  278. package/dist/vault/team.d.ts +134 -0
  279. package/dist/vault/team.js +217 -0
  280. package/dist/vault/vault-item.d.ts +45 -0
  281. package/dist/vault/vault-item.js +62 -0
  282. package/dist/vault/vault-migrate-digest.d.ts +10 -0
  283. package/dist/vault/vault-migrate-digest.js +22 -0
  284. package/dist/vault/wrapped.d.ts +19 -0
  285. package/dist/vault/wrapped.js +52 -0
  286. package/dist/wire/adapters/messages/anthropic-map.d.ts +8 -0
  287. package/dist/wire/adapters/messages/anthropic-map.js +32 -0
  288. package/dist/wire/adapters/messages/index.d.ts +7 -0
  289. package/dist/wire/adapters/messages/index.js +7 -0
  290. package/dist/wire/adapters/messages/reasoning-from-items.d.ts +14 -0
  291. package/dist/wire/adapters/messages/reasoning-from-items.js +39 -0
  292. package/dist/wire/adapters/messages/reasoning-signature.d.ts +81 -0
  293. package/dist/wire/adapters/messages/reasoning-signature.js +180 -0
  294. package/dist/wire/adapters/messages/request.d.ts +28 -0
  295. package/dist/wire/adapters/messages/request.js +490 -0
  296. package/dist/wire/adapters/messages/response.d.ts +10 -0
  297. package/dist/wire/adapters/messages/response.js +177 -0
  298. package/dist/wire/adapters/messages/streaming.d.ts +134 -0
  299. package/dist/wire/adapters/messages/streaming.js +791 -0
  300. package/dist/wire/adapters/messages/usage.d.ts +20 -0
  301. package/dist/wire/adapters/messages/usage.js +10 -0
  302. package/dist/wire/adapters/responses/index.d.ts +3 -0
  303. package/dist/wire/adapters/responses/index.js +3 -0
  304. package/dist/wire/adapters/responses/request.d.ts +2 -0
  305. package/dist/wire/adapters/responses/request.js +287 -0
  306. package/dist/wire/adapters/responses/response.d.ts +11 -0
  307. package/dist/wire/adapters/responses/response.js +69 -0
  308. package/dist/wire/adapters/responses/streaming.d.ts +2 -0
  309. package/dist/wire/adapters/responses/streaming.js +267 -0
  310. package/dist/wire/features/account-rank.d.ts +61 -0
  311. package/dist/wire/features/account-rank.js +109 -0
  312. package/dist/wire/features/compaction/compact-request.d.ts +69 -0
  313. package/dist/wire/features/compaction/compact-request.js +667 -0
  314. package/dist/wire/features/compaction/compaction-text.d.ts +17 -0
  315. package/dist/wire/features/compaction/compaction-text.js +29 -0
  316. package/dist/wire/features/context-demote.d.ts +15 -0
  317. package/dist/wire/features/context-demote.js +45 -0
  318. package/dist/wire/features/context-overflow-strategy.d.ts +12 -0
  319. package/dist/wire/features/context-overflow-strategy.js +8 -0
  320. package/dist/wire/features/context-skip.d.ts +120 -0
  321. package/{wire/features/context-skip.ts → dist/wire/features/context-skip.js} +23 -57
  322. package/dist/wire/features/conversation-affinity.d.ts +49 -0
  323. package/dist/wire/features/conversation-affinity.js +121 -0
  324. package/dist/wire/features/max-tokens-backfill.d.ts +50 -0
  325. package/dist/wire/features/max-tokens-backfill.js +118 -0
  326. package/dist/wire/features/model-caps.d.ts +7 -0
  327. package/dist/wire/features/model-caps.js +40 -0
  328. package/dist/wire/features/model-settings.d.ts +3 -0
  329. package/dist/wire/features/model-settings.js +13 -0
  330. package/dist/wire/features/output-limit-clamp.d.ts +14 -0
  331. package/dist/wire/features/output-limit-clamp.js +36 -0
  332. package/dist/wire/features/quota-gate.d.ts +16 -0
  333. package/dist/wire/features/quota-gate.js +48 -0
  334. package/dist/wire/index.d.ts +44 -0
  335. package/dist/wire/index.js +44 -0
  336. package/dist/wire/lib/attempt-outcome.d.ts +19 -0
  337. package/dist/wire/lib/attempt-outcome.js +18 -0
  338. package/{wire/lib/canonical/content-part.ts → dist/wire/lib/canonical/content-part.d.ts} +12 -18
  339. package/dist/wire/lib/canonical/content-part.js +11 -0
  340. package/dist/wire/lib/canonical/count-tokens-capability.d.ts +52 -0
  341. package/dist/wire/lib/canonical/count-tokens-capability.js +109 -0
  342. package/{wire/lib/canonical/encoding-select.ts → dist/wire/lib/canonical/encoding-select.d.ts} +7 -24
  343. package/dist/wire/lib/canonical/encoding-select.js +26 -0
  344. package/dist/wire/lib/canonical/image-signature.d.ts +20 -0
  345. package/dist/wire/lib/canonical/image-signature.js +184 -0
  346. package/dist/wire/lib/canonical/image-sse.d.ts +88 -0
  347. package/dist/wire/lib/canonical/image-sse.js +173 -0
  348. package/{wire/lib/canonical/message.ts → dist/wire/lib/canonical/message.d.ts} +2 -20
  349. package/dist/wire/lib/canonical/message.js +31 -0
  350. package/dist/wire/lib/canonical/token-estimate.d.ts +98 -0
  351. package/dist/wire/lib/canonical/token-estimate.js +230 -0
  352. package/dist/wire/lib/encrypted-content.d.ts +22 -0
  353. package/dist/wire/lib/encrypted-content.js +55 -0
  354. package/dist/wire/lib/error-class.d.ts +57 -0
  355. package/dist/wire/lib/error-class.js +97 -0
  356. package/dist/wire/lib/error-envelope.d.ts +20 -0
  357. package/dist/wire/lib/error-envelope.js +53 -0
  358. package/dist/wire/lib/forwarded-headers.d.ts +16 -0
  359. package/{wire/lib/forwarded-headers.ts → dist/wire/lib/forwarded-headers.js} +62 -72
  360. package/dist/wire/lib/provider-error-rules.d.ts +21 -0
  361. package/dist/wire/lib/provider-error-rules.js +20 -0
  362. package/{wire/lib/refusal.ts → dist/wire/lib/refusal.d.ts} +3 -13
  363. package/dist/wire/lib/refusal.js +27 -0
  364. package/dist/wire/lib/responses-apply-patch.d.ts +57 -0
  365. package/dist/wire/lib/responses-apply-patch.js +81 -0
  366. package/dist/wire/lib/responses-namespace.d.ts +27 -0
  367. package/{wire/lib/responses-namespace.ts → dist/wire/lib/responses-namespace.js} +16 -32
  368. package/dist/wire/lib/secret-scrub.d.ts +23 -0
  369. package/dist/wire/lib/secret-scrub.js +72 -0
  370. package/dist/wire/lib/streaming/accumulate.d.ts +12 -0
  371. package/dist/wire/lib/streaming/accumulate.js +187 -0
  372. package/dist/wire/lib/streaming/finish-reason.d.ts +20 -0
  373. package/dist/wire/lib/streaming/finish-reason.js +15 -0
  374. package/{wire/lib/streaming/peek.ts → dist/wire/lib/streaming/peek.d.ts} +13 -82
  375. package/dist/wire/lib/streaming/peek.js +100 -0
  376. package/dist/wire/lib/streaming/provider-decode.d.ts +57 -0
  377. package/dist/wire/lib/streaming/provider-decode.js +210 -0
  378. package/dist/wire/lib/streaming/response-stream.d.ts +16 -0
  379. package/dist/wire/lib/streaming/response-stream.js +64 -0
  380. package/dist/wire/lib/streaming/sse.d.ts +130 -0
  381. package/dist/wire/lib/streaming/sse.js +600 -0
  382. package/dist/wire/lib/streaming/strip-tool-calls.d.ts +14 -0
  383. package/dist/wire/lib/streaming/strip-tool-calls.js +75 -0
  384. package/dist/wire/lib/streaming/upstream-error.d.ts +32 -0
  385. package/dist/wire/lib/streaming/upstream-error.js +45 -0
  386. package/dist/wire/lib/strip-subagent-isolation.d.ts +16 -0
  387. package/dist/wire/lib/strip-subagent-isolation.js +240 -0
  388. package/dist/wire/lib/thinking-signature.d.ts +56 -0
  389. package/{wire/lib/thinking-signature.ts → dist/wire/lib/thinking-signature.js} +77 -84
  390. package/dist/wire/lib/token-ruler/bpe-core.d.ts +105 -0
  391. package/dist/wire/lib/token-ruler/bpe-core.js +398 -0
  392. package/dist/wire/lib/token-ruler/index.d.ts +2 -0
  393. package/dist/wire/lib/token-ruler/index.js +2 -0
  394. package/dist/wire/lib/token-ruler/ruler.d.ts +36 -0
  395. package/dist/wire/lib/token-ruler/ruler.js +50 -0
  396. package/dist/wire/lib/token-ruler/vocab/claude-ranks.d.ts +14 -0
  397. package/dist/wire/lib/token-ruler/vocab/claude-ranks.js +16 -0
  398. package/{wire/lib/token-ruler/vocab/claude.ts → dist/wire/lib/token-ruler/vocab/claude.d.ts} +2 -12
  399. package/dist/wire/lib/token-ruler/vocab/claude.js +8 -0
  400. package/dist/wire/lib/token-ruler/vocab/o200k-ranks.d.ts +3 -0
  401. package/dist/wire/lib/token-ruler/vocab/o200k-ranks.js +18 -0
  402. package/dist/wire/lib/token-ruler/vocab/o200k.d.ts +11 -0
  403. package/dist/wire/lib/token-ruler/vocab/o200k.js +6 -0
  404. package/dist/wire/lib/tool-name-map.d.ts +44 -0
  405. package/dist/wire/lib/tool-name-map.js +186 -0
  406. package/dist/wire/lib/tool-schema.d.ts +15 -0
  407. package/dist/wire/lib/tool-schema.js +307 -0
  408. package/dist/wire/lib/usage-observer.d.ts +9 -0
  409. package/dist/wire/lib/usage-observer.js +108 -0
  410. package/dist/wire/providers/anthropic/adaptive-thinking.d.ts +125 -0
  411. package/dist/wire/providers/anthropic/adaptive-thinking.js +221 -0
  412. package/dist/wire/providers/anthropic/beta-headers.d.ts +44 -0
  413. package/{wire/providers/anthropic/beta-headers.ts → dist/wire/providers/anthropic/beta-headers.js} +57 -79
  414. package/dist/wire/providers/anthropic/index.d.ts +6 -0
  415. package/{wire/providers/anthropic/index.ts → dist/wire/providers/anthropic/index.js} +6 -6
  416. package/dist/wire/providers/anthropic/request.d.ts +12 -0
  417. package/dist/wire/providers/anthropic/request.js +456 -0
  418. package/dist/wire/providers/anthropic/response.d.ts +3 -0
  419. package/dist/wire/providers/anthropic/response.js +126 -0
  420. package/dist/wire/providers/anthropic/streaming.d.ts +28 -0
  421. package/dist/wire/providers/anthropic/streaming.js +268 -0
  422. package/dist/wire/providers/anthropic/web-search-domains.d.ts +7 -0
  423. package/dist/wire/providers/anthropic/web-search-domains.js +36 -0
  424. package/dist/wire/providers/chatgpt/common.d.ts +27 -0
  425. package/{wire/providers/chatgpt/common.ts → dist/wire/providers/chatgpt/common.js} +69 -89
  426. package/dist/wire/providers/chatgpt/index.d.ts +4 -0
  427. package/{wire/providers/chatgpt/index.ts → dist/wire/providers/chatgpt/index.js} +4 -4
  428. package/dist/wire/providers/chatgpt/request.d.ts +132 -0
  429. package/dist/wire/providers/chatgpt/request.js +696 -0
  430. package/dist/wire/providers/chatgpt/streaming.d.ts +69 -0
  431. package/dist/wire/providers/chatgpt/streaming.js +761 -0
  432. package/dist/wire/providers/chatgpt/web-search.d.ts +19 -0
  433. package/dist/wire/providers/chatgpt/web-search.js +55 -0
  434. package/dist/wire/providers/grok/web-search.d.ts +23 -0
  435. package/dist/wire/providers/grok/web-search.js +74 -0
  436. package/dist/wire/providers/kimi/web-search.d.ts +48 -0
  437. package/dist/wire/providers/kimi/web-search.js +106 -0
  438. package/dist/wire/providers/upstream-deny.d.ts +61 -0
  439. package/dist/wire/providers/upstream-deny.js +293 -0
  440. package/dist/wire/providers/upstream-request.d.ts +104 -0
  441. package/dist/wire/providers/upstream-request.js +411 -0
  442. package/package.json +105 -23
  443. package/ARCHITECTURE.md +0 -43
  444. package/client/chat.ts +0 -140
  445. package/client/devices.ts +0 -269
  446. package/client/http.ts +0 -72
  447. package/client/index.ts +0 -129
  448. package/client/relay-mux.ts +0 -547
  449. package/client/types.ts +0 -51
  450. package/client/vault.ts +0 -239
  451. package/connect/chat.ts +0 -58
  452. package/connect/client.ts +0 -240
  453. package/connect/config.ts +0 -47
  454. package/connect/errors.ts +0 -121
  455. package/connect/oauth.ts +0 -265
  456. package/connect/routes.ts +0 -234
  457. package/connect/store.ts +0 -107
  458. package/mcp/handle.ts +0 -24
  459. package/mcp/index.ts +0 -76
  460. package/mcp/server.ts +0 -319
  461. package/mcp/tools/marketplace.ts +0 -439
  462. package/mcp/tools/memory-client.ts +0 -297
  463. package/mcp/tools/memory-config.ts +0 -32
  464. package/mcp/tools/memory.ts +0 -369
  465. package/mcp/tools/model-priority.ts +0 -88
  466. package/mcp/tools/openllm.ts +0 -883
  467. package/mcp/types.ts +0 -28
  468. package/openapi/call.ts +0 -90
  469. package/openapi/index.ts +0 -8
  470. package/openapi/openapi.json +0 -80213
  471. package/openapi/operations.ts +0 -2075
  472. package/protocol/CONTRIBUTING.md +0 -21
  473. package/protocol/README.md +0 -134
  474. package/protocol/access.ts +0 -186
  475. package/protocol/agent.ts +0 -991
  476. package/protocol/api-key-syntax.ts +0 -105
  477. package/protocol/assets/openllm-light.svg +0 -18
  478. package/protocol/assets/openllm.svg +0 -18
  479. package/protocol/audio.ts +0 -29
  480. package/protocol/auth.ts +0 -142
  481. package/protocol/changelog.ts +0 -155
  482. package/protocol/chat.ts +0 -458
  483. package/protocol/client-registry.ts +0 -356
  484. package/protocol/config.ts +0 -345
  485. package/protocol/cooldown-reason.ts +0 -78
  486. package/protocol/cost.ts +0 -10
  487. package/protocol/daemon-port.ts +0 -31
  488. package/protocol/daemon.ts +0 -1524
  489. package/protocol/default-chains.ts +0 -66
  490. package/protocol/device-state.ts +0 -85
  491. package/protocol/doctor-report.ts +0 -947
  492. package/protocol/errors.ts +0 -14
  493. package/protocol/image-edit-parse.ts +0 -263
  494. package/protocol/images.ts +0 -298
  495. package/protocol/index.ts +0 -74
  496. package/protocol/keepalive.ts +0 -69
  497. package/protocol/local-auth.ts +0 -300
  498. package/protocol/local-provider.ts +0 -288
  499. package/protocol/local-session.ts +0 -118
  500. package/protocol/marketplace.ts +0 -187
  501. package/protocol/media-bytes.ts +0 -28
  502. package/protocol/media-default.ts +0 -357
  503. package/protocol/media-input.ts +0 -61
  504. package/protocol/media-model.ts +0 -142
  505. package/protocol/media-types.ts +0 -70
  506. package/protocol/model-match.ts +0 -1051
  507. package/protocol/model-settings.ts +0 -327
  508. package/protocol/models.ts +0 -767
  509. package/protocol/mux.ts +0 -722
  510. package/protocol/provider-status.ts +0 -206
  511. package/protocol/provider-usage.ts +0 -263
  512. package/protocol/providers.ts +0 -901
  513. package/protocol/public-usage-index.ts +0 -354
  514. package/protocol/registry-pointer.ts +0 -118
  515. package/protocol/responses.ts +0 -280
  516. package/protocol/semver.ts +0 -182
  517. package/protocol/sha256-hex.ts +0 -98
  518. package/protocol/stats.ts +0 -406
  519. package/protocol/streaming.ts +0 -19
  520. package/protocol/subscription-provider-compat.ts +0 -104
  521. package/protocol/subscription-provider.ts +0 -32
  522. package/protocol/transcription-encoding.ts +0 -76
  523. package/protocol/url-locality.ts +0 -288
  524. package/protocol/video-job-plan.ts +0 -50
  525. package/protocol/videos.ts +0 -227
  526. package/tsconfig.json +0 -14
  527. package/tunnel/ARCHITECTURE.md +0 -111
  528. package/tunnel/assets/openllm-light.svg +0 -18
  529. package/tunnel/assets/openllm.svg +0 -18
  530. package/tunnel/channel-envelope.ts +0 -139
  531. package/tunnel/codec.ts +0 -191
  532. package/tunnel/device-anchor.ts +0 -229
  533. package/tunnel/device-control.ts +0 -118
  534. package/tunnel/device-grant.ts +0 -173
  535. package/tunnel/fleet.ts +0 -77
  536. package/tunnel/index.ts +0 -22
  537. package/tunnel/mux.ts +0 -580
  538. package/tunnel/peer-link.ts +0 -390
  539. package/tunnel/rtc-auth.ts +0 -415
  540. package/tunnel/rtc-duplex.ts +0 -187
  541. package/tunnel/rtc-ice.ts +0 -136
  542. package/tunnel/secure.ts +0 -1298
  543. package/tunnel/stream-reset-error.ts +0 -14
  544. package/tunnel/streams.ts +0 -1430
  545. package/tunnel/team-grant.ts +0 -302
  546. package/tunnel/wire-bytes.ts +0 -102
  547. package/vault/ARCHITECTURE.md +0 -470
  548. package/vault/api-key.ts +0 -190
  549. package/vault/cli-auth-seal.ts +0 -157
  550. package/vault/cred-seal.ts +0 -146
  551. package/vault/credential.ts +0 -55
  552. package/vault/crypto.ts +0 -210
  553. package/vault/daemon-attest.ts +0 -229
  554. package/vault/derive.ts +0 -113
  555. package/vault/device-access.ts +0 -87
  556. package/vault/device-anchor.ts +0 -185
  557. package/vault/handoff.ts +0 -396
  558. package/vault/index.ts +0 -21
  559. package/vault/pin.ts +0 -153
  560. package/vault/public-key-seal.ts +0 -131
  561. package/vault/seed.ts +0 -272
  562. package/vault/team.ts +0 -355
  563. package/vault/vault-item.ts +0 -131
  564. package/vault/vault-migrate-digest.ts +0 -29
  565. package/vault/wrapped.ts +0 -77
  566. package/wire/ARCHITECTURE.md +0 -90
  567. package/wire/CONTRIBUTING.md +0 -19
  568. package/wire/adapters/messages/anthropic-map.ts +0 -37
  569. package/wire/adapters/messages/index.ts +0 -7
  570. package/wire/adapters/messages/reasoning-from-items.ts +0 -38
  571. package/wire/adapters/messages/reasoning-signature.ts +0 -243
  572. package/wire/adapters/messages/request.ts +0 -574
  573. package/wire/adapters/messages/response.ts +0 -215
  574. package/wire/adapters/messages/streaming.ts +0 -1027
  575. package/wire/adapters/messages/usage.ts +0 -43
  576. package/wire/adapters/responses/index.ts +0 -3
  577. package/wire/adapters/responses/request.ts +0 -395
  578. package/wire/adapters/responses/response.ts +0 -88
  579. package/wire/adapters/responses/streaming.ts +0 -344
  580. package/wire/assets/openllm-light.svg +0 -18
  581. package/wire/assets/openllm.svg +0 -18
  582. package/wire/features/account-rank.ts +0 -166
  583. package/wire/features/compaction/compact-request.ts +0 -862
  584. package/wire/features/compaction/compaction-text.ts +0 -43
  585. package/wire/features/context-demote.ts +0 -47
  586. package/wire/features/context-overflow-strategy.ts +0 -26
  587. package/wire/features/conversation-affinity.ts +0 -144
  588. package/wire/features/max-tokens-backfill.ts +0 -141
  589. package/wire/features/model-caps.ts +0 -53
  590. package/wire/features/model-settings.ts +0 -24
  591. package/wire/features/output-limit-clamp.ts +0 -64
  592. package/wire/features/quota-gate.ts +0 -85
  593. package/wire/index.ts +0 -44
  594. package/wire/lib/attempt-outcome.ts +0 -43
  595. package/wire/lib/canonical/count-tokens-capability.ts +0 -138
  596. package/wire/lib/canonical/image-signature.ts +0 -202
  597. package/wire/lib/canonical/image-sse.ts +0 -216
  598. package/wire/lib/canonical/token-estimate.ts +0 -266
  599. package/wire/lib/encrypted-content.ts +0 -66
  600. package/wire/lib/error-class.ts +0 -154
  601. package/wire/lib/error-envelope.ts +0 -56
  602. package/wire/lib/provider-error-rules.ts +0 -48
  603. package/wire/lib/responses-apply-patch.ts +0 -104
  604. package/wire/lib/secret-scrub.ts +0 -101
  605. package/wire/lib/streaming/accumulate.ts +0 -221
  606. package/wire/lib/streaming/finish-reason.ts +0 -33
  607. package/wire/lib/streaming/provider-decode.ts +0 -259
  608. package/wire/lib/streaming/response-stream.ts +0 -71
  609. package/wire/lib/streaming/sse.ts +0 -699
  610. package/wire/lib/streaming/strip-tool-calls.ts +0 -95
  611. package/wire/lib/streaming/upstream-error.ts +0 -58
  612. package/wire/lib/strip-subagent-isolation.ts +0 -284
  613. package/wire/lib/token-ruler/bpe-core.ts +0 -426
  614. package/wire/lib/token-ruler/index.ts +0 -2
  615. package/wire/lib/token-ruler/ruler.ts +0 -79
  616. package/wire/lib/token-ruler/vocab/claude-ranks.ts +0 -16
  617. package/wire/lib/token-ruler/vocab/o200k-ranks.ts +0 -18
  618. package/wire/lib/token-ruler/vocab/o200k.ts +0 -19
  619. package/wire/lib/tool-name-map.ts +0 -271
  620. package/wire/lib/tool-schema.ts +0 -353
  621. package/wire/lib/usage-observer.ts +0 -125
  622. package/wire/providers/anthropic/adaptive-thinking.ts +0 -291
  623. package/wire/providers/anthropic/request.ts +0 -607
  624. package/wire/providers/anthropic/response.ts +0 -155
  625. package/wire/providers/anthropic/streaming.ts +0 -315
  626. package/wire/providers/anthropic/web-search-domains.ts +0 -49
  627. package/wire/providers/chatgpt/request.ts +0 -959
  628. package/wire/providers/chatgpt/streaming.ts +0 -1007
  629. package/wire/providers/chatgpt/web-search.ts +0 -63
  630. package/wire/providers/grok/web-search.ts +0 -87
  631. package/wire/providers/kimi/web-search.ts +0 -145
  632. package/wire/providers/upstream-deny.ts +0 -355
  633. package/wire/providers/upstream-request.ts +0 -619
  634. /package/{protocol/inference-headers.ts → dist/protocol/inference-headers.js} +0 -0
package/tunnel/secure.ts DELETED
@@ -1,1298 +0,0 @@
1
- /**
2
- * Noise_IK end-to-end encryption for traffic that crosses the blind relay.
3
- *
4
- * Why: on the relay mux fallback (RTC unavailable or forced off) every byte
5
- * of an agent stream passes through the relay. RTC is already E2E (DTLS bound
6
- * to the daemon key in `rtc-auth.ts`); this module gives the relay rung the
7
- * same property, so the relay forwards ciphertext only.
8
- *
9
- * Pattern: `Noise_IK_25519_AESGCM_SHA256` (Noise spec rev 34), built only on
10
- * WebCrypto (X25519, HMAC-SHA-256, AES-256-GCM). The package keeps no crypto
11
- * dependency and runs unchanged in browsers, Bun and Node.
12
- *
13
- * IK:
14
- * <- s responder static = the daemon's X25519 key
15
- * ... (`dpk`, verified by the caller — dpk proof
16
- * or control attestation)
17
- * -> e, es, s, ss payload: host-defined (a device grant)
18
- * <- e, ee, se payload: host-defined (may be empty)
19
- *
20
- * The initiator (browser) must already know the daemon static key: a relay
21
- * that swaps keys cannot read message 1 or answer it, so the handshake fails
22
- * closed. The initiator's own static key may be per-session; it is
23
- * authenticated by the device grant carried in the message-1 payload, which
24
- * the responder checks in `authorize` (including the grant's `dpk`).
25
- *
26
- * Two carriers share one handshake core:
27
- * - {@link secureDuplex} wraps a message-oriented {@link TDuplex}. Each
28
- * Noise message is one duplex message; a plaintext larger than one Noise
29
- * message is split into records with a continuation flag and reassembled
30
- * (bounded by `maxMessageBytes`).
31
- * - {@link secureMuxStream} wraps one {@link TMuxStream} (the agent path).
32
- * DATA is a byte stream, so each Noise message is framed with the Noise
33
- * spec's 2-byte big-endian length prefix. Stream CTRL payloads are
34
- * encrypted too, under a second key pair derived from the final chaining
35
- * key (`HKDF(ck, "openllm-secure-ctrl-v1")`) — CTRL and DATA may leave the
36
- * mux in a different order than they were written (DATA waits for flow
37
- * credit), so each needs its own nonce counter. RESET payloads, END and
38
- * WINDOW stay plaintext: they carry reset codes and flow control the relay
39
- * and both peers must read, never session content.
40
- *
41
- * Deviation from the spec, deliberate and documented: the CTRL key pair above
42
- * is an extra output of the final chaining key. It does not change the Noise
43
- * handshake or the DATA transport keys from `Split()`.
44
- */
45
- import type { TStreamResetCode } from "@openllmsh/sdk/protocol";
46
- import { encodeJsonPayload } from "./codec";
47
- import type { TDuplex, TMuxEventHandler, TMuxStream } from "./mux";
48
-
49
- export const NOISE_PROTOCOL_NAME = "Noise_IK_25519_AESGCM_SHA256";
50
- export const NOISE_PSK_PROTOCOL_NAME = "Noise_IKpsk2_25519_AESGCM_SHA256";
51
- export const NOISE_DH_LEN = 32;
52
- export const NOISE_TAG_LEN = 16;
53
- /** Noise spec limit on one handshake or transport message. */
54
- export const NOISE_MAX_MESSAGE_BYTES = 65_535;
55
- /** Default prologue; hosts should bind the channel / stream id via `prologue`. */
56
- export const SECURE_DEFAULT_PROLOGUE = "openllm-secure-v1";
57
- export const SECURE_HANDSHAKE_TIMEOUT_MS = 15_000;
58
- /** {@link secureDuplex} reassembly cap for one plaintext message. */
59
- export const SECURE_DUPLEX_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
60
- /** Cap on a handshake payload (a device grant fits easily). */
61
- export const SECURE_MAX_HANDSHAKE_PAYLOAD_BYTES = 16 * 1024;
62
-
63
- const CTRL_KEY_INFO = "openllm-secure-ctrl-v1";
64
- /** CTRL frames held while the local side finishes the handshake. */
65
- const SECURE_MAX_EARLY_CTRL = 64;
66
- /** Messages / records held while the local side finishes the handshake. */
67
- const SECURE_MAX_EARLY_MESSAGES = 64;
68
- /** Plaintext per stream record (one Noise transport message). */
69
- const STREAM_RECORD_PLAINTEXT = NOISE_MAX_MESSAGE_BYTES - NOISE_TAG_LEN;
70
- /** Plaintext per duplex record: one byte is the continuation flag. */
71
- const DUPLEX_RECORD_PLAINTEXT = STREAM_RECORD_PLAINTEXT - 1;
72
- const RECORD_MORE = 0x01;
73
- const RECORD_FINAL = 0x00;
74
- const LENGTH_PREFIX_BYTES = 2;
75
- /** DER prefix of an X25519 SubjectPublicKeyInfo (RFC 8410). */
76
- const X25519_SPKI_PREFIX = new Uint8Array([
77
- 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00,
78
- ]);
79
-
80
- export type TSecureErrorCode =
81
- /** AEAD failed: wrong responder key, tampering, or replay. */
82
- | "decrypt_failed"
83
- /** Bytes do not parse as a Noise message. */
84
- | "malformed"
85
- /** The responder's `authorize` refused the initiator. */
86
- | "refused"
87
- | "timeout"
88
- /** The carrier closed or reset before the handshake finished. */
89
- | "closed";
90
-
91
- export class SecureChannelError extends Error {
92
- readonly code: TSecureErrorCode;
93
- constructor(code: TSecureErrorCode, message: string) {
94
- super(message);
95
- this.name = "SecureChannelError";
96
- this.code = code;
97
- }
98
- }
99
-
100
- /**
101
- * A static X25519 identity. `dh` keeps the private key with its owner, so a
102
- * daemon can back it with its node:crypto `KeyObject` without exporting it.
103
- */
104
- export type TNoiseStaticKey = {
105
- /** Raw 32-byte X25519 public key. */
106
- readonly publicKey: Uint8Array;
107
- /** X25519(private, remotePublic) → 32-byte shared secret. */
108
- readonly dh: (remotePublic: Uint8Array) => Promise<Uint8Array>;
109
- };
110
-
111
- export type TSecureAuthorizeContext = {
112
- /** The initiator's raw 32-byte static key (authenticated by Noise). */
113
- readonly remoteStatic: Uint8Array;
114
- /** The initiator's message-1 payload (e.g. a device grant). */
115
- readonly payload: Uint8Array;
116
- };
117
-
118
- type TSecureCommonOptions = {
119
- /** Bound into the handshake hash; both sides must agree. */
120
- readonly prologue?: Uint8Array;
121
- /** Optional 32-byte pre-shared key; selects Noise IKpsk2. */
122
- readonly psk?: Uint8Array;
123
- readonly timeoutMs?: number;
124
- readonly signal?: AbortSignal;
125
- };
126
-
127
- export type TSecureInitiatorOptions = TSecureCommonOptions & {
128
- readonly role: "initiator";
129
- /** The responder's static key (`dpk`): raw 32 bytes or SPKI DER base64. */
130
- readonly remoteStatic: Uint8Array | string;
131
- /** Defaults to a fresh per-session key. */
132
- readonly localStatic?: TNoiseStaticKey;
133
- /** Message-1 payload, encrypted to the responder (e.g. a device grant). */
134
- readonly payload?: Uint8Array;
135
- };
136
-
137
- export type TSecureResponderOptions = TSecureCommonOptions & {
138
- readonly role: "responder";
139
- readonly localStatic: TNoiseStaticKey;
140
- /**
141
- * Admit or refuse the initiator after message 1 decrypts. Return the
142
- * message-2 payload (may be empty) to admit, or `null` to refuse. Throwing
143
- * also refuses.
144
- */
145
- readonly authorize: (
146
- context: TSecureAuthorizeContext,
147
- ) => Uint8Array | null | Promise<Uint8Array | null>;
148
- };
149
-
150
- export type TSecureOptions = TSecureInitiatorOptions | TSecureResponderOptions;
151
-
152
- export type TSecureSession = {
153
- /** The peer's raw 32-byte static key. */
154
- readonly remoteStatic: Uint8Array;
155
- /** The peer's handshake payload. */
156
- readonly peerPayload: Uint8Array;
157
- /** Final handshake hash `h` — a channel-binding value. */
158
- readonly handshakeHash: Uint8Array;
159
- };
160
-
161
- export type TSecureDuplex = TDuplex & TSecureSession;
162
- type TSecurePhase = "handshake" | "open" | "dead";
163
- export type TSecureMuxStream = TMuxStream & TSecureSession;
164
-
165
- // ---------------------------------------------------------------------------
166
- // Bytes + key helpers
167
- // ---------------------------------------------------------------------------
168
-
169
- const subtle = (): SubtleCrypto => globalThis.crypto.subtle;
170
-
171
- /** Copy into a fresh ArrayBuffer-backed view (what WebCrypto accepts). */
172
- const own = (bytes: Uint8Array): Uint8Array<ArrayBuffer> =>
173
- new Uint8Array(bytes);
174
-
175
- const concatBytes = (...parts: ReadonlyArray<Uint8Array>): Uint8Array => {
176
- let length = 0;
177
- for (const part of parts) length += part.byteLength;
178
- const out = new Uint8Array(length);
179
- let offset = 0;
180
- for (const part of parts) {
181
- out.set(part, offset);
182
- offset += part.byteLength;
183
- }
184
- return out;
185
- };
186
-
187
- const bytesEqual = (a: Uint8Array, b: Uint8Array): boolean => {
188
- if (a.byteLength !== b.byteLength) return false;
189
- let diff = 0;
190
- for (let i = 0; i < a.byteLength; i++) {
191
- diff |= (a[i] as number) ^ (b[i] as number);
192
- }
193
- return diff === 0;
194
- };
195
-
196
- const isAllZero = (bytes: Uint8Array): boolean => {
197
- let acc = 0;
198
- for (const byte of bytes) acc |= byte;
199
- return acc === 0;
200
- };
201
-
202
- const base64ToBytes = (b64: string): Uint8Array | null => {
203
- try {
204
- const bin = atob(b64);
205
- const out = new Uint8Array(bin.length);
206
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
207
- return out;
208
- } catch {
209
- return null;
210
- }
211
- };
212
-
213
- const bytesToBase64 = (bytes: Uint8Array): string => {
214
- let bin = "";
215
- for (const byte of bytes) bin += String.fromCharCode(byte);
216
- return btoa(bin);
217
- };
218
-
219
- /**
220
- * Raw 32-byte X25519 key from SPKI DER base64 (the `DaemonStatus.pubkey` /
221
- * `dpk` format). Null when it is not an X25519 SPKI.
222
- */
223
- export const x25519RawFromSpkiB64 = (spkiB64: string): Uint8Array | null => {
224
- const der = base64ToBytes(spkiB64);
225
- if (der === null) return null;
226
- if (der.byteLength !== X25519_SPKI_PREFIX.byteLength + NOISE_DH_LEN) {
227
- return null;
228
- }
229
- if (
230
- !bytesEqual(
231
- der.subarray(0, X25519_SPKI_PREFIX.byteLength),
232
- X25519_SPKI_PREFIX,
233
- )
234
- ) {
235
- return null;
236
- }
237
- return der.slice(X25519_SPKI_PREFIX.byteLength);
238
- };
239
-
240
- /** SPKI DER base64 for a raw 32-byte X25519 key. */
241
- export const x25519SpkiB64FromRaw = (raw: Uint8Array): string => {
242
- if (raw.byteLength !== NOISE_DH_LEN) {
243
- throw new RangeError("X25519 public key must be 32 bytes");
244
- }
245
- return bytesToBase64(concatBytes(X25519_SPKI_PREFIX, raw));
246
- };
247
-
248
- const resolveRemoteStatic = (value: Uint8Array | string): Uint8Array => {
249
- const raw = typeof value === "string" ? x25519RawFromSpkiB64(value) : value;
250
- if (raw === null || raw.byteLength !== NOISE_DH_LEN) {
251
- throw new SecureChannelError(
252
- "malformed",
253
- "responder static key is not an X25519 key",
254
- );
255
- }
256
- return raw;
257
- };
258
-
259
- const x25519 = async (
260
- privateKey: CryptoKey,
261
- remotePublic: Uint8Array,
262
- ): Promise<Uint8Array> => {
263
- let shared: Uint8Array;
264
- try {
265
- const publicKey = await subtle().importKey(
266
- "raw",
267
- own(remotePublic),
268
- { name: "X25519" },
269
- false,
270
- [],
271
- );
272
- shared = new Uint8Array(
273
- await subtle().deriveBits(
274
- { name: "X25519", public: publicKey },
275
- privateKey,
276
- NOISE_DH_LEN * 8,
277
- ),
278
- );
279
- } catch {
280
- throw new SecureChannelError("malformed", "invalid X25519 public key");
281
- }
282
- // A low-order point yields an all-zero secret; never key from it.
283
- if (isAllZero(shared)) {
284
- throw new SecureChannelError("malformed", "invalid X25519 public key");
285
- }
286
- return shared;
287
- };
288
-
289
- /** A {@link TNoiseStaticKey} backed by a WebCrypto X25519 key pair. */
290
- export const noiseStaticKeyFromCryptoKeyPair = async (
291
- pair: CryptoKeyPair,
292
- ): Promise<TNoiseStaticKey> => {
293
- const publicKey = new Uint8Array(
294
- await subtle().exportKey("raw", pair.publicKey),
295
- );
296
- return {
297
- publicKey,
298
- dh: (remotePublic) => x25519(pair.privateKey, remotePublic),
299
- };
300
- };
301
-
302
- /** Mint a fresh WebCrypto X25519 static (or ephemeral) key. */
303
- export const generateNoiseStaticKey = async (): Promise<TNoiseStaticKey> => {
304
- const pair = (await subtle().generateKey({ name: "X25519" }, true, [
305
- "deriveBits",
306
- ])) as CryptoKeyPair;
307
- return noiseStaticKeyFromCryptoKeyPair(pair);
308
- };
309
-
310
- // ---------------------------------------------------------------------------
311
- // Noise symmetric state (spec §5.1–5.2)
312
- // ---------------------------------------------------------------------------
313
-
314
- type TCipherState = {
315
- key: CryptoKey | null;
316
- nonce: number;
317
- };
318
-
319
- const sha256 = async (data: Uint8Array): Promise<Uint8Array> =>
320
- new Uint8Array(await subtle().digest("SHA-256", own(data)));
321
-
322
- const hmac = async (key: Uint8Array, data: Uint8Array): Promise<Uint8Array> => {
323
- const k = await subtle().importKey(
324
- "raw",
325
- own(key),
326
- { name: "HMAC", hash: "SHA-256" },
327
- false,
328
- ["sign"],
329
- );
330
- return new Uint8Array(await subtle().sign("HMAC", k, own(data)));
331
- };
332
-
333
- /** Derive the team-specific Noise PSK from the team key. */
334
- export const deriveTeamTunnelPsk = async (
335
- teamKey: Uint8Array,
336
- teamId: string,
337
- ): Promise<Uint8Array> => {
338
- const key = await subtle().importKey("raw", own(teamKey), "HKDF", false, [
339
- "deriveBits",
340
- ]);
341
- return new Uint8Array(
342
- await subtle().deriveBits(
343
- {
344
- name: "HKDF",
345
- hash: "SHA-256",
346
- salt: own(new TextEncoder().encode(teamId)),
347
- info: own(new TextEncoder().encode("openllm-team-tunnel-psk-v1")),
348
- },
349
- key,
350
- 256,
351
- ),
352
- );
353
- };
354
-
355
- /** Noise HKDF with two outputs. */
356
- const hkdf2 = async (
357
- chainingKey: Uint8Array,
358
- ikm: Uint8Array,
359
- ): Promise<readonly [Uint8Array, Uint8Array]> => {
360
- const temp = await hmac(chainingKey, ikm);
361
- const out1 = await hmac(temp, new Uint8Array([0x01]));
362
- const out2 = await hmac(temp, concatBytes(out1, new Uint8Array([0x02])));
363
- return [out1, out2];
364
- };
365
-
366
- const aesKey = (raw: Uint8Array): Promise<CryptoKey> =>
367
- subtle().importKey("raw", own(raw), { name: "AES-GCM" }, false, [
368
- "encrypt",
369
- "decrypt",
370
- ]);
371
-
372
- /** Noise AESGCM nonce: 32 zero bits then the 64-bit big-endian counter. */
373
- const gcmNonce = (counter: number): Uint8Array<ArrayBuffer> => {
374
- const iv = new Uint8Array(12);
375
- new DataView(iv.buffer).setBigUint64(4, BigInt(counter), false);
376
- return iv;
377
- };
378
-
379
- const cipherState = (key: CryptoKey | null): TCipherState => ({
380
- key,
381
- nonce: 0,
382
- });
383
-
384
- /** Claim the next nonce synchronously so concurrent callers never reuse one. */
385
- const nextNonce = (cs: TCipherState): number => {
386
- if (cs.nonce >= Number.MAX_SAFE_INTEGER) {
387
- throw new SecureChannelError("closed", "nonce space exhausted");
388
- }
389
- const n = cs.nonce;
390
- cs.nonce += 1;
391
- return n;
392
- };
393
-
394
- const encryptWithAd = async (
395
- cs: TCipherState,
396
- ad: Uint8Array,
397
- plaintext: Uint8Array,
398
- ): Promise<Uint8Array> => {
399
- if (cs.key === null) return plaintext;
400
- const n = nextNonce(cs);
401
- return new Uint8Array(
402
- await subtle().encrypt(
403
- { name: "AES-GCM", iv: gcmNonce(n), additionalData: own(ad) },
404
- cs.key,
405
- own(plaintext),
406
- ),
407
- );
408
- };
409
-
410
- const decryptWithAd = async (
411
- cs: TCipherState,
412
- ad: Uint8Array,
413
- ciphertext: Uint8Array,
414
- ): Promise<Uint8Array> => {
415
- if (cs.key === null) return ciphertext;
416
- if (ciphertext.byteLength < NOISE_TAG_LEN) {
417
- throw new SecureChannelError("malformed", "ciphertext shorter than a tag");
418
- }
419
- const n = nextNonce(cs);
420
- try {
421
- return new Uint8Array(
422
- await subtle().decrypt(
423
- { name: "AES-GCM", iv: gcmNonce(n), additionalData: own(ad) },
424
- cs.key,
425
- own(ciphertext),
426
- ),
427
- );
428
- } catch {
429
- throw new SecureChannelError("decrypt_failed", "authentication failed");
430
- }
431
- };
432
-
433
- type TSymmetricState = {
434
- ck: Uint8Array;
435
- h: Uint8Array;
436
- cs: TCipherState;
437
- };
438
-
439
- const initSymmetric = async (
440
- prologue: Uint8Array,
441
- psk?: Uint8Array,
442
- ): Promise<TSymmetricState> => {
443
- if (psk !== undefined && psk.byteLength !== 32) {
444
- throw new SecureChannelError("malformed", "Noise PSK must be 32 bytes");
445
- }
446
- const name = new TextEncoder().encode(
447
- psk === undefined ? NOISE_PROTOCOL_NAME : NOISE_PSK_PROTOCOL_NAME,
448
- );
449
- const h = new Uint8Array(32);
450
- if (name.byteLength <= 32) h.set(name);
451
- else h.set(await sha256(name));
452
- const state: TSymmetricState = { ck: h.slice(), h, cs: cipherState(null) };
453
- await mixHash(state, prologue);
454
- return state;
455
- };
456
-
457
- const mixHash = async (
458
- state: TSymmetricState,
459
- data: Uint8Array,
460
- ): Promise<void> => {
461
- state.h = await sha256(concatBytes(state.h, data));
462
- };
463
-
464
- const mixKey = async (
465
- state: TSymmetricState,
466
- ikm: Uint8Array,
467
- ): Promise<void> => {
468
- const [ck, tempK] = await hkdf2(state.ck, ikm);
469
- state.ck = ck;
470
- state.cs = cipherState(await aesKey(tempK));
471
- };
472
-
473
- const mixKeyAndHash = async (
474
- state: TSymmetricState,
475
- psk: Uint8Array,
476
- ): Promise<void> => {
477
- const temp = await hmac(state.ck, psk);
478
- const ck = await hmac(temp, new Uint8Array([1]));
479
- const tempH = await hmac(temp, concatBytes(ck, new Uint8Array([2])));
480
- const tempK = await hmac(temp, concatBytes(tempH, new Uint8Array([3])));
481
- state.ck = ck;
482
- await mixHash(state, tempH);
483
- state.cs = cipherState(await aesKey(tempK));
484
- };
485
-
486
- const encryptAndHash = async (
487
- state: TSymmetricState,
488
- plaintext: Uint8Array,
489
- ): Promise<Uint8Array> => {
490
- const ciphertext = await encryptWithAd(state.cs, state.h, plaintext);
491
- await mixHash(state, ciphertext);
492
- return ciphertext;
493
- };
494
-
495
- const decryptAndHash = async (
496
- state: TSymmetricState,
497
- ciphertext: Uint8Array,
498
- ): Promise<Uint8Array> => {
499
- const plaintext = await decryptWithAd(state.cs, state.h, ciphertext);
500
- await mixHash(state, ciphertext);
501
- return plaintext;
502
- };
503
-
504
- type TTransportKeys = {
505
- readonly send: TCipherState;
506
- readonly receive: TCipherState;
507
- readonly ctrlSend: TCipherState;
508
- readonly ctrlReceive: TCipherState;
509
- };
510
-
511
- /** `Split()` plus the CTRL key pair (see the module comment). */
512
- const splitKeys = async (
513
- state: TSymmetricState,
514
- role: "initiator" | "responder",
515
- ): Promise<TTransportKeys> => {
516
- const [k1, k2] = await hkdf2(state.ck, new Uint8Array());
517
- const [c1, c2] = await hkdf2(
518
- state.ck,
519
- new TextEncoder().encode(CTRL_KEY_INFO),
520
- );
521
- const [i2r, r2i, ci2r, cr2i] = await Promise.all([
522
- aesKey(k1),
523
- aesKey(k2),
524
- aesKey(c1),
525
- aesKey(c2),
526
- ]);
527
- return role === "initiator"
528
- ? {
529
- send: cipherState(i2r),
530
- receive: cipherState(r2i),
531
- ctrlSend: cipherState(ci2r),
532
- ctrlReceive: cipherState(cr2i),
533
- }
534
- : {
535
- send: cipherState(r2i),
536
- receive: cipherState(i2r),
537
- ctrlSend: cipherState(cr2i),
538
- ctrlReceive: cipherState(ci2r),
539
- };
540
- };
541
-
542
- // ---------------------------------------------------------------------------
543
- // Handshake (IK)
544
- // ---------------------------------------------------------------------------
545
-
546
- /** Handshake message transport: one call per whole Noise message. */
547
- type TMessagePipe = {
548
- readonly send: (message: Uint8Array) => void;
549
- readonly next: () => Promise<Uint8Array>;
550
- };
551
-
552
- type THandshakeResult = TSecureSession & { readonly keys: TTransportKeys };
553
-
554
- const prologueOf = (options: TSecureCommonOptions): Uint8Array =>
555
- options.prologue ?? new TextEncoder().encode(SECURE_DEFAULT_PROLOGUE);
556
-
557
- const checkPayloadSize = (payload: Uint8Array): void => {
558
- if (payload.byteLength > SECURE_MAX_HANDSHAKE_PAYLOAD_BYTES) {
559
- throw new RangeError("handshake payload exceeds the size cap");
560
- }
561
- };
562
-
563
- const runInitiator = async (
564
- pipe: TMessagePipe,
565
- options: TSecureInitiatorOptions,
566
- ): Promise<THandshakeResult> => {
567
- const rs = resolveRemoteStatic(options.remoteStatic);
568
- const s = options.localStatic ?? (await generateNoiseStaticKey());
569
- const payload = options.payload ?? new Uint8Array();
570
- checkPayloadSize(payload);
571
- const state = await initSymmetric(prologueOf(options), options.psk);
572
- await mixHash(state, rs);
573
-
574
- // -> e, es, s, ss
575
- const e = await generateNoiseStaticKey();
576
- await mixHash(state, e.publicKey);
577
- if (options.psk !== undefined) await mixKey(state, e.publicKey);
578
- await mixKey(state, await e.dh(rs));
579
- const encryptedStatic = await encryptAndHash(state, s.publicKey);
580
- await mixKey(state, await s.dh(rs));
581
- const encryptedPayload = await encryptAndHash(state, payload);
582
- pipe.send(concatBytes(e.publicKey, encryptedStatic, encryptedPayload));
583
-
584
- // <- e, ee, se
585
- const reply = await pipe.next();
586
- if (reply.byteLength < NOISE_DH_LEN + NOISE_TAG_LEN) {
587
- throw new SecureChannelError("malformed", "handshake reply too short");
588
- }
589
- const re = reply.slice(0, NOISE_DH_LEN);
590
- await mixHash(state, re);
591
- if (options.psk !== undefined) await mixKey(state, re);
592
- await mixKey(state, await e.dh(re));
593
- await mixKey(state, await s.dh(re));
594
- if (options.psk !== undefined) await mixKeyAndHash(state, options.psk);
595
- const peerPayload = await decryptAndHash(state, reply.subarray(NOISE_DH_LEN));
596
- return {
597
- remoteStatic: rs,
598
- peerPayload,
599
- handshakeHash: state.h,
600
- keys: await splitKeys(state, "initiator"),
601
- };
602
- };
603
-
604
- const runResponder = async (
605
- pipe: TMessagePipe,
606
- options: TSecureResponderOptions,
607
- ): Promise<THandshakeResult> => {
608
- const s = options.localStatic;
609
- const state = await initSymmetric(prologueOf(options), options.psk);
610
- await mixHash(state, s.publicKey);
611
-
612
- // -> e, es, s, ss
613
- const first = await pipe.next();
614
- const staticEnd = NOISE_DH_LEN + NOISE_DH_LEN + NOISE_TAG_LEN;
615
- if (first.byteLength < staticEnd + NOISE_TAG_LEN) {
616
- throw new SecureChannelError("malformed", "handshake message too short");
617
- }
618
- const re = first.slice(0, NOISE_DH_LEN);
619
- await mixHash(state, re);
620
- if (options.psk !== undefined) await mixKey(state, re);
621
- await mixKey(state, await s.dh(re));
622
- const rs = await decryptAndHash(
623
- state,
624
- first.subarray(NOISE_DH_LEN, staticEnd),
625
- );
626
- await mixKey(state, await s.dh(rs));
627
- const peerPayload = await decryptAndHash(state, first.subarray(staticEnd));
628
-
629
- let reply: Uint8Array | null;
630
- try {
631
- reply = await options.authorize({ remoteStatic: rs, payload: peerPayload });
632
- } catch {
633
- reply = null;
634
- }
635
- if (reply === null) {
636
- throw new SecureChannelError("refused", "initiator refused");
637
- }
638
- checkPayloadSize(reply);
639
-
640
- // <- e, ee, se
641
- const e = await generateNoiseStaticKey();
642
- await mixHash(state, e.publicKey);
643
- if (options.psk !== undefined) await mixKey(state, e.publicKey);
644
- await mixKey(state, await e.dh(re));
645
- await mixKey(state, await e.dh(rs));
646
- if (options.psk !== undefined) await mixKeyAndHash(state, options.psk);
647
- const encryptedPayload = await encryptAndHash(state, reply);
648
- pipe.send(concatBytes(e.publicKey, encryptedPayload));
649
- return {
650
- remoteStatic: rs,
651
- peerPayload,
652
- handshakeHash: state.h,
653
- keys: await splitKeys(state, "responder"),
654
- };
655
- };
656
-
657
- /** Run the handshake under a timeout + abort signal. */
658
- const runHandshake = (
659
- pipe: TMessagePipe,
660
- options: TSecureOptions,
661
- fail: (error: SecureChannelError) => void,
662
- ): Promise<THandshakeResult> => {
663
- const timeoutMs = options.timeoutMs ?? SECURE_HANDSHAKE_TIMEOUT_MS;
664
- return new Promise<THandshakeResult>((resolve, reject) => {
665
- let done = false;
666
- const settle = (
667
- error: SecureChannelError | null,
668
- value?: THandshakeResult,
669
- ): void => {
670
- if (done) return;
671
- done = true;
672
- clearTimeout(timer);
673
- options.signal?.removeEventListener("abort", onAbort);
674
- if (error !== null) {
675
- fail(error);
676
- reject(error);
677
- return;
678
- }
679
- if (value !== undefined) resolve(value);
680
- };
681
- const onAbort = (): void => {
682
- settle(new SecureChannelError("timeout", "secure handshake aborted"));
683
- };
684
- const timer = setTimeout(() => {
685
- settle(new SecureChannelError("timeout", "secure handshake timed out"));
686
- }, timeoutMs);
687
- if (options.signal?.aborted === true) {
688
- onAbort();
689
- return;
690
- }
691
- options.signal?.addEventListener("abort", onAbort, { once: true });
692
- const run =
693
- options.role === "initiator"
694
- ? runInitiator(pipe, options)
695
- : runResponder(pipe, options);
696
- run.then(
697
- (value) => settle(null, value),
698
- (error: unknown) =>
699
- settle(
700
- error instanceof SecureChannelError
701
- ? error
702
- : new SecureChannelError(
703
- "malformed",
704
- error instanceof Error ? error.message : "handshake failed",
705
- ),
706
- ),
707
- );
708
- });
709
- };
710
-
711
- /** Inbound message queue that feeds {@link TMessagePipe.next}. */
712
- const createInbox = (): {
713
- readonly push: (message: Uint8Array) => void;
714
- readonly fail: (error: SecureChannelError) => void;
715
- readonly next: () => Promise<Uint8Array>;
716
- /** Take one queued message without waiting (records behind the handshake). */
717
- readonly drain: () => Uint8Array | undefined;
718
- readonly size: () => number;
719
- } => {
720
- const queued: Uint8Array[] = [];
721
- let failure: SecureChannelError | null = null;
722
- let waiter: {
723
- readonly resolve: (message: Uint8Array) => void;
724
- readonly reject: (error: SecureChannelError) => void;
725
- } | null = null;
726
- return {
727
- push: (message) => {
728
- if (waiter !== null) {
729
- const w = waiter;
730
- waiter = null;
731
- w.resolve(message);
732
- return;
733
- }
734
- queued.push(message);
735
- },
736
- fail: (error) => {
737
- if (failure !== null) return;
738
- failure = error;
739
- if (waiter !== null) {
740
- const w = waiter;
741
- waiter = null;
742
- w.reject(error);
743
- }
744
- },
745
- next: () => {
746
- const message = queued.shift();
747
- if (message !== undefined) return Promise.resolve(message);
748
- if (failure !== null) return Promise.reject(failure);
749
- return new Promise<Uint8Array>((resolve, reject) => {
750
- waiter = { resolve, reject };
751
- });
752
- },
753
- drain: () => queued.shift(),
754
- size: () => queued.length,
755
- };
756
- };
757
-
758
- // ---------------------------------------------------------------------------
759
- // Carrier 1: message-oriented TDuplex
760
- // ---------------------------------------------------------------------------
761
-
762
- /**
763
- * Run a Noise_IK handshake over `duplex`, then return a {@link TDuplex} that
764
- * carries plaintext messages end-to-end encrypted. The returned duplex keeps
765
- * message boundaries; a message larger than one Noise message is split into
766
- * records and reassembled (up to {@link SECURE_DUPLEX_MAX_MESSAGE_BYTES}).
767
- *
768
- * Rejects with {@link SecureChannelError} (and closes `duplex`) when the
769
- * handshake fails. After it succeeds, an inbound message that fails AEAD
770
- * closes `duplex` and delivers `null` (peer gone) to the listener.
771
- *
772
- * Call it before the peer can send (it subscribes to `duplex.onBytes`).
773
- */
774
- export const secureDuplex = async (
775
- duplex: TDuplex,
776
- options: TSecureOptions & { readonly maxMessageBytes?: number },
777
- ): Promise<TSecureDuplex> => {
778
- const maxMessageBytes =
779
- options.maxMessageBytes ?? SECURE_DUPLEX_MAX_MESSAGE_BYTES;
780
- const inbox = createInbox();
781
- let phase: TSecurePhase = "handshake";
782
- let listener: ((bytes: Uint8Array | null) => void) | null = null;
783
- let keys: TTransportKeys | null = null;
784
- let receiveChain: Promise<void> = Promise.resolve();
785
- let sendChain: Promise<void> = Promise.resolve();
786
- let partial: Uint8Array[] = [];
787
- let partialBytes = 0;
788
-
789
- const pendingMessages: Array<Uint8Array | null> = [];
790
- const deliver = (bytes: Uint8Array | null): void => {
791
- if (listener === null) {
792
- pendingMessages.push(bytes);
793
- return;
794
- }
795
- try {
796
- listener(bytes);
797
- } catch {
798
- // A listener cannot destabilize the carrier.
799
- }
800
- };
801
- const die = (notify: boolean): void => {
802
- if (phase === "dead") return;
803
- phase = "dead";
804
- partial = [];
805
- duplex.close();
806
- if (notify) deliver(null);
807
- };
808
-
809
- const receiveRecord = async (ciphertext: Uint8Array): Promise<void> => {
810
- if (phase !== "open" || keys === null) return;
811
- let record: Uint8Array;
812
- try {
813
- record = await decryptWithAd(keys.receive, new Uint8Array(), ciphertext);
814
- } catch {
815
- die(true);
816
- return;
817
- }
818
- if (phase !== "open") return;
819
- const flag = record[0];
820
- if (
821
- record.byteLength < 1 ||
822
- (flag !== RECORD_MORE && flag !== RECORD_FINAL)
823
- ) {
824
- die(true);
825
- return;
826
- }
827
- const chunk = record.subarray(1);
828
- partialBytes += chunk.byteLength;
829
- if (partialBytes > maxMessageBytes) {
830
- die(true);
831
- return;
832
- }
833
- partial.push(chunk);
834
- if (flag === RECORD_MORE) return;
835
- const message = concatBytes(...partial);
836
- partial = [];
837
- partialBytes = 0;
838
- deliver(message);
839
- };
840
-
841
- duplex.onBytes((bytes) => {
842
- if (phase === "dead") return;
843
- if (bytes === null) {
844
- if (phase === "handshake") {
845
- inbox.fail(
846
- new SecureChannelError("closed", "peer closed during handshake"),
847
- );
848
- return;
849
- }
850
- receiveChain = receiveChain.then(() => {
851
- if (phase === "dead") return;
852
- phase = "dead";
853
- deliver(null);
854
- });
855
- return;
856
- }
857
- if (phase === "handshake") {
858
- if (inbox.size() >= SECURE_MAX_EARLY_MESSAGES) {
859
- inbox.fail(
860
- new SecureChannelError("malformed", "flooded during handshake"),
861
- );
862
- return;
863
- }
864
- inbox.push(new Uint8Array(bytes));
865
- return;
866
- }
867
- const copy = new Uint8Array(bytes);
868
- receiveChain = receiveChain.then(() => receiveRecord(copy));
869
- });
870
-
871
- const handshake = await runHandshake(
872
- { send: (message) => duplex.send(message), next: inbox.next },
873
- options,
874
- (error) => {
875
- inbox.fail(error);
876
- die(false);
877
- },
878
- );
879
- keys = handshake.keys;
880
- phase = "open";
881
- // Records that arrived right behind the last handshake message.
882
- for (;;) {
883
- const early = inbox.drain();
884
- if (early === undefined) break;
885
- receiveChain = receiveChain.then(() => receiveRecord(early));
886
- }
887
-
888
- const send = (bytes: Uint8Array): void => {
889
- if (phase !== "open" || keys === null) return;
890
- const transport = keys;
891
- const copy = new Uint8Array(bytes);
892
- sendChain = sendChain.then(async () => {
893
- let offset = 0;
894
- do {
895
- const end = Math.min(offset + DUPLEX_RECORD_PLAINTEXT, copy.byteLength);
896
- const flag = end < copy.byteLength ? RECORD_MORE : RECORD_FINAL;
897
- const record = concatBytes(
898
- new Uint8Array([flag]),
899
- copy.subarray(offset, end),
900
- );
901
- const ciphertext = await encryptWithAd(
902
- transport.send,
903
- new Uint8Array(),
904
- record,
905
- );
906
- if (phase !== "open") return;
907
- duplex.send(ciphertext);
908
- offset = end;
909
- } while (offset < copy.byteLength);
910
- });
911
- };
912
-
913
- return {
914
- send,
915
- bufferedAmount: duplex.bufferedAmount,
916
- highWaterMark: duplex.highWaterMark,
917
- onDrain: duplex.onDrain,
918
- onBytes: (callback) => {
919
- listener = callback;
920
- if (pendingMessages.length === 0) return;
921
- const queued = pendingMessages.splice(0);
922
- for (const message of queued) deliver(message);
923
- },
924
- close: () => {
925
- die(false);
926
- },
927
- remoteStatic: handshake.remoteStatic,
928
- peerPayload: handshake.peerPayload,
929
- handshakeHash: handshake.handshakeHash,
930
- };
931
- };
932
-
933
- // ---------------------------------------------------------------------------
934
- // Carrier 2: one mux stream (the agent path over the relay)
935
- // ---------------------------------------------------------------------------
936
-
937
- export type TSecureMuxStreamOptions = TSecureOptions & {
938
- /** RESET code sent when the handshake fails. Defaults to `unauthorized`. */
939
- readonly handshakeResetCode?: TStreamResetCode;
940
- };
941
-
942
- /** Append the Noise spec's 2-byte big-endian length prefix. */
943
- const lengthPrefixed = (message: Uint8Array): Uint8Array => {
944
- const out = new Uint8Array(LENGTH_PREFIX_BYTES + message.byteLength);
945
- new DataView(out.buffer).setUint16(0, message.byteLength, false);
946
- out.set(message, LENGTH_PREFIX_BYTES);
947
- return out;
948
- };
949
-
950
- /** Reassemble length-prefixed records from an arbitrarily chunked byte stream. */
951
- const createRecordReader = (): {
952
- readonly push: (bytes: Uint8Array) => void;
953
- readonly next: () => Uint8Array | null;
954
- readonly buffered: () => number;
955
- } => {
956
- let buffer: Uint8Array = new Uint8Array();
957
- return {
958
- push: (bytes) => {
959
- buffer =
960
- buffer.byteLength === 0
961
- ? new Uint8Array(bytes)
962
- : concatBytes(buffer, bytes);
963
- },
964
- next: () => {
965
- if (buffer.byteLength < LENGTH_PREFIX_BYTES) return null;
966
- const length = new DataView(
967
- buffer.buffer,
968
- buffer.byteOffset,
969
- LENGTH_PREFIX_BYTES,
970
- ).getUint16(0, false);
971
- const end = LENGTH_PREFIX_BYTES + length;
972
- if (buffer.byteLength < end) return null;
973
- const record = buffer.slice(LENGTH_PREFIX_BYTES, end);
974
- buffer = buffer.slice(end);
975
- return record;
976
- },
977
- buffered: () => buffer.byteLength,
978
- };
979
- };
980
-
981
- const emitAll = <T>(
982
- handlers: ReadonlySet<T>,
983
- invoke: (handler: T) => void,
984
- ): void => {
985
- for (const handler of handlers) {
986
- try {
987
- invoke(handler);
988
- } catch {
989
- // Handlers cannot destabilize the secure carrier.
990
- }
991
- }
992
- };
993
-
994
- /**
995
- * Run a Noise_IK handshake over one mux stream's DATA, then return a
996
- * {@link TMuxStream} whose DATA and CTRL are end-to-end encrypted. Hand the
997
- * result to the unchanged stream helpers (`acceptAgentStream`,
998
- * `pumpAgentCommands`, `sendAgentEvent`, …) in place of the raw stream.
999
- *
1000
- * Call it synchronously from the OPEN handler (serving side) or right after
1001
- * `openStream` (consumer side), before the first `await`: it subscribes to
1002
- * the stream's DATA, and the peer may already be sending.
1003
- *
1004
- * - Handshake failure: RESETs the stream with `handshakeResetCode`
1005
- * (`unauthorized`) and rejects with {@link SecureChannelError}.
1006
- * - After the handshake, a record or CTRL that fails AEAD (relay tampering,
1007
- * reordering, replay, truncation at END) RESETs `protocol_error`.
1008
- * - RESET payloads, END and WINDOW stay plaintext; CTRL from the peer that
1009
- * arrives before the handshake completes is dropped.
1010
- * - Receive credit is returned to the underlying stream only after a record
1011
- * is decrypted and delivered; `consume` on the wrapper is a no-op.
1012
- */
1013
- export const secureMuxStream = async (
1014
- stream: TMuxStream,
1015
- options: TSecureMuxStreamOptions,
1016
- ): Promise<TSecureMuxStream> => {
1017
- const inbox = createInbox();
1018
- const reader = createRecordReader();
1019
- const dataHandlers = new Set<TMuxEventHandler>();
1020
- const endHandlers = new Set<() => void>();
1021
- const resetHandlers = new Set<TMuxEventHandler>();
1022
- const ctrlHandlers = new Set<TMuxEventHandler>();
1023
- // Plaintext that lands before the caller has registered a handler (the
1024
- // await of secureMuxStream returns, then the peer may already have sent).
1025
- const pendingData: Uint8Array[] = [];
1026
- const pendingCtrl: Uint8Array[] = [];
1027
- let phase: TSecurePhase = "handshake";
1028
- const currentPhase = (): TSecurePhase => phase;
1029
- let keys: TTransportKeys | null = null;
1030
- let receiveChain: Promise<void> = Promise.resolve();
1031
- let ctrlReceiveChain: Promise<void> = Promise.resolve();
1032
- let sendChain: Promise<void> = Promise.resolve();
1033
-
1034
- const fail = (code: TStreamResetCode, message: string): void => {
1035
- if (phase === "dead") return;
1036
- if (phase === "handshake") {
1037
- inbox.fail(new SecureChannelError("malformed", message));
1038
- }
1039
- phase = "dead";
1040
- // A local reset fires the underlying onReset → our resetHandlers.
1041
- stream.reset(encodeJsonPayload({ code, message }));
1042
- };
1043
-
1044
- const emitData = (plaintext: Uint8Array): void => {
1045
- if (dataHandlers.size === 0) {
1046
- pendingData.push(plaintext);
1047
- return;
1048
- }
1049
- emitAll(dataHandlers, (handler) => handler(plaintext));
1050
- };
1051
- const emitCtrl = (plaintext: Uint8Array): void => {
1052
- if (ctrlHandlers.size === 0) {
1053
- pendingCtrl.push(plaintext);
1054
- return;
1055
- }
1056
- emitAll(ctrlHandlers, (handler) => handler(plaintext));
1057
- };
1058
-
1059
- const receiveRecord = async (record: Uint8Array): Promise<void> => {
1060
- if (phase !== "open" || keys === null) return;
1061
- let plaintext: Uint8Array;
1062
- try {
1063
- plaintext = await decryptWithAd(keys.receive, new Uint8Array(), record);
1064
- } catch {
1065
- fail("protocol_error", "secure stream integrity failure");
1066
- return;
1067
- }
1068
- if (phase !== "open") return;
1069
- emitData(plaintext);
1070
- stream.consume(LENGTH_PREFIX_BYTES + record.byteLength);
1071
- };
1072
-
1073
- const drainRecords = (): void => {
1074
- for (;;) {
1075
- const record = reader.next();
1076
- if (record === null) return;
1077
- if (phase === "handshake") {
1078
- if (inbox.size() >= SECURE_MAX_EARLY_MESSAGES) {
1079
- fail("protocol_error", "flooded during handshake");
1080
- return;
1081
- }
1082
- stream.consume(LENGTH_PREFIX_BYTES + record.byteLength);
1083
- inbox.push(record);
1084
- continue;
1085
- }
1086
- receiveChain = receiveChain.then(() => receiveRecord(record));
1087
- }
1088
- };
1089
-
1090
- const offData = stream.onData((bytes) => {
1091
- if (phase === "dead") return;
1092
- reader.push(bytes);
1093
- drainRecords();
1094
- // Credit is returned per record once it is delivered.
1095
- return false;
1096
- });
1097
- const offEnd = stream.onEnd(() => {
1098
- if (phase === "handshake") {
1099
- inbox.fail(
1100
- new SecureChannelError("closed", "peer ended during handshake"),
1101
- );
1102
- return;
1103
- }
1104
- receiveChain = receiveChain.then(() => {
1105
- if (phase !== "open") return;
1106
- if (reader.buffered() > 0) {
1107
- fail("protocol_error", "secure stream truncated");
1108
- return;
1109
- }
1110
- emitAll(endHandlers, (handler) => handler());
1111
- });
1112
- });
1113
- const offReset = stream.onReset((payload) => {
1114
- const wasHandshake = phase === "handshake";
1115
- phase = "dead";
1116
- if (wasHandshake) {
1117
- inbox.fail(
1118
- new SecureChannelError("closed", "stream reset during handshake"),
1119
- );
1120
- }
1121
- emitAll(resetHandlers, (handler) => handler(payload));
1122
- });
1123
- const receiveCtrl = (ciphertext: Uint8Array): void => {
1124
- ctrlReceiveChain = ctrlReceiveChain.then(async () => {
1125
- if (phase !== "open" || keys === null) return;
1126
- let plaintext: Uint8Array;
1127
- try {
1128
- plaintext = await decryptWithAd(
1129
- keys.ctrlReceive,
1130
- new Uint8Array(),
1131
- ciphertext,
1132
- );
1133
- } catch {
1134
- fail("protocol_error", "secure stream integrity failure");
1135
- return;
1136
- }
1137
- if (phase !== "open") return;
1138
- emitCtrl(plaintext);
1139
- });
1140
- };
1141
- // The peer finishes its side first and may send CTRL (e.g. `open_ack`)
1142
- // while this side is still processing the last handshake message.
1143
- const earlyCtrl: Uint8Array[] = [];
1144
- const offCtrl = stream.onCtrl((payload) => {
1145
- if (phase === "dead") return;
1146
- const copy = new Uint8Array(payload);
1147
- if (phase === "handshake") {
1148
- if (earlyCtrl.length >= SECURE_MAX_EARLY_CTRL) {
1149
- fail("protocol_error", "too much CTRL before the handshake finished");
1150
- return;
1151
- }
1152
- earlyCtrl.push(copy);
1153
- return;
1154
- }
1155
- receiveCtrl(copy);
1156
- });
1157
-
1158
- let handshake: THandshakeResult;
1159
- try {
1160
- handshake = await runHandshake(
1161
- {
1162
- send: (message) => {
1163
- void stream.write(lengthPrefixed(message)).catch(() => {});
1164
- },
1165
- next: inbox.next,
1166
- },
1167
- options,
1168
- (error) => {
1169
- inbox.fail(error);
1170
- fail(options.handshakeResetCode ?? "unauthorized", error.message);
1171
- },
1172
- );
1173
- } catch (error) {
1174
- offData();
1175
- offEnd();
1176
- offReset();
1177
- offCtrl();
1178
- throw error;
1179
- }
1180
- // `phase` is mutated by the stream callbacks while the handshake ran.
1181
- if (currentPhase() === "dead") {
1182
- throw new SecureChannelError("closed", "stream reset during handshake");
1183
- }
1184
- keys = handshake.keys;
1185
- phase = "open";
1186
- // Records that arrived right behind the last handshake message.
1187
- for (;;) {
1188
- const early = inbox.drain();
1189
- if (early === undefined) break;
1190
- // Already credited during the handshake phase; decrypt only.
1191
- receiveChain = receiveChain.then(async () => {
1192
- if (phase !== "open" || keys === null) return;
1193
- try {
1194
- const plaintext = await decryptWithAd(
1195
- keys.receive,
1196
- new Uint8Array(),
1197
- early,
1198
- );
1199
- if (phase === "open") emitData(plaintext);
1200
- } catch {
1201
- fail("protocol_error", "secure stream integrity failure");
1202
- }
1203
- });
1204
- }
1205
- for (const ctrl of earlyCtrl.splice(0)) receiveCtrl(ctrl);
1206
- const transport = keys;
1207
-
1208
- const write = (bytes: Uint8Array): Promise<void> => {
1209
- if (phase !== "open") return Promise.reject(new Error("stream is closed"));
1210
- if (bytes.byteLength === 0) return Promise.resolve();
1211
- const copy = new Uint8Array(bytes);
1212
- // Encrypt in call order and enqueue each record on the mux at once; the
1213
- // returned promise waits for the mux writes (flow-control backpressure)
1214
- // without holding later CTRL behind them.
1215
- const enqueued = sendChain.then(async () => {
1216
- const writes: Promise<void>[] = [];
1217
- for (
1218
- let offset = 0;
1219
- offset < copy.byteLength;
1220
- offset += STREAM_RECORD_PLAINTEXT
1221
- ) {
1222
- const ciphertext = await encryptWithAd(
1223
- transport.send,
1224
- new Uint8Array(),
1225
- copy.subarray(offset, offset + STREAM_RECORD_PLAINTEXT),
1226
- );
1227
- if (phase !== "open") throw new Error("stream is closed");
1228
- writes.push(stream.write(lengthPrefixed(ciphertext)));
1229
- }
1230
- return writes;
1231
- });
1232
- sendChain = enqueued.then(
1233
- () => undefined,
1234
- () => undefined,
1235
- );
1236
- return enqueued.then(async (writes) => {
1237
- await Promise.all(writes);
1238
- });
1239
- };
1240
-
1241
- return {
1242
- id: stream.id,
1243
- write,
1244
- end: () => {
1245
- sendChain = sendChain.then(() => {
1246
- if (phase === "open") stream.end();
1247
- });
1248
- },
1249
- reset: (payload) => {
1250
- phase = "dead";
1251
- stream.reset(payload);
1252
- },
1253
- sendCtrl: (payload) => {
1254
- if (phase !== "open") return;
1255
- const copy = new Uint8Array(payload);
1256
- sendChain = sendChain.then(async () => {
1257
- const ciphertext = await encryptWithAd(
1258
- transport.ctrlSend,
1259
- new Uint8Array(),
1260
- copy,
1261
- );
1262
- if (phase === "open") stream.sendCtrl(ciphertext);
1263
- });
1264
- },
1265
- consume: () => {},
1266
- onData: (handler) => {
1267
- dataHandlers.add(handler);
1268
- if (pendingData.length > 0) {
1269
- const queued = pendingData.splice(0);
1270
- for (const plaintext of queued) {
1271
- emitAll(dataHandlers, (h) => h(plaintext));
1272
- }
1273
- }
1274
- return () => dataHandlers.delete(handler);
1275
- },
1276
- onEnd: (handler) => {
1277
- endHandlers.add(handler);
1278
- return () => endHandlers.delete(handler);
1279
- },
1280
- onReset: (handler) => {
1281
- resetHandlers.add(handler);
1282
- return () => resetHandlers.delete(handler);
1283
- },
1284
- onCtrl: (handler) => {
1285
- ctrlHandlers.add(handler);
1286
- if (pendingCtrl.length > 0) {
1287
- const queued = pendingCtrl.splice(0);
1288
- for (const plaintext of queued) {
1289
- emitAll(ctrlHandlers, (h) => h(plaintext));
1290
- }
1291
- }
1292
- return () => ctrlHandlers.delete(handler);
1293
- },
1294
- remoteStatic: handshake.remoteStatic,
1295
- peerPayload: handshake.peerPayload,
1296
- handshakeHash: handshake.handshakeHash,
1297
- };
1298
- };