@fuzdev/fuz_app 0.150.0 → 0.152.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 (597) hide show
  1. package/README.md +1 -1
  2. package/dist/actions/CLAUDE.md +324 -299
  3. package/dist/actions/action_bridge.d.ts +5 -86
  4. package/dist/actions/action_bridge.d.ts.map +1 -1
  5. package/dist/actions/action_bridge.js +4 -84
  6. package/dist/actions/action_codegen.d.ts +8 -166
  7. package/dist/actions/action_codegen.d.ts.map +1 -1
  8. package/dist/actions/action_codegen.js +19 -95
  9. package/dist/actions/action_dispatcher.d.ts +10 -0
  10. package/dist/actions/action_dispatcher.d.ts.map +1 -1
  11. package/dist/actions/action_dispatcher.js +9 -6
  12. package/dist/actions/action_event.d.ts +1 -2
  13. package/dist/actions/action_event.d.ts.map +1 -1
  14. package/dist/actions/action_event.js +7 -13
  15. package/dist/actions/action_event_helpers.d.ts +1 -40
  16. package/dist/actions/action_event_helpers.d.ts.map +1 -1
  17. package/dist/actions/action_event_helpers.js +1 -25
  18. package/dist/actions/action_rpc.d.ts +10 -215
  19. package/dist/actions/action_rpc.d.ts.map +1 -1
  20. package/dist/actions/action_rpc.js +56 -111
  21. package/dist/actions/action_spec.d.ts +2 -2
  22. package/dist/actions/action_spec.js +2 -2
  23. package/dist/actions/action_types.d.ts +229 -8
  24. package/dist/actions/action_types.d.ts.map +1 -1
  25. package/dist/actions/action_types.js +56 -5
  26. package/dist/actions/broadcast_api.d.ts +22 -17
  27. package/dist/actions/broadcast_api.d.ts.map +1 -1
  28. package/dist/actions/broadcast_api.js +16 -27
  29. package/dist/actions/cancel.d.ts +4 -13
  30. package/dist/actions/cancel.d.ts.map +1 -1
  31. package/dist/actions/cancel.js +5 -17
  32. package/dist/actions/compile_action_registry.d.ts +1 -2
  33. package/dist/actions/compile_action_registry.d.ts.map +1 -1
  34. package/dist/actions/connection_closer.d.ts +120 -50
  35. package/dist/actions/connection_closer.d.ts.map +1 -1
  36. package/dist/actions/connection_closer.js +139 -31
  37. package/dist/actions/{transports_ws_backend.d.ts → connection_registry.d.ts} +120 -132
  38. package/dist/actions/connection_registry.d.ts.map +1 -0
  39. package/dist/actions/{transports_ws_backend.js → connection_registry.js} +149 -152
  40. package/dist/actions/frontend_rpc_client.d.ts +52 -2
  41. package/dist/actions/frontend_rpc_client.d.ts.map +1 -1
  42. package/dist/actions/frontend_rpc_client.js +42 -4
  43. package/dist/actions/peer_ping.d.ts +7 -9
  44. package/dist/actions/peer_ping.d.ts.map +1 -1
  45. package/dist/actions/peer_ping.js +6 -8
  46. package/dist/actions/peer_request.d.ts +6 -5
  47. package/dist/actions/peer_request.d.ts.map +1 -1
  48. package/dist/actions/peer_request.js +6 -5
  49. package/dist/actions/perform_action.d.ts +36 -28
  50. package/dist/actions/perform_action.d.ts.map +1 -1
  51. package/dist/actions/perform_action.js +60 -34
  52. package/dist/actions/protocol.d.ts +14 -0
  53. package/dist/actions/protocol.d.ts.map +1 -1
  54. package/dist/actions/protocol.js +18 -0
  55. package/dist/actions/register_action_ws.d.ts +137 -298
  56. package/dist/actions/register_action_ws.d.ts.map +1 -1
  57. package/dist/actions/register_action_ws.js +155 -923
  58. package/dist/actions/socket.svelte.d.ts +9 -0
  59. package/dist/actions/socket.svelte.d.ts.map +1 -1
  60. package/dist/actions/socket.svelte.js +16 -5
  61. package/dist/actions/transports.d.ts +88 -34
  62. package/dist/actions/transports.d.ts.map +1 -1
  63. package/dist/actions/transports.js +76 -76
  64. package/dist/actions/transports_http.d.ts +48 -12
  65. package/dist/actions/transports_http.d.ts.map +1 -1
  66. package/dist/actions/transports_http.js +75 -44
  67. package/dist/actions/transports_ws.d.ts +29 -0
  68. package/dist/actions/transports_ws.d.ts.map +1 -1
  69. package/dist/actions/transports_ws.js +34 -8
  70. package/dist/actions/ws_endpoint_spec.d.ts +52 -75
  71. package/dist/actions/ws_endpoint_spec.d.ts.map +1 -1
  72. package/dist/actions/ws_endpoint_spec.js +27 -10
  73. package/dist/actions/ws_outbound_writer.d.ts +3 -3
  74. package/dist/actions/ws_outbound_writer.js +3 -3
  75. package/dist/actions/ws_socket_session.d.ts +321 -0
  76. package/dist/actions/ws_socket_session.d.ts.map +1 -0
  77. package/dist/actions/ws_socket_session.js +783 -0
  78. package/dist/auth/CLAUDE.md +70 -44
  79. package/dist/auth/account_action_specs.d.ts +2 -0
  80. package/dist/auth/account_action_specs.d.ts.map +1 -1
  81. package/dist/auth/account_actions.d.ts +1 -1
  82. package/dist/auth/account_actions.d.ts.map +1 -1
  83. package/dist/auth/account_actions.js +9 -3
  84. package/dist/auth/account_queries.d.ts +10 -0
  85. package/dist/auth/account_queries.d.ts.map +1 -1
  86. package/dist/auth/account_queries.js +27 -17
  87. package/dist/auth/account_routes.d.ts +2 -1
  88. package/dist/auth/account_routes.d.ts.map +1 -1
  89. package/dist/auth/account_routes.js +14 -17
  90. package/dist/auth/account_schema.d.ts +5 -5
  91. package/dist/auth/account_schema.d.ts.map +1 -1
  92. package/dist/auth/account_schema.js +5 -2
  93. package/dist/auth/actor_lookup_actions.d.ts +1 -1
  94. package/dist/auth/actor_lookup_actions.d.ts.map +1 -1
  95. package/dist/auth/actor_lookup_actions.js +1 -1
  96. package/dist/auth/actor_search_action_specs.d.ts.map +1 -1
  97. package/dist/auth/actor_search_action_specs.js +2 -1
  98. package/dist/auth/actor_search_actions.d.ts +1 -1
  99. package/dist/auth/actor_search_actions.d.ts.map +1 -1
  100. package/dist/auth/actor_search_actions.js +1 -1
  101. package/dist/auth/actor_search_queries.d.ts +5 -5
  102. package/dist/auth/actor_search_queries.d.ts.map +1 -1
  103. package/dist/auth/actor_search_queries.js +7 -7
  104. package/dist/auth/admin_action_specs.d.ts.map +1 -1
  105. package/dist/auth/admin_action_specs.js +3 -1
  106. package/dist/auth/admin_actions.d.ts +1 -1
  107. package/dist/auth/admin_actions.d.ts.map +1 -1
  108. package/dist/auth/admin_actions.js +12 -42
  109. package/dist/auth/all_cell_actions.d.ts +6 -4
  110. package/dist/auth/all_cell_actions.d.ts.map +1 -1
  111. package/dist/auth/all_cell_actions.js +1 -1
  112. package/dist/auth/api_token_queries.d.ts +1 -0
  113. package/dist/auth/api_token_queries.d.ts.map +1 -1
  114. package/dist/auth/api_token_queries.js +1 -0
  115. package/dist/auth/audit_emitter.d.ts +3 -3
  116. package/dist/auth/audit_emitter.js +2 -2
  117. package/dist/auth/audit_log_route_schema.d.ts.map +1 -1
  118. package/dist/auth/audit_log_route_schema.js +3 -2
  119. package/dist/auth/audit_log_routes.d.ts +20 -11
  120. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  121. package/dist/auth/audit_log_routes.js +49 -29
  122. package/dist/auth/audit_log_schema.d.ts +13 -21
  123. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  124. package/dist/auth/audit_log_schema.js +10 -18
  125. package/dist/auth/bearer_auth.d.ts +7 -4
  126. package/dist/auth/bearer_auth.d.ts.map +1 -1
  127. package/dist/auth/bearer_auth.js +21 -15
  128. package/dist/auth/cell_action_helpers.d.ts +89 -0
  129. package/dist/auth/cell_action_helpers.d.ts.map +1 -0
  130. package/dist/auth/cell_action_helpers.js +113 -0
  131. package/dist/auth/cell_actions.d.ts +22 -13
  132. package/dist/auth/cell_actions.d.ts.map +1 -1
  133. package/dist/auth/cell_actions.js +105 -167
  134. package/dist/auth/cell_audit_actions.d.ts +1 -1
  135. package/dist/auth/cell_audit_actions.d.ts.map +1 -1
  136. package/dist/auth/cell_audit_actions.js +3 -12
  137. package/dist/auth/cell_audit_metadata.d.ts +1 -1
  138. package/dist/auth/cell_audit_metadata.js +1 -1
  139. package/dist/auth/cell_field_actions.d.ts +1 -1
  140. package/dist/auth/cell_field_actions.d.ts.map +1 -1
  141. package/dist/auth/cell_field_actions.js +16 -66
  142. package/dist/auth/cell_grant_action_specs.d.ts +2 -2
  143. package/dist/auth/cell_grant_action_specs.js +3 -3
  144. package/dist/auth/cell_grant_actions.d.ts +73 -11
  145. package/dist/auth/cell_grant_actions.d.ts.map +1 -1
  146. package/dist/auth/cell_grant_actions.js +63 -55
  147. package/dist/auth/cell_grant_audit_metadata.d.ts +6 -3
  148. package/dist/auth/cell_grant_audit_metadata.d.ts.map +1 -1
  149. package/dist/auth/cell_grant_audit_metadata.js +7 -4
  150. package/dist/auth/cell_item_actions.d.ts +1 -1
  151. package/dist/auth/cell_item_actions.d.ts.map +1 -1
  152. package/dist/auth/cell_item_actions.js +21 -82
  153. package/dist/auth/cleanup.d.ts +1 -1
  154. package/dist/auth/cleanup.d.ts.map +1 -1
  155. package/dist/auth/cleanup.js +6 -3
  156. package/dist/auth/credential_deadline.d.ts +3 -3
  157. package/dist/auth/credential_deadline.js +3 -3
  158. package/dist/auth/credential_type_schema.d.ts +5 -5
  159. package/dist/auth/credential_type_schema.js +5 -5
  160. package/dist/auth/daemon_token_middleware.d.ts +12 -6
  161. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  162. package/dist/auth/daemon_token_middleware.js +28 -17
  163. package/dist/auth/deps.d.ts +4 -4
  164. package/dist/auth/fail_floor.d.ts +55 -0
  165. package/dist/auth/fail_floor.d.ts.map +1 -0
  166. package/dist/auth/fail_floor.js +63 -0
  167. package/dist/auth/invite_queries.d.ts +3 -15
  168. package/dist/auth/invite_queries.d.ts.map +1 -1
  169. package/dist/auth/invite_queries.js +3 -21
  170. package/dist/auth/middleware.d.ts +12 -7
  171. package/dist/auth/middleware.d.ts.map +1 -1
  172. package/dist/auth/middleware.js +42 -29
  173. package/dist/auth/migrations.d.ts +5 -33
  174. package/dist/auth/migrations.d.ts.map +1 -1
  175. package/dist/auth/migrations.js +9 -16
  176. package/dist/auth/request_context.d.ts +101 -71
  177. package/dist/auth/request_context.d.ts.map +1 -1
  178. package/dist/auth/request_context.js +137 -140
  179. package/dist/auth/resolved_auth.d.ts +122 -36
  180. package/dist/auth/resolved_auth.d.ts.map +1 -1
  181. package/dist/auth/resolved_auth.js +89 -38
  182. package/dist/auth/role_grant_offer_action_specs.d.ts +99 -14
  183. package/dist/auth/role_grant_offer_action_specs.d.ts.map +1 -1
  184. package/dist/auth/role_grant_offer_action_specs.js +26 -13
  185. package/dist/auth/role_grant_offer_actions.d.ts +13 -7
  186. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  187. package/dist/auth/role_grant_offer_actions.js +14 -12
  188. package/dist/auth/role_grant_offer_notifications.d.ts +3 -3
  189. package/dist/auth/role_grant_offer_notifications.js +1 -1
  190. package/dist/auth/role_grant_offer_queries.d.ts +0 -5
  191. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  192. package/dist/auth/role_grant_offer_queries.js +9 -41
  193. package/dist/auth/role_grant_queries.d.ts +17 -67
  194. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  195. package/dist/auth/role_grant_queries.js +34 -106
  196. package/dist/auth/role_grant_sql.d.ts +42 -0
  197. package/dist/auth/role_grant_sql.d.ts.map +1 -0
  198. package/dist/auth/role_grant_sql.js +54 -0
  199. package/dist/auth/scope_kind_schema.d.ts +1 -1
  200. package/dist/auth/scope_kind_schema.js +1 -1
  201. package/dist/auth/self_service_role_actions.d.ts +1 -1
  202. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  203. package/dist/auth/self_service_role_actions.js +1 -1
  204. package/dist/auth/session_queries.d.ts +2 -1
  205. package/dist/auth/session_queries.d.ts.map +1 -1
  206. package/dist/auth/session_queries.js +2 -1
  207. package/dist/auth/signup_routes.d.ts +2 -1
  208. package/dist/auth/signup_routes.d.ts.map +1 -1
  209. package/dist/auth/signup_routes.js +14 -13
  210. package/dist/auth/standard_rpc_actions.d.ts +1 -1
  211. package/dist/auth/standard_rpc_actions.d.ts.map +1 -1
  212. package/dist/auth/token_scope.d.ts +19 -46
  213. package/dist/auth/token_scope.d.ts.map +1 -1
  214. package/dist/auth/token_scope.js +23 -41
  215. package/dist/db/CLAUDE.md +9 -4
  216. package/dist/db/cell_ddl.d.ts +5 -142
  217. package/dist/db/cell_ddl.d.ts.map +1 -1
  218. package/dist/db/cell_ddl.js +17 -16
  219. package/dist/db/cell_field_queries.d.ts +0 -13
  220. package/dist/db/cell_field_queries.d.ts.map +1 -1
  221. package/dist/db/cell_field_queries.js +0 -16
  222. package/dist/db/cell_grant_queries.d.ts +10 -5
  223. package/dist/db/cell_grant_queries.d.ts.map +1 -1
  224. package/dist/db/cell_grant_queries.js +13 -7
  225. package/dist/db/cell_item_queries.d.ts +0 -7
  226. package/dist/db/cell_item_queries.d.ts.map +1 -1
  227. package/dist/db/cell_item_queries.js +0 -10
  228. package/dist/db/cell_queries.d.ts +12 -48
  229. package/dist/db/cell_queries.d.ts.map +1 -1
  230. package/dist/db/cell_queries.js +24 -55
  231. package/dist/db/cell_view_sql.d.ts +1 -6
  232. package/dist/db/cell_view_sql.d.ts.map +1 -1
  233. package/dist/db/cell_view_sql.js +1 -2
  234. package/dist/db/fact_ddl.d.ts +5 -30
  235. package/dist/db/fact_ddl.d.ts.map +1 -1
  236. package/dist/db/fact_ddl.js +14 -13
  237. package/dist/db/fact_store.d.ts +11 -0
  238. package/dist/db/fact_store.d.ts.map +1 -1
  239. package/dist/db/fact_store.js +4 -1
  240. package/dist/db/migrate.d.ts +44 -6
  241. package/dist/db/migrate.d.ts.map +1 -1
  242. package/dist/db/migrate.js +63 -4
  243. package/dist/dev/setup.d.ts +18 -14
  244. package/dist/dev/setup.d.ts.map +1 -1
  245. package/dist/dev/setup.js +42 -39
  246. package/dist/env/dotenv.d.ts +2 -2
  247. package/dist/env/dotenv.js +2 -2
  248. package/dist/env/update_env_variable.d.ts +33 -21
  249. package/dist/env/update_env_variable.d.ts.map +1 -1
  250. package/dist/env/update_env_variable.js +54 -35
  251. package/dist/hono_context.d.ts +15 -90
  252. package/dist/hono_context.d.ts.map +1 -1
  253. package/dist/hono_context.js +9 -56
  254. package/dist/http/CLAUDE.md +35 -20
  255. package/dist/http/auth_shape.d.ts +1 -8
  256. package/dist/http/auth_shape.d.ts.map +1 -1
  257. package/dist/http/auth_shape.js +6 -12
  258. package/dist/http/common_routes.d.ts.map +1 -1
  259. package/dist/http/common_routes.js +3 -2
  260. package/dist/http/db_routes.d.ts +3 -3
  261. package/dist/http/db_routes.js +3 -3
  262. package/dist/http/error_schemas.d.ts +1 -2
  263. package/dist/http/error_schemas.d.ts.map +1 -1
  264. package/dist/http/error_schemas.js +1 -2
  265. package/dist/http/health_schema.d.ts +16 -0
  266. package/dist/http/health_schema.d.ts.map +1 -0
  267. package/dist/http/health_schema.js +12 -0
  268. package/dist/http/jsonrpc_errors.d.ts +22 -2
  269. package/dist/http/jsonrpc_errors.d.ts.map +1 -1
  270. package/dist/http/jsonrpc_errors.js +41 -3
  271. package/dist/http/jsonrpc_helpers.d.ts +60 -17
  272. package/dist/http/jsonrpc_helpers.d.ts.map +1 -1
  273. package/dist/http/jsonrpc_helpers.js +67 -25
  274. package/dist/http/origin.d.ts +30 -1
  275. package/dist/http/origin.d.ts.map +1 -1
  276. package/dist/http/origin.js +46 -9
  277. package/dist/http/origin_wildcard.d.ts +97 -0
  278. package/dist/http/origin_wildcard.d.ts.map +1 -0
  279. package/dist/http/origin_wildcard.js +142 -0
  280. package/dist/http/pending_effects.d.ts +28 -0
  281. package/dist/http/pending_effects.d.ts.map +1 -1
  282. package/dist/http/pending_effects.js +32 -1
  283. package/dist/http/route_spec.d.ts +4 -3
  284. package/dist/http/route_spec.d.ts.map +1 -1
  285. package/dist/http/route_spec.js +54 -45
  286. package/dist/http/surface.d.ts +1 -1
  287. package/dist/http/surface.d.ts.map +1 -1
  288. package/dist/http/surface_query.d.ts +9 -50
  289. package/dist/http/surface_query.d.ts.map +1 -1
  290. package/dist/http/surface_query.js +48 -94
  291. package/dist/realtime/audit_log_sse.d.ts +180 -0
  292. package/dist/realtime/audit_log_sse.d.ts.map +1 -0
  293. package/dist/realtime/audit_log_sse.js +154 -0
  294. package/dist/realtime/sse.d.ts +21 -6
  295. package/dist/realtime/sse.d.ts.map +1 -1
  296. package/dist/realtime/sse.js +33 -10
  297. package/dist/realtime/sse_constants.d.ts +29 -2
  298. package/dist/realtime/sse_constants.d.ts.map +1 -1
  299. package/dist/realtime/sse_constants.js +35 -2
  300. package/dist/realtime/{subscriber_registry.d.ts → sse_registry.d.ts} +12 -12
  301. package/dist/realtime/sse_registry.d.ts.map +1 -0
  302. package/dist/realtime/{subscriber_registry.js → sse_registry.js} +4 -4
  303. package/dist/schema_meta.d.ts +30 -10
  304. package/dist/schema_meta.d.ts.map +1 -1
  305. package/dist/schema_meta.js +85 -21
  306. package/dist/sensitivity.d.ts +9 -3
  307. package/dist/sensitivity.d.ts.map +1 -1
  308. package/dist/sensitivity.js +3 -2
  309. package/dist/server/app_backend.d.ts +8 -5
  310. package/dist/server/app_backend.d.ts.map +1 -1
  311. package/dist/server/app_backend.js +6 -12
  312. package/dist/server/app_server.d.ts +62 -51
  313. package/dist/server/app_server.d.ts.map +1 -1
  314. package/dist/server/app_server.js +84 -71
  315. package/dist/server/app_server_context.d.ts +1 -1
  316. package/dist/server/app_server_context.d.ts.map +1 -1
  317. package/dist/server/env.d.ts +24 -20
  318. package/dist/server/env.d.ts.map +1 -1
  319. package/dist/server/env.js +24 -34
  320. package/dist/server/serve_fact_route.d.ts +12 -16
  321. package/dist/server/serve_fact_route.d.ts.map +1 -1
  322. package/dist/server/serve_fact_route.js +59 -34
  323. package/dist/server/static.d.ts.map +1 -1
  324. package/dist/server/static.js +2 -2
  325. package/dist/testing/CLAUDE.md +179 -158
  326. package/dist/testing/admin_integration.d.ts.map +1 -1
  327. package/dist/testing/admin_integration.js +10 -19
  328. package/dist/testing/adversarial_headers.d.ts.map +1 -1
  329. package/dist/testing/adversarial_headers.js +8 -0
  330. package/dist/testing/app_server.d.ts +9 -77
  331. package/dist/testing/app_server.d.ts.map +1 -1
  332. package/dist/testing/app_server.js +31 -112
  333. package/dist/testing/attack_surface.d.ts.map +1 -1
  334. package/dist/testing/attack_surface.js +3 -4
  335. package/dist/testing/audit_completeness.d.ts.map +1 -1
  336. package/dist/testing/audit_completeness.js +4 -5
  337. package/dist/testing/auth_apps.d.ts +3 -3
  338. package/dist/testing/auth_apps.d.ts.map +1 -1
  339. package/dist/testing/auth_apps.js +9 -6
  340. package/dist/testing/connection_closer_helpers.d.ts +8 -16
  341. package/dist/testing/connection_closer_helpers.d.ts.map +1 -1
  342. package/dist/testing/connection_closer_helpers.js +7 -20
  343. package/dist/testing/cross_backend/action_manifest.d.ts +15 -4
  344. package/dist/testing/cross_backend/action_manifest.d.ts.map +1 -1
  345. package/dist/testing/cross_backend/action_manifest.js +13 -3
  346. package/dist/testing/cross_backend/action_manifest_parity.d.ts +15 -7
  347. package/dist/testing/cross_backend/action_manifest_parity.d.ts.map +1 -1
  348. package/dist/testing/cross_backend/action_manifest_parity.js +8 -1
  349. package/dist/testing/cross_backend/body_size.d.ts.map +1 -1
  350. package/dist/testing/cross_backend/body_size.js +25 -22
  351. package/dist/testing/cross_backend/build_test_backend_paths.d.ts +22 -3
  352. package/dist/testing/cross_backend/build_test_backend_paths.d.ts.map +1 -1
  353. package/dist/testing/cross_backend/build_test_backend_paths.js +34 -11
  354. package/dist/testing/cross_backend/capabilities.d.ts +13 -7
  355. package/dist/testing/cross_backend/capabilities.d.ts.map +1 -1
  356. package/dist/testing/cross_backend/cell_grant_role.js +2 -2
  357. package/dist/testing/cross_backend/cell_grant_steward.d.ts +4 -0
  358. package/dist/testing/cross_backend/cell_grant_steward.d.ts.map +1 -0
  359. package/dist/testing/cross_backend/cell_grant_steward.js +120 -0
  360. package/dist/testing/cross_backend/cell_relations.d.ts.map +1 -1
  361. package/dist/testing/cross_backend/cell_relations.js +21 -0
  362. package/dist/testing/cross_backend/conformance_table.d.ts +1 -1
  363. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  364. package/dist/testing/cross_backend/default_backend_configs.d.ts +18 -4
  365. package/dist/testing/cross_backend/default_backend_configs.d.ts.map +1 -1
  366. package/dist/testing/cross_backend/default_backend_configs.js +29 -9
  367. package/dist/testing/cross_backend/default_spine_surface.d.ts +7 -7
  368. package/dist/testing/cross_backend/default_spine_surface.js +2 -2
  369. package/dist/testing/cross_backend/fact_serving.d.ts.map +1 -1
  370. package/dist/testing/cross_backend/fact_serving.js +48 -0
  371. package/dist/testing/cross_backend/full_spine_mount.d.ts +3 -4
  372. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  373. package/dist/testing/cross_backend/full_spine_mount.js +9 -2
  374. package/dist/testing/cross_backend/origin_scope.d.ts.map +1 -1
  375. package/dist/testing/cross_backend/origin_scope.js +5 -13
  376. package/dist/testing/cross_backend/peer_ping_ws.d.ts.map +1 -1
  377. package/dist/testing/cross_backend/peer_ping_ws.js +29 -4
  378. package/dist/testing/cross_backend/postgres_database.d.ts +32 -0
  379. package/dist/testing/cross_backend/postgres_database.d.ts.map +1 -1
  380. package/dist/testing/cross_backend/postgres_database.js +56 -1
  381. package/dist/testing/cross_backend/query_shape.d.ts.map +1 -1
  382. package/dist/testing/cross_backend/query_shape.js +18 -1
  383. package/dist/testing/cross_backend/role_grant_offer_lifecycle.d.ts.map +1 -1
  384. package/dist/testing/cross_backend/role_grant_offer_lifecycle.js +23 -1
  385. package/dist/testing/cross_backend/rpc_success_fixtures.js +2 -2
  386. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +1 -1
  387. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  388. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts +17 -5
  389. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts.map +1 -1
  390. package/dist/testing/cross_backend/rust_spine_stub_backend_config.js +5 -4
  391. package/dist/testing/cross_backend/session_cap.d.ts +8 -0
  392. package/dist/testing/cross_backend/session_cap.d.ts.map +1 -1
  393. package/dist/testing/cross_backend/session_cap.js +66 -2
  394. package/dist/testing/cross_backend/setup.d.ts.map +1 -1
  395. package/dist/testing/cross_backend/setup.js +5 -4
  396. package/dist/testing/cross_backend/spine_suites.d.ts +4 -1
  397. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  398. package/dist/testing/cross_backend/spine_suites.js +21 -0
  399. package/dist/testing/cross_backend/spine_surface_constants.d.ts +22 -7
  400. package/dist/testing/cross_backend/spine_surface_constants.d.ts.map +1 -1
  401. package/dist/testing/cross_backend/spine_surface_constants.js +22 -7
  402. package/dist/testing/cross_backend/sse_round_trip.d.ts.map +1 -1
  403. package/dist/testing/cross_backend/sse_round_trip.js +4 -3
  404. package/dist/testing/cross_backend/standard.d.ts +6 -12
  405. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  406. package/dist/testing/cross_backend/test_cell_grant_steward_revoke_authorize.d.ts +8 -0
  407. package/dist/testing/cross_backend/test_cell_grant_steward_revoke_authorize.d.ts.map +1 -0
  408. package/dist/testing/cross_backend/test_cell_grant_steward_revoke_authorize.js +22 -0
  409. package/dist/testing/cross_backend/testing_backdoor.d.ts.map +1 -1
  410. package/dist/testing/cross_backend/testing_backdoor.js +4 -6
  411. package/dist/testing/cross_backend/testing_origin_check.d.ts +1 -1
  412. package/dist/testing/cross_backend/testing_origin_check.d.ts.map +1 -1
  413. package/dist/testing/cross_backend/testing_origin_check.js +1 -1
  414. package/dist/testing/cross_backend/testing_reset_actions.d.ts +10 -5
  415. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  416. package/dist/testing/cross_backend/testing_reset_actions.js +7 -6
  417. package/dist/testing/cross_backend/testing_server_bun.d.ts.map +1 -1
  418. package/dist/testing/cross_backend/testing_server_bun.js +5 -4
  419. package/dist/testing/cross_backend/testing_server_core.d.ts +6 -7
  420. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  421. package/dist/testing/cross_backend/testing_server_core.js +1 -1
  422. package/dist/testing/cross_backend/testing_server_node.d.ts.map +1 -1
  423. package/dist/testing/cross_backend/testing_server_node.js +13 -2
  424. package/dist/testing/cross_backend/token_lifetime.d.ts.map +1 -1
  425. package/dist/testing/cross_backend/token_lifetime.js +68 -0
  426. package/dist/testing/cross_backend/transport_composition.d.ts +1 -1
  427. package/dist/testing/cross_backend/transport_composition.d.ts.map +1 -1
  428. package/dist/testing/cross_backend/transport_composition.js +45 -3
  429. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +16 -2
  430. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  431. package/dist/testing/cross_backend/ts_spine_backend_config.js +11 -8
  432. package/dist/testing/cross_backend/ws_action_rate_limit.d.ts.map +1 -1
  433. package/dist/testing/cross_backend/ws_action_rate_limit.js +30 -12
  434. package/dist/testing/cross_backend/ws_connection_cap.d.ts.map +1 -1
  435. package/dist/testing/cross_backend/ws_connection_cap.js +5 -7
  436. package/dist/testing/cross_backend/ws_endpoint.d.ts +2 -3
  437. package/dist/testing/cross_backend/ws_endpoint.d.ts.map +1 -1
  438. package/dist/testing/cross_backend/ws_envelope.d.ts +17 -0
  439. package/dist/testing/cross_backend/ws_envelope.d.ts.map +1 -0
  440. package/dist/testing/cross_backend/ws_envelope.js +172 -0
  441. package/dist/testing/cross_backend/ws_inbound_dispatch.d.ts +16 -0
  442. package/dist/testing/cross_backend/ws_inbound_dispatch.d.ts.map +1 -1
  443. package/dist/testing/cross_backend/ws_inbound_dispatch.js +8 -4
  444. package/dist/testing/cross_backend/ws_outbound_overflow.d.ts.map +1 -1
  445. package/dist/testing/cross_backend/ws_outbound_overflow.js +5 -8
  446. package/dist/testing/cross_backend/ws_role_gated.js +2 -2
  447. package/dist/testing/cross_backend/ws_round_trip.d.ts.map +1 -1
  448. package/dist/testing/cross_backend/ws_round_trip.js +6 -4
  449. package/dist/{cli/daemon.d.ts → testing/daemon_info.d.ts} +15 -47
  450. package/dist/testing/daemon_info.d.ts.map +1 -0
  451. package/dist/testing/daemon_info.js +108 -0
  452. package/dist/testing/daemon_token_rotation.js +1 -1
  453. package/dist/testing/data_exposure.d.ts.map +1 -1
  454. package/dist/testing/data_exposure.js +3 -4
  455. package/dist/testing/db.js +2 -2
  456. package/dist/testing/integration.d.ts.map +1 -1
  457. package/dist/testing/integration.js +35 -65
  458. package/dist/testing/integration_helpers.d.ts +0 -15
  459. package/dist/testing/integration_helpers.d.ts.map +1 -1
  460. package/dist/testing/integration_helpers.js +2 -42
  461. package/dist/testing/middleware.d.ts +20 -12
  462. package/dist/testing/middleware.d.ts.map +1 -1
  463. package/dist/testing/middleware.js +49 -40
  464. package/dist/testing/rate_limiting.d.ts.map +1 -1
  465. package/dist/testing/rate_limiting.js +13 -22
  466. package/dist/testing/resolved_auth.d.ts +30 -0
  467. package/dist/testing/resolved_auth.d.ts.map +1 -0
  468. package/dist/testing/resolved_auth.js +41 -0
  469. package/dist/testing/rpc_envelope_cases.d.ts.map +1 -1
  470. package/dist/testing/rpc_envelope_cases.js +3 -0
  471. package/dist/testing/rpc_helpers.d.ts +1 -1
  472. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  473. package/dist/testing/rpc_helpers.js +2 -1
  474. package/dist/testing/sse_round_trip.d.ts +5 -4
  475. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  476. package/dist/testing/sse_round_trip.js +2 -2
  477. package/dist/testing/stubs.d.ts +2 -2
  478. package/dist/testing/stubs.d.ts.map +1 -1
  479. package/dist/testing/stubs.js +24 -21
  480. package/dist/testing/test_origin.d.ts +25 -0
  481. package/dist/testing/test_origin.d.ts.map +1 -0
  482. package/dist/testing/test_origin.js +28 -0
  483. package/dist/testing/transports/raw_http.d.ts +54 -0
  484. package/dist/testing/transports/raw_http.d.ts.map +1 -1
  485. package/dist/testing/transports/raw_http.js +58 -0
  486. package/dist/testing/transports/ws_raw_client.d.ts +8 -0
  487. package/dist/testing/transports/ws_raw_client.d.ts.map +1 -1
  488. package/dist/testing/transports/ws_raw_client.js +13 -0
  489. package/dist/testing/transports/ws_transport.d.ts +15 -2
  490. package/dist/testing/transports/ws_transport.d.ts.map +1 -1
  491. package/dist/testing/transports/ws_transport.js +4 -2
  492. package/dist/testing/ws_round_trip.d.ts +27 -25
  493. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  494. package/dist/testing/ws_round_trip.js +34 -26
  495. package/dist/ui/AccountSessions.svelte +48 -19
  496. package/dist/ui/AccountSessions.svelte.d.ts +2 -17
  497. package/dist/ui/AccountSessions.svelte.d.ts.map +1 -1
  498. package/dist/ui/AdminAccounts.svelte +6 -1
  499. package/dist/ui/AdminAuditLog.svelte +61 -22
  500. package/dist/ui/AdminAuditLog.svelte.d.ts.map +1 -1
  501. package/dist/ui/AdminInvites.svelte +1 -1
  502. package/dist/ui/AdminOverview.svelte +76 -37
  503. package/dist/ui/AdminOverview.svelte.d.ts.map +1 -1
  504. package/dist/ui/AdminRoleGrantHistory.svelte +6 -1
  505. package/dist/ui/AdminSessions.svelte +1 -1
  506. package/dist/ui/AppShell.svelte +3 -2
  507. package/dist/ui/AppShell.svelte.d.ts +3 -2
  508. package/dist/ui/AppShell.svelte.d.ts.map +1 -1
  509. package/dist/ui/CLAUDE.md +121 -35
  510. package/dist/ui/Datatable.svelte +33 -18
  511. package/dist/ui/Datatable.svelte.d.ts +2 -14
  512. package/dist/ui/Datatable.svelte.d.ts.map +1 -1
  513. package/dist/ui/OpenSignupToggle.svelte +10 -1
  514. package/dist/ui/OpenSignupToggle.svelte.d.ts.map +1 -1
  515. package/dist/ui/PopoverButton.svelte +13 -8
  516. package/dist/ui/PopoverButton.svelte.d.ts.map +1 -1
  517. package/dist/ui/RoleGrantOfferForm.svelte +3 -2
  518. package/dist/ui/RoleGrantOfferForm.svelte.d.ts +3 -2
  519. package/dist/ui/RoleGrantOfferForm.svelte.d.ts.map +1 -1
  520. package/dist/ui/RoleGrantOfferHistory.svelte +3 -3
  521. package/dist/ui/RoleGrantOfferInbox.svelte +19 -15
  522. package/dist/ui/RoleGrantOfferInbox.svelte.d.ts.map +1 -1
  523. package/dist/ui/SurfaceExplorer.svelte +66 -27
  524. package/dist/ui/SurfaceExplorer.svelte.d.ts.map +1 -1
  525. package/dist/ui/account_sessions_state.svelte.d.ts +7 -14
  526. package/dist/ui/account_sessions_state.svelte.d.ts.map +1 -1
  527. package/dist/ui/admin_accounts_state.svelte.d.ts +14 -9
  528. package/dist/ui/admin_accounts_state.svelte.d.ts.map +1 -1
  529. package/dist/ui/admin_accounts_state.svelte.js +6 -4
  530. package/dist/ui/admin_invites_state.svelte.d.ts +2 -2
  531. package/dist/ui/admin_invites_state.svelte.d.ts.map +1 -1
  532. package/dist/ui/admin_rpc_adapters.d.ts +9 -9
  533. package/dist/ui/admin_rpc_adapters.d.ts.map +1 -1
  534. package/dist/ui/admin_rpc_adapters.js +9 -9
  535. package/dist/ui/app_settings_state.svelte.d.ts +2 -2
  536. package/dist/ui/app_settings_state.svelte.d.ts.map +1 -1
  537. package/dist/ui/audit_log_state.svelte.d.ts +70 -13
  538. package/dist/ui/audit_log_state.svelte.d.ts.map +1 -1
  539. package/dist/ui/audit_log_state.svelte.js +239 -47
  540. package/dist/ui/backend_probe.svelte.d.ts +93 -0
  541. package/dist/ui/backend_probe.svelte.d.ts.map +1 -0
  542. package/dist/ui/backend_probe.svelte.js +140 -0
  543. package/dist/ui/format_scope.d.ts +7 -7
  544. package/dist/ui/format_scope.d.ts.map +1 -1
  545. package/dist/ui/format_scope.js +4 -4
  546. package/dist/ui/keyed_async_slot.svelte.d.ts +2 -2
  547. package/dist/ui/keyed_async_slot.svelte.js +2 -2
  548. package/dist/ui/popover.svelte.d.ts +18 -19
  549. package/dist/ui/popover.svelte.d.ts.map +1 -1
  550. package/dist/ui/popover.svelte.js +103 -16
  551. package/dist/ui/role_grant_offers_state.svelte.d.ts +41 -46
  552. package/dist/ui/role_grant_offers_state.svelte.d.ts.map +1 -1
  553. package/dist/ui/role_grant_offers_state.svelte.js +37 -19
  554. package/dist/ui/ui_format.d.ts +17 -0
  555. package/dist/ui/ui_format.d.ts.map +1 -1
  556. package/dist/ui/ui_format.js +20 -0
  557. package/package.json +9 -8
  558. package/dist/actions/register_ws_endpoint.d.ts +0 -79
  559. package/dist/actions/register_ws_endpoint.d.ts.map +0 -1
  560. package/dist/actions/register_ws_endpoint.js +0 -109
  561. package/dist/actions/transports_ws_auth_guard.d.ts +0 -96
  562. package/dist/actions/transports_ws_auth_guard.d.ts.map +0 -1
  563. package/dist/actions/transports_ws_auth_guard.js +0 -141
  564. package/dist/actions/transports_ws_backend.d.ts.map +0 -1
  565. package/dist/cli/args.d.ts +0 -55
  566. package/dist/cli/args.d.ts.map +0 -1
  567. package/dist/cli/args.js +0 -100
  568. package/dist/cli/config.d.ts +0 -47
  569. package/dist/cli/config.d.ts.map +0 -1
  570. package/dist/cli/config.js +0 -77
  571. package/dist/cli/daemon.d.ts.map +0 -1
  572. package/dist/cli/daemon.js +0 -181
  573. package/dist/cli/help.d.ts +0 -124
  574. package/dist/cli/help.d.ts.map +0 -1
  575. package/dist/cli/help.js +0 -215
  576. package/dist/cli/logger.d.ts +0 -46
  577. package/dist/cli/logger.d.ts.map +0 -1
  578. package/dist/cli/logger.js +0 -48
  579. package/dist/cli/util.d.ts +0 -36
  580. package/dist/cli/util.d.ts.map +0 -1
  581. package/dist/cli/util.js +0 -50
  582. package/dist/realtime/sse_auth_guard.d.ts +0 -197
  583. package/dist/realtime/sse_auth_guard.d.ts.map +0 -1
  584. package/dist/realtime/sse_auth_guard.js +0 -239
  585. package/dist/realtime/subscriber_registry.d.ts.map +0 -1
  586. package/dist/testing/bootstrap_success.d.ts +0 -29
  587. package/dist/testing/bootstrap_success.d.ts.map +0 -1
  588. package/dist/testing/bootstrap_success.js +0 -144
  589. package/dist/testing/mock_fs.d.ts +0 -20
  590. package/dist/testing/mock_fs.d.ts.map +0 -1
  591. package/dist/testing/mock_fs.js +0 -28
  592. package/dist/testing/standard.d.ts +0 -122
  593. package/dist/testing/standard.d.ts.map +0 -1
  594. package/dist/testing/standard.js +0 -73
  595. package/dist/testing/testing_rate_limiter.d.ts +0 -65
  596. package/dist/testing/testing_rate_limiter.d.ts.map +0 -1
  597. package/dist/testing/testing_rate_limiter.js +0 -80
@@ -1,255 +1,92 @@
1
1
  /**
2
- * WebSocket JSON-RPC dispatch — the low-level WS transport binding.
2
+ * WebSocket JSON-RPC endpoint — the WS transport binding.
3
3
  *
4
4
  * Consumers declare WS endpoints on `create_app_server`'s `ws_endpoints`,
5
- * which mounts each through `register_ws_endpoint`
6
- * (`actions/register_ws_endpoint.ts`) — this function wrapped in the
7
- * standard upgrade stack (origin check + auth + token scope + actor
8
- * resolution + optional role). This module stays exported as the
9
- * lower-level entry point for tests that drive the dispatcher directly via
10
- * `create_ws_test_harness`.
5
+ * which mounts each through `register_action_ws`; call it directly only to
6
+ * mount an endpoint outside that assembly. Tests drive the dispatcher
7
+ * directly via `create_ws_test_harness`.
11
8
  *
12
- * Symmetric to `create_rpc_endpoint` (from `actions/action_rpc.ts`):
13
- * both transports parse their wire envelope, then call the shared
14
- * `perform_action` core (`actions/perform_action.ts`) for the post-parse
15
- * pipeline. WS-specific concerns — connection lifecycle, heartbeat,
16
- * cancel-notification interception, socket-scoped notify — stay in this
17
- * module; everything else (auth gates, input validation, authorization
18
- * phase, rate limiting, transactional dispatch, DEV output validation,
19
- * thrown-error normalization) is shared.
20
- *
21
- * ## Auth expectations
22
- *
23
- * The consumer is responsible for rejecting unauthenticated upgrades
24
- * *before* routing to this handler (fuz_app's `require_auth` middleware,
25
- * or `register_ws_endpoint` which wires it for you). Per-action auth
26
- * runs inside `perform_action` on every message via the same gates HTTP
27
- * RPC uses.
9
+ * ## The upgrade route
28
10
  *
29
- * ## Admission: the revocation race
11
+ * One `GET path` route, its guards in coarse-to-fine order — the route-spec
12
+ * pipeline's, from `fuz_auth_guard_resolver`:
30
13
  *
31
- * The auth middleware resolves the credential before the handshake, and the
32
- * socket exists only once `onOpen` fires. Every revocation (session revoke,
33
- * logout, password change, token revoke, account delete) closes the sockets
34
- * *registered* under what it revoked, so one landing in that gap would close
35
- * nothing, and the socket would then be admitted on the dead credential and
36
- * keep it: per-message dispatch re-authorizes the *actor*, never the session
37
- * or token — and its admission could evict a live socket of the same account
38
- * past the cap.
14
+ * 1. `verify_request_source(allowed_origins)` — a disallowed origin is
15
+ * refused before the upgrade handshake runs (403).
16
+ * 2. `require_auth` — an unauthenticated upgrade is refused (401).
17
+ * 3. `require_token_scope('surface:ws_upgrade')` — rule 3: a narrowed token
18
+ * cannot hold a socket (403 `token_scope_required`). Server-initiated
19
+ * pushes (broadcasts, role-grant-offer notifications, peer requests)
20
+ * reach whatever the account's connection reaches, with no per-recipient
21
+ * filter to narrow them by, so a scoped token that could upgrade would
22
+ * observe far more than it was granted.
23
+ * 4. **Authorization phase** (`run_authorization_phase`) — the acting actor
24
+ * from the `?acting=<uuid>` query string (`parse_acting`; malformed reads
25
+ * as omitted), against the authenticated account, building the
26
+ * `RequestContext` per-message dispatch reads (400s on actor selection).
27
+ * Multi-actor accounts must supply `?acting`; single-actor accounts work
28
+ * without it.
29
+ * 5. `require_role(required_roles)`, for a gated endpoint (403).
39
30
  *
40
- * `onOpen` closes the gap in three steps: register the connection **pending**
41
- * (`BackendWebsocketTransport.register_pending` — closeable by every
42
- * revocation, inert otherwise), re-read the credential
43
- * (`revalidate_resolved_auth`), then `BackendWebsocketTransport.admit`. A
44
- * revocation whose close ran after the registration found the pending entry,
45
- * so `admit` refuses; one that committed before the re-read is seen by it. The
46
- * cap is enforced only by `admit`, so a refused upgrade evicts nothing, and
47
- * pending registrations never count toward it.
31
+ * Only `GET` is mounted (Hono serves `HEAD` through it), so any other method
32
+ * on the path is a 404. The guards run as middleware ahead of
33
+ * `upgradeWebSocket`, whose callback must return `WSEvents` and so cannot
34
+ * produce a refusal.
48
35
  *
49
- * That argument needs every revocation to close only after its commit —
50
- * otherwise a close could miss the registration while the re-read still sees
51
- * the credential alive. Every one does: the revocation handlers queue their
52
- * close behind the commit (`queue_connection_close`), and the audit emitter
53
- * announces a success row to the listeners behind it too. So no interleaving
54
- * admits a revoked credential; `docs/security.md` §Connection Admission says
55
- * what that rests on.
56
- *
57
- * The acting actor the upgrade resolved is re-read beside the credential on
58
- * every endpoint, gated or not: an actor soft-deleted under its live account
59
- * keeps the account's sessions and tokens and its own grant rows, so neither
60
- * the credential nor the role re-read would refuse it. A tombstoned acting
61
- * actor is refused like a dead credential.
62
- *
63
- * An endpoint gated on `required_roles` re-reads them beside the credential:
64
- * its upgrade passed the role gate before the socket registered, so a role
65
- * revocation landing in between would close nothing (`close_sockets_for_role`
66
- * matches registrations), and the socket would be admitted without the role
67
- * for its lifetime. The re-read reads the acting actor's grants afresh and
68
- * admits on a global grant of any listed role, as the gate did.
69
- *
70
- * A refused upgrade is closed with `WS_CLOSE_SESSION_REVOKED` (4001, the
71
- * reason a revoked socket gets) for a dead credential or a deleted acting actor,
72
- * `WS_CLOSE_PERMISSION_REVOKED` (4006) for a lost role, or
73
- * `WS_CLOSE_INTERNAL_ERROR` (1011) when a re-read itself failed — fail
74
- * closed, never admitted unchecked. The handshake has already answered `101`,
75
- * so a refusal can only be a close frame.
76
- *
77
- * Once the server is shutting down (`AppServer.close` ran the transport's
78
- * `close_all_sockets`) a refusal is `WS_CLOSE_GOING_AWAY` instead, so the
79
- * client reconnects rather than treating its credential as revoked: an upgrade
80
- * pending at the close-all is closed by it — and its abort makes the refusal
81
- * that follows the re-read send nothing more, even when the database closed
82
- * under that re-read — and one that registers after it is born closed and
83
- * skips the re-read (`BackendWebsocketTransport` module doc, "Shutdown").
84
- *
85
- * Frames that arrive before admission are queued, not dispatched: nothing runs
86
- * on a credential that has not been re-read. They dispatch in arrival order
87
- * once the socket is admitted and `on_socket_open` has completed, and are
88
- * dropped unread on a refusal. The queue holds at most
89
- * `MAX_PRE_ADMISSION_FRAMES` frames and
90
- * `PRE_ADMISSION_QUEUE_BYTES_FACTOR` × `max_message_bytes` bytes; past either
91
- * the socket is closed.
36
+ * Symmetric to `create_rpc_endpoint` (from `actions/action_rpc.ts`):
37
+ * both transports parse their wire envelope, then call the shared
38
+ * `perform_action` core (`actions/perform_action.ts`) for the post-parse
39
+ * pipeline. WS-specific concerns — connection lifecycle, heartbeat,
40
+ * cancel-notification interception, socket-scoped notify — live in
41
+ * `actions/ws_socket_session.ts`; everything else (auth gates, input
42
+ * validation, authorization phase, rate limiting, transactional dispatch, DEV
43
+ * output validation, thrown-error normalization) is shared.
92
44
  *
93
- * ## Credential deadline
45
+ * ## Per-message auth
94
46
  *
95
- * Expiry writes nothing a revocation listener could hear, so the socket
96
- * watches its own credential's expiry (`ResolvedAuth.credential_deadline`,
97
- * the earlier of a session's cookie and row, an API token's row, none for a
98
- * daemon token or an eternal token). From admission, a timer closes it at the
99
- * deadline with `WS_CLOSE_SESSION_REVOKED` (4001) and
100
- * `WS_CLOSE_CREDENTIAL_EXPIRED_REASON`. The wait is a chain of timers of at
101
- * most an hour (`schedule_credential_deadline`), so a session's 30 days — past
102
- * `setTimeout`'s ceiling — does not fire at once, and each wake-up checks the
103
- * wall clock too, so a host suspend does not extend the deadline.
47
+ * Per-action auth runs inside `perform_action` on every message via the same
48
+ * gates HTTP RPC uses.
104
49
  *
105
- * ## A server-closed socket dispatches nothing
50
+ * ## Per-socket lifecycle
106
51
  *
107
- * A runtime adapter can keep delivering inbound frames after the server calls
108
- * `ws.close(…)`, until the close handshake completes (`@hono/node-ws` does —
109
- * up to the `ws` close timeout when the client withholds its close frame).
110
- * So every server-side close — revocation, cap eviction, heartbeat timeout,
111
- * an oversized message, a refused admission — removes the connection from the
112
- * transport and aborts the socket's signal *at close time*, and `onMessage`
113
- * drops any frame on a socket that has ended. A connection the transport no
114
- * longer holds though nothing closed its socket (a bare `remove_connection`)
115
- * is ended on its next frame (`BackendWebsocketTransport.is_registered`), with
116
- * `WS_CLOSE_INTERNAL_ERROR` — it must not linger as a socket that reads
117
- * everything and answers nothing.
52
+ * Admission (the revocation race), the credential deadline, and the rule that a
53
+ * server-closed socket dispatches nothing are the per-socket half, in
54
+ * `actions/ws_socket_session.ts`.
118
55
  *
119
56
  * @module
120
57
  */
121
- import { wait } from '@fuzdev/fuz_util/async.ts';
122
58
  import { Logger } from '@fuzdev/fuz_util/log.ts';
123
- import { get_request_context, has_any_scoped_role, refresh_role_grants, require_request_context, token_scope_surface_denial } from '../auth/request_context.js';
124
- import { get_resolved_auth, revalidate_resolved_auth } from '../auth/resolved_auth.js';
125
- import { query_active_actors_by_account } from '../auth/account_queries.js';
126
- import { schedule_credential_deadline } from '../auth/credential_deadline.js';
59
+ import { get_request_context, require_request_context, run_authorization_phase } from '../auth/request_context.js';
60
+ import { fuz_auth_guard_resolver } from '../auth/auth_guard_resolver.js';
61
+ import { get_resolved_auth } from '../auth/resolved_auth.js';
62
+ import { verify_request_source } from '../http/origin.js';
63
+ import { parse_acting } from '../http/auth_shape.js';
127
64
  import { get_client_ip } from '../http/client_ip.js';
128
- import { flush_pending_effects, flush_post_commit_effects } from '../http/pending_effects.js';
129
- import { JsonrpcRequest } from '../http/jsonrpc.js';
130
- import { dev_only, jsonrpc_error_messages } from '../http/jsonrpc_errors.js';
131
- import { create_jsonrpc_error_response, create_jsonrpc_notification, to_jsonrpc_envelope_id, to_jsonrpc_message_id, to_jsonrpc_params, is_jsonrpc_object, is_jsonrpc_request, is_jsonrpc_request_id } from '../http/jsonrpc_helpers.js';
132
- import { TOKEN_SCOPE_KEY, TEST_CONTEXT_PRESET_KEY } from '../hono_context.js';
65
+ import { TEST_CONTEXT_PRESET_KEY } from '../hono_context.js';
133
66
  import {} from './action_types.js';
134
67
  import { compile_action_registry } from './compile_action_registry.js';
135
- import { cancel_action_spec, CancelNotificationParams } from './cancel.js';
136
- import { DEFAULT_WS_MAX_MESSAGE_BYTES, WS_CLOSE_GOING_AWAY, WS_CLOSE_INTERNAL_ERROR, WS_CLOSE_MESSAGE_TOO_BIG, WS_CLOSE_PERMISSION_REVOKED, WS_CLOSE_PERMISSION_REVOKED_REASON, WS_CLOSE_POLICY_VIOLATION, WS_CLOSE_CREDENTIAL_EXPIRED_REASON, WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_SESSION_REVOKED_REASON, utf8_length, utf8_length_over } from './transports.js';
137
- import { BackendWebsocketTransport } from './transports_ws_backend.js';
138
- import { audit_unmatched_peer_response } from './peer_request.js';
139
- import { perform_action, perform_action_result_to_envelope } from './perform_action.js';
140
- /** Default inactivity window before the server closes a silent socket. */
141
- export const DEFAULT_SERVER_HEARTBEAT_TIMEOUT = 60_000;
68
+ import { DEFAULT_WS_MAX_MESSAGE_BYTES } from './transports.js';
69
+ import { ConnectionRegistry } from './connection_registry.js';
70
+ import { create_ws_socket_events, PRE_ADMISSION_QUEUE_BYTES_FACTOR } from './ws_socket_session.js';
142
71
  /**
143
- * Max inbound frames one socket may have queued while it is still opening —
144
- * between the handshake and the end of the credential re-check plus
145
- * `on_socket_open`. One more closes the socket with
146
- * `WS_CLOSE_POLICY_VIOLATION`.
147
- *
148
- * Frames sent before the socket is open wait rather than dispatch (nothing
149
- * runs on a credential that has not been re-read), and a runtime adapter hands
150
- * them over with no backpressure, so the wait needs a bound. This is the count
151
- * half; `PRE_ADMISSION_QUEUE_BYTES_FACTOR` is the byte half.
152
- *
153
- * Sized so a client flushing its durable queue on reopen never meets it at the
154
- * default `DEFAULT_QUEUE_MAX_SIZE` (`actions/socket.svelte.ts`). A consumer
155
- * that raises the client's queue above this cap makes a full flush overflow
156
- * it: the socket closes with `WS_CLOSE_POLICY_VIOLATION`, the flushed requests
157
- * fail, and the client reconnects.
72
+ * Default receive silence (ms) past which the server closes a socket with
73
+ * `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT` — the `receive_timeout` of
74
+ * `register_action_ws`. Twin of the Rust spine's `DEFAULT_WS_RECEIVE_TIMEOUT`.
158
75
  */
159
- export const MAX_PRE_ADMISSION_FRAMES = 256;
76
+ export const DEFAULT_WS_RECEIVE_TIMEOUT = 60_000;
160
77
  /**
161
- * The byte budget of one socket's pre-admission queue, as a multiple of the
162
- * endpoint's `max_message_bytes`: the frames queued while the socket is still
163
- * opening may total at most this many maximum-size messages. The frame that
164
- * would pass it closes the socket with `WS_CLOSE_POLICY_VIOLATION`.
165
- *
166
- * The count cap alone (`MAX_PRE_ADMISSION_FRAMES`) would let each pending
167
- * socket hold that many full-size messages, and pending sockets are not
168
- * capped per account — a registration that is never admitted must not be able
169
- * to pin that much memory. Small requests, which is what a client flushes on
170
- * reopen, meet the count cap long before this one.
171
- *
172
- * A client whose queued requests total more than this budget and flushes
173
- * them all on reopen overflows it: the socket closes, the flushed requests
174
- * fail, and the client reconnects.
175
- */
176
- export const PRE_ADMISSION_QUEUE_BYTES_FACTOR = 4;
177
- /**
178
- * The close reason sent with `WS_CLOSE_POLICY_VIOLATION` when a socket
179
- * overflows its pre-admission queue, by count or by bytes.
78
+ * The longest `receive_timeout` `register_action_ws` accepts — 2³¹ − 1 ms,
79
+ * about 24.8 days, the longest delay a timer honors (the same bound as the
80
+ * SSE keep-alive). It keeps the receive check's half-timeout tick well inside
81
+ * that delay; `Infinity`, or a timeout of about 2³² ms and up, would make the
82
+ * tick fire every millisecond on every socket. TS-only: the Rust spine's
83
+ * `Duration` takes any length.
180
84
  */
181
- export const WS_CLOSE_PRE_ADMISSION_OVERFLOW_REASON = 'too much sent before the socket opened';
85
+ export const WS_RECEIVE_TIMEOUT_MAX = 2_147_483_647;
182
86
  /**
183
- * Max requests one socket may have dispatching at once. A request that
184
- * arrives past it is answered `queue_overflow` with its id
185
- * (`WS_INBOUND_DISPATCH_OVERFLOW_MESSAGE`) and not dispatched; the socket
186
- * stays open, and the requests already running keep answering.
187
- *
188
- * A runtime adapter can hand frames over without awaiting the previous one's
189
- * dispatch (`@hono/node-ws` does not await `onMessage`), so without a ceiling
190
- * one socket could hold any number of handlers — and their pooled database
191
- * work — at once. Shedding rather than queueing keeps the socket reading, so a
192
- * reply to a server-initiated request still reaches the handler awaiting it.
193
- * Generous, so ordinary pipelining never meets it. Same value as the Rust
194
- * spine's `MAX_INBOUND_DISPATCHES_PER_CONN`.
195
- *
196
- * Counted are the requests that passed envelope validation and are not yet
197
- * answered — the entries of the socket's cancellation map. Notifications,
198
- * replies to server-initiated requests, and refused frames never count.
199
- */
200
- export const MAX_INBOUND_DISPATCHES_PER_CONNECTION = 128;
201
- /**
202
- * The `queue_overflow` message a request gets past
203
- * `MAX_INBOUND_DISPATCHES_PER_CONNECTION`. Same text as the Rust spine's.
204
- */
205
- export const WS_INBOUND_DISPATCH_OVERFLOW_MESSAGE = 'too many concurrent requests on this connection';
206
- /**
207
- * The `data.reason` of the `invalid_request` a WebSocket request gets when its
208
- * id names a request still running on the same socket. The duplicate is not
209
- * dispatched; the running request keeps its id, so its reply, and a `cancel`
210
- * naming that id, stay its own. An id is free again once its request has been
211
- * answered.
212
- */
213
- export const ERROR_DUPLICATE_REQUEST_ID = 'duplicate_request_id';
214
- /**
215
- * Send one JSON-RPC error response frame to `connection_id` through the
216
- * transport's outbound queue.
217
- */
218
- const send_error_response = (transport, connection_id, id, error) => {
219
- transport.send_to(connection_id, JSON.stringify(create_jsonrpc_error_response(id, error)));
220
- };
221
- /**
222
- * Whether a frame is a reply to a server-initiated request, in the shape the
223
- * Rust twin's `classify` accepts: `jsonrpc: '2.0'`, **no** string `method`, a
224
- * string/number `id`, and exactly one of `result` / `error`.
225
- *
226
- * The method axis is string-typed like the twin, whose
227
- * `obj.get("method").and_then(Value::as_str)` reads a present-but-non-string
228
- * `method` as absent — so `{id, method: 123, result}` is a response on both
229
- * sides, not a request. The `result` / `error` XOR likewise refuses a frame
230
- * carrying both, so neither side has to pick a winner between them.
231
- *
232
- * Deliberately narrower than the `is_jsonrpc_response` /
233
- * `is_jsonrpc_error_response` guards, which only ask for a version, an `id`,
234
- * and a `result` or `error` — those stay loose because a client matching a
235
- * reply must still recognize an error response carrying `id: null`. Here a
236
- * loose match would swallow hybrids the twin answers: `{method, id, result}`
237
- * is a request the dispatcher should run, and `{id, result, error}` or a
238
- * boolean `id` is `invalid_request`. Everything this rejects falls through to
239
- * the version guard / notification / envelope steps below.
240
- */
241
- const is_peer_response = (json) => {
242
- if (!is_jsonrpc_object(json))
243
- return false;
244
- if (typeof json.method === 'string')
245
- return false;
246
- if (!is_jsonrpc_request_id(json.id))
247
- return false;
248
- return 'result' in json !== 'error' in json;
249
- };
250
- /**
251
- * Mount a JSON-RPC WebSocket endpoint that dispatches via the shared
252
- * `perform_action` core.
87
+ * Mount a JSON-RPC WebSocket endpoint — the upgrade route with its origin,
88
+ * auth, token-scope, acting-actor, and role guards (module doc, "The upgrade
89
+ * route") — that dispatches via the shared `perform_action` core.
253
90
  *
254
91
  * Wire behavior:
255
92
  * - Batch JSON-RPC is rejected (single-message only).
@@ -269,8 +106,8 @@ const is_peer_response = (json) => {
269
106
  * - Authorization phase runs **per message** — role_grant changes during a
270
107
  * connection lifetime are picked up on the next message without any
271
108
  * in-place refresh. Authentication invalidation closes the socket: the
272
- * revocation handlers through `connection_closer`, and `create_ws_auth_guard`
273
- * on the audit row.
109
+ * revocation handlers through `connection_closer`, and the revocation guard
110
+ * (`create_revocation_guard`) on the audit row.
274
111
  * - Admission re-reads the credential once, after the handshake: a socket
275
112
  * whose session or token was revoked while it was upgrading closes with
276
113
  * `WS_CLOSE_SESSION_REVOKED`, one that lost a role `required_roles` lists
@@ -278,40 +115,40 @@ const is_peer_response = (json) => {
278
115
  * `WS_CLOSE_INTERNAL_ERROR`. Frames sent before admission wait for it.
279
116
  * - A revoked global grant of a role `required_roles` lists closes the
280
117
  * account's sockets on this endpoint with `WS_CLOSE_PERMISSION_REVOKED`,
281
- * through `create_ws_auth_guard`; nothing more is sent on them.
118
+ * through the revocation guard; nothing more is sent on them.
282
119
  * - A socket the server has closed dispatches nothing more, whether or not
283
120
  * its client answers the close.
284
121
  * - Every frame sent — responses, error frames, notifications — goes through
285
- * the transport's outbound queue. A connection with more waiting than its
122
+ * the registry's outbound queue. A connection with more waiting than its
286
123
  * `outbound_queue_bytes` budget closes with `WS_CLOSE_OUTBOUND_OVERFLOW`, and
287
124
  * the response of the request whose handler overflowed it is not sent.
288
125
  *
289
- * @returns the transport (supplied or freshly created) — retain it to wire
290
- * `create_ws_auth_guard` or broadcast on audit events.
291
- * @mutates options.app - registers a `GET path` route via `upgradeWebSocket`
292
- * @mutates options.transport - per socket, registers, admits, and removes a
126
+ * @returns the registry (supplied or freshly created) — retain it to broadcast
127
+ * @mutates options.app - registers the `GET path` upgrade route, its guards
128
+ * ahead of `upgradeWebSocket`
129
+ * @mutates options.registry - per socket, registers, admits, and removes a
293
130
  * connection via `register_pending` / `admit` / `remove_connection`
294
- * @mutates options.connection_closer - adds the endpoint's transport, once the
131
+ * @mutates options.connection_closer - adds the endpoint's registry, once the
295
132
  * mount has succeeded
296
133
  * @throws Error when `max_connections_per_account` or `outbound_queue_bytes`
297
- * is passed alongside `transport`, when the cap is neither `null` nor a
134
+ * is passed alongside `registry`, when the cap is neither `null` nor a
298
135
  * positive integer, when the budget is not a positive integer, or when
299
136
  * `actions` fails to compile (`compile_action_registry`)
300
137
  */
301
138
  export const register_action_ws = (options) => {
302
- if (options.transport && options.max_connections_per_account !== undefined) {
139
+ if (options.registry && options.max_connections_per_account !== undefined) {
303
140
  // a cap that silently did nothing would read as enforced
304
- throw new Error(`register_action_ws: max_connections_per_account configures the transport created for ${options.path}, ` +
305
- 'but a transport was supplied — set the cap on that BackendWebsocketTransport instead');
141
+ throw new Error(`register_action_ws: max_connections_per_account configures the registry created for ${options.path}, ` +
142
+ 'but a registry was supplied — set the cap on that ConnectionRegistry instead');
306
143
  }
307
- if (options.transport && options.outbound_queue_bytes !== undefined) {
144
+ if (options.registry && options.outbound_queue_bytes !== undefined) {
308
145
  // a budget that silently did nothing would read as enforced
309
- throw new Error(`register_action_ws: outbound_queue_bytes configures the transport created for ${options.path}, ` +
310
- 'but a transport was supplied — set the budget on that BackendWebsocketTransport instead');
146
+ throw new Error(`register_action_ws: outbound_queue_bytes configures the registry created for ${options.path}, ` +
147
+ 'but a registry was supplied — set the budget on that ConnectionRegistry instead');
311
148
  }
312
- const { path, app, upgradeWebSocket, actions, db, heartbeat = true, artificial_delay = 0, max_message_bytes = DEFAULT_WS_MAX_MESSAGE_BYTES, log = new Logger('[ws]'), on_socket_open, on_socket_close, action_ip_rate_limiter, action_account_rate_limiter, required_roles = [] } = options;
313
- const transport = options.transport ??
314
- new BackendWebsocketTransport({
149
+ const { path, app, upgradeWebSocket, actions, db, receive_timeout = DEFAULT_WS_RECEIVE_TIMEOUT, allowed_origins, max_message_bytes = DEFAULT_WS_MAX_MESSAGE_BYTES, log = new Logger('[ws]'), on_socket_open, on_socket_close, action_ip_rate_limiter, action_account_rate_limiter, on_effect_error, required_roles = [] } = options;
150
+ const registry = options.registry ??
151
+ new ConnectionRegistry({
315
152
  max_connections_per_account: options.max_connections_per_account,
316
153
  outbound_queue_bytes: options.outbound_queue_bytes,
317
154
  log
@@ -324,83 +161,85 @@ export const register_action_ws = (options) => {
324
161
  // `cancel_action_spec.method` directly.
325
162
  const { action_map } = compile_action_registry(actions, 'WS action');
326
163
  const pre_admission_queue_max_bytes = PRE_ADMISSION_QUEUE_BYTES_FACTOR * max_message_bytes;
327
- const heartbeat_enabled = heartbeat !== false;
328
- const heartbeat_config = typeof heartbeat === 'object' ? heartbeat : {};
329
- const heartbeat_timeout = heartbeat_config.timeout ?? DEFAULT_SERVER_HEARTBEAT_TIMEOUT;
164
+ if (receive_timeout !== null &&
165
+ !(receive_timeout > 0 && receive_timeout <= WS_RECEIVE_TIMEOUT_MAX)) {
166
+ // a zero (or NaN) timeout would close every socket at its first tick, and
167
+ // `Infinity` would make the half-timeout tick fire every millisecond
168
+ throw new Error(`register_action_ws: receive_timeout must be a positive number of ms up to ${WS_RECEIVE_TIMEOUT_MAX} for ${options.path}, got ${receive_timeout} — pass null to keep silent sockets open`);
169
+ }
330
170
  // Run the checker on timeout/2 so event-loop blockage pauses the timer
331
171
  // itself — a dead-because-blocked socket is close enough to
332
172
  // dead-because-unresponsive that closing is arguably correct.
333
- const heartbeat_tick_interval = Math.max(100, Math.floor(heartbeat_timeout / 2));
334
- app.get(path,
335
- // Token-scope surface gate — a narrowed token cannot hold a socket.
336
- //
337
- // Mounted as pre-upgrade middleware rather than inside the
338
- // `upgradeWebSocket` callback, which must return `WSEvents` and so has no
339
- // way to produce a denial response.
340
- //
341
- // Rule 3, doing real work rather than being conservative for its own
342
- // sake: server-initiated pushes (broadcasts, role-grant-offer
343
- // notifications, peer requests) reach whatever the account's connection
344
- // reaches, and there is no per-recipient filter to narrow them by. So a
345
- // scoped token that could upgrade would observe far more than it was
346
- // granted.
347
- async (c, next) => {
348
- const denied = token_scope_surface_denial(c, 'surface:ws_upgrade');
349
- if (denied)
350
- return denied;
173
+ const receive_tick_interval = receive_timeout === null ? null : Math.max(100, Math.floor(receive_timeout / 2));
174
+ // The upgrade's auth shape: account and actor required, the endpoint's roles,
175
+ // and rule 3's surface — the guards the route-spec pipeline would mount for it
176
+ // (module doc, "The upgrade route").
177
+ const upgrade_auth = {
178
+ account: 'required',
179
+ actor: 'required',
180
+ ...(required_roles.length > 0 ? { roles: required_roles } : {}),
181
+ required_scope: 'surface:ws_upgrade'
182
+ };
183
+ const { pre_authorization, post_authorization } = fuz_auth_guard_resolver(upgrade_auth);
184
+ const endpoint = {
185
+ path,
186
+ db,
187
+ log,
188
+ registry,
189
+ action_map,
190
+ receive_timeout,
191
+ receive_tick_interval,
192
+ max_message_bytes,
193
+ pre_admission_queue_max_bytes,
194
+ on_socket_open,
195
+ on_socket_close,
196
+ action_ip_rate_limiter,
197
+ action_account_rate_limiter,
198
+ on_effect_error,
199
+ required_roles
200
+ };
201
+ app.get(path, verify_request_source(allowed_origins), ...pre_authorization, async (c, next) => {
202
+ const refused = await run_authorization_phase(c, { db }, upgrade_auth, parse_acting(c.req.query('acting')));
203
+ if (refused)
204
+ return refused;
351
205
  return next();
352
- }, upgradeWebSocket((c) => {
353
- // Upgrade-time identity capture. `require_auth` middleware has
354
- // already rejected unauthenticated upgrades, so request_context is
355
- // non-null here. Per-message dispatch reads `account_id` +
356
- // `credential_type` from this closure; the live request_context is
357
- // only used by the test-preset escape hatch (perform_action runs
358
- // the authorization phase fresh on every message in production).
206
+ }, ...post_authorization, upgradeWebSocket((c) => {
207
+ // Upgrade-time identity capture. The route's `require_auth` has
208
+ // already rejected unauthenticated upgrades, and its authorization
209
+ // phase set the request context, so it is non-null here. Per-message
210
+ // dispatch reads the captured resolved credential; the live
211
+ // request_context is only used by the test-preset escape hatch
212
+ // (perform_action runs the authorization phase fresh on every message
213
+ // in production).
359
214
  //
360
215
  // Session / token validity is read here, by the auth middleware,
361
- // and re-read once at admission (`onOpen` below) — never per
216
+ // and re-read once at admission (`onOpen` in
217
+ // `actions/ws_socket_session.ts`) — never per
362
218
  // message: per-message dispatch reloads role_grants via the
363
219
  // authorization phase and nothing else. From admission on,
364
220
  // revocation enforcement lives outside this dispatcher: the
365
221
  // revocation handlers close through `deps.connection_closer`
366
- // (which holds this endpoint's transport — see the
367
- // `connection_closer` option), and the audit-driven WS auth guard
368
- // (`transports_ws_auth_guard.ts`) repeats the close. With neither
369
- // reaching this transport, `session_revoke` / `token_revoke` are
370
- // no-ops for connections that are already open.
222
+ // (which holds this endpoint's registry — see the
223
+ // `connection_closer` option), and the revocation guard on that
224
+ // closer repeats the close on the audit row. With the registry out
225
+ // of the closer, `session_revoke` / `token_revoke` are no-ops for
226
+ // connections that are already open.
371
227
  const upgrade_context = require_request_context(c);
372
- const account_id = upgrade_context.account.id;
373
228
  const client_ip = get_client_ip(c);
374
229
  // The credential the auth middleware resolved — the one derivation
375
- // both long-lived transports share (`get_resolved_auth`), read off
376
- // the keys the middleware set rather than re-derived here, so a
377
- // custom session context key or a daemon token riding beside a
378
- // session cookie can't make this path disagree with the middleware.
230
+ // both long-lived transports share (`get_resolved_auth`), the value
231
+ // the middleware set rather than re-derived here, so a custom
232
+ // session context key or a daemon token riding beside a session
233
+ // cookie can't make this path disagree with the middleware.
379
234
  // Fail closed: no credential, or one on another account than the
380
235
  // request context's, never reaches the upgrade.
381
236
  const resolved = get_resolved_auth(c);
382
237
  if (resolved === null) {
383
238
  throw new Error(`register_action_ws: no resolved credential for the upgrade on ${path} — is the auth middleware wired?`);
384
239
  }
385
- if (resolved.account_id !== account_id) {
240
+ if (resolved.account_id !== upgrade_context.account.id) {
386
241
  throw new Error(`register_action_ws: the credential and the request context name different accounts for the upgrade on ${path}`);
387
242
  }
388
- const { credential_type } = resolved;
389
- // Captured at upgrade and consulted per message. Rule 3 rejects a
390
- // narrowed token at the boundary below, so in practice this is always
391
- // `full` on a live socket — but the per-message gate runs regardless,
392
- // so the invariant is enforced rather than assumed.
393
- const token_scope = c.get(TOKEN_SCOPE_KEY) ?? null;
394
- // Session-based connections have a token hash for targeted revocation.
395
- // Bearer/daemon connections pass null — still reachable via
396
- // `close_sockets_for_account` / `close_sockets_for_token`. A session
397
- // credential with no hash on the context is a shape the middleware
398
- // never builds; the admission re-read refuses it.
399
- const { token_hash } = resolved;
400
- // `api_token.id` — set only for bearer connections; enables
401
- // `close_sockets_for_token` to tear down just this socket on
402
- // `token_revoke` without affecting the account's other sockets.
403
- const { api_token_id } = resolved;
404
243
  // Test escape hatch — captured once at upgrade. perform_action
405
244
  // honors it per-message so harnesses with pre-baked
406
245
  // `RequestContext` skip the live authorization phase. It skips the
@@ -409,626 +248,19 @@ export const register_action_ws = (options) => {
409
248
  const upgrade_preset = c.get(TEST_CONTEXT_PRESET_KEY)
410
249
  ? { request_context: get_request_context(c) }
411
250
  : undefined;
412
- // Per-socket abort controller — fires when the socket ends, chained
413
- // into every in-flight handler's per-request controller via
414
- // `AbortSignal.any`. Keeping both signals lets the client
415
- // cancel-one-request-by-id (via the `cancel` notification) without
416
- // tearing down the whole socket. Registered with the transport, which
417
- // aborts it when it closes the connection (revocation, cap eviction),
418
- // and aborted here on every other end (`end_socket`, `onClose`) — at
419
- // close time, not when the close handshake lands.
420
- const socket_abort_controller = new AbortController();
421
- // Per-request controllers keyed by JSON-RPC request id — lets an
422
- // incoming `cancel` notification abort just the matching handler.
423
- // Populated on request dispatch, cleared in the handler's `finally`
424
- // so a late-arriving cancel for a completed id (or a reused id)
425
- // can't null-abort a freshly-arrived request. Idempotent: cancel
426
- // for unknown ids no-ops. One entry per running request — a
427
- // request reusing a live id is refused before it gets one — so its
428
- // size is the in-flight count `MAX_INBOUND_DISPATCHES_PER_CONNECTION`
429
- // bounds.
430
- const pending_controllers = new Map();
431
- // Identity is assembled at upgrade time so `on_socket_close` can
432
- // read it — by the time the hook runs the transport record is gone,
433
- // removed in `onClose` or earlier by a revocation, a connection-cap
434
- // eviction, or another server-side close.
435
- const identity = {
436
- token_hash,
437
- account_id,
438
- api_token_id,
439
- required_roles
440
- };
441
- // Captured on open, consumed on close. Undefined before onOpen
442
- // fires or when a consumer never opens (e.g. immediate disconnect).
443
- let captured_connection_id;
444
- // Where the socket is in its life:
445
- // - `opening` — from the handshake until admission and `on_socket_open`
446
- // have both completed. Inbound frames are queued.
447
- // - `open` — admitted; inbound frames dispatch.
448
- // - `ended` — the client closed it, the server closed it, or it was
449
- // refused at admission. Inbound frames are dropped: an adapter can
450
- // keep delivering them until the close handshake lands.
451
- let phase = 'opening';
452
- // read through a function so a check after an `await` isn't narrowed
453
- // to the value assigned before it
454
- const phase_is = (expected) => phase === expected;
455
- // Whether the connection was ever admitted — gates `on_socket_close`,
456
- // the counterpart of an `on_socket_open` a refused socket never ran.
457
- let was_admitted = false;
458
- // The code the transport closed the pending registration with, taken
459
- // before `onClose` removes it: the client's answer to that close can
460
- // arrive before the re-read returns.
461
- let pending_close_code = null;
462
- // Frames received while `opening`, in arrival order — dispatched once
463
- // the socket is open, dropped if it ends first. Each carries the
464
- // settlers of the promise its `onMessage` call returned, so a caller
465
- // awaiting that call (the test harnesses do) resumes when the frame
466
- // has been dispatched or dropped.
467
- const queued_frames = [];
468
- // bytes queued so far, against `pre_admission_queue_max_bytes` — only
469
- // read while the socket is opening, so never reset
470
- let queued_bytes = 0;
471
- const drop_queued_frames = () => {
472
- for (const frame of queued_frames.splice(0))
473
- frame.resolve();
474
- };
475
- // Receive-silence watchdog. Seeded at admission so the first window is
476
- // exempt (cold-start grace — avoid killing mid-handshake sockets).
477
- // Bumped by onMessage. Any incoming activity counts, not just
478
- // heartbeats — chatty clients don't need to send extras.
479
- let last_receive_time = 0;
480
- let heartbeat_timer = null;
481
- const stop_heartbeat_timer = () => {
482
- if (heartbeat_timer !== null) {
483
- clearInterval(heartbeat_timer);
484
- heartbeat_timer = null;
485
- }
486
- };
487
- // The credential deadline: the socket closes when the credential it
488
- // upgraded on expires (4001, `WS_CLOSE_CREDENTIAL_EXPIRED_REASON`) —
489
- // expiry writes nothing a revocation listener hears. Started at
490
- // admission, cancelled when the socket ends.
491
- let cancel_credential_deadline = null;
492
- const stop_credential_deadline = () => {
493
- cancel_credential_deadline?.();
494
- cancel_credential_deadline = null;
495
- };
496
- // The one place a socket's end is recorded, whoever ended it — the
497
- // transport (revocation, cap eviction), `end_socket`, or `onClose` all
498
- // abort this controller.
499
- socket_abort_controller.signal.addEventListener('abort', () => {
500
- phase = 'ended';
501
- stop_heartbeat_timer();
502
- stop_credential_deadline();
503
- drop_queued_frames();
504
- }, { once: true });
505
- // End the socket from the server side: unregister it and abort its
506
- // signal *now* — so nothing more dispatches and in-flight handlers
507
- // see `signal.aborted` while the close handshake is still in flight —
508
- // then send the close frame. The transport does all three for a
509
- // connection it still holds, sending the close behind the waiting
510
- // frames the socket has room for and under the close deadline; a socket
511
- // whose connection is already gone has nothing waiting and is closed
512
- // directly.
513
- const end_socket = (ws, code, reason) => {
514
- const closed = captured_connection_id !== undefined &&
515
- transport.close_connection(captured_connection_id, code, reason);
516
- socket_abort_controller.abort();
517
- if (closed)
518
- return;
519
- try {
520
- ws.close(code, reason);
521
- }
522
- catch (error) {
523
- log.error(`ws close ${code} failed:`, error);
524
- }
525
- };
526
- // Refuse an upgrade at admission. A socket that already ended needs no
527
- // close frame: a revocation closed its pending registration (the
528
- // transport sent the 4001), the shutdown did (the 1001 — so a refusal
529
- // during shutdown never sends a revocation's or a failure's code), or
530
- // the client went away. Its registration is gone too — the transport
531
- // removed it with its close, `onClose` with the client's — and it is
532
- // not removed again here: `remove_connection` is for a socket that has
533
- // closed, and would drop the close deadline of one that has not.
534
- const refuse_upgrade = (ws, code, reason) => {
535
- if (!socket_abort_controller.signal.aborted)
536
- end_socket(ws, code, reason);
537
- };
538
- // Socket-scoped notification helper — routes to this socket only,
539
- // matches the `ctx.notify` semantics exposed to per-message handlers.
540
- // Through the transport's outbound queue, like every other frame: a
541
- // handler that notifies past the connection's budget closes it.
542
- const notify_socket = (connection_id) => (notify_method, notify_params) => {
543
- try {
544
- const notification = create_jsonrpc_notification(notify_method, to_jsonrpc_params(notify_params));
545
- transport.send_to(connection_id, JSON.stringify(notification));
546
- }
547
- catch (error) {
548
- log.error('notify send failed:', notify_method, error);
549
- }
550
- };
551
- // Admit the upgraded socket: register it pending, re-check its
552
- // credential, admit it (module doc, "Admission: the revocation
553
- // race"). Returns the connection id once admitted, or `null` after
554
- // refusing — the socket is then already closed.
555
- const admit_upgrade = async (ws) => {
556
- // Pending first, synchronously: from here every revocation finds it.
557
- const connection_id = transport.register_pending(ws, token_hash, account_id, api_token_id, socket_abort_controller, required_roles);
558
- captured_connection_id = connection_id;
559
- // Born closed — the server is shutting down, and the transport has
560
- // already closed the socket with `WS_CLOSE_GOING_AWAY` — or ended
561
- // otherwise before the re-read: nothing to re-read for. The removal
562
- // is a no-op for a born-closed registration, which was never inserted.
563
- if (socket_abort_controller.signal.aborted) {
564
- transport.remove_connection(connection_id);
565
- log.info(transport.is_closing()
566
- ? 'ws upgrade admission: refused, the server is shutting down'
567
- : 'ws upgrade admission: socket ended before the re-check', connection_id, account_id);
568
- return null;
569
- }
570
- if (!upgrade_preset) {
571
- let credential_is_live;
572
- let actor_is_active = true;
573
- let role_is_held = true;
574
- try {
575
- // pool-level `db`: the statements must see every revocation
576
- // committed before they start
577
- credential_is_live = await revalidate_resolved_auth({ db }, resolved);
578
- // The acting actor the upgrade resolved, on every endpoint: a
579
- // soft-deleted actor keeps its account's credential and its
580
- // grant rows, so neither re-read above or below refuses it.
581
- const acting_actor = upgrade_context.actor;
582
- if (credential_is_live && acting_actor) {
583
- actor_is_active = (await query_active_actors_by_account({ db }, account_id)).some((a) => a.id === acting_actor.id);
584
- }
585
- // Global grants only, like the gate in front: a scoped grant
586
- // never admitted this socket.
587
- if (credential_is_live && actor_is_active && required_roles.length > 0) {
588
- role_is_held = has_any_scoped_role(await refresh_role_grants(upgrade_context, { db }), required_roles, null);
589
- }
590
- }
591
- catch (error) {
592
- // fail closed — never admitted unchecked. During shutdown the
593
- // database may close under the re-read; that is the shutdown's
594
- // refusal, not a failure.
595
- if (transport.is_closing()) {
596
- log.info('ws upgrade admission: re-check ended by the shutdown', error);
597
- }
598
- else {
599
- log.error('ws upgrade admission: credential, actor, or role re-check failed', error);
600
- }
601
- refuse_upgrade(ws, WS_CLOSE_INTERNAL_ERROR, 'internal error');
602
- return null;
603
- }
604
- if (!credential_is_live) {
605
- log.info('ws upgrade admission: credential revoked during the upgrade', connection_id, account_id);
606
- refuse_upgrade(ws, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_SESSION_REVOKED_REASON);
607
- return null;
608
- }
609
- if (!actor_is_active) {
610
- log.info('ws upgrade admission: acting actor deleted during the upgrade', connection_id, account_id);
611
- refuse_upgrade(ws, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_SESSION_REVOKED_REASON);
612
- return null;
613
- }
614
- if (!role_is_held) {
615
- log.info('ws upgrade admission: role revoked during the upgrade', connection_id, account_id);
616
- refuse_upgrade(ws, WS_CLOSE_PERMISSION_REVOKED, WS_CLOSE_PERMISSION_REVOKED_REASON);
617
- return null;
618
- }
619
- }
620
- // The cap's eviction happens here, after every gate and the re-read,
621
- // so a refused upgrade never closes someone else's socket.
622
- if (!transport.admit(connection_id)) {
623
- // why the entry closed, from the code the transport closed it with
624
- const code = pending_close_code ?? transport.take_pending_close_code(connection_id);
625
- log.info(code === WS_CLOSE_PERMISSION_REVOKED
626
- ? 'ws upgrade admission: closed by a permission revocation while pending'
627
- : code === WS_CLOSE_SESSION_REVOKED
628
- ? 'ws upgrade admission: closed by a credential revocation while pending'
629
- : code === WS_CLOSE_GOING_AWAY || transport.is_closing()
630
- ? 'ws upgrade admission: closed by the shutdown while pending'
631
- : 'ws upgrade admission: ended while pending', connection_id, account_id);
632
- refuse_upgrade(ws, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_SESSION_REVOKED_REASON);
633
- return null;
634
- }
635
- was_admitted = true;
636
- return connection_id;
637
- };
638
- const open_socket = async (ws) => {
639
- const connection_id = await admit_upgrade(ws);
640
- if (connection_id === null)
641
- return;
642
- log.debug('ws opened', connection_id);
643
- // Not on a socket that ended in the tick since `admit`, for the same
644
- // reason as the heartbeat timer below.
645
- if (!phase_is('ended')) {
646
- cancel_credential_deadline = schedule_credential_deadline(resolved.credential_deadline, () => {
647
- log.info('ws credential expired — closing', WS_CLOSE_SESSION_REVOKED, connection_id, identity.account_id);
648
- end_socket(ws, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_CREDENTIAL_EXPIRED_REASON);
649
- });
650
- }
651
- // Not on a socket that ended in the tick since `admit` (a revocation
652
- // can land there): its abort listener has already run, so nothing
653
- // would ever stop the timer.
654
- if (heartbeat_enabled && !phase_is('ended')) {
655
- last_receive_time = Date.now();
656
- heartbeat_timer = setInterval(() => {
657
- const now = Date.now();
658
- const silence = now - last_receive_time;
659
- if (silence >= heartbeat_timeout) {
660
- log.info(`heartbeat timeout (${silence}ms) — closing ${WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT}`, connection_id, identity.account_id);
661
- stop_heartbeat_timer();
662
- end_socket(ws, WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT, 'server heartbeat timeout');
663
- }
664
- }, heartbeat_tick_interval);
665
- }
666
- if (on_socket_open) {
667
- try {
668
- await on_socket_open({
669
- ws,
670
- connection_id,
671
- identity,
672
- notify: notify_socket(connection_id),
673
- signal: socket_abort_controller.signal
674
- });
675
- }
676
- catch (error) {
677
- log.error('on_socket_open failed — closing socket:', error);
678
- // an ended socket has no one to tell
679
- if (phase_is('ended'))
680
- return;
681
- send_error_response(transport, connection_id, null, jsonrpc_error_messages.internal_error());
682
- end_socket(ws, WS_CLOSE_INTERNAL_ERROR, 'socket bootstrap failed');
683
- return;
684
- }
685
- }
686
- // Ended while the hook ran (a revocation, the client leaving) — the
687
- // queue is already dropped.
688
- if (!phase_is('opening'))
689
- return;
690
- // Open: dispatch what arrived meanwhile, in arrival order and back
691
- // to back, the way the adapter would have delivered it.
692
- phase = 'open';
693
- for (const frame of queued_frames.splice(0)) {
694
- if (transport.is_registered(connection_id)) {
695
- handle_frame(frame.data, connection_id).then(frame.resolve, frame.reject);
696
- }
697
- else {
698
- frame.resolve();
699
- }
700
- }
701
- };
702
- // Dispatch one inbound frame on an admitted, still-registered
703
- // connection.
704
- const handle_frame = async (data, connection_id) => {
705
- const send_error = (id, error) => send_error_response(transport, connection_id, id, error);
706
- let json;
707
- try {
708
- json = JSON.parse(String(data));
709
- }
710
- catch (error) {
711
- log.error('JSON parse error:', error);
712
- send_error(null, jsonrpc_error_messages.parse_error());
713
- return;
714
- }
715
- // Batch JSON-RPC is not supported on the WebSocket path.
716
- if (Array.isArray(json)) {
717
- send_error(null, jsonrpc_error_messages.invalid_request('batch JSON-RPC requests are not supported on WebSocket'));
718
- return;
719
- }
720
- // Inbound responses to server-initiated requests (`peer/ping`,
721
- // etc.) — route to the pending-request registry scoped to THIS
722
- // socket. A response carries a string/number `id`, exactly one
723
- // of `result` / `error`, and no string `method`, so it precedes the
724
- // request/notification split below. An unmatched id
725
- // (unsolicited, cross-connection, or already settled) resolves
726
- // nothing and is dropped, so the read loop survives a junk
727
- // frame.
728
- if (is_peer_response(json)) {
729
- const matched = transport.resolve_peer_response(connection_id, json);
730
- if (!matched)
731
- audit_unmatched_peer_response(log, connection_id, json.id);
732
- return;
733
- }
734
- // Envelope version — the first thing the Rust twin's `classify`
735
- // checks (version → id → method → params). A frame without
736
- // `jsonrpc: '2.0'` is `invalid_request` on both transports
737
- // rather than falling through to the notification branch,
738
- // which would silently drop `{method: 'x'}` and
739
- // `{jsonrpc: '1.0', method: 'x'}`. It also covers a
740
- // non-object frame (a scalar has no id to echo — `id: null`).
741
- // A genuine peer response carries the version and is matched
742
- // above; a response-shaped frame that misses that shape check
743
- // falls through here on purpose, so it is answered rather
744
- // than swallowed.
745
- if (!is_jsonrpc_object(json)) {
746
- send_error(to_jsonrpc_envelope_id(json), jsonrpc_error_messages.invalid_request());
747
- return;
748
- }
749
- // Notifications (string method + no id) — `cancel` is
750
- // intercepted for request-scoped cancellation; other
751
- // notifications are silenced per JSON-RPC spec (consumer
752
- // notification handlers are not a feature yet). The method
753
- // axis is string-typed like the twin's `classify`, so a
754
- // non-string `method` is answered `invalid_request` below
755
- // rather than silently dropped as a notification.
756
- if (!is_jsonrpc_request(json)) {
757
- const notification_method = json.method;
758
- if (typeof notification_method === 'string' && !('id' in json)) {
759
- if (notification_method === cancel_action_spec.method) {
760
- const parsed = CancelNotificationParams.safeParse(json.params);
761
- if (!parsed.success) {
762
- log.debug('cancel: invalid params, ignoring', parsed.error.issues);
763
- return;
764
- }
765
- const controller = pending_controllers.get(parsed.data.request_id);
766
- if (controller) {
767
- controller.abort();
768
- }
769
- else {
770
- log.debug('cancel: no pending request for id', parsed.data.request_id);
771
- }
772
- }
773
- return;
774
- }
775
- send_error(to_jsonrpc_message_id(json), jsonrpc_error_messages.invalid_request());
776
- return;
777
- }
778
- // Envelope validation — the same `JsonrpcRequest.safeParse` the
779
- // HTTP POST path runs, so a malformed envelope (`params: null`,
780
- // an array `params`, a boolean `id`) answers `invalid_request`
781
- // on both transports instead of reaching the dispatcher and
782
- // surfacing as `invalid_params`. It sits after the
783
- // notification / cancel block so notifications stay
784
- // unvalidated (they carry no id to echo) and `cancel` routing
785
- // precedes it.
786
- const envelope = JsonrpcRequest.safeParse(json);
787
- if (!envelope.success) {
788
- send_error(to_jsonrpc_message_id(json), jsonrpc_error_messages.invalid_request(dev_only({ issues: envelope.error.issues })));
789
- return;
790
- }
791
- const { method, id, params } = envelope.data;
792
- // A request is live from here until its reply is sent. One reusing
793
- // a live id is refused rather than dispatched: two requests under
794
- // one id would share a cancel entry and a reply id, and the first to
795
- // finish would clear the other's. Checked before the ceiling — a
796
- // duplicate is the client's error whatever the load, and retrying it
797
- // cannot succeed while the first runs. Neither refusal reaches
798
- // `perform_action`, so neither charges the action rate limiters —
799
- // the same on the Rust spine.
800
- if (pending_controllers.has(id)) {
801
- send_error(id, jsonrpc_error_messages.invalid_request({ reason: ERROR_DUPLICATE_REQUEST_ID }));
802
- return;
803
- }
804
- // The in-flight ceiling: shed, don't queue — see
805
- // `MAX_INBOUND_DISPATCHES_PER_CONNECTION`.
806
- if (pending_controllers.size >= MAX_INBOUND_DISPATCHES_PER_CONNECTION) {
807
- send_error(id, jsonrpc_error_messages.queue_overflow(WS_INBOUND_DISPATCH_OVERFLOW_MESSAGE));
808
- return;
809
- }
810
- // Per-action method lookup — return method_not_found before
811
- // we engage the dispatch machinery. Specs without a handler
812
- // (client-only / dispatcher-handled) miss action_map and
813
- // surface as method_not_found just like unknown methods.
814
- const action = action_map.get(method);
815
- if (!action) {
816
- send_error(id, jsonrpc_error_messages.method_not_found(method));
817
- return;
818
- }
819
- // Per-request controller — fires on explicit `cancel` or when the
820
- // socket ends (via the socket_abort_controller chain below).
821
- // Registered before dispatch — ahead of `artificial_delay` too, so
822
- // the request is live (counted, and its id taken) from the moment
823
- // it is accepted — so a cancel arriving mid-handler finds it;
824
- // cleared in `finally` so late cancels for a completed id (or a
825
- // future request that reuses the id) can't null-abort the wrong
826
- // handler.
827
- const request_controller = new AbortController();
828
- pending_controllers.set(id, request_controller);
829
- // Per-message side-effect queues. `pending_effects` collects
830
- // eager fire-and-forget pool writes (audit emits, etc.);
831
- // `post_commit_effects` collects deferred thunks pushed
832
- // via `emit_after_commit` (WS notifications). Both flush
833
- // in the `finally` so the next message sees a clean slate.
834
- //
835
- // Ordering invariant — the deferred queue starts first. Its
836
- // thunks are invoked before the eager writes are awaited, so
837
- // a revocation's close never waits on the audit INSERT: held
838
- // behind a slow write, the socket would stay open on a
839
- // credential already committed gone, and its next frame
840
- // would be dispatched. The thunks that need a write (a
841
- // success row's listener fan-out) await it themselves.
842
- //
843
- // Ordering invariant — reply-before-flush is load-bearing.
844
- // A handler that revokes its own credential
845
- // (`session_revoke_all`, `token_revoke` of the calling
846
- // bearer) queues a close of this very socket on
847
- // `post_commit_effects` (`queue_connection_close`), and
848
- // the audit listeners repeat it from the same queue. The
849
- // send on the success path runs before the `finally`
850
- // flushes that queue, so the caller reads its reply and
851
- // then the 4001 close. Inverting the order — flushing the
852
- // queues before the send — would strand the caller without
853
- // a reply.
854
- const pending_effects = [];
855
- const post_commit_effects = [];
856
- const notify = notify_socket(connection_id);
857
- // Server→client request seam (ActionPeer) — closes over this
858
- // socket's connection_id so a handler can initiate a request to
859
- // the originating client and await the reply.
860
- const request_client = (request_method, request_params, request_options) => transport.request_connection(connection_id, request_method, request_params, request_options);
861
- const signal = AbortSignal.any([socket_abort_controller.signal, request_controller.signal]);
862
- try {
863
- if (artificial_delay > 0) {
864
- log.debug(`throttling ${artificial_delay}ms`);
865
- await wait(artificial_delay);
866
- }
867
- const result = await perform_action({
868
- action,
869
- raw_params: params,
870
- request_id: id,
871
- account_id,
872
- credential_type,
873
- token_scope,
874
- client_ip,
875
- signal,
876
- notify,
877
- connection_id,
878
- request_client,
879
- preset: upgrade_preset
880
- }, {
881
- db,
882
- pending_effects,
883
- post_commit_effects,
884
- log,
885
- action_ip_rate_limiter,
886
- action_account_rate_limiter
887
- });
888
- let frame;
889
- try {
890
- frame = JSON.stringify(perform_action_result_to_envelope(id, result));
891
- }
892
- catch (error) {
893
- // The handler's output is not JSON (a `bigint`, a cycle). Answer
894
- // `internal_error` rather than throwing: the adapter does not await
895
- // this promise, so a rejection here is unhandled, and the caller
896
- // would get no reply to a request that did run.
897
- log.error(`action result is not serializable: ${method}`, error);
898
- frame = JSON.stringify(create_jsonrpc_error_response(id, jsonrpc_error_messages.internal_error(dev_only(error instanceof Error ? error.message : undefined))));
899
- }
900
- // Refused when the connection is gone — closed while the handler
901
- // ran, or closed by the handler's own notifications overflowing
902
- // its outbound budget — so nothing follows a close frame.
903
- transport.send_to(connection_id, frame);
904
- }
905
- finally {
906
- pending_controllers.delete(id);
907
- // deferred first — see the ordering invariant above
908
- const deferred = flush_post_commit_effects(post_commit_effects, log);
909
- await flush_pending_effects(pending_effects, log);
910
- await deferred;
911
- }
912
- };
913
- return {
914
- onOpen: async (_event, ws) => {
915
- // An adapter may not await this (`@hono/node-ws` doesn't), so it
916
- // must never reject.
917
- try {
918
- await open_socket(ws);
919
- }
920
- catch (error) {
921
- log.error('ws open failed — closing socket:', error);
922
- refuse_upgrade(ws, WS_CLOSE_INTERNAL_ERROR, 'internal error');
923
- }
924
- },
925
- onMessage: (event, ws) => {
926
- // A socket the server closed — or refused — dispatches nothing
927
- // more, however long its client withholds the close frame.
928
- if (phase_is('ended'))
929
- return;
930
- const size = ws_message_size_over(event.data, max_message_bytes);
931
- if (size !== null) {
932
- log.warn(`closing socket: ${size}-byte message exceeds the ${max_message_bytes}-byte cap`);
933
- end_socket(ws, WS_CLOSE_MESSAGE_TOO_BIG, 'message too big');
934
- return;
935
- }
936
- if (phase_is('opening')) {
937
- // Not open yet: queue, never dispatch — nothing runs on a
938
- // credential that has not been re-read. Bounded by count and
939
- // by bytes, since the adapter applies no backpressure.
940
- const bytes = ws_message_size(event.data);
941
- if (queued_frames.length >= MAX_PRE_ADMISSION_FRAMES ||
942
- queued_bytes + bytes > pre_admission_queue_max_bytes) {
943
- log.warn(`closing socket: pre-admission queue overflow (${queued_frames.length} frames, ${queued_bytes} + ${bytes} bytes)`);
944
- end_socket(ws, WS_CLOSE_POLICY_VIOLATION, WS_CLOSE_PRE_ADMISSION_OVERFLOW_REASON);
945
- return;
946
- }
947
- queued_bytes += bytes;
948
- last_receive_time = Date.now();
949
- return new Promise((resolve, reject) => {
950
- queued_frames.push({ data: event.data, resolve, reject });
951
- });
952
- }
953
- // The transport is the authority on whether the connection is
954
- // still live. A close it made (revocation, cap eviction) ended the
955
- // socket above; a connection it no longer holds though nothing
956
- // closed the socket — a bare `remove_connection` — is ended here,
957
- // rather than left reading every frame and answering none, where
958
- // a chatty client would also keep the heartbeat from reaping it.
959
- const connection_id = captured_connection_id;
960
- if (connection_id === undefined || !transport.is_registered(connection_id)) {
961
- log.warn('closing socket: its connection is no longer registered', connection_id);
962
- end_socket(ws, WS_CLOSE_INTERNAL_ERROR, 'connection unregistered');
963
- return;
964
- }
965
- // only a frame that is accepted counts as activity
966
- last_receive_time = Date.now();
967
- return handle_frame(event.data, connection_id);
968
- },
969
- onClose: async (event, ws) => {
970
- // belt and braces: the abort listener stops the timer and the
971
- // start is skipped on an ended socket, so this matters only if
972
- // one of those is ever broken
973
- stop_heartbeat_timer();
974
- socket_abort_controller.abort();
975
- // Removed by the id captured on open — an adapter may hand each
976
- // event its own `WSContext` (`@hono/bun` does), so the one this
977
- // event carries can't identify the connection. And removed before
978
- // the hook is awaited: the socket is gone, so a slow hook must not
979
- // keep a dead entry that broadcasts still target and the
980
- // per-account cap still counts.
981
- if (captured_connection_id) {
982
- if (!was_admitted) {
983
- pending_close_code = transport.take_pending_close_code(captured_connection_id);
984
- }
985
- transport.remove_connection(captured_connection_id);
986
- }
987
- if (on_socket_close && captured_connection_id && was_admitted) {
988
- try {
989
- await on_socket_close({
990
- ws,
991
- connection_id: captured_connection_id,
992
- identity
993
- });
994
- }
995
- catch (error) {
996
- log.error('on_socket_close failed:', error);
997
- }
998
- }
999
- log.debug('ws closed', captured_connection_id, {
1000
- code: event.code,
1001
- reason: event.reason
1002
- });
1003
- }
1004
- };
251
+ // Captured at upgrade and passed per message, its scope consulted
252
+ // there. Rule 3 rejects a narrowed token at the upgrade's guards
253
+ // above, so in practice the scope is always `full` on a live socket —
254
+ // but the per-message gate runs regardless, so the invariant is
255
+ // enforced rather than assumed.
256
+ return create_ws_socket_events(endpoint, {
257
+ client_ip,
258
+ upgrade_preset,
259
+ resolved,
260
+ upgrade_context
261
+ });
1005
262
  }));
1006
263
  // last, after everything that can throw, so a failed mount leaves no member
1007
- options.connection_closer?.add(transport);
1008
- return { transport };
1009
- };
1010
- /**
1011
- * The byte size of an inbound WebSocket message — UTF-8 bytes for a text
1012
- * frame, the buffer or blob size for a binary one.
1013
- */
1014
- const ws_message_size = (data) => {
1015
- if (typeof data === 'string')
1016
- return utf8_length(data);
1017
- if (data instanceof Blob)
1018
- return data.size;
1019
- if (data instanceof ArrayBuffer || ArrayBuffer.isView(data))
1020
- return data.byteLength;
1021
- return 0;
1022
- };
1023
- /**
1024
- * The byte size of an inbound WebSocket message when it exceeds `max_bytes`,
1025
- * else `null` — UTF-8 bytes for a text frame, the buffer or blob size for a
1026
- * binary one. A text frame that cannot exceed the cap is not encoded to be
1027
- * measured.
1028
- */
1029
- const ws_message_size_over = (data, max_bytes) => {
1030
- if (typeof data === 'string')
1031
- return utf8_length_over(data, max_bytes);
1032
- const size = ws_message_size(data);
1033
- return size > max_bytes ? size : null;
264
+ options.connection_closer?.add(registry);
265
+ return { registry };
1034
266
  };