clinkx 1.1.2 → 1.3.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 (309) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +67 -14
  3. package/clinkx-workflows/dist/allowed-roots.js +2 -0
  4. package/clinkx-workflows/dist/allowed-roots.js.map +1 -1
  5. package/clinkx-workflows/dist/architecture-arena/admission.d.ts +16 -0
  6. package/clinkx-workflows/dist/architecture-arena/admission.js +107 -0
  7. package/clinkx-workflows/dist/architecture-arena/admission.js.map +1 -0
  8. package/clinkx-workflows/dist/architecture-arena/contract.d.ts +1368 -0
  9. package/clinkx-workflows/dist/architecture-arena/contract.js +254 -0
  10. package/clinkx-workflows/dist/architecture-arena/contract.js.map +1 -0
  11. package/clinkx-workflows/dist/architecture-arena/runtime.d.ts +53 -0
  12. package/clinkx-workflows/dist/architecture-arena/runtime.js +511 -0
  13. package/clinkx-workflows/dist/architecture-arena/runtime.js.map +1 -0
  14. package/clinkx-workflows/dist/architecture-comparison/admission.d.ts +17 -1
  15. package/clinkx-workflows/dist/architecture-comparison/admission.js +27 -4
  16. package/clinkx-workflows/dist/architecture-comparison/admission.js.map +1 -1
  17. package/clinkx-workflows/dist/architecture-comparison/contract.d.ts +59 -62
  18. package/clinkx-workflows/dist/architecture-comparison/contract.js +4 -21
  19. package/clinkx-workflows/dist/architecture-comparison/contract.js.map +1 -1
  20. package/clinkx-workflows/dist/architecture-comparison/runtime.d.ts +4 -3
  21. package/clinkx-workflows/dist/architecture-comparison/runtime.js +22 -67
  22. package/clinkx-workflows/dist/architecture-comparison/runtime.js.map +1 -1
  23. package/clinkx-workflows/dist/artifacts.d.ts +19 -4
  24. package/clinkx-workflows/dist/artifacts.js +16 -7
  25. package/clinkx-workflows/dist/artifacts.js.map +1 -1
  26. package/clinkx-workflows/dist/backend.d.ts +30 -0
  27. package/clinkx-workflows/dist/child-env.d.ts +3 -1
  28. package/clinkx-workflows/dist/child-env.js +6 -2
  29. package/clinkx-workflows/dist/child-env.js.map +1 -1
  30. package/clinkx-workflows/dist/clink-client.d.ts +8 -2
  31. package/clinkx-workflows/dist/clink-client.js +4 -2
  32. package/clinkx-workflows/dist/clink-client.js.map +1 -1
  33. package/clinkx-workflows/dist/config.d.ts +28 -5
  34. package/clinkx-workflows/dist/config.js +137 -20
  35. package/clinkx-workflows/dist/config.js.map +1 -1
  36. package/clinkx-workflows/dist/contained-file.js +9 -0
  37. package/clinkx-workflows/dist/contained-file.js.map +1 -1
  38. package/clinkx-workflows/dist/context-preflight.d.ts +6 -0
  39. package/clinkx-workflows/dist/context-preflight.js.map +1 -1
  40. package/clinkx-workflows/dist/council-execution-policy.d.ts +3 -1
  41. package/clinkx-workflows/dist/council-execution-policy.js +4 -0
  42. package/clinkx-workflows/dist/council-execution-policy.js.map +1 -1
  43. package/clinkx-workflows/dist/dashboard/contracts.d.ts +586 -586
  44. package/clinkx-workflows/dist/dashboard/progress-report-contract.d.ts +28 -28
  45. package/clinkx-workflows/dist/dashboard/session-log-contract.d.ts +32 -32
  46. package/clinkx-workflows/dist/dashboard/session-log-identity.js +2 -1
  47. package/clinkx-workflows/dist/dashboard/session-log-identity.js.map +1 -1
  48. package/clinkx-workflows/dist/dashboard-ui/assets/index-DRId2DVA.js +119 -0
  49. package/clinkx-workflows/dist/dashboard-ui/assets/style-CHAw57y5.css +1 -0
  50. package/clinkx-workflows/dist/dashboard-ui/index.html +2 -2
  51. package/clinkx-workflows/dist/delegate-signature.d.ts +4 -3
  52. package/clinkx-workflows/dist/delegate-signature.js +4 -3
  53. package/clinkx-workflows/dist/delegate-signature.js.map +1 -1
  54. package/clinkx-workflows/dist/durable-file.d.ts +69 -0
  55. package/clinkx-workflows/dist/durable-file.js +145 -0
  56. package/clinkx-workflows/dist/durable-file.js.map +1 -0
  57. package/clinkx-workflows/dist/engine.d.ts +42 -7
  58. package/clinkx-workflows/dist/engine.js +196 -24
  59. package/clinkx-workflows/dist/engine.js.map +1 -1
  60. package/clinkx-workflows/dist/ping-pong/admission.d.ts +127 -0
  61. package/clinkx-workflows/dist/ping-pong/admission.js +522 -0
  62. package/clinkx-workflows/dist/ping-pong/admission.js.map +1 -0
  63. package/clinkx-workflows/dist/ping-pong/contract.d.ts +2539 -0
  64. package/clinkx-workflows/dist/ping-pong/contract.js +819 -0
  65. package/clinkx-workflows/dist/ping-pong/contract.js.map +1 -0
  66. package/clinkx-workflows/dist/ping-pong/control.d.ts +67 -0
  67. package/clinkx-workflows/dist/ping-pong/control.js +12 -0
  68. package/clinkx-workflows/dist/ping-pong/control.js.map +1 -0
  69. package/clinkx-workflows/dist/ping-pong/runtime-handle.d.ts +24 -0
  70. package/clinkx-workflows/dist/ping-pong/runtime-handle.js +55 -0
  71. package/clinkx-workflows/dist/ping-pong/runtime-handle.js.map +1 -0
  72. package/clinkx-workflows/dist/ping-pong/runtime.d.ts +235 -0
  73. package/clinkx-workflows/dist/ping-pong/runtime.js +1183 -0
  74. package/clinkx-workflows/dist/ping-pong/runtime.js.map +1 -0
  75. package/clinkx-workflows/dist/ping-pong/settle.d.ts +57 -0
  76. package/clinkx-workflows/dist/ping-pong/settle.js +58 -0
  77. package/clinkx-workflows/dist/ping-pong/settle.js.map +1 -0
  78. package/clinkx-workflows/dist/ping-pong/sidecar.d.ts +65 -0
  79. package/clinkx-workflows/dist/ping-pong/sidecar.js +138 -0
  80. package/clinkx-workflows/dist/ping-pong/sidecar.js.map +1 -0
  81. package/clinkx-workflows/dist/plan-review/publication.d.ts +2 -1
  82. package/clinkx-workflows/dist/plan-review/publication.js +5 -6
  83. package/clinkx-workflows/dist/plan-review/publication.js.map +1 -1
  84. package/clinkx-workflows/dist/plan-review/snapshot.d.ts +3 -2
  85. package/clinkx-workflows/dist/plan-review/snapshot.js +8 -8
  86. package/clinkx-workflows/dist/plan-review/snapshot.js.map +1 -1
  87. package/clinkx-workflows/dist/recipe-host.d.ts +315 -0
  88. package/clinkx-workflows/dist/recipe-host.js +183 -0
  89. package/clinkx-workflows/dist/recipe-host.js.map +1 -0
  90. package/clinkx-workflows/dist/recipe-seats.d.ts +96 -0
  91. package/clinkx-workflows/dist/recipe-seats.js +163 -0
  92. package/clinkx-workflows/dist/recipe-seats.js.map +1 -0
  93. package/clinkx-workflows/dist/recipe-shared/evidence.d.ts +67 -0
  94. package/clinkx-workflows/dist/recipe-shared/evidence.js +111 -0
  95. package/clinkx-workflows/dist/recipe-shared/evidence.js.map +1 -0
  96. package/clinkx-workflows/dist/reducers/index.d.ts +9 -1
  97. package/clinkx-workflows/dist/reducers/index.js +30 -0
  98. package/clinkx-workflows/dist/reducers/index.js.map +1 -1
  99. package/clinkx-workflows/dist/root-path-validation.d.ts +12 -0
  100. package/clinkx-workflows/dist/root-path-validation.js +63 -0
  101. package/clinkx-workflows/dist/root-path-validation.js.map +1 -0
  102. package/clinkx-workflows/dist/rosters.d.ts +1 -0
  103. package/clinkx-workflows/dist/rosters.js +16 -6
  104. package/clinkx-workflows/dist/rosters.js.map +1 -1
  105. package/clinkx-workflows/dist/run-lock-reclaim.d.ts +44 -0
  106. package/clinkx-workflows/dist/run-lock-reclaim.js +86 -0
  107. package/clinkx-workflows/dist/run-lock-reclaim.js.map +1 -0
  108. package/clinkx-workflows/dist/server.js +5 -2
  109. package/clinkx-workflows/dist/server.js.map +1 -1
  110. package/clinkx-workflows/dist/state-schema.d.ts +24 -0
  111. package/clinkx-workflows/dist/state-schema.js +4 -1
  112. package/clinkx-workflows/dist/state-schema.js.map +1 -1
  113. package/clinkx-workflows/dist/state.d.ts +185 -4
  114. package/clinkx-workflows/dist/state.js +684 -88
  115. package/clinkx-workflows/dist/state.js.map +1 -1
  116. package/clinkx-workflows/dist/transport.d.ts +2 -1
  117. package/clinkx-workflows/dist/transport.js +5 -0
  118. package/clinkx-workflows/dist/transport.js.map +1 -1
  119. package/clinkx-workflows/dist/validators/architecture-arena.d.ts +6 -0
  120. package/clinkx-workflows/dist/validators/architecture-arena.js +16 -0
  121. package/clinkx-workflows/dist/validators/architecture-arena.js.map +1 -0
  122. package/clinkx-workflows/dist/validators/index.js +4 -0
  123. package/clinkx-workflows/dist/validators/index.js.map +1 -1
  124. package/clinkx-workflows/dist/validators/ping-pong.d.ts +6 -0
  125. package/clinkx-workflows/dist/validators/ping-pong.js +10 -0
  126. package/clinkx-workflows/dist/validators/ping-pong.js.map +1 -0
  127. package/clinkx-workflows/dist/workflow-completion.d.ts +83 -0
  128. package/clinkx-workflows/dist/workflow-completion.js +250 -0
  129. package/clinkx-workflows/dist/workflow-completion.js.map +1 -0
  130. package/clinkx-workflows/dist/workflow-tools.d.ts +53 -6
  131. package/clinkx-workflows/dist/workflow-tools.js +1123 -65
  132. package/clinkx-workflows/dist/workflow-tools.js.map +1 -1
  133. package/clinkx-workflows/dist/workflow-verification-contract.d.ts +4 -4
  134. package/clinkx-workflows/templates/architecture-arena/candidate.txt +39 -0
  135. package/clinkx-workflows/templates/architecture-arena/judge.txt +34 -0
  136. package/clinkx-workflows/templates/ping-pong/implement.txt +14 -0
  137. package/clinkx-workflows/templates/ping-pong/remediate.txt +14 -0
  138. package/clinkx-workflows/templates/ping-pong/review.txt +27 -0
  139. package/clinkx-workflows/workflows/architecture-arena.yaml +127 -0
  140. package/clinkx-workflows/workflows/ping-pong.yaml +158 -0
  141. package/dist/allowed-roots.d.ts +1 -1
  142. package/dist/allowed-roots.js +124 -14
  143. package/dist/allowed-roots.js.map +1 -1
  144. package/dist/context-builder/bundle.js +4 -3
  145. package/dist/context-builder/bundle.js.map +1 -1
  146. package/dist/context-builder/config.d.ts +1 -0
  147. package/dist/context-builder/config.js +21 -9
  148. package/dist/context-builder/config.js.map +1 -1
  149. package/dist/context-builder/delegate-packet.d.ts +1 -0
  150. package/dist/context-builder/delegate-packet.js +66 -7
  151. package/dist/context-builder/delegate-packet.js.map +1 -1
  152. package/dist/context-builder/delegate-validation.d.ts +12 -3
  153. package/dist/context-builder/delegate-validation.js +23 -13
  154. package/dist/context-builder/delegate-validation.js.map +1 -1
  155. package/dist/context-builder/external-gaps.d.ts +14 -3
  156. package/dist/context-builder/external-gaps.js +124 -18
  157. package/dist/context-builder/external-gaps.js.map +1 -1
  158. package/dist/context-builder/handler.js +108 -191
  159. package/dist/context-builder/handler.js.map +1 -1
  160. package/dist/context-builder/mutation-lock.d.ts +4 -0
  161. package/dist/context-builder/mutation-lock.js +7 -1
  162. package/dist/context-builder/mutation-lock.js.map +1 -1
  163. package/dist/context-builder/review-coverage.js +27 -1
  164. package/dist/context-builder/review-coverage.js.map +1 -1
  165. package/dist/context-builder/secrets.js +1 -1
  166. package/dist/context-builder/secrets.js.map +1 -1
  167. package/dist/context-builder/storage.d.ts +10 -2
  168. package/dist/context-builder/storage.js +213 -16
  169. package/dist/context-builder/storage.js.map +1 -1
  170. package/dist/context-builder/versions.d.ts +10 -4
  171. package/dist/context-builder/versions.js +10 -4
  172. package/dist/context-builder/versions.js.map +1 -1
  173. package/dist/context-builder/workflow-runner.js +33 -24
  174. package/dist/context-builder/workflow-runner.js.map +1 -1
  175. package/dist/dashboard-cli.d.ts +8 -0
  176. package/dist/dashboard-cli.js +155 -86
  177. package/dist/dashboard-cli.js.map +1 -1
  178. package/dist/dashboard-companion/client.d.ts +10 -0
  179. package/dist/dashboard-companion/client.js +43 -1
  180. package/dist/dashboard-companion/client.js.map +1 -1
  181. package/dist/dashboard-companion/config.d.ts +19 -1
  182. package/dist/dashboard-companion/config.js +104 -3
  183. package/dist/dashboard-companion/config.js.map +1 -1
  184. package/dist/dashboard-companion/protocol.d.ts +16 -0
  185. package/dist/dashboard-companion/protocol.js +38 -1
  186. package/dist/dashboard-companion/protocol.js.map +1 -1
  187. package/dist/dashboard-companion/workstation-binding.d.ts +69 -0
  188. package/dist/dashboard-companion/workstation-binding.js +192 -0
  189. package/dist/dashboard-companion/workstation-binding.js.map +1 -0
  190. package/dist/dashboard-gateway/admin-cli.d.ts +10 -0
  191. package/dist/dashboard-gateway/admin-cli.js +266 -0
  192. package/dist/dashboard-gateway/admin-cli.js.map +1 -0
  193. package/dist/dashboard-gateway/config.d.ts +50 -0
  194. package/dist/dashboard-gateway/config.js +235 -1
  195. package/dist/dashboard-gateway/config.js.map +1 -1
  196. package/dist/dashboard-gateway/connection-registry.d.ts +100 -0
  197. package/dist/dashboard-gateway/connection-registry.js +228 -0
  198. package/dist/dashboard-gateway/connection-registry.js.map +1 -0
  199. package/dist/dashboard-gateway/control-plane/account-auth.d.ts +78 -0
  200. package/dist/dashboard-gateway/control-plane/account-auth.js +198 -0
  201. package/dist/dashboard-gateway/control-plane/account-auth.js.map +1 -0
  202. package/dist/dashboard-gateway/control-plane/billing.d.ts +264 -0
  203. package/dist/dashboard-gateway/control-plane/billing.js +787 -0
  204. package/dist/dashboard-gateway/control-plane/billing.js.map +1 -0
  205. package/dist/dashboard-gateway/control-plane/contracts.d.ts +1293 -0
  206. package/dist/dashboard-gateway/control-plane/contracts.js +280 -0
  207. package/dist/dashboard-gateway/control-plane/contracts.js.map +1 -0
  208. package/dist/dashboard-gateway/control-plane/cookies.d.ts +13 -0
  209. package/dist/dashboard-gateway/control-plane/cookies.js +46 -0
  210. package/dist/dashboard-gateway/control-plane/cookies.js.map +1 -0
  211. package/dist/dashboard-gateway/control-plane/credentials.d.ts +63 -0
  212. package/dist/dashboard-gateway/control-plane/credentials.js +66 -0
  213. package/dist/dashboard-gateway/control-plane/credentials.js.map +1 -0
  214. package/dist/dashboard-gateway/control-plane/entitlements.d.ts +118 -0
  215. package/dist/dashboard-gateway/control-plane/entitlements.js +329 -0
  216. package/dist/dashboard-gateway/control-plane/entitlements.js.map +1 -0
  217. package/dist/dashboard-gateway/control-plane/errors.d.ts +17 -0
  218. package/dist/dashboard-gateway/control-plane/errors.js +23 -0
  219. package/dist/dashboard-gateway/control-plane/errors.js.map +1 -0
  220. package/dist/dashboard-gateway/control-plane/hosts.d.ts +6 -0
  221. package/dist/dashboard-gateway/control-plane/hosts.js +16 -0
  222. package/dist/dashboard-gateway/control-plane/hosts.js.map +1 -0
  223. package/dist/dashboard-gateway/control-plane/http.d.ts +34 -0
  224. package/dist/dashboard-gateway/control-plane/http.js +331 -0
  225. package/dist/dashboard-gateway/control-plane/http.js.map +1 -0
  226. package/dist/dashboard-gateway/control-plane/schema.d.ts +9 -0
  227. package/dist/dashboard-gateway/control-plane/schema.js +247 -0
  228. package/dist/dashboard-gateway/control-plane/schema.js.map +1 -0
  229. package/dist/dashboard-gateway/control-plane/secrets.d.ts +20 -0
  230. package/dist/dashboard-gateway/control-plane/secrets.js +39 -0
  231. package/dist/dashboard-gateway/control-plane/secrets.js.map +1 -0
  232. package/dist/dashboard-gateway/control-plane/store.d.ts +579 -0
  233. package/dist/dashboard-gateway/control-plane/store.js +1115 -0
  234. package/dist/dashboard-gateway/control-plane/store.js.map +1 -0
  235. package/dist/dashboard-gateway/cookie-boundary.d.ts +60 -0
  236. package/dist/dashboard-gateway/cookie-boundary.js +205 -0
  237. package/dist/dashboard-gateway/cookie-boundary.js.map +1 -0
  238. package/dist/dashboard-gateway/index.js +271 -494
  239. package/dist/dashboard-gateway/index.js.map +1 -1
  240. package/dist/dashboard-gateway/main.js +7 -2
  241. package/dist/dashboard-gateway/main.js.map +1 -1
  242. package/dist/dashboard-gateway/routing.d.ts +43 -0
  243. package/dist/dashboard-gateway/routing.js +65 -0
  244. package/dist/dashboard-gateway/routing.js.map +1 -0
  245. package/dist/dashboard-gateway/tenant-gateway.d.ts +56 -0
  246. package/dist/dashboard-gateway/tenant-gateway.js +989 -0
  247. package/dist/dashboard-gateway/tenant-gateway.js.map +1 -0
  248. package/dist/dashboard-gateway/tenant-main.d.ts +41 -0
  249. package/dist/dashboard-gateway/tenant-main.js +303 -0
  250. package/dist/dashboard-gateway/tenant-main.js.map +1 -0
  251. package/dist/dashboard-gateway/tunnel-errors.d.ts +16 -0
  252. package/dist/dashboard-gateway/tunnel-errors.js +22 -0
  253. package/dist/dashboard-gateway/tunnel-errors.js.map +1 -0
  254. package/dist/dashboard-gateway/tunnel-http.d.ts +21 -0
  255. package/dist/dashboard-gateway/tunnel-http.js +175 -0
  256. package/dist/dashboard-gateway/tunnel-http.js.map +1 -0
  257. package/dist/handler.d.ts +6 -0
  258. package/dist/handler.js +17 -1
  259. package/dist/handler.js.map +1 -1
  260. package/dist/local-clink-backend.d.ts +2 -1
  261. package/dist/local-clink-backend.js +28 -4
  262. package/dist/local-clink-backend.js.map +1 -1
  263. package/dist/parsers/extract.d.ts +19 -1
  264. package/dist/parsers/extract.js +68 -3
  265. package/dist/parsers/extract.js.map +1 -1
  266. package/dist/pipeline.d.ts +17 -1
  267. package/dist/pipeline.js +34 -6
  268. package/dist/pipeline.js.map +1 -1
  269. package/dist/process-group.d.ts +65 -0
  270. package/dist/process-group.js +153 -0
  271. package/dist/process-group.js.map +1 -0
  272. package/dist/progress-report/schema.d.ts +23 -23
  273. package/dist/project-verification/files.js +1 -1
  274. package/dist/project-verification/files.js.map +1 -1
  275. package/dist/project-verification/process.js +23 -44
  276. package/dist/project-verification/process.js.map +1 -1
  277. package/dist/project-verification/service.js +9 -1
  278. package/dist/project-verification/service.js.map +1 -1
  279. package/dist/prompt.d.ts +7 -0
  280. package/dist/prompt.js +18 -1
  281. package/dist/prompt.js.map +1 -1
  282. package/dist/recipe-host/git-trust.d.ts +43 -0
  283. package/dist/recipe-host/git-trust.js +360 -0
  284. package/dist/recipe-host/git-trust.js.map +1 -0
  285. package/dist/recipe-host/git.d.ts +42 -0
  286. package/dist/recipe-host/git.js +207 -0
  287. package/dist/recipe-host/git.js.map +1 -0
  288. package/dist/recipe-host/native-recipe-host.d.ts +127 -0
  289. package/dist/recipe-host/native-recipe-host.js +880 -0
  290. package/dist/recipe-host/native-recipe-host.js.map +1 -0
  291. package/dist/recipe-host/seat-cwd.d.ts +16 -0
  292. package/dist/recipe-host/seat-cwd.js +170 -0
  293. package/dist/recipe-host/seat-cwd.js.map +1 -0
  294. package/dist/registry.d.ts +1 -1
  295. package/dist/registry.js +5 -1
  296. package/dist/registry.js.map +1 -1
  297. package/dist/runner.d.ts +43 -1
  298. package/dist/runner.js +234 -35
  299. package/dist/runner.js.map +1 -1
  300. package/dist/server.js +21 -6
  301. package/dist/server.js.map +1 -1
  302. package/docs/configuration.md +181 -15
  303. package/docs/engineering-recipes.md +291 -0
  304. package/docs/security.md +87 -0
  305. package/docs/verification/project-checks.md +24 -2
  306. package/package.json +5 -1
  307. package/scripts/provider-doctor-core.mjs +21 -5
  308. package/clinkx-workflows/dist/dashboard-ui/assets/index-BdpmbPps.js +0 -115
  309. package/clinkx-workflows/dist/dashboard-ui/assets/style-Im5i1iAs.css +0 -1
@@ -0,0 +1,989 @@
1
+ import { randomInt, randomUUID } from "node:crypto";
2
+ import { createServer, } from "node:http";
3
+ import { WebSocketServer } from "ws";
4
+ import { DASHBOARD_GATEWAY_V2_SUBPROTOCOL, formatGatewayV2Hello, isForwardableV2PostPath, parseGatewayV2Request, parseGatewayV2Response, } from "../dashboard-companion/protocol.js";
5
+ import { ConnectionRegistry, } from "./connection-registry.js";
6
+ import { CONTROL_ERROR_HTTP_STATUS, CONTROL_PATH_PREFIX } from "./control-plane/contracts.js";
7
+ import { createControlPlaneHttpHandler, } from "./control-plane/http.js";
8
+ import { filterBrowserCookieHeaderForWorkstation, filterCompanionSetCookiesForWorkstation, } from "./cookie-boundary.js";
9
+ import { OBSERVED_CONTEXT_HEADER, REQUEST_CONTEXT_HEADER, WORKSTATION_HEADER, formatRequestContext, isClinkxHeader, isPublicHost, observedContextMatches, parseObservedContext, parseWorkstationHeader, publicOriginAllowed, } from "./routing.js";
10
+ import { TUNNEL_CONTEXT_MISMATCH, TUNNEL_UNAUTHENTICATED } from "./tunnel-errors.js";
11
+ import { COMPANION_UNAVAILABLE, DEFAULT_PING_INTERVAL_MS, DEFAULT_REQUEST_TIMEOUT_MS, MAX_AGENT_FRAME_BYTES, MAX_FORWARD_HEADER_BYTES, MAX_V2_IN_FLIGHT, OUTCOME_UNKNOWN, PASSKEY_COMPANION_UNAVAILABLE, isAllowedApiTarget, readV2RequestBody, rejectUpgrade, sendJson, sendText, v2PostBodyLimit, v2RequestHeaders, v2ResponseHeaders, } from "./tunnel-http.js";
12
+ const DEFAULT_UPGRADE_CLAIM_TIMEOUT_MS = 10_000;
13
+ // One check for the current access epoch plus one superseded by an epoch bump.
14
+ const MAX_ACCESS_CHECKS_PER_TENANT = 2;
15
+ const ACCESS_UNAVAILABLE = { ok: false, code: "store_unavailable" };
16
+ const DEVICE_BEARER_PREFIX = "Bearer ";
17
+ const CLOSE_REASON_PATTERN = /^[A-Za-z0-9_ .-]{1,64}$/;
18
+ const DEFAULT_CLOSE_REASON = "access changed";
19
+ const WORKSTATION_CLOSE_REASON = "credential revoked";
20
+ // Rendered by the gateway from a typed V2 field and carries no authority; every
21
+ // other X-Clinkx-* response header is gateway-owned.
22
+ const COMPANION_CLINKX_RESPONSE_HEADERS = new Set(["x-clinkx-validator-schema-id"]);
23
+ const UPGRADE_REASONS = {
24
+ 401: "Unauthorized",
25
+ 402: "Payment Required",
26
+ 404: "Not Found",
27
+ 409: "Conflict",
28
+ 421: "Misdirected Request",
29
+ 426: "Upgrade Required",
30
+ 503: "Service Unavailable",
31
+ };
32
+ function rejectTenantUpgrade(socket, status) {
33
+ if (socket.destroyed || !socket.writable)
34
+ return;
35
+ rejectUpgrade(socket, status, UPGRADE_REASONS[status] ?? "Bad Request");
36
+ }
37
+ function sendControlError(response, code) {
38
+ const body = `${JSON.stringify({ error: { code } })}\n`;
39
+ response.writeHead(CONTROL_ERROR_HTTP_STATUS[code], {
40
+ "cache-control": "no-store",
41
+ "content-type": "application/json; charset=utf-8",
42
+ "content-length": Buffer.byteLength(body),
43
+ "referrer-policy": "no-referrer",
44
+ "x-content-type-options": "nosniff",
45
+ });
46
+ response.end(body);
47
+ }
48
+ function deviceSecret(values) {
49
+ if (values === undefined || values.length !== 1)
50
+ return null;
51
+ const header = values[0] ?? "";
52
+ return header.startsWith(DEVICE_BEARER_PREFIX) ? header.slice(DEVICE_BEARER_PREFIX.length) : null;
53
+ }
54
+ function offersV2(request) {
55
+ return request.headersDistinct["sec-websocket-protocol"]?.some((value) => value.split(",").some((protocol) => protocol.trim() === DASHBOARD_GATEWAY_V2_SUBPROTOCOL)) ?? false;
56
+ }
57
+ function isLive(response) {
58
+ return !response.destroyed && !response.writableEnded;
59
+ }
60
+ function stripCompanionClinkxHeaders(headers) {
61
+ return Object.fromEntries(Object.entries(headers).filter(([name]) => !isClinkxHeader(name) || COMPANION_CLINKX_RESPONSE_HEADERS.has(name.toLowerCase())));
62
+ }
63
+ const TUNNELED_RESPONSE_CSP = "default-src 'none'; sandbox; frame-ancestors 'none'";
64
+ /** Set before any exit, including host routing, so gateway-authored errors carry the same protection as companion responses. */
65
+ function setTunneledSecurityHeaders(response) {
66
+ response.setHeader("x-content-type-options", "nosniff");
67
+ response.setHeader("content-security-policy", TUNNELED_RESPONSE_CSP);
68
+ response.setHeader("referrer-policy", "no-referrer");
69
+ }
70
+ /**
71
+ * Every workstation shares the public origin with the hosted UI, so a
72
+ * companion response must never run as a document or be sniffed into one.
73
+ * The two fixed values are the strictest their headers allow; a companion
74
+ * CSP, if one is ever allowed through, is kept beside ours because browsers
75
+ * enforce every policy given.
76
+ */
77
+ function withTunneledSecurityHeaders(headers) {
78
+ const merged = { ...headers };
79
+ const existing = merged["content-security-policy"];
80
+ const companionPolicies = existing === undefined ? [] : Array.isArray(existing) ? existing : [String(existing)];
81
+ merged["content-security-policy"] =
82
+ companionPolicies.length === 0 ? TUNNELED_RESPONSE_CSP : [...companionPolicies, TUNNELED_RESPONSE_CSP];
83
+ merged["x-content-type-options"] = "nosniff";
84
+ merged["referrer-policy"] = "no-referrer";
85
+ return merged;
86
+ }
87
+ /**
88
+ * Hosted gateway for tenant mode on one public origin. The account session
89
+ * decides the workspace; `X-Clinkx-Workstation` only selects one of its live
90
+ * workstations and is never a source of authority. Each companion is
91
+ * authenticated by its API key, whose record supplies tenant and workstation.
92
+ * Every tunneled route, including local auth and status routes, requires the
93
+ * session, and session, workstation, and access are re-checked after every
94
+ * asynchronous wait before the companion is contacted and before its response
95
+ * is released.
96
+ */
97
+ export function createTenantDashboardGateway(options) {
98
+ const { publicOrigin, accountAuth, credentials } = options;
99
+ const publicHost = new URL(publicOrigin).host;
100
+ if (typeof options.checkTenantAccess !== "function") {
101
+ throw new Error("Tenant dashboard gateway requires a tenant access check");
102
+ }
103
+ const checkTenantAccess = options.checkTenantAccess;
104
+ const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
105
+ const pingIntervalMs = options.pingIntervalMs ?? DEFAULT_PING_INTERVAL_MS;
106
+ const upgradeClaimTimeoutMs = options.upgradeClaimTimeoutMs ?? DEFAULT_UPGRADE_CLAIM_TIMEOUT_MS;
107
+ for (const [label, value] of [
108
+ ["request timeout", requestTimeoutMs],
109
+ ["ping interval", pingIntervalMs],
110
+ ["upgrade claim timeout", upgradeClaimTimeoutMs],
111
+ ]) {
112
+ if (!Number.isSafeInteger(value) || value <= 0) {
113
+ throw new Error(`Tenant dashboard gateway ${label} must be a positive integer`);
114
+ }
115
+ }
116
+ const pongDeadlineMs = pingIntervalMs * 2;
117
+ const registry = new ConnectionRegistry((socket) => socket.websocket.readyState === 1, options.generationSource ?? (() => randomInt(1, 2 ** 48)));
118
+ const live = new Set();
119
+ const pendingUpgrades = new Set();
120
+ const accessEpochs = new Map();
121
+ const tenantReservations = new Map();
122
+ let closing = false;
123
+ const reportError = (error) => {
124
+ try {
125
+ options.onError?.(error);
126
+ }
127
+ catch {
128
+ // Diagnostics must never change a response.
129
+ }
130
+ };
131
+ const accessFlights = new Map();
132
+ const accessCapacityWaiters = new Map();
133
+ const startAccessFlight = (tenantId, epoch) => {
134
+ const flight = { epoch, waiters: new Set() };
135
+ accessFlights.set(tenantId, [...(accessFlights.get(tenantId) ?? []), flight]);
136
+ const settle = (decision) => {
137
+ const remaining = (accessFlights.get(tenantId) ?? []).filter((candidate) => candidate !== flight);
138
+ if (remaining.length === 0)
139
+ accessFlights.delete(tenantId);
140
+ else
141
+ accessFlights.set(tenantId, remaining);
142
+ const current = (accessEpochs.get(tenantId) ?? 0) === flight.epoch;
143
+ const waiters = [...flight.waiters];
144
+ flight.waiters.clear();
145
+ for (const waiter of waiters) {
146
+ if (current)
147
+ waiter.deliver(decision);
148
+ else
149
+ waiter.rejoin();
150
+ }
151
+ const queued = accessCapacityWaiters.get(tenantId);
152
+ accessCapacityWaiters.delete(tenantId);
153
+ for (const wake of queued ?? [])
154
+ wake();
155
+ };
156
+ void Promise.resolve()
157
+ .then(() => checkTenantAccess(tenantId))
158
+ .then((decision) => settle(decision.ok ? { ok: true } : { ok: false, code: decision.code }), (error) => {
159
+ reportError(error);
160
+ settle(ACCESS_UNAVAILABLE);
161
+ });
162
+ return flight;
163
+ };
164
+ /**
165
+ * Single-flight access check: callers share the tenant's in-flight check for
166
+ * the current access epoch, and a result is never reused after it settles.
167
+ * A check that settles after an epoch bump is not delivered; its waiters join
168
+ * a check for the new epoch. A caller whose signal aborts stops waiting
169
+ * without starting or cancelling any check.
170
+ */
171
+ const checkAccess = (tenantId, signal) => new Promise((resolve) => {
172
+ if (signal.aborted) {
173
+ resolve(ACCESS_UNAVAILABLE);
174
+ return;
175
+ }
176
+ let detach = () => undefined;
177
+ const onAbort = () => {
178
+ detach();
179
+ resolve(ACCESS_UNAVAILABLE);
180
+ };
181
+ signal.addEventListener("abort", onAbort, { once: true });
182
+ const join = () => {
183
+ if (closing) {
184
+ signal.removeEventListener("abort", onAbort);
185
+ resolve(ACCESS_UNAVAILABLE);
186
+ return;
187
+ }
188
+ const epoch = accessEpochs.get(tenantId) ?? 0;
189
+ const flights = accessFlights.get(tenantId) ?? [];
190
+ let flight = flights.find((candidate) => candidate.epoch === epoch);
191
+ if (flight === undefined) {
192
+ if (flights.length >= MAX_ACCESS_CHECKS_PER_TENANT) {
193
+ const queued = accessCapacityWaiters.get(tenantId) ?? new Set();
194
+ queued.add(join);
195
+ accessCapacityWaiters.set(tenantId, queued);
196
+ detach = () => {
197
+ queued.delete(join);
198
+ if (queued.size === 0 && accessCapacityWaiters.get(tenantId) === queued)
199
+ accessCapacityWaiters.delete(tenantId);
200
+ };
201
+ return;
202
+ }
203
+ flight = startAccessFlight(tenantId, epoch);
204
+ }
205
+ const joined = flight;
206
+ const waiter = {
207
+ deliver: (decision) => {
208
+ signal.removeEventListener("abort", onAbort);
209
+ resolve(decision);
210
+ },
211
+ rejoin: join,
212
+ };
213
+ joined.waiters.add(waiter);
214
+ detach = () => {
215
+ joined.waiters.delete(waiter);
216
+ };
217
+ };
218
+ join();
219
+ });
220
+ const memberOf = (cookieHeader) => {
221
+ try {
222
+ return accountAuth.resolveTenantMemberFromCookies(cookieHeader) ?? "denied";
223
+ }
224
+ catch (error) {
225
+ reportError(error);
226
+ return "unavailable";
227
+ }
228
+ };
229
+ /** The session must still resolve to `tenantId`, and `companionId` must still be one of its live workstations. */
230
+ const authorizeWorkstation = (cookieHeader, tenantId, companionId) => {
231
+ const member = memberOf(cookieHeader);
232
+ if (member === "unavailable")
233
+ return { ok: false, status: 503, code: "store_unavailable" };
234
+ if (member === "denied" || (tenantId !== null && member.tenant.id !== tenantId)) {
235
+ return { ok: false, status: TUNNEL_UNAUTHENTICATED.status, code: TUNNEL_UNAUTHENTICATED.code };
236
+ }
237
+ try {
238
+ if (credentials.findLiveWorkstation(member.tenant.id, companionId) === null) {
239
+ return { ok: false, status: 404, code: "workstation_not_found" };
240
+ }
241
+ }
242
+ catch (error) {
243
+ reportError(error);
244
+ return { ok: false, status: 503, code: "store_unavailable" };
245
+ }
246
+ return { ok: true, member };
247
+ };
248
+ const contextOf = (tenantId, companionId) => ({
249
+ tenantId,
250
+ companionId,
251
+ generation: companionId === null ? 0 : (registry.current(companionId)?.generation ?? 0),
252
+ });
253
+ const setContext = (response, context) => {
254
+ if (!response.headersSent)
255
+ response.setHeader(REQUEST_CONTEXT_HEADER, formatRequestContext(context));
256
+ };
257
+ const finish = (connection, id, outcome) => {
258
+ const settled = registry.settle(connection, id, outcome);
259
+ if (settled === undefined)
260
+ return undefined;
261
+ clearTimeout(settled.value.timeout);
262
+ settled.value.cancel.abort();
263
+ return settled.value;
264
+ };
265
+ const respondCompanionLost = (lost) => {
266
+ const item = lost.value;
267
+ if (!isLive(item.response))
268
+ return;
269
+ const uncertainMutation = lost.phase === "forwarded" && item.method !== "GET" && item.method !== "HEAD";
270
+ if (uncertainMutation)
271
+ sendJson(item.response, 502, OUTCOME_UNKNOWN);
272
+ else
273
+ sendJson(item.response, 503, item.unavailableError);
274
+ };
275
+ const failOwnerLost = (lost) => {
276
+ clearTimeout(lost.value.timeout);
277
+ lost.value.cancel.abort();
278
+ respondCompanionLost(lost);
279
+ };
280
+ const reserveTenantSlot = (tenantId) => {
281
+ const held = tenantReservations.get(tenantId) ?? 0;
282
+ if (held >= MAX_V2_IN_FLIGHT)
283
+ return undefined;
284
+ tenantReservations.set(tenantId, held + 1);
285
+ let released = false;
286
+ return () => {
287
+ if (released)
288
+ return;
289
+ released = true;
290
+ const remaining = (tenantReservations.get(tenantId) ?? 1) - 1;
291
+ if (remaining <= 0)
292
+ tenantReservations.delete(tenantId);
293
+ else
294
+ tenantReservations.set(tenantId, remaining);
295
+ };
296
+ };
297
+ const startDeadline = (connection, id, delayMs) => {
298
+ const timeout = setTimeout(() => {
299
+ const authorizing = registry.owned(connection, id)?.value.authorizing === true;
300
+ const item = finish(connection, id, "abandoned");
301
+ if (item !== undefined && isLive(item.response)) {
302
+ if (authorizing)
303
+ sendJson(item.response, 503, item.unavailableError);
304
+ else
305
+ sendJson(item.response, 504, "dashboard_companion_timeout");
306
+ }
307
+ }, Math.max(1, delayMs));
308
+ timeout.unref();
309
+ return timeout;
310
+ };
311
+ const forward = (connection, id, wireRequest) => {
312
+ const failSend = () => {
313
+ const lost = registry.settle(connection, id, "abandoned");
314
+ if (lost !== undefined)
315
+ failOwnerLost(lost);
316
+ };
317
+ if (!registry.markForwarded(connection, id)) {
318
+ failSend();
319
+ return;
320
+ }
321
+ try {
322
+ connection.socket.websocket.send(wireRequest, (error) => {
323
+ if (error)
324
+ failSend();
325
+ });
326
+ }
327
+ catch {
328
+ failSend();
329
+ }
330
+ };
331
+ const disconnect = (connection, reason) => {
332
+ live.delete(connection);
333
+ for (const lost of registry.detach(connection))
334
+ failOwnerLost(lost);
335
+ try {
336
+ connection.socket.websocket.close(1008, reason);
337
+ }
338
+ catch {
339
+ connection.socket.websocket.terminate();
340
+ }
341
+ };
342
+ const closeTenantConnections = (tenantId, reason) => {
343
+ accessEpochs.set(tenantId, (accessEpochs.get(tenantId) ?? 0) + 1);
344
+ const closeReason = CLOSE_REASON_PATTERN.test(reason) ? reason : DEFAULT_CLOSE_REASON;
345
+ let closed = 0;
346
+ for (const connection of [...live]) {
347
+ if (connection.socket.tenantId !== tenantId)
348
+ continue;
349
+ disconnect(connection, closeReason);
350
+ closed += 1;
351
+ }
352
+ return closed;
353
+ };
354
+ const closeWorkstationConnections = (companionId) => {
355
+ let closed = 0;
356
+ for (const connection of [...live]) {
357
+ if (connection.socket.companionId !== companionId)
358
+ continue;
359
+ disconnect(connection, WORKSTATION_CLOSE_REASON);
360
+ closed += 1;
361
+ }
362
+ return closed;
363
+ };
364
+ const workstationConnection = (companionId) => {
365
+ const connection = registry.current(companionId);
366
+ return connection === undefined ? null : { connectionGeneration: connection.generation };
367
+ };
368
+ const controlHandler = createControlPlaneHttpHandler({
369
+ publicOrigin,
370
+ accountAuth,
371
+ credentials,
372
+ entitlementStatus: options.entitlementStatus,
373
+ ...(options.maxControlBodyBytes === undefined ? {} : { maxBodyBytes: options.maxControlBodyBytes }),
374
+ ...(options.billing === undefined ? {} : { billing: options.billing }),
375
+ workstationConnection,
376
+ closeWorkstationConnections,
377
+ onError: (error) => reportError(error),
378
+ });
379
+ const handleControl = async (request, response) => {
380
+ const observed = parseObservedContext(request.headersDistinct[OBSERVED_CONTEXT_HEADER]);
381
+ const visible = memberOf(request.headers.cookie);
382
+ if (typeof visible === "object") {
383
+ const context = contextOf(visible.tenant.id, null);
384
+ setContext(response, context);
385
+ if (observed.kind === "invalid"
386
+ || (observed.kind === "present" && !observedContextMatches(observed.context, context, "tenant"))) {
387
+ request.resume();
388
+ sendControlError(response, "context_mismatch");
389
+ return;
390
+ }
391
+ }
392
+ await controlHandler(request, response);
393
+ };
394
+ const handleTunnel = async (request, response, method, path) => {
395
+ let clientGone = false;
396
+ let authorizationExpired = false;
397
+ response.once("close", () => {
398
+ clientGone = true;
399
+ });
400
+ const alive = () => !clientGone && !authorizationExpired && isLive(response);
401
+ const reject = (status, code) => {
402
+ request.resume();
403
+ sendJson(response, status, code);
404
+ };
405
+ const pathname = path.split("?", 1)[0] ?? "";
406
+ if (!isAllowedApiTarget(path) || pathname === "/api/control") {
407
+ reject(404, "not_found");
408
+ return;
409
+ }
410
+ const v2Post = method === "POST" && isForwardableV2PostPath(path);
411
+ if (!v2Post && method !== "GET" && method !== "HEAD") {
412
+ response.setHeader("allow", "GET, HEAD");
413
+ reject(405, "method_not_allowed");
414
+ return;
415
+ }
416
+ if (!v2Post) {
417
+ const contentLength = request.headers["content-length"];
418
+ if (request.headers["transfer-encoding"] !== undefined || (contentLength !== undefined && contentLength !== "0")) {
419
+ response.setHeader("connection", "close");
420
+ reject(413, "request_body_not_allowed");
421
+ return;
422
+ }
423
+ }
424
+ if (!publicOriginAllowed(request, method, publicOrigin)) {
425
+ reject(403, "forbidden");
426
+ return;
427
+ }
428
+ const cookieHeader = request.headers.cookie;
429
+ const member = memberOf(cookieHeader);
430
+ if (member === "unavailable") {
431
+ reject(503, "store_unavailable");
432
+ return;
433
+ }
434
+ if (member === "denied") {
435
+ reject(TUNNEL_UNAUTHENTICATED.status, TUNNEL_UNAUTHENTICATED.code);
436
+ return;
437
+ }
438
+ const tenantId = member.tenant.id;
439
+ setContext(response, contextOf(tenantId, null));
440
+ const selection = parseWorkstationHeader(request.headersDistinct[WORKSTATION_HEADER]);
441
+ if (selection.kind === "absent") {
442
+ reject(400, "workstation_required");
443
+ return;
444
+ }
445
+ if (selection.kind === "invalid") {
446
+ reject(404, "workstation_not_found");
447
+ return;
448
+ }
449
+ const companionId = selection.companionId;
450
+ const selected = authorizeWorkstation(cookieHeader, tenantId, companionId);
451
+ if (!selected.ok) {
452
+ reject(selected.status, selected.code);
453
+ return;
454
+ }
455
+ setContext(response, contextOf(tenantId, companionId));
456
+ const observed = parseObservedContext(request.headersDistinct[OBSERVED_CONTEXT_HEADER]);
457
+ if (observed.kind === "invalid") {
458
+ reject(TUNNEL_CONTEXT_MISMATCH.status, TUNNEL_CONTEXT_MISMATCH.code);
459
+ return;
460
+ }
461
+ const cookies = filterBrowserCookieHeaderForWorkstation(request.headersDistinct.cookie, companionId);
462
+ if (!cookies.ok) {
463
+ reject(cookies.status, cookies.code);
464
+ return;
465
+ }
466
+ const headers = v2RequestHeaders(request, v2Post ? "POST" : method, path, cookies.cookie);
467
+ if (headers === undefined) {
468
+ reject(400, "invalid_request");
469
+ return;
470
+ }
471
+ headers.host = publicHost;
472
+ const unavailableError = v2Post ? PASSKEY_COMPANION_UNAVAILABLE : COMPANION_UNAVAILABLE;
473
+ const releaseSlot = reserveTenantSlot(tenantId);
474
+ if (releaseSlot === undefined) {
475
+ reject(503, "dashboard_gateway_capacity_exceeded");
476
+ return;
477
+ }
478
+ const requestDeadlineAt = Date.now() + requestTimeoutMs;
479
+ const admissionWait = new AbortController();
480
+ const authorizationDeadline = setTimeout(() => {
481
+ admissionWait.abort();
482
+ if (!alive())
483
+ return;
484
+ authorizationExpired = true;
485
+ reject(503, unavailableError);
486
+ }, requestTimeoutMs);
487
+ authorizationDeadline.unref();
488
+ const release = () => {
489
+ clearTimeout(authorizationDeadline);
490
+ admissionWait.abort();
491
+ releaseSlot();
492
+ };
493
+ response.once("finish", release);
494
+ response.once("close", release);
495
+ const admissionAccess = await checkAccess(tenantId, admissionWait.signal);
496
+ if (!alive()) {
497
+ request.resume();
498
+ return;
499
+ }
500
+ if (!admissionAccess.ok) {
501
+ reject(CONTROL_ERROR_HTTP_STATUS[admissionAccess.code], admissionAccess.code);
502
+ return;
503
+ }
504
+ const stillSelected = authorizeWorkstation(cookieHeader, tenantId, companionId);
505
+ if (!stillSelected.ok) {
506
+ reject(stillSelected.status, stillSelected.code);
507
+ return;
508
+ }
509
+ const connection = registry.current(companionId);
510
+ const current = contextOf(tenantId, companionId);
511
+ setContext(response, current);
512
+ if (observed.kind === "present" && !observedContextMatches(observed.context, current, "tunnel")) {
513
+ reject(TUNNEL_CONTEXT_MISMATCH.status, TUNNEL_CONTEXT_MISMATCH.code);
514
+ return;
515
+ }
516
+ if (connection !== undefined && connection.socket.tenantId !== tenantId) {
517
+ reportError(new Error("companion connection is bound to another tenant"));
518
+ reject(503, unavailableError);
519
+ return;
520
+ }
521
+ if (connection === undefined || Date.now() >= requestDeadlineAt) {
522
+ reject(503, unavailableError);
523
+ return;
524
+ }
525
+ const id = randomUUID();
526
+ const cancel = new AbortController();
527
+ const timeout = startDeadline(connection, id, requestDeadlineAt - Date.now());
528
+ const pending = {
529
+ response,
530
+ method,
531
+ timeout,
532
+ cancel,
533
+ unavailableError,
534
+ cookieHeader,
535
+ tenantId,
536
+ companionId,
537
+ authorizing: false,
538
+ responding: false,
539
+ };
540
+ const admitted = registry.admit(connection, id, pending, MAX_V2_IN_FLIGHT);
541
+ if (admitted !== "admitted") {
542
+ clearTimeout(timeout);
543
+ reject(503, "dashboard_gateway_capacity_exceeded");
544
+ return;
545
+ }
546
+ clearTimeout(authorizationDeadline);
547
+ response.once("close", () => {
548
+ finish(connection, id, "abandoned");
549
+ });
550
+ const buildWire = (bodyBase64) => {
551
+ try {
552
+ return JSON.stringify(parseGatewayV2Request(JSON.stringify({
553
+ v: 2,
554
+ type: "request",
555
+ id,
556
+ method: v2Post ? "POST" : method,
557
+ path,
558
+ headers,
559
+ bodyBase64,
560
+ })));
561
+ }
562
+ catch {
563
+ return undefined;
564
+ }
565
+ };
566
+ if (!v2Post) {
567
+ const wireRequest = buildWire("");
568
+ if (wireRequest === undefined) {
569
+ finish(connection, id, "failed");
570
+ sendJson(response, 400, "invalid_request");
571
+ return;
572
+ }
573
+ forward(connection, id, wireRequest);
574
+ return;
575
+ }
576
+ const stillAdmitted = () => registry.owned(connection, id)?.phase === "admitted";
577
+ const failAdmitted = (status, code) => {
578
+ finish(connection, id, "failed");
579
+ if (alive())
580
+ sendJson(response, status, code);
581
+ };
582
+ const gateAfterWait = (afterAuthorization) => {
583
+ if (!stillAdmitted())
584
+ return false;
585
+ if (!alive()) {
586
+ finish(connection, id, "failed");
587
+ return false;
588
+ }
589
+ if (Date.now() >= requestDeadlineAt) {
590
+ if (afterAuthorization)
591
+ failAdmitted(503, unavailableError);
592
+ else
593
+ failAdmitted(504, "dashboard_companion_timeout");
594
+ return false;
595
+ }
596
+ const check = authorizeWorkstation(cookieHeader, tenantId, companionId);
597
+ if (!check.ok) {
598
+ failAdmitted(check.status, check.code);
599
+ return false;
600
+ }
601
+ return true;
602
+ };
603
+ try {
604
+ const body = await readV2RequestBody(request, v2PostBodyLimit(path), cancel.signal);
605
+ if (!gateAfterWait(false))
606
+ return;
607
+ if (body === undefined) {
608
+ failAdmitted(413, "payload_too_large");
609
+ return;
610
+ }
611
+ pending.authorizing = true;
612
+ const dispatchAccess = await checkAccess(tenantId, cancel.signal);
613
+ pending.authorizing = false;
614
+ if (!gateAfterWait(true))
615
+ return;
616
+ if (!dispatchAccess.ok) {
617
+ failAdmitted(CONTROL_ERROR_HTTP_STATUS[dispatchAccess.code], dispatchAccess.code);
618
+ return;
619
+ }
620
+ if (!registry.isCurrent(connection)) {
621
+ failAdmitted(503, PASSKEY_COMPANION_UNAVAILABLE);
622
+ return;
623
+ }
624
+ const wireRequest = buildWire(body.toString("base64"));
625
+ if (wireRequest === undefined) {
626
+ failAdmitted(400, "invalid_request");
627
+ return;
628
+ }
629
+ forward(connection, id, wireRequest);
630
+ }
631
+ catch {
632
+ if (finish(connection, id, "failed") === undefined)
633
+ return;
634
+ if (isLive(response))
635
+ sendJson(response, 400, "invalid_request");
636
+ }
637
+ };
638
+ const handleRequest = async (request, response) => {
639
+ const method = request.method ?? "";
640
+ const path = request.url ?? "";
641
+ if (method === "GET" && path === "/healthz") {
642
+ sendText(response, 200, "ok\n");
643
+ return;
644
+ }
645
+ const control = path.startsWith(CONTROL_PATH_PREFIX);
646
+ if (!control)
647
+ setTunneledSecurityHeaders(response);
648
+ if (!isPublicHost(request.headersDistinct.host, publicOrigin)) {
649
+ request.resume();
650
+ if (control)
651
+ sendControlError(response, "misdirected_request");
652
+ else
653
+ sendJson(response, 421, "misdirected_request");
654
+ return;
655
+ }
656
+ if (control) {
657
+ await handleControl(request, response);
658
+ return;
659
+ }
660
+ await handleTunnel(request, response, method, path);
661
+ };
662
+ const server = createServer({ maxHeaderSize: MAX_FORWARD_HEADER_BYTES }, (request, response) => {
663
+ void handleRequest(request, response).catch((error) => {
664
+ reportError(error);
665
+ request.resume();
666
+ if (response.headersSent) {
667
+ response.destroy();
668
+ return;
669
+ }
670
+ sendJson(response, 503, "store_unavailable");
671
+ });
672
+ });
673
+ const websocketServer = new WebSocketServer({
674
+ noServer: true,
675
+ maxPayload: MAX_AGENT_FRAME_BYTES,
676
+ perMessageDeflate: false,
677
+ handleProtocols(protocols) {
678
+ return protocols.has(DASHBOARD_GATEWAY_V2_SUBPROTOCOL) ? DASHBOARD_GATEWAY_V2_SUBPROTOCOL : false;
679
+ },
680
+ });
681
+ const completeResponse = async (connection, id, item, status, headers, body) => {
682
+ const access = await checkAccess(item.tenantId, item.cancel.signal);
683
+ if (registry.owned(connection, id)?.phase !== "forwarded")
684
+ return;
685
+ const selected = access.ok ? authorizeWorkstation(item.cookieHeader, item.tenantId, item.companionId).ok : false;
686
+ if (!access.ok || !selected || !registry.isCurrent(connection)) {
687
+ const lost = registry.settle(connection, id, "failed");
688
+ if (lost !== undefined)
689
+ failOwnerLost(lost);
690
+ return;
691
+ }
692
+ try {
693
+ item.response.writeHead(status, headers);
694
+ }
695
+ catch {
696
+ finish(connection, id, "failed");
697
+ try {
698
+ if (!item.response.headersSent && !item.response.writableEnded) {
699
+ sendJson(item.response, 502, "invalid_companion_response");
700
+ }
701
+ else {
702
+ item.response.destroy();
703
+ }
704
+ }
705
+ catch {
706
+ item.response.destroy();
707
+ }
708
+ if (registry.isAttached(connection))
709
+ connection.socket.websocket.close(1008, "invalid response");
710
+ return;
711
+ }
712
+ finish(connection, id, "completed");
713
+ item.response.end(item.method === "HEAD" ? undefined : body);
714
+ };
715
+ const handleAgentMessage = (connection, data, isBinary) => {
716
+ if (!registry.isAttached(connection))
717
+ return;
718
+ const websocket = connection.socket.websocket;
719
+ if (isBinary) {
720
+ websocket.close(1003, "text messages required");
721
+ return;
722
+ }
723
+ let message;
724
+ try {
725
+ const parsed = JSON.parse(data.toString());
726
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
727
+ throw new Error();
728
+ message = parsed;
729
+ }
730
+ catch {
731
+ websocket.close(1007, "invalid response");
732
+ return;
733
+ }
734
+ if (typeof message.id !== "string") {
735
+ websocket.close(1008, "invalid response");
736
+ return;
737
+ }
738
+ const id = message.id;
739
+ const lookup = registry.lookupResponse(connection, id);
740
+ if (lookup.kind === "late" || lookup.kind === "stale_connection")
741
+ return;
742
+ if (lookup.kind === "unknown") {
743
+ websocket.close(1008, "unknown response id");
744
+ return;
745
+ }
746
+ const item = lookup.request.value;
747
+ if (item.responding) {
748
+ websocket.close(1008, "duplicate response id");
749
+ return;
750
+ }
751
+ let parsed;
752
+ try {
753
+ parsed = parseGatewayV2Response(data.toString());
754
+ }
755
+ catch {
756
+ finish(connection, id, "failed");
757
+ sendJson(item.response, 502, "invalid_companion_response");
758
+ websocket.close(1008, "invalid response");
759
+ return;
760
+ }
761
+ const cookies = filterCompanionSetCookiesForWorkstation(parsed.headers.setCookies, connection.socket.companionId);
762
+ if (!cookies.ok) {
763
+ finish(connection, id, "failed");
764
+ process.stderr.write(`Dashboard gateway rejected companion Set-Cookie: code=${cookies.code} index=${String(cookies.index)}\n`);
765
+ sendJson(item.response, 502, "companion_cookie_rejected");
766
+ return;
767
+ }
768
+ const body = Buffer.from(parsed.bodyBase64, "base64");
769
+ if (parsed.headers.contentLength !== undefined
770
+ && item.method !== "HEAD"
771
+ && Number(parsed.headers.contentLength) !== body.byteLength) {
772
+ finish(connection, id, "failed");
773
+ sendJson(item.response, 502, "invalid_companion_response");
774
+ websocket.close(1008, "invalid response");
775
+ return;
776
+ }
777
+ item.responding = true;
778
+ const headers = withTunneledSecurityHeaders(stripCompanionClinkxHeaders(v2ResponseHeaders(parsed.headers, cookies.setCookies)));
779
+ void completeResponse(connection, id, item, parsed.status, headers, body).catch((error) => {
780
+ reportError(error);
781
+ const lost = registry.settle(connection, id, "failed");
782
+ if (lost !== undefined)
783
+ failOwnerLost(lost);
784
+ });
785
+ };
786
+ const installConnection = (connection) => {
787
+ const websocket = connection.socket.websocket;
788
+ live.add(connection);
789
+ websocket.on("error", () => undefined);
790
+ let lastPongAt = Date.now();
791
+ const heartbeat = setInterval(() => {
792
+ if (websocket.readyState !== 1)
793
+ return;
794
+ if (Date.now() - lastPongAt > pongDeadlineMs) {
795
+ websocket.terminate();
796
+ return;
797
+ }
798
+ try {
799
+ websocket.ping();
800
+ }
801
+ catch {
802
+ websocket.terminate();
803
+ }
804
+ }, pingIntervalMs);
805
+ heartbeat.unref();
806
+ websocket.on("pong", () => {
807
+ lastPongAt = Date.now();
808
+ });
809
+ websocket.once("close", () => {
810
+ clearInterval(heartbeat);
811
+ live.delete(connection);
812
+ for (const lost of registry.detach(connection))
813
+ failOwnerLost(lost);
814
+ });
815
+ websocket.on("message", (data, isBinary) => handleAgentMessage(connection, data, isBinary));
816
+ };
817
+ const handleUpgrade = async (request, socket, head) => {
818
+ socket.on("error", () => undefined);
819
+ if (closing) {
820
+ rejectTenantUpgrade(socket, 503);
821
+ return;
822
+ }
823
+ if (!isPublicHost(request.headersDistinct.host, publicOrigin)) {
824
+ rejectTenantUpgrade(socket, 421);
825
+ return;
826
+ }
827
+ if (request.url !== "/agent") {
828
+ rejectTenantUpgrade(socket, 404);
829
+ return;
830
+ }
831
+ const secret = deviceSecret(request.headersDistinct.authorization);
832
+ const verify = () => {
833
+ try {
834
+ return credentials.verifyDeviceCredential(secret);
835
+ }
836
+ catch (error) {
837
+ reportError(error);
838
+ return "unavailable";
839
+ }
840
+ };
841
+ const check = verify();
842
+ if (check === "unavailable") {
843
+ rejectTenantUpgrade(socket, 503);
844
+ return;
845
+ }
846
+ if (!check.ok) {
847
+ rejectTenantUpgrade(socket, 401);
848
+ return;
849
+ }
850
+ const tenantId = check.tenant.id;
851
+ const companionId = check.companionId;
852
+ if (!offersV2(request)) {
853
+ rejectTenantUpgrade(socket, 426);
854
+ return;
855
+ }
856
+ const claim = registry.claim(companionId);
857
+ if (claim === undefined) {
858
+ rejectTenantUpgrade(socket, 409);
859
+ return;
860
+ }
861
+ const epoch = accessEpochs.get(tenantId) ?? 0;
862
+ let expired = false;
863
+ const upgradeWait = new AbortController();
864
+ socket.once("close", () => upgradeWait.abort());
865
+ pendingUpgrades.add(socket);
866
+ const claimTimer = setTimeout(() => {
867
+ expired = true;
868
+ upgradeWait.abort();
869
+ registry.release(claim);
870
+ rejectTenantUpgrade(socket, 503);
871
+ }, upgradeClaimTimeoutMs);
872
+ claimTimer.unref();
873
+ let access;
874
+ try {
875
+ access = await checkAccess(tenantId, upgradeWait.signal);
876
+ }
877
+ finally {
878
+ clearTimeout(claimTimer);
879
+ pendingUpgrades.delete(socket);
880
+ }
881
+ if (expired)
882
+ return;
883
+ try {
884
+ if (closing || !registry.isClaimValid(claim) || (accessEpochs.get(tenantId) ?? 0) !== epoch) {
885
+ rejectTenantUpgrade(socket, 503);
886
+ return;
887
+ }
888
+ if (socket.destroyed || !socket.writable)
889
+ return;
890
+ if (!access.ok) {
891
+ rejectTenantUpgrade(socket, CONTROL_ERROR_HTTP_STATUS[access.code]);
892
+ return;
893
+ }
894
+ const recheck = verify();
895
+ if (recheck === "unavailable") {
896
+ rejectTenantUpgrade(socket, 503);
897
+ return;
898
+ }
899
+ if (!recheck.ok
900
+ || recheck.credentialId !== check.credentialId
901
+ || recheck.tenant.id !== tenantId
902
+ || recheck.companionId !== companionId) {
903
+ rejectTenantUpgrade(socket, 401);
904
+ return;
905
+ }
906
+ websocketServer.handleUpgrade(request, socket, head, (websocket) => {
907
+ const attached = registry.attach(claim, {
908
+ websocket,
909
+ tenantId,
910
+ credentialId: recheck.credentialId,
911
+ companionId,
912
+ }, 2);
913
+ if (attached === undefined) {
914
+ websocket.terminate();
915
+ return;
916
+ }
917
+ for (const lost of attached.displacedRequests)
918
+ failOwnerLost(lost);
919
+ if (attached.displaced !== undefined)
920
+ live.delete(attached.displaced);
921
+ // Queued before any request can be forwarded on this socket, so the companion learns its identity first.
922
+ websocket.send(formatGatewayV2Hello({ tenantId, companionId }));
923
+ installConnection(attached.connection);
924
+ });
925
+ }
926
+ finally {
927
+ registry.release(claim);
928
+ }
929
+ };
930
+ server.on("upgrade", (request, socket, head) => {
931
+ void handleUpgrade(request, socket, head).catch((error) => {
932
+ reportError(error);
933
+ socket.destroy();
934
+ });
935
+ });
936
+ return {
937
+ listen(port, host) {
938
+ return new Promise((resolve, reject) => {
939
+ const onError = (error) => reject(error);
940
+ server.once("error", onError);
941
+ server.listen(port, host, () => {
942
+ server.off("error", onError);
943
+ resolve();
944
+ });
945
+ });
946
+ },
947
+ address() {
948
+ return server.address();
949
+ },
950
+ close() {
951
+ return new Promise((resolve, reject) => {
952
+ closing = true;
953
+ for (const flights of accessFlights.values()) {
954
+ for (const flight of flights) {
955
+ const waiters = [...flight.waiters];
956
+ flight.waiters.clear();
957
+ for (const waiter of waiters)
958
+ waiter.deliver(ACCESS_UNAVAILABLE);
959
+ }
960
+ }
961
+ accessFlights.clear();
962
+ const queued = [...accessCapacityWaiters.values()].flatMap((waiters) => [...waiters]);
963
+ accessCapacityWaiters.clear();
964
+ for (const wake of queued)
965
+ wake();
966
+ for (const socket of pendingUpgrades)
967
+ socket.destroy();
968
+ pendingUpgrades.clear();
969
+ for (const connection of registry.shutdown())
970
+ connection.socket.websocket.terminate();
971
+ live.clear();
972
+ if (!server.listening) {
973
+ resolve();
974
+ return;
975
+ }
976
+ server.close((error) => {
977
+ if (error)
978
+ reject(error);
979
+ else
980
+ resolve();
981
+ });
982
+ });
983
+ },
984
+ workstationConnection,
985
+ closeWorkstationConnections,
986
+ closeTenantConnections,
987
+ };
988
+ }
989
+ //# sourceMappingURL=tenant-gateway.js.map