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