@fuzdev/fuz_app 0.183.0 → 0.185.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 (223) hide show
  1. package/dist/actions/CLAUDE.md +538 -1223
  2. package/dist/actions/action_codegen.d.ts +1 -1
  3. package/dist/actions/action_codegen.d.ts.map +1 -1
  4. package/dist/actions/action_codegen.js +3 -2
  5. package/dist/actions/connection_closer.d.ts +11 -9
  6. package/dist/actions/connection_closer.d.ts.map +1 -1
  7. package/dist/actions/connection_closer.js +11 -9
  8. package/dist/actions/frontend_rpc_client.d.ts +1 -1
  9. package/dist/actions/register_action_ws.d.ts +21 -1
  10. package/dist/actions/register_action_ws.d.ts.map +1 -1
  11. package/dist/actions/register_action_ws.js +2 -1
  12. package/dist/actions/ws_socket_session.d.ts +25 -4
  13. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  14. package/dist/actions/ws_socket_session.js +81 -25
  15. package/dist/auth/CLAUDE.md +433 -1048
  16. package/dist/auth/account_queries.d.ts +1 -1
  17. package/dist/auth/account_queries.js +1 -1
  18. package/dist/auth/account_routes.d.ts +4 -5
  19. package/dist/auth/account_routes.d.ts.map +1 -1
  20. package/dist/auth/account_routes.js +8 -10
  21. package/dist/auth/admin_actions.d.ts.map +1 -1
  22. package/dist/auth/admin_actions.js +10 -11
  23. package/dist/auth/api_token.d.ts +20 -3
  24. package/dist/auth/api_token.d.ts.map +1 -1
  25. package/dist/auth/api_token.js +28 -9
  26. package/dist/auth/api_token_queries.d.ts +2 -2
  27. package/dist/auth/api_token_queries.js +2 -2
  28. package/dist/auth/audit_log_routes.d.ts +1 -1
  29. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  30. package/dist/auth/audit_log_routes.js +3 -2
  31. package/dist/auth/audit_log_schema.d.ts +15 -9
  32. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  33. package/dist/auth/audit_log_schema.js +1 -2
  34. package/dist/auth/auth_guard_resolver.d.ts +1 -1
  35. package/dist/auth/auth_guard_resolver.js +1 -1
  36. package/dist/auth/bearer_auth.d.ts +2 -5
  37. package/dist/auth/bearer_auth.d.ts.map +1 -1
  38. package/dist/auth/bearer_auth.js +4 -13
  39. package/dist/auth/bootstrap_account.d.ts +13 -15
  40. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  41. package/dist/auth/bootstrap_account.js +9 -11
  42. package/dist/auth/bootstrap_routes.d.ts +20 -21
  43. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  44. package/dist/auth/bootstrap_routes.js +21 -19
  45. package/dist/auth/bootstrap_token_store.d.ts +3 -4
  46. package/dist/auth/bootstrap_token_store.d.ts.map +1 -1
  47. package/dist/auth/bootstrap_token_store.js +1 -1
  48. package/dist/auth/cleanup.d.ts +34 -3
  49. package/dist/auth/cleanup.d.ts.map +1 -1
  50. package/dist/auth/cleanup.js +11 -3
  51. package/dist/auth/daemon_token.d.ts +5 -1
  52. package/dist/auth/daemon_token.d.ts.map +1 -1
  53. package/dist/auth/daemon_token_middleware.d.ts +12 -8
  54. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  55. package/dist/auth/daemon_token_middleware.js +15 -21
  56. package/dist/auth/deps.d.ts +11 -0
  57. package/dist/auth/deps.d.ts.map +1 -1
  58. package/dist/auth/invite_queries.d.ts +51 -3
  59. package/dist/auth/invite_queries.d.ts.map +1 -1
  60. package/dist/auth/invite_queries.js +81 -6
  61. package/dist/auth/invite_schema.d.ts +2 -1
  62. package/dist/auth/invite_schema.d.ts.map +1 -1
  63. package/dist/auth/middleware.d.ts +2 -3
  64. package/dist/auth/middleware.d.ts.map +1 -1
  65. package/dist/auth/middleware.js +3 -3
  66. package/dist/auth/request_context.d.ts +3 -3
  67. package/dist/auth/request_context.js +3 -3
  68. package/dist/auth/role_grant_offer_actions.d.ts +2 -2
  69. package/dist/auth/role_grant_offer_actions.js +2 -2
  70. package/dist/auth/session_cookie.d.ts +82 -174
  71. package/dist/auth/session_cookie.d.ts.map +1 -1
  72. package/dist/auth/session_cookie.js +80 -130
  73. package/dist/auth/session_middleware.d.ts +8 -17
  74. package/dist/auth/session_middleware.d.ts.map +1 -1
  75. package/dist/auth/session_middleware.js +14 -23
  76. package/dist/auth/session_queries.d.ts +9 -14
  77. package/dist/auth/session_queries.d.ts.map +1 -1
  78. package/dist/auth/session_queries.js +8 -9
  79. package/dist/auth/signup_routes.d.ts.map +1 -1
  80. package/dist/auth/signup_routes.js +4 -6
  81. package/dist/db/CLAUDE.md +5 -3
  82. package/dist/dev/setup.d.ts +3 -1
  83. package/dist/dev/setup.d.ts.map +1 -1
  84. package/dist/dev/setup.js +3 -1
  85. package/dist/http/CLAUDE.md +315 -768
  86. package/dist/http/db_routes.d.ts +1 -1
  87. package/dist/http/db_routes.js +1 -1
  88. package/dist/http/origin.d.ts +7 -8
  89. package/dist/http/origin.d.ts.map +1 -1
  90. package/dist/http/origin.js +7 -8
  91. package/dist/http/pending_effects.d.ts +82 -4
  92. package/dist/http/pending_effects.d.ts.map +1 -1
  93. package/dist/http/pending_effects.js +82 -4
  94. package/dist/http/route_result.d.ts +1 -1
  95. package/dist/http/route_spec.d.ts +17 -14
  96. package/dist/http/route_spec.d.ts.map +1 -1
  97. package/dist/realtime/audit_log_sse.d.ts +1 -1
  98. package/dist/realtime/sse.d.ts +6 -25
  99. package/dist/realtime/sse.d.ts.map +1 -1
  100. package/dist/realtime/sse.js +4 -25
  101. package/dist/realtime/sse_constants.d.ts +1 -1
  102. package/dist/realtime/sse_constants.js +1 -1
  103. package/dist/server/app_backend.d.ts +4 -5
  104. package/dist/server/app_backend.d.ts.map +1 -1
  105. package/dist/server/app_backend.js +3 -1
  106. package/dist/server/app_server.d.ts +87 -76
  107. package/dist/server/app_server.d.ts.map +1 -1
  108. package/dist/server/app_server.js +111 -91
  109. package/dist/server/app_server_context.d.ts +1 -2
  110. package/dist/server/app_server_context.d.ts.map +1 -1
  111. package/dist/server/env.js +2 -2
  112. package/dist/server/shutdown_drain.d.ts +69 -0
  113. package/dist/server/shutdown_drain.d.ts.map +1 -0
  114. package/dist/server/shutdown_drain.js +77 -0
  115. package/dist/testing/CLAUDE.md +89 -57
  116. package/dist/testing/admin_integration.d.ts +4 -5
  117. package/dist/testing/admin_integration.d.ts.map +1 -1
  118. package/dist/testing/admin_integration.js +39 -23
  119. package/dist/testing/app_server.d.ts +3 -8
  120. package/dist/testing/app_server.d.ts.map +1 -1
  121. package/dist/testing/app_server.js +10 -9
  122. package/dist/testing/attack_surface.d.ts +1 -1
  123. package/dist/testing/attack_surface.d.ts.map +1 -1
  124. package/dist/testing/audit_completeness.d.ts +2 -3
  125. package/dist/testing/audit_completeness.d.ts.map +1 -1
  126. package/dist/testing/audit_completeness.js +1 -1
  127. package/dist/testing/cross_backend/bootstrap_backend.d.ts +3 -1
  128. package/dist/testing/cross_backend/bootstrap_backend.d.ts.map +1 -1
  129. package/dist/testing/cross_backend/bootstrap_backend.js +5 -1
  130. package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -1
  131. package/dist/testing/cross_backend/capability_mounts.js +16 -11
  132. package/dist/testing/cross_backend/conformance_table.d.ts +5 -6
  133. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/conformance_table.js +4 -4
  135. package/dist/testing/cross_backend/cookie_attributes.js +1 -1
  136. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts +10 -1
  137. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts.map +1 -1
  138. package/dist/testing/cross_backend/create_dual_spawn_global_setup.js +33 -7
  139. package/dist/testing/cross_backend/default_backend_configs.d.ts +3 -3
  140. package/dist/testing/cross_backend/default_spine_surface.d.ts +0 -6
  141. package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/default_spine_surface.js +4 -9
  143. package/dist/testing/cross_backend/differential.d.ts +2 -3
  144. package/dist/testing/cross_backend/differential.d.ts.map +1 -1
  145. package/dist/testing/cross_backend/differential.js +1 -1
  146. package/dist/testing/cross_backend/full_spine_mount.d.ts +1 -42
  147. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  148. package/dist/testing/cross_backend/full_spine_mount.js +45 -4
  149. package/dist/testing/cross_backend/in_process_setup.d.ts +7 -8
  150. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  151. package/dist/testing/cross_backend/in_process_setup.js +10 -13
  152. package/dist/testing/cross_backend/rpc_success_fixtures.d.ts.map +1 -1
  153. package/dist/testing/cross_backend/rpc_success_fixtures.js +2 -1
  154. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +3 -4
  155. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  156. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -2
  157. package/dist/testing/cross_backend/setup.d.ts +1 -1
  158. package/dist/testing/cross_backend/spawn_backend.d.ts +14 -0
  159. package/dist/testing/cross_backend/spawn_backend.d.ts.map +1 -1
  160. package/dist/testing/cross_backend/spawn_backend.js +56 -8
  161. package/dist/testing/cross_backend/spine_suites.d.ts +18 -16
  162. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  163. package/dist/testing/cross_backend/spine_suites.js +38 -18
  164. package/dist/testing/cross_backend/standard.d.ts +19 -84
  165. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  166. package/dist/testing/cross_backend/standard.js +8 -23
  167. package/dist/testing/cross_backend/standard_auth.d.ts +74 -0
  168. package/dist/testing/cross_backend/standard_auth.d.ts.map +1 -0
  169. package/dist/testing/cross_backend/standard_auth.js +28 -0
  170. package/dist/testing/cross_backend/standard_bundle.d.ts +48 -0
  171. package/dist/testing/cross_backend/standard_bundle.d.ts.map +1 -0
  172. package/dist/testing/cross_backend/standard_bundle.js +43 -0
  173. package/dist/testing/cross_backend/testing_credential_read.d.ts +10 -11
  174. package/dist/testing/cross_backend/testing_credential_read.d.ts.map +1 -1
  175. package/dist/testing/cross_backend/testing_credential_read.js +12 -12
  176. package/dist/testing/cross_backend/testing_reset_actions.d.ts +46 -30
  177. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  178. package/dist/testing/cross_backend/testing_reset_actions.js +52 -31
  179. package/dist/testing/cross_backend/testing_server_bun.d.ts.map +1 -1
  180. package/dist/testing/cross_backend/testing_server_bun.js +5 -4
  181. package/dist/testing/cross_backend/testing_server_core.d.ts +16 -3
  182. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  183. package/dist/testing/cross_backend/testing_server_core.js +22 -7
  184. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +6 -2
  185. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  186. package/dist/testing/cross_backend/ts_spine_backend_config.js +7 -3
  187. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  188. package/dist/testing/daemon_token_rotation.js +2 -3
  189. package/dist/testing/error_coverage.d.ts +5 -0
  190. package/dist/testing/error_coverage.d.ts.map +1 -1
  191. package/dist/testing/error_coverage.js +2 -1
  192. package/dist/testing/integration.d.ts +6 -23
  193. package/dist/testing/integration.d.ts.map +1 -1
  194. package/dist/testing/integration.js +53 -83
  195. package/dist/testing/integration_helpers.d.ts +16 -0
  196. package/dist/testing/integration_helpers.d.ts.map +1 -1
  197. package/dist/testing/integration_helpers.js +29 -1
  198. package/dist/testing/middleware_gate_probes.d.ts +55 -1
  199. package/dist/testing/middleware_gate_probes.d.ts.map +1 -1
  200. package/dist/testing/middleware_gate_probes.js +69 -3
  201. package/dist/testing/rate_limiting.d.ts +2 -3
  202. package/dist/testing/rate_limiting.d.ts.map +1 -1
  203. package/dist/testing/rate_limiting.js +3 -3
  204. package/dist/testing/rpc_helpers.d.ts +1 -2
  205. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  206. package/dist/testing/rpc_helpers.js +3 -3
  207. package/dist/testing/rpc_round_trip.d.ts +2 -3
  208. package/dist/testing/rpc_round_trip.d.ts.map +1 -1
  209. package/dist/testing/rpc_round_trip.js +1 -1
  210. package/dist/testing/sse_round_trip.d.ts +2 -3
  211. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  212. package/dist/testing/sse_round_trip.js +2 -2
  213. package/dist/testing/stubs.d.ts +5 -6
  214. package/dist/testing/stubs.d.ts.map +1 -1
  215. package/dist/testing/stubs.js +10 -8
  216. package/dist/testing/test_app.d.ts +8 -5
  217. package/dist/testing/test_app.d.ts.map +1 -1
  218. package/dist/testing/test_app.js +7 -7
  219. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  220. package/dist/testing/ws_round_trip.js +3 -0
  221. package/dist/ui/ui_format.d.ts.map +1 -1
  222. package/dist/ui/ui_format.js +1 -2
  223. package/package.json +1 -1
@@ -8,29 +8,48 @@ For consumer wiring (client-authoritative vs server-authoritative dispatch,
8
8
  role-grant-offer UI integration), see ../../../docs/usage.md §Deriving
9
9
  Event Specs from Action Specs, §Single JSON-RPC 2.0 Endpoint, §WebSocket Endpoint. For
10
10
  DEV-only output validation semantics see ../../../docs/architecture.md
11
- §DEV-only Output Validation. For the SAES binding matrix and middleware
12
- ordering see the root ../../../CLAUDE.md §Action Spec System (SAES) and
13
- §Middleware Ordering.
11
+ §DEV-only Output Validation. For the phase order and middleware ordering see
12
+ the root ../../../CLAUDE.md §Action Spec System (SAES) and §Middleware
13
+ Ordering. The WS security properties (admission, the per-account cap, request
14
+ and outbound bounds, closing on revocation) are ../../../docs/security.md's.
14
15
 
15
16
  **CLAUDE.md is a map; TSDoc is the detail.** Per-symbol semantics
16
- (parameters, options, lifecycle methods, narrowing rules) live on TSDoc next
17
- to the code. This file documents the cross-cutting invariants and the
18
- shapes that span multiple files.
17
+ (parameters, options, defaults, lifecycle methods, narrowing rules) live on
18
+ TSDoc next to the code. This file says what each module is, when to reach for
19
+ it, and the cross-cutting rules a caller would miss.
19
20
 
20
21
  Every exported schema is a `@fuzdev/fuz_schema` schema paired with a
21
22
  same-named `Infer` type export. New schemas keep the pair invariant.
22
23
 
24
+ ## Module map
25
+
26
+ - `action_spec.ts` — `ActionSpec`, its three kinds, `ActionSpecUnion`, the kind / initiator / phase enums
27
+ - `action_types.ts` — the handler-side surface: `Action`, `RpcAction`, `ActionContext` and its narrowed tiers, the handler signatures, `HandlerForSpec`, `rpc_action`. Kept free of server-only imports so composable primitives (`heartbeat_action`) can name the types
28
+ - `compile_action_registry.ts` — the registration checks both dispatchers run
29
+ - `action_registry.ts`, `action_codegen.ts` — `ActionRegistry` and the codegen helpers
30
+ - `action_rpc.ts` — `create_rpc_endpoint` (HTTP JSON-RPC), `RPC_GET_CACHE_CONTROL`, `RPC_GET_UNDECODABLE_QUERY_REASON`
31
+ - `perform_action.ts` — the transport-agnostic dispatch core and `serialize_action_result`
32
+ - `ws_endpoint_spec.ts` — `WsEndpointSpec`, `resolve_ws_endpoints`
33
+ - `register_action_ws.ts` — the WS upgrade route; `ws_socket_session.ts` — one upgraded socket's events
34
+ - `connection_registry.ts` — `ConnectionRegistry`; `ws_outbound_writer.ts` — one connection's outbound queue; `peer_request.ts` — server→client request correlation
35
+ - `connection_closer.ts` — `ConnectionCloser`, `RealtimeCloser`, the revocation guard; `notification_sender.ts` — `NotificationSender`
36
+ - `room_registry.ts`, `room_action_specs.ts`, `room_actions.ts`, `room_client.svelte.ts` — rooms
37
+ - `protocol.ts`, `heartbeat.ts`, `cancel.ts`, `peer_ping.ts` — the protocol actions
38
+ - `action_event_types.ts`, `action_event_data.ts`, `action_event_helpers.ts`, `action_event.ts`, `action_dispatcher.ts` — the event state machine
39
+ - `transports.ts`, `transports_http.ts`, `transports_ws.ts` — `Transport`, the frontend transports, the WS close codes
40
+ - `socket.svelte.ts` — `FrontendWebsocketClient`
41
+ - `rpc_client.ts`, `frontend_rpc_client.ts` — the typed RPC clients
42
+ - `broadcast_api.ts` — `create_broadcast_api`
43
+ - `action_bridge.ts` — `create_action_event_spec`
44
+
23
45
  ## Action specs (`actions/action_spec.ts`)
24
46
 
25
47
  Canonical source of truth. Specs are plain objects typed by TS interfaces
26
48
  (`ActionSpec` and its three kinds, `ActionSpecUnion`), written with
27
49
  `satisfies` so their literals survive; nothing parses a spec at runtime, so
28
50
  every required field is spelled — no defaults. `input` / `output` are a
29
- `@fuzdev/fuz_schema` schema (`AnySchema`). `ActionKind`,
30
- `ActionInitiator` and `ActionEventPhase` are fuz_schema `one_of`s
31
- (`ActionEventData` validates with them), built from the const lists `ACTION_KINDS`,
32
- `ACTION_INITIATORS` and `ACTION_EVENT_PHASES`; `is_action_spec` reads
33
- `ACTION_KINDS`. Three concrete kinds discriminate on `kind`:
51
+ `@fuzdev/fuz_schema` schema (`AnySchema`). Three concrete kinds discriminate
52
+ on `kind`:
34
53
 
35
54
  - `request_response` — `auth: RouteAuth` (non-null), `side_effects` arbitrary, `output` arbitrary, `async: true`.
36
55
  - `remote_notification` — `auth: null`, `side_effects: true`, `output` fuz_schema's void schema, `s.void`, `async: true`.
@@ -38,16 +57,13 @@ every required field is spelled — no defaults. `input` / `output` are a
38
57
 
39
58
  `RouteAuth` is the flat record
40
59
  `{account, actor, roles?, credential_types?, required_scope?}` from
41
- `http/auth_shape.ts` — same shape governs `RouteSpec.auth` so one auth
42
- surface drives routes and SAES. Cross-axis invariants: roles imply
43
- `actor: 'required'`; `account: 'none'` implies `actor: 'none'` (no
44
- accountless actors in v1); the unrestricted leaf
45
- (`account: 'none', actor: 'none'`) cannot declare roles or credential
46
- gates — checked at registration time via `assert_route_auth_invariants`, on
47
- action and route specs alike (a spec is a plain object nothing parses). The
48
- biconditional `actor !== 'none' ⟺ input declares acting?: ActingActor`
49
- is enforced at registration time via `assert_route_auth_acting_biconditional`.
50
- `required_scope` is the one axis actions cannot use — see §Registry compile.
60
+ `http/auth_shape.ts` — one auth shape drives routes and SAES. Its cross-axis
61
+ invariants (roles imply `actor: 'required'`; `account: 'none'` implies
62
+ `actor: 'none'`, no accountless actors; the unrestricted leaf declares no
63
+ roles or credential gates) and the biconditional
64
+ `actor !== 'none' ⟺ input declares acting?: ActingActor` are checked at
65
+ registration (§Registry compile). `required_scope` is the one axis actions
66
+ cannot use.
51
67
 
52
68
  Optional fields:
53
69
 
@@ -59,17 +75,15 @@ Optional fields:
59
75
  caught per-module by source-scanning unit tests (e.g.
60
76
  ../../test/auth/role_grant_offer_actions.error_reasons.test.ts).
61
77
  - `rate_limit?: 'ip' | 'account' | 'both'` — opts the action into the
62
- dispatcher's per-action rate-limit hook. **Throttle-requests semantics**
63
- — every invocation records regardless of outcome (different from REST
64
- login's throttle-failures), and the gate fires ahead of param validation
65
- so malformed calls are charged too. `'account'` / `'both'` rejected at
66
- registration when paired with `auth.account !== 'required'`. Limiters configured via
67
- `AppServerOptions.action_ip_rate_limiter` / `action_account_rate_limiter`
68
- and threaded into both dispatchers automatically.
69
-
70
- Canonical spec shape: module-scope `satisfies` declaration with
71
- `{method}_action_spec` naming, preserving the literal `method` type and
72
- dropping per-spec `*_METHOD` constants (readers dereference `.method`). See
78
+ dispatcher's per-action rate limit. **Throttle-requests semantics**: every
79
+ invocation records regardless of outcome (unlike REST login's
80
+ throttle-failures), ahead of param validation so malformed calls are
81
+ charged too. The limiters are `AppServerOptions.action_ip_rate_limiter` /
82
+ `action_account_rate_limiter`, threaded into both dispatchers.
83
+
84
+ Canonical spec shape: module-scope `satisfies` declaration named
85
+ `{method}_action_spec`, preserving the literal `method` type (readers
86
+ dereference `.method`; no `*_METHOD` constants). See
73
87
  ../../../docs/usage.md §Canonical action-spec shape.
74
88
 
75
89
  ## Kind → binding matrix
@@ -101,530 +115,251 @@ registry-only.
101
115
 
102
116
  ## Registry + codegen (`actions/action_registry.ts`, `actions/action_codegen.ts`)
103
117
 
104
- **Symmetric design — universal calling abstraction.** SAES is one spec
105
- shape driving dispatch across (a) network boundaries (frontend ⇄ backend
106
- over HTTP / WS) and (b) within the same runtime (`local_call` actions).
107
- `ActionDispatcher` is symmetric on both sides (`send` + `receive`). Typed
108
- surfaces are paired: `FrontendActionsApi` is "what the frontend can call"
109
- (typed Proxy from `create_rpc_client`); `BackendActionsApi` is "what the
110
- backend can call" (typed object from `create_broadcast_api` today;
111
- broader runtime constructors will join). Remaining asymmetry:
112
- `create_broadcast_api` returns `Promise<void>` while `FrontendActionsApi`
113
- methods return `Promise<Result<...>>`. Closing those gaps is on the
114
- deferred follow-up set from the SAES RPC closeout work
115
- — wait for a second backend runtime case.
116
-
117
- ### `ActionRegistry`
118
-
119
- Query/filter wrapper over `ActionSpecUnion[]`. Codegen-relevant getter
120
- groups (each pairs `_specs` with matching `_methods`):
121
-
122
- - Kind-narrow — filter by `kind`; drives `*ActionMethod` enums.
123
- - `*_handled` — `request_response` + handler-side initiator; drives `BackendActionHandlers` map.
124
- - `specs_relevant_to_*` — everything the side might encounter; drives typed-Proxy method enums.
125
- - `broadcast` — `remote_notification`, `initiator !== 'frontend'`, excludes streams; drives `BackendActionsApi` interface.
126
- - `backend_initiated` — forward-looking kind-agnostic broadcast; same content today.
127
-
128
- Other getters (auth filters, initiator-direction filters) are pre-built API
129
- surface unused by codegen today.
130
-
131
- ### Codegen helpers (`actions/action_codegen.ts`)
132
-
133
- Used by consumer `*.gen.ts` producers, not the runtime. Detailed signatures
134
- and options on each function's TSDoc.
135
-
136
- - `ImportBuilder` — class managing value/type/namespace imports; auto-tree-shakes type-only.
137
- - `get_executor_phases(spec, executor)` — phases an executor participates in for the spec.
138
- - `get_handler_return_type` — TS type a phase handler must return; side-effect imports `ActionOutputs`.
139
- - `generate_phase_handlers` — per-action typed handler-map fragment.
140
- - `generate_frontend_actions_api` — typed `FrontendActionsApi` interface. A void or null input (`is_void_schema`, `is_null_schema`) emits `input?: void`; otherwise each method's `input?:` follows `action_input_is_optional` (by `parse`) — the schema accepts `undefined`, or accepts `{}` and is not marked `meta(…, {empty_input_handler_guarded: true})` (read by `is_empty_input_handler_guarded` in `schema_meta.ts` — set on `cell_get`, `cell_field_list` and `cell_item_list`, whose `{}` reaches a handler guard that refuses it with a declared reason, so their input stays required; a consumer marks its own the same way); an input-shape invariant test reads the same rule. Each input is typed `ActionCallInputs[method]`, the schema's input type — what a caller passes before the parse, so a `with_default` field is optional at the call.
141
- - `generate_action_method_enums` — up to nine `@fuzdev/fuz_schema` `one_of` + `Infer` pairs, importing `{one_of, type Infer}` from `@fuzdev/fuz_schema/schema.ts`; a const's `def` is its method array.
142
- - `generate_typed_action_event_alias` — fixed-shape `TypedActionEvent<TMethod, TPhase, TStep>` alias.
143
- - `generate_action_specs_record` — `ActionSpecs` runtime const + type + `action_specs` array. The const is annotated with the type (`readonly` members), so a consumer's declaration emit names the type instead of writing every spec's schema types out, which past enough specs is TS7056. The type is an alias, not an interface: an alias has an implicit index signature, so `Object.values(ActionSpecs)` stays typed and `action_specs` checks each spec against `ActionSpecUnion` (over an interface it is `any[]`).
144
- - `generate_action_inputs_outputs` — the `ActionInputs`, `ActionCallInputs` and `ActionOutputs` interfaces, types only (a const's inferred type would be written out whole in a declaration file, TS7056 past enough specs; the schemas are read off `ActionSpecs`), importing `Infer` and `InferInput`; a value that is no schema throws naming the method. The two sides of a call see one input schema differently, so its types split by side: `ActionInputs` is each input's output type (`Infer<typeof …>`) — the parsed value a handler, an action event (`ActionEventDatas`) or a notification receiver reads, defaults filled and transforms applied; `ActionCallInputs` is its input type (`InferInput<typeof …>`) — what a caller passes, which the call surfaces (`FrontendActionsApi`, `BackendActionsApi`) take, so a `with_default` field is optional there and required in `ActionInputs`. `ActionOutputs` is each output's output type, what a caller receives.
145
- - `generate_action_event_datas` — `ActionEventDatas` interface; per-spec variants.
146
- - `generate_frontend_action_handlers` — `FrontendActionHandlers` interface (Tier 2 only).
147
- - `generate_backend_actions_api` — `BackendActionsApi` interface + `broadcast_action_specs` array.
148
- - `compose_gen_file` — wrapper: banner + `imports.build()` + blocks join.
149
- - `create_namespace_qualifier(sources, imports)` — multi-source consumer helper; registers `import * as ns` per source.
150
-
151
- Shared defaults: `collections_path` is `'./action_collections.ts'`,
152
- `specs_module` is `'./action_specs.ts'`, and `metatypes_path` is
153
- `'./action_metatypes.ts'`.
154
-
155
- ### Codegen invariants
156
-
157
- **Protocol actions filtered by default.** Every spec-iterating helper
158
- accepts `{include_protocol_actions?: boolean}` (default `false`) and drops
159
- `heartbeat` / `cancel` / `peer/ping`. Protocol actions ship from fuz_app and spread into
160
- each consumer's `actions` array at registration time (via
161
- `protocol_actions` from `actions/protocol.ts`); they should not appear in
162
- consumer-owned typed surfaces. Pass `include_protocol_actions: true` only
163
- if a consumer genuinely owns protocol actions in their typed API.
164
-
165
- **Consumer tiers.** Single-source consumers (zzz) drop into the helpers
166
- and accept the default `* as specs` namespace import. Multi-source
167
- consumers (stitching local specs with `all_admin_action_specs` /
168
- `all_role_grant_offer_action_specs` / `all_account_action_specs` /
169
- `all_self_service_role_action_specs` from fuz_app) call
170
- `create_namespace_qualifier` once, then pass the returned
171
- `qualify_spec` callback to multi-source helpers.
172
-
173
- **Tier 1** (HTTP-only) emits a smaller surface — typically
174
- `ActionMethod` + `FrontendActionsApi` + `ActionInputs` / `ActionOutputs`.
175
- Never calls `generate_typed_action_event_alias` or
176
- `generate_frontend_action_handlers`. **Tier 2** (`TypedActionEvent`-aware,
177
- zzz) emits the full set including `ActionEventDatas`, `TypedActionEvent`,
178
- and `FrontendActionHandlers`.
118
+ This is the home of the codegen docs; signatures and options are on each
119
+ function's TSDoc. The typed surfaces come in pairs: `FrontendActionsApi`
120
+ (what the frontend can call, the typed Proxy from `create_rpc_client`) and
121
+ `BackendActionsApi` (what the backend can call, from `create_broadcast_api`).
122
+
123
+ `ActionRegistry` is a query/filter wrapper over `ActionSpecUnion[]`. The
124
+ getter groups codegen reads (each pairs `_specs` with `_methods`): kind-narrow
125
+ (the `*ActionMethod` enums), `*_handled` (`BackendActionHandlers`),
126
+ `specs_relevant_to_*` (the typed-Proxy method enums), and `broadcast`
127
+ (`remote_notification`, not frontend-initiated, streams excluded —
128
+ `BackendActionsApi`).
129
+
130
+ The helpers, used by consumer `*.gen.ts` producers, not the runtime:
131
+ `ImportBuilder`, `compose_gen_file`, `create_namespace_qualifier`, and a
132
+ `generate_*` per emitted block — `generate_action_method_enums`,
133
+ `generate_action_specs_record`, `generate_action_inputs_outputs`,
134
+ `generate_frontend_actions_api`, `generate_backend_actions_api`,
135
+ `generate_action_event_datas`, `generate_typed_action_event_alias`,
136
+ `generate_phase_handlers`, `generate_frontend_action_handlers`. The default
137
+ paths are `DEFAULT_COLLECTIONS_PATH` and siblings.
138
+
139
+ The rules a consumer acts on:
140
+
141
+ - **Protocol actions are filtered by default.** Every spec-iterating helper
142
+ takes `{include_protocol_actions?: boolean}` (default `false`) and drops the
143
+ `PROTOCOL_ACTION_METHODS` (`heartbeat`, `cancel`, `peer/ping`): they ship
144
+ from fuz_app and spread into each consumer's `actions` at registration
145
+ (§Protocol actions), not into consumer-owned typed surfaces.
146
+ - **Call inputs vs handler inputs.** `ActionCallInputs` is each input
147
+ schema's input type (`InferInput`) — what a caller passes, so a
148
+ `with_default` field is optional; `ActionInputs` is its output type
149
+ (`Infer`) — what a handler, an action event or a notification receiver
150
+ reads. The call surfaces (`FrontendActionsApi`, `BackendActionsApi`) take
151
+ `ActionCallInputs`.
152
+ - **Optional input.** `generate_frontend_actions_api` makes a method's input
153
+ optional when its schema accepts `undefined`, or accepts `{}` and is not
154
+ marked `meta(…, {empty_input_handler_guarded: true})` (`schema_meta.ts`).
155
+ Mark an input whose `{}` reaches a handler guard that refuses it with a
156
+ declared reason, as `cell_get`, `cell_field_list` and `cell_item_list` do,
157
+ so its input stays required.
158
+ - **Consumer tiers.** Single-source consumers (zzz) take the default
159
+ `* as specs` namespace import. Multi-source consumers (local specs plus
160
+ fuz_app's `all_*_action_specs`) call `create_namespace_qualifier` once and
161
+ pass its `qualify_spec` to the helpers. **Tier 1** (HTTP-only) emits
162
+ `ActionMethod` + `FrontendActionsApi` + `ActionInputs` / `ActionOutputs`;
163
+ **Tier 2** (`TypedActionEvent`-aware, zzz) adds `ActionEventDatas`,
164
+ `TypedActionEvent` and `FrontendActionHandlers`.
179
165
 
180
166
  ## Single JSON-RPC 2.0 endpoint (`actions/action_rpc.ts`)
181
167
 
182
- `create_rpc_endpoint({path, actions, log, action_ip_rate_limiter, action_account_rate_limiter, notification_sender}): RouteSpec[]`
183
- produces **two** route specs on the same path (GET + POST) that share one
184
- internal dispatcher. The two limiters are required `RateLimiter | null` with
185
- no default — `null` is the explicit off switch — and the same holds on
186
- `register_action_ws`, so a hand mount can't run
187
- unthrottled by omission. `create_app_server` passes its own to every endpoint
188
- it mounts (../../../docs/usage.md §Rate limiters). `notification_sender` is
189
- required on both the same way (§Notification sender). Per-action auth lives inside the dispatcher; the outer routes
190
- use `auth: {account: 'none', actor: 'none'}` and `transaction: false`.
191
-
192
- The HTTP RPC dispatcher is a thin shim around `perform_action`
193
- (`actions/perform_action.ts`). The shim owns wire-shape concerns (envelope
194
- parsing, GET vs POST split, the envelope responses — each a `route_raw` data result); the
195
- auth/validation/dispatch pipeline is shared with the WebSocket dispatcher.
196
-
197
- **Phase order: 401 → authz → 403 → 429 → 400 → handler.** Authorize first,
198
- throttle, validate after — a caller the authority gates refuse never learns
199
- the action's input shape, the coarse authority facts settle before the fine
200
- ones, and a malformed flood burns the budget it should. The Rust spine's
201
- dispatcher enforces the same order: after the rate limit it refuses a
202
- non-object `params` (which only `GET`'s `?params=` can carry past the
203
- envelope) and validates the `acting` selector, and leaves every other field
204
- to the handlers. So an anonymous `GET` with `?params=42` is a 401 on both
205
- spines, and an authorized one is `invalid_params`.
206
-
207
- Shim responsibilities (per-request):
208
-
209
- 1. Parse envelope (POST body / GET query string, each through `parse_json_text`, `http/json_text.ts`, so JSON the Rust spine refuses is refused here too); parse errors → `parse_error` 400, a `GET` `params` that is no JSON `invalid_params`. GET reads `method` / `id` / `params` with `query_first` over `route.query_pairs` (the query decoded strictly, `http/request_target.ts`) — a query holding an escape that doesn't decode is `invalid_request` on `id: null` with reason `undecodable query string` (`RPC_GET_UNDECODABLE_QUERY_REASON`), ahead of the method lookup; first occurrence wins on a duplicated key, unknown keys are ignored, and an empty value counts as missing. This is the cross-impl contract (the Rust GET dispatch mirrors it via `fuz_http`'s `query_first`, including the id numeric-vs-string normalization), pinned by the `query_shape` cross suite.
210
- 2. Lookup method in the `compile_action_registry`-built map; unknown → `method_not_found`.
211
- 3. GET read restriction — GET rejected for `side_effects: true` actions. Every answer of the GET route carries `Cache-Control: no-store` (`RPC_GET_CACHE_CONTROL`), declared as the spec's `response_headers`, so the handler's refusals and the error catch's 500 carry it too; a refusal by middleware ahead of the route, like the origin 403, does not: a read answers one caller at one moment.
212
- 4. Build `PerformActionInput` from the route context: `route.credential`, `route.client_ip`, `route.signal`. The test-preset escape hatch reads `route.has_test_context_preset` and `route.auth`.
213
- 5. Call `perform_action` (shared core).
214
- 6. Bind result via `serialize_action_result(id, result, method, log)` (`actions/perform_action.ts`, shared with WS) → `{body, status}`, spelled with `c.json`'s bytes and content type as a `route_raw` data result, as is every envelope the shim answers: no REST definition describes one.
215
-
216
- Error paths: `ThrownJsonrpcError` (recognized through
217
- `to_thrown_jsonrpc_error` in `http/jsonrpc_errors.ts` by its realm-global
218
- brand, so one from a second fuz_app copy — e.g. a consumer like zzz resolving
219
- its own — matches where `instanceof` misses; the REST catch layer, the frontend
220
- transports, and `ActionEvent` read thrown errors the same way) preserves code +
221
- data verbatim. Anything else takes the generic path: a foreign error class
222
- carrying a JSON-RPC `code`, a `ThrownJsonrpcError` whose `code` was cast
223
- outside the JSON-RPC set, a `DOMException`. Generic throws become
224
- `internal_error` 500; message is the raw error under `DEV`, "internal server
225
- error" otherwise.
226
-
227
- A result that cannot be serialized (a `bigint`, a cycle) answers the same
228
- `internal_error` 500 rather than throwing (`serialize_action_result`, which the
229
- WS dispatcher shares). By then `perform_action` has
230
- committed, and a throw would have the route wrapper
231
- (`dispatch_with_post_commit_rollback`) discard the handler's
232
- `post_commit_effects` — the connection closes of a revocation that did land.
233
-
234
- ### Per-request handler shape
235
-
236
- Unified across HTTP RPC + WS via `ActionContext` (`actions/action_types.ts`):
237
-
238
- ```ts
239
- interface ActionContext {
240
- auth: RequestContext | null; // null for public actions
241
- request_id: JsonrpcRequestId;
242
- connection_id?: Uuid; // populated on WS, undefined on HTTP
243
- request_client?: RequestClient; // WS only: initiate a server→client request + await the reply (ActionPeer); undefined on HTTP
244
- db: Db; // transaction for mutations, pool for reads
245
- pending_effects: Array<Promise<void>>; // eager — see http/CLAUDE.md §Pending Effects
246
- post_commit_effects: Array<() => void | Promise<void>>; // deferred — push via `emit_after_commit`
247
- client_ip: string;
248
- credential_type: BuiltinCredentialType | null; // same value the credential_types gate consumed
249
- log: Logger;
250
- notify: (method, params) => void; // HTTP: DEV-mode warn + drop; WS: socket-scoped
251
- notification_sender: NotificationSender; // every socket of an account, on every mounted registry; never null
252
- signal: AbortSignal; // HTTP: client-disconnect; WS: AbortSignal.any([socket_close, request_cancel])
253
- }
254
-
255
- interface RpcAction {
256
- spec: RequestResponseActionSpec;
257
- handler: ActionHandler;
258
- }
259
- ```
168
+ `create_rpc_endpoint(options): RouteSpec[]` produces **two** route specs on
169
+ one path (GET + POST) sharing one dispatcher; per-action auth lives inside
170
+ it, so the outer routes are `auth: {account: 'none', actor: 'none'}`,
171
+ `transaction: false`. `create_app_server` mounts every `rpc_endpoints` entry
172
+ itself. The two action limiters and `notification_sender` are required with
173
+ no default (`null` limiter is the explicit off switch), the same on
174
+ `register_action_ws`, so a hand mount can't run unthrottled by omission
175
+ (../../../docs/usage.md §Rate limiters).
176
+
177
+ The HTTP dispatcher is a thin shim around `perform_action`: it owns the wire
178
+ shape — envelope parsing (`parse_json_text`, so JSON the Rust spine refuses
179
+ is refused here too), the GET vs POST split, method lookup
180
+ (`method_not_found`), and the envelope responses, each a `route_raw` result
181
+ built by `serialize_action_result`. GET's query-reading rules (first
182
+ occurrence wins, an undecodable query is `invalid_request` with
183
+ `RPC_GET_UNDECODABLE_QUERY_REASON`) are the cross-impl contract, on the
184
+ module's TSDoc and pinned by the `query_shape` cross suite.
185
+
186
+ - **GET is for reads.** A `side_effects: true` action is refused over GET.
187
+ Every answer of the GET route carries `Cache-Control: no-store`
188
+ (`RPC_GET_CACHE_CONTROL`, declared as `response_headers`); a refusal by
189
+ middleware ahead of the route does not.
190
+ - **Phase order: 401 → authz → 403 → 429 → 400 → handler.** Authorize first,
191
+ throttle, validate after — a caller the authority gates refuse never learns
192
+ the action's input shape, the coarse authority facts settle before the fine
193
+ ones, and a malformed flood burns the budget it should. The Rust spine's
194
+ dispatcher keeps the same order (it refuses a non-object `params` and
195
+ validates the `acting` selector after the rate limit), so an anonymous
196
+ `GET` with `?params=42` is a 401 on both spines and an authorized one is
197
+ `invalid_params`.
198
+ - **Errors.** A `ThrownJsonrpcError` (recognized by its realm-global brand,
199
+ `http/CLAUDE.md` §JSON-RPC) keeps its code and data; any other throw is
200
+ `internal_error` 500, its message the raw error only under `DEV`. A result
201
+ that can't be serialized answers the same 500 rather than throwing: the
202
+ action has committed by then, and a throw would discard the handler's
203
+ `post_commit_effects` — the connection closes of a revocation that landed.
260
204
 
261
205
  ### `rpc_action(spec, handler)` — typed binder
262
206
 
263
- `rpc_action<TSpec extends RequestResponseActionSpec>(spec, handler)` pins
264
- the handler's input / output types to `Infer<TSpec['input']>` /
265
- `Infer<TSpec['output']>` and tightens `ctx.auth` per the conditional
266
- `HandlerForSpec<TSpec>`, built on `RequestContextForAuth`
267
- (`auth/request_context.ts`) — the same narrowing a REST handler's
268
- `route.auth` takes:
207
+ `rpc_action` pins the handler's input / output types to the spec's schemas
208
+ and narrows `ctx.auth` through `HandlerForSpec<TSpec>`, built on
209
+ `RequestContextForAuth` (`auth/request_context.ts`) — the narrowing a REST
210
+ handler's `route.auth` takes:
269
211
 
270
212
  - `auth.actor === 'required'` → `ctx.auth: RequestActorContext`.
271
213
  - `auth.account === 'required' && auth.actor === 'none'` → `ctx.auth: RequestContext`.
272
214
  - else (public, optional axes) → `ctx.auth: RequestContext | null`.
273
215
 
274
- Use at every spec → handler binding site so handler-type errors surface
275
- at the factory call instead of at runtime. The bracketed form
276
- `[T] extends ['required']` defeats distributive conditionals so a degraded
277
- `AuthAxisState` union (when the spec was typed without preserving its
278
- literal) falls through to the loosest tier instead of the narrowest.
279
-
280
- fuz_app's handlers close over factory-captured deps (`log`, `audit`,
281
- `options.max_tokens`), so per-pair typing via `rpc_action()` is the shape
282
- that fits.
216
+ Use it at every spec → handler binding site so handler-type errors surface
217
+ at the factory call. A spec typed without its literal `auth` falls through to
218
+ the loosest tier. fuz_app's handlers close over factory-captured deps (`log`,
219
+ `audit`, options), so per-pair typing is the shape that fits.
283
220
 
284
221
  ## Shared dispatch core (`actions/perform_action.ts`)
285
222
 
286
- The transport-agnostic post-parse pipeline. Each transport assembles a
287
- `PerformActionInput` from its wire envelope + connection identity, calls
288
- `perform_action(input, deps)`, and binds the discriminated
289
- `PerformActionResult` to its wire shape.
290
-
291
- Pipeline (401 → authz → 403 → 429 → 400 → handler):
223
+ The transport-agnostic post-parse pipeline: each transport assembles a
224
+ `PerformActionInput` (the request's `ResolvedAuth`, client IP, signal,
225
+ `notify`, the WS connection and peer client) and binds the
226
+ `PerformActionResult` to its wire shape. `ActionContext`
227
+ (`actions/action_types.ts`) is the one handler context on both transports;
228
+ fields on TSDoc. The steps, in the phase order above:
292
229
 
293
230
  1. Pre-authorization auth (401)
294
- 2. Authorization phase — `apply_authorization_phase` against `account_id` + `read_acting(auth, raw_params)`, which takes the selector off the raw params (malformed reads as omitted) since validation runs later. Test escape hatch via `preset.request_context`
295
- 3. Post-authorization auth (403) — credential-type gate, then token scope, then role
296
- 4. Rate limit (429) — throttle-requests semantics, ahead of validation so malformed params charge the budget and a throttled caller pays no schema work
297
- 5. Validate params (400) — first, one walk of object params (`scan_json_value` in `http/schema_helpers.ts`, iterative) refuses, on every input, an own `__proto__` key at any depth with `data.reason` `params_proto_key` (`ERROR_PARAMS_PROTO_KEY`), then U+0000 in any string or key with `params_nul` (`ERROR_PARAMS_NUL` — Postgres refuses it in `text` and `jsonb`); the Rust twin walks after its params-shape check, so a non-object `params` stays the schema's reasonless refusal; then `spec.input` parses them (`parse`) with void / `?? {}` rules; a void input (`is_void_schema`: `s.void`) reads absent, `null` (GET `?params=null`), and `{}` alike as the no-arg call (`to_input_params` in `http/schema_helpers.ts`, via `to_void_params`, the twin of the Rust `require_void_params`; the peer receive path in `ActionDispatcher` runs the same normalizer) and refuses any other shape. A refusal is `to_invalid_params_error`: the generic `invalid params`, `data.reason` when the first issue's field declares an `invalid_reason` in its `meta` and no issue sits on the input itself, such as an unknown key (`resolve_issues_invalid_reason`, `schema_meta.ts` — see ../../../docs/architecture.md §Error Schema System), and the issues DEV-only, as `WireIssue`s (`to_wire_issues`)
298
- 6. Dispatch + DEV output validation + error normalization — `spec.side_effects` picks transaction vs pool. `ThrownJsonrpcError` preserves code + data; generic throws become `internal_error`
299
-
300
- `PerformActionInput` carries `credential` (the request's `ResolvedAuth`, `null` for
301
- anonymous — the authorization phase reads its account, the post-authorization
302
- gates its type and scope, `ActionContext` its type and session hash),
303
- `client_ip`, `signal`, `notify`, optional `connection_id`, optional `preset`.
304
- `PerformActionDeps` carries `db` (pool-level), `pending_effects`, `log`,
305
- the two rate limiters, and `notification_sender` — put on the context, wrapped
306
- under DEV in `create_validated_notification_sender` once per dispatch. Audit writes are out-of-band: factories close over
307
- `AppDeps.audit` independently.
308
-
309
- Authorization-phase resolution failures from the auth domain come back as
310
- `AuthorizationResult.ok === false` carrying `{status, body}` — folded into
311
- a JSON-RPC envelope where `error.code` maps from
312
- `http_status_to_jsonrpc_error_code(result.status)`, `error.message` is the
313
- reason string, and `error.data: {reason, ...rest}` flattens diagnostic
314
- fields. REST emits the same `body` directly via `c.json(body, status)` for
315
- surface consistency.
231
+ 2. Authorization phase — `apply_authorization_phase` against the account and `read_acting(auth, raw_params)`, which reads the selector off the raw params (malformed reads as omitted) since validation runs later
232
+ 3. Post-authorization auth (403) — credential-type gate, then token scope (`rpc:<method>`), then role
233
+ 4. Rate limit (429) — charged ahead of validation, so a throttled caller pays no schema work
234
+ 5. Validate params (400) — `to_input_params` (`http/schema_helpers.ts`: the `__proto__` and NUL refusals, the void-input normalization, `http/CLAUDE.md` §Schema Helpers), then `spec.input`; a refusal is `to_invalid_params_error`, its `data.reason` the field's declared `invalid_reason` (../../../docs/architecture.md §Error Schema System)
235
+ 6. Dispatch — `spec.side_effects` picks a transaction or the pool; DEV-only output validation
236
+
237
+ Rules a handler author would miss:
238
+
239
+ - **A success audit row needs `side_effects: true`.** Handlers audit through
240
+ `deps.audit.emit(ctx, …)`, which refuses a success row with no transaction
241
+ open, and the dispatcher opens one only for a `side_effects: true` action
242
+ (`auth/CLAUDE.md` §Audit emitter).
243
+ - **Post-commit work goes on `ctx.post_commit_effects`** (`emit_after_commit`,
244
+ `queue_connection_close`); the queue is discarded when the action rolls
245
+ back. The eager and deferred queues have one home: `http/CLAUDE.md`
246
+ §Pending Effects.
247
+ - **Authorization refusals fold to JSON-RPC.** The auth domain's
248
+ `{status, body}` becomes an error whose code is
249
+ `http_status_to_jsonrpc_error_code(status)` and whose `data` carries the
250
+ body's `reason` and fields; REST answers the same `body` directly.
316
251
 
317
252
  ## DEV-only output validation — uniform across surfaces
318
253
 
319
- Critical invariant: every action-handler surface applies DEV-only output
320
- validation and produces the **same failure mode** as REST routes'
321
- `wrap_output_validation` (`http/route_spec.ts`) — log an error, return
322
- the response unchanged, do not throw, do not mutate status.
323
-
324
- - HTTP RPC + WebSocket dispatch — `actions/perform_action.ts` `if (DEV) parse(spec.output, output)` inside the shared dispatch core. Production hot path short-circuits (no parse).
325
-
326
- Caller-facing `input` schemas are validated **always** (DEV + production)
327
- — they're the contract with external callers. Server-authored `output`
328
- schemas are internal data. See ../../../docs/architecture.md §DEV-only Output
329
- Validation for full rationale.
254
+ Every action-handler surface validates output in DEV only and fails the way
255
+ REST's `wrap_output_validation` does — log an error, return the response
256
+ unchanged, never throw or change the status. `input` schemas are validated
257
+ always: they are the contract with external callers. Rationale:
258
+ ../../../docs/architecture.md §DEV-only Output Validation.
330
259
 
331
260
  ## Transports
332
261
 
333
- `Transport` is the unifying interface — overloaded `send(message, options?)`
334
- returning `Promise<JsonrpcResponseOrError>` for requests and
335
- `Promise<JsonrpcErrorResponse | null>` for notifications, plus `is_ready()`,
336
- optional `queues` (a request sent with `queue` waits on it while not ready —
337
- `FrontendWebsocketTransport`, while its connection `will_reconnect`), and
338
- optional `dispose()`. All transports share
339
- `TransportSendOptions`:
340
-
341
- - `signal?: AbortSignal` — per-call cancel. Bottoms out at
342
- `FrontendWebsocketClient.request({signal})` on WS (sends `cancel`
343
- notification on abort) and at `fetch({signal})` on HTTP.
344
- - `queue?: boolean` — per-call durable-queue opt-in. Honored only by
345
- `FrontendWebsocketTransport` on the `request_response` path (default
346
- `false`). HTTP and WS notifications ignore it.
347
-
348
- `Transports` holds transports by name; the first registered is the default.
349
- `get_transport(name?, {queue?})` returns the preferred transport — the named
350
- one, else the default — when it is ready, or when it is not but the call is a
351
- queued request and it `queues`; otherwise the first ready transport, the
352
- default first. Explicit `transport_for_method` (on `rpc_client`) or
353
- `default_send_options.transport_name` (on `ActionDispatcher`) names it.
354
-
355
- **Queue routing.** `ActionDispatcher.send` resolves a request's `queue` once —
356
- the call's, else `default_send_options.queue`, else off — and it drives both
357
- the transport choice and the send, so a WS-routed request on a disconnected
358
- socket waits in the client's durable queue and replays on reconnect (or
359
- rejects when its `signal` aborts; the queue is size-bounded, not timed). It
360
- queues only while a reconnect is coming: `FrontendWebsocketTransport.queues`
361
- reads the connection's `will_reconnect` (`FrontendWebsocketClient`:
362
- `connecting` or `reconnecting`), so after a close that reopens nothing on its
363
- own — superseded (4004), permission revoked (4006), `disconnect()`,
364
- `cancel_reconnect()`, auto-reconnect off — the request falls back to a ready
365
- transport (HTTP) rather than wait for a `connect()`. (Requests already queued
366
- before a `cancel_reconnect()` or `set_reconnect(false)` stay queued for the
367
- next `connect()`.) A notification never queues: it fails fast, or falls back to
368
- a ready transport.
369
- The RPC layer defaults it off; a client-authoritative app opts in on the peer
370
- (`create_frontend_rpc_client`'s `ws.queue`). `FrontendWebsocketClient`'s own
371
- raw `request()` keeps its default-on queue.
262
+ `Transport` is the unifying interface: overloaded `send(message, options?)`,
263
+ `is_ready()`, optional `queues` and `dispose()`. `TransportSendOptions` is
264
+ `{signal?, queue?}` — `signal` cancels one call (a WS `cancel` notification,
265
+ or `fetch`'s abort); `queue` is honored only by `FrontendWebsocketTransport`
266
+ on requests. `Transports` holds transports by name, the first registered the
267
+ default; `get_transport` picks the named or default one when it is ready (or
268
+ queues for a queued request), else the first ready one.
269
+
270
+ **Queue routing.** `ActionDispatcher.send` resolves a request's `queue` once
271
+ (the call's, else `default_send_options.queue`, else off), and it drives both
272
+ the transport choice and the send. A WS request queues only while a reconnect
273
+ is coming (`will_reconnect`); after a close that reopens nothing on its own
274
+ (4004, 4006, `disconnect()`, `cancel_reconnect()`, auto-reconnect off) it falls
275
+ back to a ready transport. A notification never queues. The RPC layer defaults
276
+ `queue` off; `FrontendWebsocketClient.request` defaults it on. Consumer
277
+ framing: ../../../docs/usage.md §Client-authoritative vs server-authoritative
278
+ dispatch.
279
+
280
+ - `actions/transports_http.ts` — `FrontendHttpTransport` (`frontend_http_rpc`). It owns the request policy, derived from the spec its `lookup_action_spec` returns, so a hand-built transport can't drop a rule: POST by default; a read (`side_effects: false`) is a GET unless its input carries a `'secret'` or `'personal'` value at any depth (`schema_has_sensitive_field` — a GET puts params in the URL) or the URL passes `max_get_url_length`. On a non-OK status it keeps a JSON-RPC error body for its request as-is (the status → code map is lossy) and synthesizes one otherwise.
281
+ - `actions/transports_ws.ts` — `FrontendWebsocketTransport` (`frontend_websocket_rpc`) over a `WebsocketRpcConnection` (default `FrontendWebsocketClient`), plus `to_same_origin_ws_url`. A notification fails fast while disconnected, whatever `queue` says. It answers inbound server→client requests: `peer/ping` through the built-in `peer_ping_responder`, any other through `peer.receive`.
282
+
283
+ **WS message cap.** `DEFAULT_WS_MAX_MESSAGE_BYTES` (`actions/transports.ts`,
284
+ equal to `DEFAULT_BODY_LIMIT_BYTES`, the Rust spine's value) bounds one
285
+ message both ways. The server (`max_message_bytes`) closes the socket with
286
+ `WS_CLOSE_MESSAGE_TOO_BIG` on a larger inbound message, before parsing; the
287
+ client (`FrontendWebsocketTransportOptions.max_message_bytes`) answers an
288
+ oversized outbound message locally with `invalid_request` /
289
+ `payload_too_large` and never sends it, since the close would fail every
290
+ request in flight. A consumer that raises the server cap passes the same value
291
+ to the client.
372
292
 
373
293
  ### WS close codes (`actions/transports.ts`)
374
294
 
375
- - `WS_CLOSE_SESSION_REVOKED = 4001` — server revoked auth (reason `WS_CLOSE_SESSION_REVOKED_REASON`, `Session revoked`); client enters permanent `revoked` state, no reconnect. Also the close for an upgrade refused at admission because its credential was revoked, or its acting actor soft-deleted, mid-upgrade — indistinguishable on the wire by design — and for a socket whose credential expired while open, with reason `WS_CLOSE_CREDENTIAL_EXPIRED_REASON` (`Credential expired`), which the client treats as the same `revoked` state.
376
- - `WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT = 4002` — client observed receive-silence past its receive timeout (`resolve_heartbeat_receive_timeout`), with reason `WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT_REASON` (`client heartbeat timeout`). TS-only reason: the client is the same against either spine.
377
- - `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT = 4003` — server observed receive-silence past `DEFAULT_WS_RECEIVE_TIMEOUT` (60s), with reason `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT_REASON` (`server heartbeat timeout`). Twin of the Rust spine's constants.
378
- - `WS_CLOSE_CONNECTION_LIMIT = 4004` — server closed this socket to admit a newer one on the same account, past the per-account connection cap (reason `WS_CLOSE_CONNECTION_LIMIT_REASON`, `connection limit`). Not a revocation: the client stays `closed` with `superseded` set and no reconnect, until `connect()` is called. Twin of the Rust spine's constant.
379
- - `WS_CLOSE_OUTBOUND_OVERFLOW = 4005` — the server had more waiting to be written to this socket than its outbound budget holds (reason `WS_CLOSE_OUTBOUND_OVERFLOW_REASON`, `outbound queue overflow`); what was waiting is dropped. Not a revocation, and nothing took the connection's place: the client reconnects under its ordinary backoff. Twin of the Rust spine's constant.
380
- - `WS_CLOSE_PERMISSION_REVOKED = 4006` — the socket's account lost a role its endpoint's `required_roles` lists: a revoked global grant (reason `WS_CLOSE_PERMISSION_REVOKED_REASON`, `Permission revoked`), mid-life or at admission. Nothing is sent after it. Not a revocation of the credential: the client stays `closed` until `connect()` is called, without setting `revoked` or `superseded`, and rejects pending and queued requests `forbidden`. Twin of the Rust spine's constant.
381
- - `WS_CLOSE_GOING_AWAY = 1001` — the server is shutting down (reason `WS_CLOSE_GOING_AWAY_REASON`, `Server shutting down`): `close_all_connections`, which `AppServer.close` runs. Also the close for an upgrade the shutdown refuses — pending at the close-all, or born closed after it. Not a revocation: the client reconnects under its ordinary backoff.
382
- - `WS_CLOSE_MESSAGE_TOO_BIG = 1009` — server received a message over its `max_message_bytes` cap (RFC 6455 "Message Too Big"), with reason `WS_CLOSE_MESSAGE_TOO_BIG_REASON` (`message too big`). Twin of the Rust spine's constants.
383
- - `WS_CLOSE_POLICY_VIOLATION = 1008` — a socket sent too much while it was still opening (before admission and `on_socket_open` completed): past `MAX_PRE_ADMISSION_FRAMES` frames or the `PRE_ADMISSION_QUEUE_BYTES_FACTOR` byte budget (reason `WS_CLOSE_PRE_ADMISSION_OVERFLOW_REASON`). TS-only: the Rust spine reads no frame before admission (they wait in the socket for its loop), so it has no pre-admission queue to overflow and never sends 1008.
384
- - `WS_CLOSE_INTERNAL_ERROR = 1011` — the admission credential re-check itself failed or opening the socket threw (reason `WS_CLOSE_INTERNAL_ERROR_REASON`, `internal error` — shared with the Rust spine), `on_socket_open` threw (`WS_CLOSE_SOCKET_OPEN_FAILED_REASON`, `socket bootstrap failed`), or the socket's connection was removed from the transport without a close (`WS_CLOSE_CONNECTION_UNREGISTERED_REASON`, `connection unregistered`) — the last two TS-only. Not a revocation: the client reconnects under its ordinary backoff. Twin of the Rust spine's constant.
385
-
386
- ### Transport modules
387
-
388
- - `actions/transports_http.ts` — `frontend_http_rpc`; thin `fetch` adapter over `FrontendHttpTransportOptions` (`{url, headers?, lookup_action_spec, max_get_url_length?}`). The transport owns the request policy, derived from the spec `lookup_action_spec` returns, so a hand-built transport can't drop a rule: POST by default; a read (`side_effects: false`) is a GET with no `content-type`, unless its input carries a `'secret'` or `'personal'` value at any depth (`schema_has_sensitive_field`, walked once per spec — a GET puts the params in the URL, which proxies and logs record) or its path and query exceed `max_get_url_length` (`DEFAULT_MAX_GET_URL_LENGTH`, 4096), which go as POST. A method the lookup doesn't know is a POST. The endpoint answers every GET with `Cache-Control: no-store` (`RPC_GET_CACHE_CONTROL`).
389
- - `actions/transports_ws.ts` — `frontend_websocket_rpc`; thin adapter over `WebsocketRpcConnection` (default impl: `FrontendWebsocketClient`), `queues` while the connection `will_reconnect`. Also `to_same_origin_ws_url(path)`, the page-origin WebSocket URL a same-origin backend is reached at (`path` itself off the browser). Answers inbound server→client requests: a built-in `peer_ping_responder` for `peer/ping` (zero-wiring liveness), any other request routed through `peer.receive` with the response sent back over the socket (the frontend half of the ActionPeer receive loop).
390
- - `actions/connection_registry.ts` — `ConnectionRegistry`, server-side WS with session tracking, two-phase registration (`register_pending` / `admit`), the per-account cap, and the per-connection outbound budget; the broadcast target of `create_broadcast_api` (`broadcast`, `broadcast_filtered`). Not a `Transport`: it sends nothing a client requested. Server→client requests via `request_connection` (correlation registry in `actions/peer_request.ts`).
391
- - `actions/ws_outbound_writer.ts` — `WsOutboundWriter`, the outbound queue and write pump of one connection, which every frame the registry sends goes through; `realtime/outbound_budget.ts` is the accounting it shares with SSE.
392
-
393
- `FrontendHttpTransport` on non-OK HTTP returns the body as-is when it's a
394
- JSON-RPC error response for the request (same `id` compared as strings since GET sends it as a query param, or `null`) — the
395
- status → code map is lossy (`queue_overflow` and `rate_limited` share 429), so
396
- the server's code, message, and data must survive. Any other body gets an
397
- envelope synthesized via `http_status_to_jsonrpc_error_code`. DEV warns when
398
- `jsonrpc_error_code_to_http_status(code)` disagrees with the status, or when an
399
- error envelope arrives with a 2xx.
400
-
401
- `FrontendWebsocketTransport` notification sends fail-fast when disconnected
402
- regardless of `queue` — `connection.send()` has no queue semantic, so
403
- buffering would masquerade as success at the rpc_client layer. Requests
404
- route via `queue`.
405
-
406
- **WS message cap.** `DEFAULT_WS_MAX_MESSAGE_BYTES` (1 MiB, in
407
- `actions/transports.ts`, equal to `DEFAULT_BODY_LIMIT_BYTES` and the twin of the
408
- Rust spine's constant) bounds one message both ways. `register_action_ws`
409
- (`max_message_bytes`, also on `WsEndpointSpec`) closes the socket with
410
- `WS_CLOSE_MESSAGE_TOO_BIG` on a larger inbound message, before parsing — no
411
- per-message reply, like the Rust spine. The check runs after the runtime
412
- adapter has buffered the message, so it bounds dispatch work, not memory.
413
- `FrontendWebsocketTransport`'s optional third argument
414
- (`FrontendWebsocketTransportOptions.max_message_bytes`, same default) answers
415
- an outbound request or notification whose JSON encoding exceeds it (in UTF-8
416
- bytes) locally with an `invalid_request` error carrying
417
- `data.reason: 'payload_too_large'` (`create_message_too_large_error`) and never
418
- sends it — otherwise the close would fail every request in flight on the
419
- socket. A consumer that raises the server cap passes the same value to the
420
- client; `null` skips the client-side measurement.
421
-
422
- ### `ConnectionRegistry` — server-side WS state
423
-
424
- One map keyed by `connection_id` (branded `Uuid`), in registration order:
425
- `#connections: Map<Uuid, ConnectionEntry>`, each entry `{ws, identity,
426
- admitted, abort_controller, writer}`. `identity` is the `ConnectionIdentity`
427
- `{session_hash, account_id, api_token_id, required_roles}` (session sets
428
- `session_hash`, bearer sets `api_token_id`, daemon-token sets both null;
429
- `required_roles` is what the endpoint gated the upgrade on, per registration,
430
- since endpoints with different gates can share one registry).
431
-
432
- The id is the connection's only handle — `register_pending` / `add_connection`
433
- return it and `admit` / `remove_connection` / `is_registered` take it. There is
434
- no socket → id lookup: a runtime adapter may hand each socket event its own
435
- `WSContext` (`@hono/bun` builds one per event), so the object a close event
436
- carries can't identify the connection. `register_action_ws` captures the id on
437
- open and removes by it.
438
-
439
- **Two-phase registration.** An upgrade resolves its credential before the
440
- socket exists, and a revocation closes only the connections *registered* under
441
- what it revoked — so a one-step registration leaves a window in which a
442
- revocation closes nothing and the socket is then admitted on a dead credential.
443
- The registry splits registration to close it (the twin of the Rust
444
- `fuz_realtime` `ConnectionRegistry`, same method names):
445
-
446
- - `register_pending(ws, identity, abort_controller?)` (`identity: ConnectionIdentity`, as
447
- the Rust `register_pending(sender, identity, signal)`; `add_connection` takes the same)
448
- inserts the entry **un-admitted**. Every `close_connections` matches it
449
- from that instant. Otherwise it is inert: no `broadcast`,
450
- `broadcast_filtered` (the predicate never sees it), `send_to_account`, or
451
- `request_connection` (`connection_gone`) reaches it; `connection_count`
452
- and `is_registered` don't see it
453
- (`pending_connection_count` does); the cap neither counts nor evicts it.
454
- - the caller re-reads the credential (`revalidate_resolved_auth`).
455
- - `take_pending_close_code(connection_id)` — after a refused `admit`, the
456
- close code the registry closed the pending entry with (4001, 4006, 1001),
457
- read once; what `register_action_ws` logs the refusal by.
458
- - `admit(connection_id)` returns `false` when the entry is gone — a revocation
459
- closed it while pending — and evicts nothing; otherwise it enforces the cap
460
- (counting admitted connections only) and marks the entry admitted.
461
-
462
- Nothing is queued for a pending entry, so a server-initiated message sent
463
- between the handshake and admission is not delivered — the same as one sent
464
- before the handshake. `add_connection` is the one-step form (register and admit
465
- together) for a connection with nothing revocable behind it: tests and
466
- harnesses that register a socket directly. An upgrade that authenticated a session or token
467
- uses the two-phase form.
468
-
469
- **Abort at close time.** The `abort_controller` passed at registration is the
470
- socket's per-connection controller. The registry aborts it when it closes the
471
- connection — a revocation or a cap eviction — so in-flight handlers see
472
- `signal.aborted` at once, not when the close handshake lands.
473
- `remove_connection` only removes: it neither closes nor aborts.
474
-
475
- **Per-account connection cap.** `new ConnectionRegistry({max_connections_per_account})`
476
- — default `DEFAULT_MAX_CONNECTIONS_PER_ACCOUNT` (50), `null` disables, anything
477
- but a positive integer throws. The policy is **evict-oldest**: admission always
478
- admits the new connection, first closing the account's oldest admitted ones
479
- (registration order) with `WS_CLOSE_CONNECTION_LIMIT` so the account never
480
- holds more than the cap. It keys on `account_id` across every credential type —
481
- session, bearer, and daemon-token connections all count, none exempt. Refusing
482
- the newcomer instead would let half-open sockets lock a user out with their
483
- own dead connections, and let a stolen credential hold every slot ahead of the
484
- real user. The check runs at **admission** (`admit`, or `add_connection`),
485
- which `register_action_ws` reaches in `onOpen` — after every upgrade gate
486
- (origin, auth, token scope, acting actor, role) and the credential re-read — so a refused or
487
- just-revoked request never closes someone's socket. An evicted connection
488
- leaves the registry's map at once — no broadcast or peer request reaches it,
489
- its pending peer requests drain as `connection_gone`, it stops counting toward
490
- the cap, its controller is aborted, and `register_action_ws` dispatches nothing
491
- more on it — while the socket itself is only closed once the close handshake
492
- completes. Its `on_socket_close` fires when the close lands, and the
493
- `remove_connection` before it is a no-op. An eviction logs
494
- `ws: connection cap closed oldest` at
495
- info with `{account_id, closed, max}` (the Rust spine's line) through the
496
- registry's `log` (a `[ws]` logger when unset, `null` silences;
497
- `register_action_ws` passes its own to the registry it creates). The cap is per registry:
498
- endpoints sharing one registry share one count per account. The twin of the
499
- Rust `fuz_realtime` `ConnectionRegistry`'s cap — same default, same policy,
500
- same close code and reason — pinned on both by the
501
- `describe_ws_connection_cap_cross_tests` suite.
502
-
503
- **Outbound bound.** Every frame the server sends a connection goes through
504
- its `WsOutboundWriter` (`actions/ws_outbound_writer.ts`), reached by one path:
505
- `send_to(connection_id, frame)` — which `register_action_ws` uses for every
506
- response, error frame, and socket-scoped notification — and the fan-outs
507
- (`send`, `broadcast_filtered`, `send_to_account`, `request_connection`). The
508
- one way around it is a consumer sending on the raw `SocketOpenContext.ws`,
509
- which bypasses the budget. A send never waits and never throws.
510
-
511
- - **What waits.** A frame sent to an idle connection — nothing waiting,
512
- nothing unwritten in the runtime's socket buffer, no other frame sent in the
513
- same synchronous run — goes straight to the socket. Everything else waits in
514
- the writer's queue: the rest of a burst sent in one synchronous run (a loop
515
- with no `await` gives the pump no turn), and anything sent while the socket's
516
- buffer is at or over `WS_WRITE_HIGH_WATER_BYTES`. The pump hands waiting
517
- frames over in order, on the microtask after a send and as the buffer drains.
518
- So a second send in one synchronous run reaches the socket a microtask later.
519
- - **The budget.** What waits is held to `outbound_queue_bytes`
520
- (`new ConnectionRegistry({outbound_queue_bytes})`, default
521
- `DEFAULT_WS_OUTBOUND_QUEUE_BYTES`, 4 MiB — its own constant, not derived from
522
- `max_message_bytes`; anything but a positive integer throws): each waiting
523
- frame is charged its UTF-8 length plus `OUTBOUND_FRAME_OVERHEAD_BYTES` (64),
524
- and a frame is always accepted when nothing is waiting. Nothing counts
525
- frames (`OutboundBudget`, `realtime/outbound_budget.ts`).
526
- - **Overflow.** A frame that does not fit closes the connection with
527
- `WS_CLOSE_OUTBOUND_OVERFLOW`: the entry leaves the map in the same
528
- synchronous step (the overflowing send returns `false` / is not counted,
529
- later sends miss it, the count accessors and the cap stop seeing it), its
530
- pending peer requests drain as `connection_gone`, its controller is aborted,
531
- and what was waiting is discarded. Frames already handed to the socket may
532
- still reach the client ahead of the close frame; nothing follows it.
533
- - **Deadlines.** Bytes a socket still holds `WS_WRITE_STALL_TIMEOUT` (10 s)
534
- after they were handed to it drop the connection with no close frame
535
- (`terminate()` on Node's `ws` and Bun; the client sees 1006), removing it and
536
- aborting its controller the same way. A close frame gets
537
- `WS_CLOSE_WRITE_TIMEOUT` (1 s), after which a socket still holding unwritten
538
- bytes is cut. A socket with no `terminate` (a web-standard `WebSocket`)
539
- cannot be cut, so there a stalled connection is closed with
540
- `WS_CLOSE_OUTBOUND_OVERFLOW` instead, the close deadline cuts nothing, and
541
- the runtime keeps the socket until it or the client ends it. The timers are
542
- unref'd and cleared when the socket's close arrives (`remove_connection`,
543
- which is for a socket that has closed).
544
- - **Other closes.** A revocation, a cap eviction, the shutdown, and
545
- `close_connection` run the pump's rule once more: the frames still waiting
546
- are handed to the socket ahead of the close frame while its buffer is below
547
- `WS_WRITE_HIGH_WATER_BYTES` (64 KiB), and the rest are discarded. A reply
548
- sent to an otherwise idle connection just before a self-revoking close still
549
- arrives; one queued behind a backed-up socket does not.
550
- - **After a close.** A closed or dropped connection is out of the map, so the
551
- per-account cap does not count it while its socket is still closing. Where
552
- the runtime reports its buffer, what it holds for that socket is less than
553
- the high-water mark plus one frame, and the close frame — for the close
554
- deadline on Node and Bun, and on a socket that cannot be cut until the
555
- runtime or the client ends it.
556
- - **Logging.** One `warn` per overflow (`ws: outbound queue overflow, closing
557
- the connection`, the Rust spine's line) or stall (`ws: write stalled,
558
- dropping the connection`), with `{connection_id, account_id, queued_bytes,
559
- queued_frames, …}`. No audit row: a client can provoke either at will.
560
-
561
- The twin of the Rust `fuz_realtime` outbound queue — same budget, charge,
562
- rule, close code, reason, and deadlines, pinned on both by
563
- `describe_ws_outbound_overflow_cross_tests`. Where they differ (the Rust spine
564
- queues every frame and discards the whole backlog at every close) is listed in
565
- ../../../docs/security.md §Outbound Bounds.
566
-
567
- `close_connection(connection_id, code, reason)` closes one connection, pending
568
- or admitted — removal, abort, then the close through the writer — and answers
569
- `false` for an id that names nothing. `register_action_ws` makes its own closes
570
- with it (heartbeat timeout, oversized message, failed `on_socket_open`, refused
571
- admission).
572
-
573
- Targeted closure is `close_connections(target)` (`ConnectionCloser`, below):
574
- it returns the socket count closed, matches pending and admitted entries alike
575
- by `connection_identity_matches(identity, target)` — the twin of the Rust
576
- `ConnectionIdentity::matches` — and aborts each closed connection's
577
- controller. A `session` (`session_hash`), `token` (`api_token_id`), or
578
- `account` (`account_id` — coarse, covers session + bearer + daemon-token)
579
- target closes with `WS_CLOSE_SESSION_REVOKED`; a `role` target closes the
580
- account's connections whose `required_roles` include `role` with
581
- `WS_CLOSE_PERMISSION_REVOKED` instead — over-closing an any-of gate (the loss
582
- of any listed role closes, whether or not the account still holds another).
583
-
584
- `close_all_connections()` closes every connection, pending and admitted, with
585
- `WS_CLOSE_GOING_AWAY` instead — the shutdown close, removing and aborting each
586
- the same way — and leaves the registry **closing** for good (`is_closing()`):
587
- every later registration is **born closed**. `register_pending` and
588
- `add_connection` then insert nothing, abort the caller's controller, and close
589
- the socket with `WS_CLOSE_GOING_AWAY` before returning an id that names
590
- nothing, so `admit` refuses it — an upgrade in flight when the server shuts
591
- down is closed rather than outliving it. The flag is set in the same
592
- synchronous step as the closes, so an admission that finds its entry gone
593
- during shutdown reads the shutdown, never a revocation. Twin of the Rust
594
- registry's closing flag.
595
-
596
- Fan-out, to admitted connections only, each returning how many connections
597
- accepted the message: `broadcast(notification)` to every connection;
598
- `broadcast_filtered(message, predicate)` runs per-connection ACL predicate over
599
- `ConnectionIdentity`; `send_to_account` wraps `broadcast_filtered` and
600
- structurally satisfies `NotificationSender` (§Notification sender; the
601
- role-grant-offer sends: `auth/CLAUDE.md` §WS notifications). A server→client request has no broadcast form; it targets one
602
- connection (`request_connection`, below).
603
-
604
- Server→client request/response (ActionPeer): `request_connection(connection_id,
605
- method, params, {timeout_ms?})` sends a `{jsonrpc, method, params, id}` frame to
606
- exactly one socket and awaits the reply, returning a `PeerRequestOutcome`
607
- (`{ok: true, value}` | `{ok: false, error: PeerRequestError}` —
608
- `timeout`/`connection_gone`/`too_many_in_flight`/`client_error`, the last carrying
609
- the client's error as `parse_inbound_jsonrpc_error` reads it). The registry
610
- owns the socket + the send; the correlation registry — id allocation, the pending
611
- map (nested `connection_id → s{n}` id, the nesting being the per-connection
612
- isolation guarantee), deadlines, and the in-flight cap — is `PendingPeerRequests`
613
- in **`actions/peer_request.ts`** (also home to the peer types/constants +
614
- `audit_unmatched_peer_response`), composed as `#pending` and unit-tested without a
615
- socket. `register_action_ws` routes inbound responses back via
616
- `resolve_peer_response` (→ `#pending.resolve`); connection close drains pending as
617
- `connection_gone`. Defaults: `DEFAULT_PEER_REQUEST_TIMEOUT` (10s),
618
- `DEFAULT_MAX_IN_FLIGHT_PEER_REQUESTS_PER_CONNECTION` (256). Threaded to handlers as
619
- `ActionContext.request_client` (WS only; `undefined` on HTTP RPC). The `peer/ping`
620
- protocol action drives it; see `actions/peer_ping.ts`. An inbound reply matching
621
- no pending entry (unsolicited / cross-connection / late) is dropped + audited via
622
- `audit_unmatched_peer_response` (sampled warn — first 8, then 1/256; twin of the
623
- Rust `audit_unmatched_response`).
624
-
625
- Return values are bookkeeping, not delivery receipts — `0` means no live
626
- sockets, non-zero means the connection's outbound queue accepted the frame. Durable delivery requires
627
- persistence + rehydration by the consumer.
295
+ Each constant's TSDoc carries its reason string and when it is sent; the
296
+ client's reaction is §`FrontendWebsocketClient`.
297
+
298
+ | Code | Constant | Client reconnects? |
299
+ | --- | --- | --- |
300
+ | 4001 | `WS_CLOSE_SESSION_REVOKED` (also a credential expiry, `WS_CLOSE_CREDENTIAL_EXPIRED_REASON`) | no — terminal `revoked` |
301
+ | 4002 | `WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT` (client-side, TS-only reason) | yes |
302
+ | 4003 | `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT` | yes |
303
+ | 4004 | `WS_CLOSE_CONNECTION_LIMIT` (evicted past the per-account cap) | no — `superseded` until `connect()` |
304
+ | 4005 | `WS_CLOSE_OUTBOUND_OVERFLOW` (fell behind its outbound budget) | yes |
305
+ | 4006 | `WS_CLOSE_PERMISSION_REVOKED` (lost a role the endpoint gates on) | no — `closed` until `connect()` |
306
+ | 1001 | `WS_CLOSE_GOING_AWAY` (shutdown) | yes |
307
+ | 1008 | `WS_CLOSE_POLICY_VIOLATION` (pre-admission overflow, TS-only) | yes |
308
+ | 1009 | `WS_CLOSE_MESSAGE_TOO_BIG` | yes |
309
+ | 1011 | `WS_CLOSE_INTERNAL_ERROR` (admission re-check failed, `on_socket_open` threw, connection unregistered) | yes |
310
+
311
+ A refused admission is indistinguishable on the wire from a revocation (4001)
312
+ by design.
313
+
314
+ ## `ConnectionRegistry` (`actions/connection_registry.ts`)
315
+
316
+ The server-side WS state of one or more endpoints: connections keyed by a
317
+ `connection_id` (the only handle — there is no socket → id lookup, since an
318
+ adapter may hand each socket event its own `WSContext`), each matched for
319
+ revocation by its `ConnectionIdentity` (`session_hash`, `account_id`,
320
+ `api_token_id`, and the `required_roles` its endpoint gated the upgrade on).
321
+ Twin of the Rust `fuz_realtime::ConnectionRegistry`, same method names. Not a
322
+ `Transport`: it sends nothing a client requested.
323
+
324
+ - **Two-phase registration.** A revocation closes only *registered*
325
+ connections, so an upgrade registers pending (`register_pending`), re-reads
326
+ its credential, then `admit`s; a pending entry is matched by every close but
327
+ receives nothing and doesn't count toward the cap. `admit` answers `false`
328
+ when a revocation closed the entry meanwhile. `add_connection` is the
329
+ one-step form, for a connection with nothing revocable behind it (tests,
330
+ harnesses).
331
+ - **Per-account cap.** Evict-oldest at admission, across every credential
332
+ type, closing with `WS_CLOSE_CONNECTION_LIMIT`; per registry, so endpoints
333
+ sharing one share one count. Rationale and default:
334
+ ../../../docs/security.md §WebSocket Connection Cap.
335
+ - **Outbound bound.** Every frame goes through the connection's
336
+ `WsOutboundWriter` — `send_to` (every response and socket-scoped
337
+ notification) and the fan-outs. A consumer sending on the raw
338
+ `SocketOpenContext.ws` bypasses the budget. A send never waits or throws;
339
+ a frame past `outbound_queue_bytes` closes the connection with
340
+ `WS_CLOSE_OUTBOUND_OVERFLOW` (not a revocation). Charge, deadlines, closes
341
+ and the TS-vs-Rust differences: ../../../docs/security.md §Outbound Bounds.
342
+ - **Closing.** Every close the registry makes (a revocation, an eviction, an
343
+ overflow, `close_connection`) removes the entry and aborts the
344
+ connection's controller in the same step, so in-flight handlers see
345
+ `signal.aborted` at once and nothing more reaches it; `remove_connection`
346
+ only removes, for a socket that has closed. `close_connections(target)`
347
+ (§Connection closer) matches pending and admitted entries alike.
348
+ `close_all_connections()` is the shutdown (`WS_CLOSE_GOING_AWAY`) and
349
+ leaves the registry closing for good: every later registration is born
350
+ closed.
351
+ - **Fan-out** to admitted connections: `broadcast`, `broadcast_filtered`
352
+ (a per-connection predicate over `ConnectionIdentity`), and
353
+ `send_to_account`, which makes the registry a `NotificationSender`. Return
354
+ values count connections whose outbound queue accepted the frame —
355
+ bookkeeping, not delivery receipts; durable delivery needs the consumer's
356
+ persistence.
357
+ - **Server→client requests** (the ActionPeer capability):
358
+ `request_connection(connection_id, method, params, {timeout_ms?})` targets
359
+ one socket and resolves a `PeerRequestOutcome`, never throwing. Correlation
360
+ (ids nested per connection, deadlines, the in-flight cap, auditing an
361
+ unmatched reply) is `PendingPeerRequests` in `actions/peer_request.ts`.
362
+ Handlers reach it as `ctx.request_client`, WS only.
628
363
 
629
364
  ## Connection closer (`actions/connection_closer.ts`)
630
365
 
@@ -645,122 +380,64 @@ type ConnectionCloseTarget =
645
380
  | {kind: 'role'; account_id: Uuid; role: string}; // a revoked global grant
646
381
  ```
647
382
 
648
- `ConnectionRegistry` satisfies it structurally;
649
- `create_sse_connection_closer(registry, required_role)` (`realtime/audit_log_sse.ts`) adapts
650
- an `SseRegistry` (`close_all_connections` is `SseRegistry.close_all`;
651
- a `role` target closes the account's streams when `role` is the
652
- registry's gating role). The role revokes (`role_grant_revoke` of a global
653
- grant, a self-service disable) queue that close themselves, and the revocation
654
- guard (below) repeats it.
655
- Closing is idempotent and synchronous. `close_all_connections` is the one method no
656
- revocation calls: `AppServer.close` runs it on `deps.connection_closer` to end
657
- every live connection of the backend at shutdown, and it has no
658
- `ConnectionCloseTarget` variant. It also leaves each member closing — the WS connection
659
- registry and `SseRegistry` refuse every later registration (born
660
- closed) — so a closed connection registry or SSE registry hosts nothing more. Its Rust
661
- counterpart is `ShutdownCloser::close_all_connections`, a supertrait of
662
- `ConnectionCloser`.
383
+ A `session`, `token` or `account` target closes with
384
+ `WS_CLOSE_SESSION_REVOKED`; a `role` target closes the account's connections
385
+ whose `required_roles` include the role with `WS_CLOSE_PERMISSION_REVOKED`
386
+ (over-closing an any-of gate). `ConnectionRegistry` satisfies it structurally;
387
+ `create_sse_connection_closer` (`realtime/audit_log_sse.ts`) adapts an
388
+ `SseRegistry`. Closing is idempotent and synchronous. `close_all_connections`
389
+ is the one method no revocation calls — `AppServer.close` runs it.
663
390
 
664
391
  **Every revocation closes after its commit.** A handler inside a route or
665
392
  action transaction never calls a closer inline: it calls
666
- `queue_connection_close(ctx, deps.connection_closer, target)`,
667
- which puts the close on the request's post-commit queue (`emit_after_commit`).
668
- The close runs once the handler's transaction has committed and is discarded
669
- when the handler throws — a rolled-back revocation closes nothing. `target` is
670
- a `ConnectionCloseTarget`; `closer.close_connections(target)` is the
671
- immediate form the queue runs. A
672
- handler with no wrapping transaction (`/login`, `/password`) opens its own
673
- around its writes and closes straight after that commit with
674
- `close_connections_after_commit(closer, target, log)`, which logs a failing
675
- close as the post-commit flush does. Twin of `queue_connection_close` /
676
- `ConnectionCloseTarget`.
677
-
678
- The order is load-bearing for admission: a connection registers, then re-reads
679
- its credential, so a close that missed the registration must belong to a
680
- revocation the re-read can see — true only if the close came after the commit
681
- (../../../docs/security.md §Closing on Revocation).
682
-
683
- The close does not depend on the audit row's announcement (a row written
684
- outside a transaction — `/login`, `/password` — is fail-open). Failure outcomes (`revoked: false`, a 404) queue no close — they
685
- carry caller-supplied ids.
393
+ `queue_connection_close(ctx, deps.connection_closer, target)`, which puts the
394
+ close on the post-commit queue, so a rolled-back revocation closes nothing. A
395
+ handler that opens its own transaction (`/login`, `/password`) calls
396
+ `close_connections_after_commit(closer, target, log)` straight after that
397
+ commit. The order is load-bearing for admission: a connection registers, then
398
+ re-reads its credential, so a close that missed the registration must belong
399
+ to a revocation the re-read can see (../../../docs/security.md §Closing on
400
+ Revocation). Failure outcomes queue no close — they carry caller-supplied ids.
686
401
 
687
402
  **One closer for every transport.** `create_realtime_closer()` returns a
688
- `RealtimeCloser` — a `ConnectionCloser` plus `add(closer)` and `member_count()`
689
- — whose every close fans out to each member and returns the sum. Membership is
690
- by reference: a closer added twice is one member, reached once. `add` returns a
691
- remover for that addition (idempotent); additions are counted, so the closer
692
- stays a member until every addition is removed — one owner releasing a shared
693
- registry leaves it reachable for the others.
694
- `create_app_backend` puts one on `AppDeps.connection_closer`; `create_app_server`
695
- adds each mounted WS connection registry and the audit stream registry itself (passing
696
- `connection_closer: null` to the mount functions so it holds the removers),
697
- registers the revocation guard on it, and removes them when its assembly fails
698
- or `AppServer.close` runs — after `close_all_connections` across them all. Twin of
699
- `RealtimeCloser`. A member that throws does not stop the fan-out — every
700
- member is called, then the first error is thrown for the caller to log;
701
- `ConnectionRegistry` and `SseRegistry.close_by_identity` treat a
702
- throwing socket or stream the same way. `noop_connection_closer` is a `ConnectionCloser` that closes
703
- nothing, for hand-built action-factory deps on a backend with no
704
- live-connection surface.
705
-
706
- It is required where it is read, so it can't be forgotten:
707
- `RevokingActionFactoryDeps.connection_closer` (`create_account_actions`,
708
- `create_admin_actions`, `create_role_grant_offer_actions`,
709
- `create_self_service_role_actions`, `create_standard_rpc_actions`), `AppDeps` /
710
- `RouteFactoryDeps` (`create_account_route_specs`),
711
- `AuthCleanupDeps.connection_closer` (the auth cleanup's session sweep closes
712
- the connections of each expired session it deletes — `auth/CLAUDE.md`
713
- §Cleanup), and the
403
+ `RealtimeCloser`, a `ConnectionCloser` that fans each close out to its members
404
+ (`add` returns a remover; membership rules on its TSDoc). `create_app_backend`
405
+ puts one on `AppDeps.connection_closer`; `create_app_server` adds each mounted
406
+ WS registry and the audit stream registry, registers the revocation guard on
407
+ it, and releases them on a failed assembly or `AppServer.close`.
408
+ `noop_connection_closer` is for hand-built factory deps on a backend with no
409
+ live connections.
410
+
411
+ The closer is required where it is read, so it can't be forgotten:
412
+ `RevokingActionFactoryDeps.connection_closer` (the account, admin,
413
+ role-grant-offer, self-service-role and standard action factories),
414
+ `AppDeps` / `RouteFactoryDeps` (`create_account_route_specs`),
415
+ `AuthCleanupDeps.connection_closer` (`auth/CLAUDE.md` §Cleanup), and the
714
416
  `connection_closer: RealtimeCloser | null` option of `register_action_ws` /
715
- `create_audit_log_sse`, which add their registry to it
716
- (`null` is the explicit opt-out, or for a caller that adds the registry itself
717
- to hold the remover, as `create_app_server` does).
417
+ `create_audit_log_sse`, which add their registry to it (`null` opts out, or
418
+ lets the caller add the registry itself to hold the remover, as
419
+ `create_app_server` does).
718
420
 
719
421
  ### Revocation guard (`create_revocation_guard`)
720
422
 
721
- The audit-listener half of revocation: `create_revocation_guard(closer, log)`
722
- returns an `on_audit_event` callback that repeats a revocation's close when its
723
- audit row is announced. It covers a revocation emitted by code that holds no
724
- closer; for the builtin handlers it is a repeat of the close they already
725
- queued. A success row is announced only after its request's transaction commits
726
- (`auth/CLAUDE.md` §Audit emitter), so the guard's close is post-commit too. Its
727
- closes reach a connection still pending admission.
423
+ `create_revocation_guard(closer, log)` returns an `on_audit_event` listener
424
+ that repeats a revocation's close when its audit row is announced (after its
425
+ commit). It covers a revocation emitted by code that holds no closer; for the
426
+ builtin handlers it is a repeat of the close they already queued, which is
427
+ the primary — the handler's close does not wait on the row's announcement.
428
+ `to_connection_close_target(event)` maps a row to a target by the
429
+ `RevocationScope` its event declares in `audit_event_revocation_scopes`
430
+ (`auth/audit_log_schema.ts`); the mapping is on its TSDoc. Only `success` rows
431
+ act: a failure carries attacker-controlled identifiers, and reacting to it
432
+ would let a caller close another user's connection by guessing a session hash
433
+ or token id. Twin of the Rust `register_revocation_guard`.
728
434
 
729
435
  **One guard, on the fan-out.** `create_app_server` registers one on
730
436
  `deps.connection_closer` when it mounts a WS endpoint or the audit stream —
731
437
  after the audit stream's broadcast listener, so a revocation's row reaches the
732
- stream before the close — and the fan-out carries each close to every member:
733
- each WS connection registry and the audit stream registry (`create_sse_connection_closer`).
734
- A consumer wiring outside `create_app_server` registers its own, over a closer
735
- holding its transports, inside its `audit_factory` body.
736
-
737
- It maps each row to a close target with `to_connection_close_target(event)` —
738
- the twin of the Rust `ConnectionCloseTarget::from_audit_event` — then calls
739
- `closer.close_connections(target)`. The mapping dispatches on the
740
- `RevocationScope` each event declares in `audit_event_revocation_scopes`
741
- (`auth/audit_log_schema.ts`), and a row missing its key (an empty string
742
- included) maps to nothing:
743
-
744
- - `session` (`session_revoke`, `logout`) → `{kind: 'session', session_hash: metadata.session_id}`
745
- - `token` (`token_revoke`) → `{kind: 'token', api_token_id: metadata.token_id}`
746
- - `account` (`session_revoke_all`, `token_revoke_all`, `password_change`,
747
- `account_delete`, `account_purge`) →
748
- `{kind: 'account', account_id: target_account_id ?? account_id}`
749
- - `role` (`role_grant_revoke`) → `{kind: 'role', account_id: target_account_id ??
750
- account_id, role: metadata.role}` when the revoked grant was global
751
- (`to_global_role_revocation`); a scoped revoke closes nothing. Per-message
752
- dispatch re-authorizes each request against its own action, but nothing
753
- re-checks what a connection admitted by a role gate receives — every push its
754
- endpoint sends, every row the stream sends — so a socket closes with
755
- `WS_CLOSE_PERMISSION_REVOKED` and a stream gated on the role ends. The role
756
- revokes queue the same close themselves; this is its repeat.
757
- - `none` → nothing — every other event, and any event type fuz_app doesn't
758
- define
759
-
760
- Only `outcome === 'success'` events act — a failure carries attacker-controlled
761
- identifiers, and an outcome outside the enum is no revocation. Reacting to them would let an authenticated caller close
762
- another user's connection by guessing a session hash or token id. Twin of the
763
- Rust spine's `register_revocation_guard`.
438
+ stream before the close. A consumer wiring outside `create_app_server`
439
+ registers its own, over a closer holding its transports, inside its
440
+ `audit_factory` body.
764
441
 
765
442
  ## Notification sender (`actions/notification_sender.ts`)
766
443
 
@@ -773,47 +450,33 @@ one fan-out over every WS registry (twin of the Rust
773
450
  mounts and removes it on `close` or a failed assembly. Both dispatchers
774
451
  require it; a hand mount passes `backend.deps.notification_sender` (or
775
452
  `noop_notification_sender`) and adds its own registry
776
- (../../../docs/usage.md §WebSocket Endpoint). Membership and failure rules:
453
+ (§`register_action_ws` — the endpoint). Membership and failure rules:
777
454
  TSDoc. The role-grant-offer sends: `auth/CLAUDE.md` §WS notifications.
778
455
 
779
456
  ## WebSocket endpoints
780
457
 
781
- ### `create_app_server.ws_endpoints` — canonical mount surface
782
-
783
- Mirror of `rpc_endpoints` for WebSocket endpoints. Accepts either an array
784
- of `WsEndpointSpec` or a factory
785
- `(ctx: AppServerContext) => ReadonlyArray<WsEndpointSpec>`; factory form
786
- runs after server context is assembled so action lists can depend on
787
- `ctx.deps` / `ctx.action_*_rate_limiter`. Each entry is auto-mounted via
788
- `register_action_ws` against the assembled Hono app, and its registry added to
789
- `deps.notification_sender` and `deps.connection_closer`.
790
-
791
- `upgrade_websocket: UpgradeWebSocket` is the Hono runtime adapter's
792
- module-level helper — `upgradeWebSocket` from `@hono/bun`, or from
793
- `@hono/node-server` on Node, whose `serve` must then be given a `ws`
794
- `WebSocketServer` built with `noServer: true` (`websocket: {server}`).
795
- `create_app_server` throws when `ws_endpoints` resolves non-empty but the
796
- helper is missing; a `ws_endpoints` factory returning `[]` does NOT trip the check, so
797
- feature-flag gated WS surfaces stay safe.
798
-
799
- What every auto-mount gets, so no hand mount has to remember it: the
800
- `action_ip_rate_limiter` / `action_account_rate_limiter` instances the RPC
801
- endpoints charge (one budget per action across transports), the server's
802
- `allowed_origins` when the spec sets none and the sole RPC endpoint's actions
803
- when it omits `actions` (`resolve_ws_endpoints`, read by both the mount and the
804
- surface), registration ahead of `post_route_middleware` and `static_serving`,
805
- the surface entry, and the revocation guard. A `ws_endpoints` or `rpc_endpoints`
806
- path outside the auth middleware's scope (`AUTH_MIDDLEWARE_PATH`, `'/api/*'`,
807
- from `auth/middleware.ts` — matched with `middleware_applies`, so `/api` itself
808
- is inside) throws at assembly (`assert_endpoint_in_auth_scope`, which
809
- `create_test_app_surface_spec` also runs): there no session or bearer is
810
- parsed and every caller would be unauthenticated.
811
-
812
- `WsEndpointSpec` fields: `path`, `allowed_origins?` (default: the server's),
813
- `actions?`, `required_roles?`, `registry?`, `max_connections_per_account?`,
814
- `outbound_queue_bytes?`, `receive_timeout?`, `max_message_bytes?`,
815
- `on_socket_open?`, `on_socket_close?`. Every mounted registry is added to
816
- `deps.connection_closer`.
458
+ ### `ws_endpoints` — the mount surface
459
+
460
+ `AppServerOptions.ws_endpoints` mirrors `rpc_endpoints`: an array of
461
+ `WsEndpointSpec` (fields on its TSDoc) or a factory over the server context.
462
+ `create_app_server` mounts each through `register_action_ws`, ahead of
463
+ `post_route_middleware` and the static fallback, and gives it what a hand
464
+ mount would have to remember: the RPC endpoints' action limiters (one budget
465
+ per action across transports), the server's `allowed_origins` when the spec
466
+ sets none, the surface entry, the revocation guard, its registry on
467
+ `deps.notification_sender` and `deps.connection_closer`, reachable at
468
+ `app_server.ws_endpoints[path]`, and its view of `deps.request_tracker`
469
+ (`create_request_tracker_view`), which its HTTP requests share
470
+ (`request_tracker`), so `AppServer.close` waits for each message accepted,
471
+ its handler and then its effects; a message the closed tracker refuses is
472
+ answered `service_unavailable` (`WS_SHUTTING_DOWN_MESSAGE`), never
473
+ dispatched. Assembly throws on an
474
+ endpoint path outside `AUTH_MIDDLEWARE_PATH` (no credential is parsed there), duplicate paths, a
475
+ `GET` route at the same path, a non-empty `ws_endpoints` with no
476
+ `upgrade_websocket` (the runtime adapter's helper; on Node, `serve` needs a
477
+ `noServer` `ws` server), and a registry option (`max_connections_per_account`,
478
+ `outbound_queue_bytes`) passed beside a supplied `registry`, which carries its
479
+ own.
817
480
 
818
481
  **One action set across transports.** A spec that omits `actions` serves the
819
482
  actions of the server's sole `rpc_endpoints` entry through `to_ws_actions`
@@ -823,587 +486,239 @@ caller is refused `peer_no_transport` rather than `method_not_found`). One set
823
486
  of handler closures then runs on both transports. When the RPC list holds
824
487
  `role_grant_offer_create`, the handler-less
825
488
  `role_grant_offer_notification_actions` follow, so the WS surface lists what
826
- the role_grant_offer actions push as `remote_notification` methods; with no
827
- handler they never dispatch, and an inbound frame for one is answered
828
- `method_not_found`. Assembly throws when a spec omits `actions` and
829
- no RPC endpoint, or more than one, resolves.
830
-
831
- `max_connections_per_account` sets the per-account connection cap on the
832
- registry the mount creates (`RegisterActionWsOptions` carries the same field).
833
- It throws alongside `registry` — a supplied registry carries its own cap, set
834
- where it was constructed, and an option that silently did nothing would read as
835
- enforced. `outbound_queue_bytes` sets the per-connection outbound budget on that
836
- registry the same way (default `DEFAULT_WS_OUTBOUND_QUEUE_BYTES`; zero or a
837
- non-positive value throws at assembly, as does passing it alongside
838
- `registry`).
839
-
840
- Mounted registry reachable at `app_server.ws_endpoints[path]`
841
- (`Readonly<Record<string, ConnectionRegistry>>`). Duplicate paths
842
- across `WsEndpointSpec`s throw at assembly, before any endpoint mounts.
843
- Cross-surface collisions (same `GET <path>` on both `RouteSpec` and
844
- `WsEndpointSpec`) throw with exact-string match. Pattern overlap (e.g.
845
- `GET /api/:resource` vs `/api/ws`) is not detected — Hono's specific-before-wildcard routing keeps
846
- those working but avoid the overlap.
847
-
848
- `AppSurfaceWsEndpoint.methods` surfaces `request_response` +
849
- `remote_notification` specs only — `local_call` specs are filtered out
850
- because they don't dispatch over WS.
489
+ those actions push; an inbound frame for one is `method_not_found`. Assembly
490
+ throws when a spec omits `actions` and no RPC endpoint, or more than one,
491
+ resolves. The surface's `AppSurfaceWsEndpoint.methods` lists
492
+ `request_response` and `remote_notification` specs only.
851
493
 
852
494
  ### `register_action_ws` — the endpoint
853
495
 
854
- Mounts one `GET path` route, its guards in the route-spec pipeline's
855
- coarse-to-fine order (from `fuz_auth_guard_resolver` over the upgrade's auth
856
- shape `{account: 'required', actor: 'required', roles?, required_scope:
857
- 'surface:ws_upgrade'}`):
858
-
859
- 1. `verify_request_source(allowed_origins)` — 403
860
- 2. `require_auth` — 401
861
- 3. `require_token_scope('surface:ws_upgrade')` — a narrowed token cannot hold a socket (403 `token_scope_required`)
862
- 4. The authorization phase (`run_authorization_phase`, `auth/request_context.ts`) — resolves the acting actor (`?acting=` through `parse_acting`; malformed reads as omitted, and the route declares no query schema, so a credential-less `?acting=garbage` is still the 401; a query holding an escape that doesn't decode is refused here, 400 `invalid_query_params`, after the 401 and the scope gate), seeds `REQUEST_CONTEXT_KEY`
863
- 5. `require_role(required_roles)` when the endpoint is gated — any-of disjunction (coarse upgrade-time gate; per-action `auth` in each spec still applies at dispatch time)
864
- 6. `upgradeWebSocket`
865
-
866
- Only `GET` is mounted (Hono serves `HEAD` through it, guards included), so any
867
- other method on the path is the app's 405 (`Allow: GET, HEAD`; `server/unmatched_route.ts`), and a `GET` asking for no upgrade its 404. Takes
868
- `allowed_origins` (required — `create_app_server` passes the server's), the
869
- required `connection_closer` and action limiters, and optional
870
- `required_roles`; returns `{registry}`. Most consumers reach for
871
- `ws_endpoints` above; call it directly only to mount a WS endpoint outside
872
- `create_app_server`'s assembly. Tests drive the dispatcher without the
873
- guards through `create_ws_test_harness`, which invokes the captured events
874
- factory directly.
875
-
876
- The per-socket half lives in `actions/ws_socket_session.ts`:
877
- `create_ws_socket_events(endpoint, upgrade)` returns the `WSEvents` for one
878
- upgraded socket — admission, the pre-admission queue, the receive watchdog,
879
- the credential deadline, frame dispatch, and close. `register_action_ws` reads
880
- the Hono context at upgrade into a `WsSocketUpgrade` and derives the
881
- endpoint's `WsSocketEndpoint` once; the module never touches the Hono app.
882
- Its exports include the socket bounds (`MAX_PRE_ADMISSION_FRAMES`,
883
- `PRE_ADMISSION_QUEUE_BYTES_FACTOR`, `MAX_INBOUND_DISPATCHES_PER_CONNECTION`),
884
- the duplicate-id and overflow wire strings, and the `on_socket_open` /
885
- `on_socket_close` contexts (`SocketOpenContext`, `SocketCloseContext`).
886
-
887
- Per-message dispatch delegates to `perform_action` — the shared core that
888
- HTTP RPC also calls. The socket session owns only WS-specific concerns:
889
-
890
- - **Wire envelope parsing** — `parse_json_text` (`http/json_text.ts`: what the Rust spine's `serde_json` refuses is a `parse_error` here too) → batch rejection → `classify_jsonrpc_message` (`http/jsonrpc_helpers.ts`, the twin of the Rust `fuz_http::classify`, the same classifier the HTTP POST path runs) → per-arm handling: an `invalid` answers its error on its id; a `response` routes to the socket's pending peer request; a `notification` routes `cancel` and is otherwise dropped; a `request` goes on to the duplicate-id and in-flight checks and dispatch. The classifier runs the twin's order — version, then the `method` axis, then `id`, then the `JsonrpcRequest` envelope — so `{method: 'x'}` and `{jsonrpc: '1.0', method: 'x'}` answer `invalid_request` rather than being dropped as notifications; a response is the twin's shape exactly (no string `method`, a string/number `id`, exactly one of `result` / `error`), so a hybrid like `{method, id, result}` stays a dispatchable request; and `params: null`, an array `params`, or a non-string/number `id` answers `invalid_request` (-32600) on both transports rather than reaching the dispatcher as `invalid_params`. Notifications stay unvalidated (they carry no id to echo). A non-object frame answers `id: null`. POST answers a notification or a response `invalid_request` on `id: null`, as the Rust spine does.
891
- - **Cancel-notification interception** — `{request_id → AbortController}` map; aborts the matching pending controller before the cancel bubbles past the dispatcher
892
- - **Duplicate live ids refused** — a request whose id names a request still running on the socket is answered `invalid_request` with `data.reason` `ERROR_DUPLICATE_REQUEST_ID` and not dispatched; the running request keeps its controller, its cancel entry, and its reply id. An id is free again once its request is answered. Same refusal on the Rust spine
893
- - **In-flight ceiling** — at most `MAX_INBOUND_DISPATCHES_PER_CONNECTION` (128) requests run at once per socket (`@hono/node-server` does not await `onMessage`, so nothing else bounds them); one more is answered `queue_overflow` (`WS_INBOUND_DISPATCH_OVERFLOW_MESSAGE`) and not dispatched, and the socket stays open and keeps reading — a reply to a server-initiated request still gets through. The duplicate check runs first; neither refusal reaches `perform_action`, so neither charges the action rate limiters. Same cap, message, and order as the Rust spine's `MAX_INBOUND_DISPATCHES_PER_CONNECTION`
894
- - **Socket-scoped notify** — `(method, params) => registry.send_to(connection_id, notification)`, threaded into `perform_action` as `notify`
895
- - **Every send through the registry** — responses, error frames, and notifications all go through `registry.send_to`, so they are held to the connection's outbound budget; a handler that sends past it closes its own socket with `WS_CLOSE_OUTBOUND_OVERFLOW` and gets no response written
896
- - **Composed abort signal** — `AbortSignal.any([socket_close, per_request_cancel])`, threaded as `signal`
897
- - **Connection lifecycle** — admission (`registry.register_pending` → `recheck_admission` → `registry.admit`, which enforces the per-account connection cap) / `remove_connection`, `on_socket_open` / `_close` hooks, server heartbeat
898
- - **The inbound gate** — frames queue until the socket is admitted and `on_socket_open` has completed; frames on a socket the server closed are dropped
899
-
900
- **Admission.** `onOpen` registers the connection pending (synchronously, with
901
- the socket's `AbortController`), re-reads what the gates read
902
- (`recheck_admission({db}, {resolved, request_context, required_roles})`,
903
- `auth/resolved_auth.ts`, which the audit stream shares: the credential —
904
- session row / token row / account row, no touch — the acting actor, and the
905
- role; `resolved` is `get_resolved_auth(c)`, the value the auth middleware
906
- set), then `registry.admit`s. A dead credential, or a pending entry a revocation closed
907
- meanwhile, closes the socket with `WS_CLOSE_SESSION_REVOKED` and the reason a
908
- revoked socket gets; a re-check that throws closes it with
909
- `WS_CLOSE_INTERNAL_ERROR` (`internal error`) — fail closed, never admitted
910
- unchecked. A soft-deleted acting actor is refused like a dead credential. An
911
- endpoint with `required_roles` re-reads them beside the credential — the acting
912
- actor's grants afresh (`refresh_role_grants`), a global grant of any listed role
913
- admitting, as the gate in front did — and refuses a lost role with
914
- `WS_CLOSE_PERMISSION_REVOKED`; a failed role read is the same 1011. During shutdown a refusal is the shutdown's instead: an upgrade
915
- pending at the close-all was closed by it with `WS_CLOSE_GOING_AWAY` and its
916
- controller aborted, so the refusal after the re-read — even one the closing
917
- database failed — writes nothing more; an upgrade that registers after it is
918
- born closed and skips the re-read. A refused socket gets nothing else written
919
- to it, evicts nothing, and runs neither lifecycle hook. An upgrade with no resolved credential on its
920
- context, or one on another account than its request context, throws before the
921
- socket exists. The test-preset escape hatch
922
- (`TEST_CONTEXT_PRESET_KEY`) skips the re-read — a pre-baked credential has no
923
- rows behind it — so `create_ws_test_harness` admits synchronously. Admission
924
- leaves no interleaving that admits a revoked credential, because every
925
- revocation closes only after its commit — see
926
- ../../../docs/security.md §Connection Admission and §Closing on Revocation.
927
-
928
- `connection_closer: RealtimeCloser | null` is a required option: the endpoint's
929
- registry is added to it, so the revocation handlers' post-commit closes reach
930
- the sockets opened here. The add is the mount's last step, so a mount that
931
- throws (a registry that fails to compile) adds nothing; the addition is
932
- permanent, its remover not returned. `null` is for a registry no revocation
933
- has to reach (a harness driving the dispatcher directly), or one the caller
934
- adds itself to hold the remover — `create_app_server` passes `null` and adds
935
- the registry after the mount returns, releasing it when assembly fails or
936
- the server closes.
937
-
938
- Because `onOpen` awaits, an adapter can deliver `onMessage` before admission
939
- (`@hono/node-server` doesn't await `onOpen` at all). Those frames are **queued, not
940
- dispatched** — nothing runs on a credential that has not been re-read — and
941
- dispatch in arrival order, back to back, once the socket is admitted and
942
- `on_socket_open` has completed; a refusal drops them unread. The Rust spine
943
- gets the same ordering from starting its read loop at admission, with the
944
- kernel socket buffer as the queue; here the queue is in memory, bounded by
945
- count (`MAX_PRE_ADMISSION_FRAMES`, 256) and by bytes
946
- (`PRE_ADMISSION_QUEUE_BYTES_FACTOR`, 4, times the endpoint's
947
- `max_message_bytes`) — the frame that would pass either closes the socket with
948
- `WS_CLOSE_POLICY_VIOLATION` (reason `WS_CLOSE_PRE_ADMISSION_OVERFLOW_REASON`).
949
- The byte budget is what bounds memory: pending sockets are not capped per
950
- account. A consumer that raises the client's durable queue above the frame cap
951
- makes a full reopen flush overflow it. The `onMessage` call for a queued frame
952
- returns a promise that settles when the frame was dispatched or dropped.
953
-
954
- The queue holds **every** inbound frame, replies to server-initiated requests
955
- included — so an `on_socket_open` hook that awaits
956
- `registry.request_connection` on its own connection gets no reply until it
957
- returns (it times out); start such a request without awaiting it.
958
-
959
- **A server-closed socket dispatches nothing.** An adapter can keep delivering
960
- frames after the server calls `ws.close(…)`, until the close handshake
961
- completes — `@hono/node-server` does, for up to the `ws` close timeout when the
962
- client withholds its close frame. So every server-side close removes the
963
- connection from the registry and aborts the socket's controller **at close
964
- time**: the registry does both for a revocation or a cap eviction, and
965
- `ws_socket_session.ts`'s `end_socket` does both — through
966
- `registry.close_connection` — for a heartbeat timeout, a credential
967
- expiry, an oversized message, a failed `on_socket_open`, and a refused
968
- admission.
969
- `onMessage` then drops any frame whose socket has ended — no dispatch, no
970
- error reply. A connection the registry no longer holds though nothing closed
971
- its socket (a bare `registry.remove_connection`; `registry.is_registered` is
972
- the twin of the Rust `is_registered`) is ended on its next frame with
973
- `WS_CLOSE_INTERNAL_ERROR` (`WS_CLOSE_CONNECTION_UNREGISTERED_REASON`), so it can't linger as a
974
- socket that reads everything, answers nothing, and — being chatty — is never
975
- reaped by the heartbeat. Only a frame that is queued or dispatched counts as
976
- heartbeat activity.
977
-
978
- **Per-message authorization phase.** `perform_action` calls
979
- `apply_authorization_phase` per-message (HTTP and WS uniformly). Role grant
980
- changes during a connection lifetime are picked up on the next message —
981
- no in-place refresh. A revoked global grant of a role the endpoint's
982
- `required_roles` lists closes the socket (`WS_CLOSE_PERMISSION_REVOKED` —
983
- the revoking handler through `connection_closer`, the revocation guard
984
- repeating it), since nothing else re-checks what it
985
- receives. Authentication
986
- invalidation (a session or token revoke, `password_change`, a logout, an
987
- account delete, a cap eviction) still closes the socket — the revoking
988
- handler through `connection_closer`, the revocation guard again on the
989
- audit row.
990
-
991
- Per-message side-effect queues: `pending_effects` (eager) and
992
- `post_commit_effects` (deferred — pushed by handlers via
993
- `emit_after_commit`) drain through `flush_request_effects`, the flush the
994
- HTTP middleware shares. Both flush in the same `try/finally` that releases
995
- the request controller, after the reply is sent; every rejection is logged
996
- and reaches `on_effect_error` (`create_app_server` threads its own to the
997
- endpoints it mounts) with `{transport: 'ws', method, path}`. Nothing orders that
998
- flush against other frames: frames on an admitted socket are not serialized
999
- (`handle_frame` calls aren't chained, and an adapter need not await
1000
- `onMessage` — `@hono/node-server` doesn't), so a message's effects can still be
1001
- in flight when the caller reads its reply and when the next message
1002
- dispatches. A test that reads the audit log after a WS reply awaits
1003
- `_testing_drain_effects` first, which awaits the emitter's in-flight writes
1004
- (`src/lib/testing/CLAUDE.md`). The deferred thunks are
1005
- invoked first and the eager writes awaited after, so a revocation's close never
1006
- waits on a slow audit INSERT — held behind one, the socket would stay open on a
1007
- credential already committed gone and dispatch its next frame. The deferred
1008
- queue is **discarded on rollback** before it reaches that flush (a
1009
- rolled-back message fires no post-commit effect). See `http/CLAUDE.md`
1010
- §Pending Effects.
1011
-
1012
- **Reply before flush.** The response is sent before either queue flushes. A
1013
- handler that revokes the credential its own socket runs on queues a close of
1014
- that socket on `post_commit_effects`, so the caller reads its reply and then the
1015
- `WS_CLOSE_SESSION_REVOKED` close — flushing first would strand it without an
1016
- answer. The close hands the frames still waiting in the connection's outbound
1017
- queue to the socket ahead of the close frame while the socket's buffer is below
1018
- `WS_WRITE_HIGH_WATER_BYTES`, so the reply arrives when it was queued behind
1019
- another frame of the same run on a socket that is keeping up, and is discarded
1020
- when the socket is backed up past that mark. (The Rust spine drains first but marks the reply owed beforehand, and its
1021
- socket loop writes that reply ahead of the close — the same order on the wire,
1022
- held by the cross-backend WS suite.)
1023
-
1024
- **Lifecycle hooks.** `on_socket_open({ws, connection_id, identity, notify, signal})`
1025
- fires once the connection is admitted and before the first message dispatches
1026
- (frames sent meanwhile wait); awaited; throws log + an `internal_error` frame +
1027
- close with `WS_CLOSE_INTERNAL_ERROR` and `WS_CLOSE_SOCKET_OPEN_FAILED_REASON`, unregistering
1028
- the connection.
1029
- `on_socket_close({ws, connection_id, identity})` fires — only for a socket that
1030
- was admitted — after
1031
- `registry.remove_connection(connection_id)` — a slow hook never holds a dead
1032
- entry that broadcasts still target and the per-account cap still counts.
1033
- `connection_id` and `identity` are the values captured at open, so the hook
1034
- reads them the same way after a client close, a revocation, or a connection-cap
1035
- eviction; its `ws` is the close event's context, which on some adapters is not
1036
- the object `on_socket_open` received. Errors logged and swallowed.
1037
-
1038
- **Receive timeout** (`receive_timeout?: number | null`, ms): default-on at
1039
- `DEFAULT_WS_RECEIVE_TIMEOUT` (60s) — the twin of the Rust spine's
1040
- `ActionWsOptions.receive_timeout` — `null` keeps silent sockets open, and a
1041
- value that is not positive, or is past `WS_RECEIVE_TIMEOUT_MAX` (2³¹ − 1 ms,
1042
- the longest delay a timer honors; TS-only), throws at registration. Any
1043
- inbound message resets `last_receive_time` — chatty clients never trip it. The
1044
- timer starts at admission, and the first timeout window after it is exempt
1045
- (cold-start grace).
1046
- Tick interval is `timeout / 2`, so event-loop blockage pauses the timer itself.
1047
- A timeout unregisters the connection and aborts its signal along with the
1048
- `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT` close.
1049
-
1050
- **Credential deadline.** From admission, a timer closes the socket when the
1051
- credential it upgraded on expires (`ResolvedAuth.credential_deadline` — the
1052
- earlier of a session's cookie and row expiry, an API token's row; none for an
1053
- eternal token or the daemon token): `WS_CLOSE_SESSION_REVOKED` with
1054
- `WS_CLOSE_CREDENTIAL_EXPIRED_REASON`, through `end_socket`. Expiry writes
1055
- nothing a revocation listener hears, so the socket watches its own deadline.
1056
- The wait is `schedule_credential_deadline`'s chain of timers of at most an
1057
- hour (a 30-day session is past `setTimeout`'s ceiling), each also checking the
1058
- wall clock so a host suspend does not extend the deadline, cancelled when the
1059
- socket ends. Twin of the Rust loop's `WsLoopOptions::credential_deadline`.
1060
-
1061
- Two abort signals composed via `AbortSignal.any`:
1062
-
1063
- - `socket_abort_controller` — per-socket, fires when the socket ends: at the server's close (revocation, cap eviction, heartbeat timeout, …) or the client's. Registered with the registry, which aborts it on the closes it makes. Drives every handler's `ctx.signal`.
1064
- - `pending_controllers: Map<JsonrpcRequestId, AbortController>` — per-request. Registered before dispatch (one entry per running request — a duplicate live id is refused — so its size is the in-flight count the ceiling bounds), cleared in `finally` so late cancels for a completed id (or a reused id) can't null-abort the wrong handler. Unknown cancels no-op.
496
+ Mounts one `GET path` route whose guards run the route pipeline's order over
497
+ the upgrade's auth shape `{account: 'required', actor: 'required', roles?,
498
+ required_scope: 'surface:ws_upgrade'}`: origin (403), auth (401), token scope
499
+ (a narrowed token cannot hold a socket), the authorization phase (the acting
500
+ actor from `?acting=`), `required_roles` when gated (any-of), then the
501
+ upgrade. Any other method on the path is the app's 405. Returns `{registry}`.
502
+ Consumers reach for `ws_endpoints`; call it directly only outside
503
+ `create_app_server`. `create_ws_test_harness` drives the dispatcher without
504
+ the guards.
505
+
506
+ The per-socket half is `actions/ws_socket_session.ts`
507
+ (`create_ws_socket_events`): admission, the pre-admission queue, the receive
508
+ watchdog, the credential deadline, frame dispatch and close, each on its
509
+ TSDoc. Frame dispatch parses with `parse_json_text`, refuses a batch, and
510
+ classifies with `classify_jsonrpc_message` — the one classifier both
511
+ transports run (`http/CLAUDE.md` §JSON-RPC) — then routes a reply to its
512
+ pending peer request, a `cancel` to the request's controller, and a request
513
+ to `perform_action` with a socket-scoped `notify` and
514
+ `AbortSignal.any([socket_close, request_cancel])` as its signal. A request
515
+ reusing a live id, or past `MAX_INBOUND_DISPATCHES_PER_CONNECTION`, is
516
+ refused undispatched (../../../docs/security.md §WebSocket Request Bounds).
517
+
518
+ The rules a caller would miss:
519
+
520
+ - **Admission re-reads the credential.** `onOpen` registers pending, runs
521
+ `recheck_admission` (`auth/resolved_auth.ts`, shared with the audit
522
+ stream: the credential, the acting actor, the endpoint's roles), then
523
+ admits. A dead credential is closed `WS_CLOSE_SESSION_REVOKED`, a lost role
524
+ `WS_CLOSE_PERMISSION_REVOKED`, a failed re-read `WS_CLOSE_INTERNAL_ERROR` —
525
+ fail closed. A refused socket evicts nothing and runs neither hook
526
+ (../../../docs/security.md §Connection Admission). The open — the re-read
527
+ and `on_socket_open` — is held on `deps.request_tracker`, so a shutdown
528
+ landing in it waits rather than closing the database under it
529
+ (`http/CLAUDE.md` §Pending Effects).
530
+ - **Frames wait for admission and `on_socket_open`.** Frames arriving earlier
531
+ are queued (bounded; overflow closes 1008) and dispatched in order after, so
532
+ an `on_socket_open` hook that awaits `registry.request_connection` on its
533
+ own connection deadlocks until it times out — start such a request without
534
+ awaiting it.
535
+ - **A server-closed socket dispatches nothing.** Every server-side close
536
+ removes the connection and aborts its controller at close time, so frames
537
+ an adapter keeps delivering until the close handshake are dropped. A
538
+ connection removed without a close is ended on its next frame.
539
+ - **Per-message authorization.** Each message re-runs the authorization
540
+ phase, so a role grant change is picked up on the next one. What a
541
+ connection receives is not re-checked, so a credential revocation, a lost
542
+ endpoint role, or a cap eviction closes the socket — a logout only the
543
+ sockets of the session it ends.
544
+ - **Reply before flush.** The reply is sent before the message's effect
545
+ queues flush, so a handler that revokes its own socket's credential gets its
546
+ reply and then the close. The deferred thunks run before the eager writes
547
+ are awaited, so a revocation's close never waits on an audit INSERT. Frames
548
+ on a socket are not serialized, so a message's effects can still be in
549
+ flight when its reply is read: a test reading the audit log after a WS
550
+ reply awaits `_testing_drain_effects` first (`src/lib/testing/CLAUDE.md`).
551
+ Shutdown waits for the message all the same — it is held on
552
+ `deps.request_tracker` from acceptance. The queues and the tracker:
553
+ `http/CLAUDE.md` §Pending Effects.
554
+ - **Hooks.** `on_socket_open` runs once admitted, before the first dispatch,
555
+ awaited; a throw closes 1011. `on_socket_close` runs only for an admitted
556
+ socket, after `remove_connection`, with the `connection_id` and identity
557
+ captured at open; its errors are logged.
558
+ - **Timers.** The receive timeout (`receive_timeout`, default
559
+ `DEFAULT_WS_RECEIVE_TIMEOUT`, `null` disables) closes a silent socket with
560
+ `WS_CLOSE_SERVER_HEARTBEAT_TIMEOUT`; any inbound frame resets it. The
561
+ credential deadline closes the socket when its credential expires
562
+ (`WS_CLOSE_CREDENTIAL_EXPIRED_REASON`) — expiry writes nothing a revocation
563
+ listener hears, so the socket watches its own.
1065
564
 
1066
565
  ## Rooms (`actions/room_registry.ts`, `actions/room_action_specs.ts`, `actions/room_actions.ts`)
1067
566
 
1068
567
  A generic live-room primitive over one WS endpoint's `ConnectionRegistry` —
1069
568
  the TS twin of the Rust spine's `fuz_realtime::RoomRegistry` and
1070
569
  `fuz_actions::room`, one wire, held to it by the `rooms_ws` cross suite. Each
1071
- module doc holds the detail; the cross-cutting shape:
1072
-
1073
- - **`RoomRegistry`** (`new RoomRegistry(connections, options)`) — rooms keyed
1074
- by a consumer's `RoomId` (1–`ROOM_ID_MAX_LENGTH` printable ASCII), holding
1075
- seats (random `MemberId` per join, keyed by connection and actor) and watches
1076
- (one per connection and room, for whichever actor last asked). Options:
1077
- `exclusive` (one seat per actor across the registry, newest admitted wins,
1078
- with the rejoin tombstone — `ROOM_REJOIN_TOMBSTONE_TTL_MS`,
1079
- `ROOM_REJOIN_TOMBSTONES_PER_ACTOR`), `max_members_per_room`,
1080
- `max_payload_bytes`, `max_state_bytes`, `max_watches_per_connection`
1081
- (`DEFAULT_ROOM_*`), `topology`. Every method runs without an `await`, so no
1082
- check is separated from its mutation (the Rust registry's one lock). Each
1083
- room's events carry a per-room `seq`; an empty room is deleted. Refusals are
1084
- a `RoomResult` (`RoomError`), not throws.
1085
- - **Two-phase join and watch** — `reserve_seat` / `reserve_watch` before the
1086
- consumer's authorizer reads, `admit_seat` / `admit_watch` after, so an
1087
- eviction committing mid-authorizer still reaches the request (an actor or
1088
- room target refuses it, a scope target poisons it, at most
1089
- `MAX_POISONED_SCOPES`). The admit consumes the pending entry; a caller that
1090
- never reaches it calls `withdraw` in a `finally` (the Rust guard's drop). A
1091
- TS join keeps running after its socket closes, so the admit reads the
1092
- socket's signal and the close marks every join in flight.
1093
- - **Disconnect** — the first reserve on a connection adds one listener to
1094
- `ConnectionRegistry.socket_signal(connection_id)` (the registered
1095
- `abort_controller`'s signal, which every close path aborts; `null` while
1096
- pending or once gone); its abort releases every seat (`room_member_left`
1097
- reason `disconnected`), watch, and join in flight on the next microtask, so a
1098
- close inside a fan-out (an overflow) never re-enters the registry mid-step.
1099
- - **Eviction** — `evict(target, reason)` by `actor`, `actor_in_scope`, `room`,
1100
- or `scope` (`RoomEvictTarget`), covering seats, watches, and joins in flight;
1101
- the consumer calls it after its authority change commits
1102
- (`emit_after_commit`). `clear()` drops everything silently, for a test reset.
1103
- - **The verbs** — `create_room_actions({registry, authorize, limiter},
1104
- {join_extra?})` returns the `room_*` `RpcAction`s
1105
- (`all_room_action_specs`), **WS-only**: mount them on a `ws_endpoints` entry
1106
- (with `room_notification_actions` for the surface), never an RPC endpoint.
1107
- Actor-required, `side_effects: false`; `room_join` and `room_watch` carry
1108
- `rate_limit: 'account'`. `RoomAuthorize.authorize({actor_id, account_id,
1109
- room_id, access}, db)` gets the caller's ids and the pool `db`, never the
1110
- request's role grants (loaded before the reserve, so possibly older than an
1111
- eviction); `{allow: false}` answers `room_not_found`, the IDOR mask.
1112
- `RoomRateLimiter` (`DEFAULT_ROOM_RATE_LIMIT`: 300 requests and 1 MiB per
1113
- 10 s) is per connection, two refilling buckets charged on join, send, and
1114
- state set — one request plus the payload's or state's `json_escaped_len`,
1115
- the bytes it adds to each frame — but not watch; `create_room_actions` throws
1116
- when the limiter can't cover a max-size payload or state
1117
- (`check_room_limits`). Refusals: the `ERROR_ROOM_*` reasons
1118
- (`to_room_jsonrpc_error`), `rate_limited` with `data.retry_after`, and
1119
- `request_cancelled` for a cancelled join or a closed socket.
1120
- - **Notifications** — `room_member_joined`, `room_member_left`,
1121
- `room_member_state` (to the other members and the watchers),
1122
- `room_message` (addressee, or the room minus the sender), `room_seat_lost`
1123
- (the displaced or evicted seat's own connection, `moved_to` for a move), and
1124
- `room_watch_ended` — each a `remote_notification` spec with its params schema.
1125
-
1126
- ### Room client (`actions/room_client.svelte.ts`)
1127
-
1128
- The frontend side, one `RoomClient` per socket and actor (`acting`), holding a
1129
- reactive `RoomState` per room (`client.room(room_id)`): `members`, `seat`
1130
- (`RoomSeat` — `member_id`, `topology`, `extra`), `seat_status`
1131
- (`RoomSeatStatus`), `watching`, `ended` (`RoomSeatEnded`), `watch_ended`,
1132
- `error`, `local_state`. The module doc holds the reasoning; the shape:
1133
-
1134
- - **Verbs** — `create_room_rpc(socket)` builds the `RoomRpc` the client takes:
1135
- the room verbs straight over `FrontendWebsocketClient.request`, unqueued,
1136
- answers parsed with the output schemas forward-compatibly
1137
- (`safe_parse_dropping_unknown_keys`), never through the RPC client's
1138
- transports (which fall back to HTTP while the socket is down, where no room
1139
- verb is mounted), plus `connection` — the open `WebSocket`, else `null`.
1140
- - **Wants, converged one request at a time** — `join`, `leave`, `watch`,
1141
- `unwatch`, `set_state` record a want; one runner per room sends the requests
1142
- that close the gap, waiting for each answer (the server dispatches a
1143
- socket's requests concurrently, so a leave could otherwise overtake its
1144
- join). Nothing is sent while the socket is down. `send` goes out at once.
1145
- Every verb runs in `untrack`, so a page's `$effect` may call one (with its
1146
- opposite in the teardown) without depending on room state.
1147
- - **`seq`** — events before the first join or watch answer buffer, then replay
1148
- past its `seq`; a live room drops events at or below its last `seq`. A
1149
- message reaching a live watch while the join is in flight is held for the
1150
- seat and delivered after `seated`.
1151
- - **Connections** — the client follows `RoomRpc.connection` itself, an
1152
- `$effect.root` made in the constructor (a no-op on the server) and ended by
1153
- `dispose`, calling `sync_connection()`, which compares it by identity, so a
1154
- close and reopen in one batch still counts; `sync_connection` stays public
1155
- and runs before each request and notification. A seat lost to the old
1156
- connection is rejoined with `rejoin_of`; a `room_seat_moved` refusal ends it
1157
- as moved, and a `rate_limited` one is retried after its `retry_after`, up
1158
- to `ROOM_REJOIN_RATE_LIMITED_RETRIES_MAX` times (`set_timeout` /
1159
- `clear_timeout` in `RoomClientOptions`). `room_seat_lost` (moved, evicted,
1160
- room closed) is never rejoined. Watches are taken again.
1161
- - **Notifications** — `receive(method, params)` from the RPC client's
1162
- `'receive'` handlers (`is_room_notification_method`), parsing each with its
1163
- params schema. `RoomListener` (`add_listener`) hears `seated`, `unseated`
1164
- (`RoomUnseatedReason`), member events, and messages, in `seq` order except
1165
- a message held for the seat, heard once it is taken —
1166
- `rtc/rtc_mesh.svelte.ts`'s `RtcMesh` follows a room through it. A listener
1167
- that throws is logged; the others still hear, and the join or replay
1168
- carries on.
1169
- - **`dispose()`** leaves every seat, drops every watch, and stops following
1170
- the connection.
570
+ module doc holds the detail; the shape:
571
+
572
+ - **`RoomRegistry`** — rooms keyed by a consumer's `RoomId`, holding seats
573
+ (a random `MemberId` per join) and watches; options for exclusivity (one
574
+ seat per actor, newest wins), member, payload, state and watch bounds, and
575
+ topology. Every method runs without an `await`, so no check is separated
576
+ from its mutation (the Rust registry's one lock). Each room's events carry a
577
+ per-room `seq`. Refusals are a `RoomResult`, not throws.
578
+ - **Two-phase join and watch** — `reserve_*` before the consumer's authorizer
579
+ reads, `admit_*` after, so an eviction committing mid-authorizer still
580
+ reaches the request; a caller that never admits calls `withdraw` in a
581
+ `finally`. A disconnect (the connection's `socket_signal`) releases every
582
+ seat, watch and join in flight.
583
+ - **Eviction** — `evict(target, reason)` by actor, actor in scope, room or
584
+ scope, called after the consumer's authority change commits
585
+ (`emit_after_commit`).
586
+ - **The verbs** — `create_room_actions` returns the `room_*` actions,
587
+ **WS-only**: mount them on a `ws_endpoints` entry (with
588
+ `room_notification_actions` for the surface), never an RPC endpoint.
589
+ `RoomAuthorize.authorize` gets the caller's ids and the pool `db`, never the
590
+ request's role grants (possibly older than an eviction); a refusal answers
591
+ `room_not_found`, the IDOR mask. `RoomRateLimiter` charges per connection.
592
+ - **`RoomClient`** (`actions/room_client.svelte.ts`) — the frontend side, one
593
+ per socket and actor, with a reactive `RoomState` per room. Verbs record a
594
+ want, and one runner per room sends the requests that close the gap, one at
595
+ a time, straight over the socket (`create_room_rpc`), never through the RPC
596
+ client's transports, whose HTTP fallback mounts no room verb. It follows the
597
+ socket's connection, rejoins a seat lost to a reconnect, replays buffered
598
+ events past each answer's `seq`, and hears notifications through the RPC
599
+ client's `'receive'` handlers. `RtcMesh` (`rtc/`) follows a room through its
600
+ listener.
1171
601
 
1172
602
  ## Protocol actions (`actions/protocol.ts`)
1173
603
 
1174
- Three shared `{spec, handler}` tuples that every consumer spreads into both
1175
- sides' `actions` arrays — disconnect detection, per-request cancel, and the
1176
- server→client `peer/ping` round-trip work identically across every repo
1177
- without per-consumer ping plumbing.
1178
-
1179
- The category is wire-protocol concerns shipped by fuz_app, not consumer
1180
- domain logic. Protocol vs domain: a future clock-skew probe or
1181
- reconnect-resume token belongs here; a `payment_charge` action does not.
1182
-
1183
- Two const arrays:
1184
-
1185
- - `protocol_actions: ReadonlyArray<Action>` — for the server's `register_action_ws` `actions`. Spread before consumer-owned actions.
1186
- - `protocol_action_specs: ReadonlyArray<ActionSpecUnion>` — derived via `.map(a => a.spec)` so the two arrays cannot drift. For the frontend `ActionRegistry`.
1187
-
1188
- Asymmetry intentional — server runs handlers (heartbeat echo, peer/ping
1189
- round-trip; cancel is dispatcher-owned), frontend registry only stores specs. Both
1190
- bundles plus the codegen `include_protocol_actions: false` default form a
1191
- three-leg contract; `PROTOCOL_ACTION_METHODS` (in `actions/action_codegen.ts`)
1192
- is the method-name set that drives both the codegen filter and the action-manifest
1193
- exclusion.
1194
-
1195
- **Not auto-spread by `create_frontend_rpc_client` or `register_action_ws`** —
1196
- bundled helpers stay pure factories so the dispatch surface stays
1197
- grep-traceable at every registration site and consumers can override
1198
- individual protocol actions without an opt-out flag.
1199
-
1200
- ### Individual actions
1201
-
1202
- - **`heartbeat_action`** — `request_response`, `initiator: 'frontend'`, `auth: {account: 'required', actor: 'none'}`, `side_effects: false`, parameterless `void` input (absent / `null` / `{}` params — the Rust `require_void_params` shapes), empty-object output. Handler is a stateless no-op echo. Client's activity-aware heartbeat timer fires this whenever idle past `DEFAULT_HEARTBEAT_INTERVAL`; server's `register_action_ws` heartbeat tracker counts the incoming message as activity.
1203
- - **`cancel_action`** — `remote_notification`, `initiator: 'frontend'`, `auth: null`, `side_effects: true`. Params: `CancelNotificationParams = object({request_id: JsonrpcRequestId})`. **No handler** (`cancel_action = {spec}`) — cancel semantics are dispatcher-owned (`register_action_ws` has the `{request_id → AbortController}` map). Wire format is snake_case `cancel` + `{request_id}`, not MCP's `$/cancelRequest` + `{requestId}` — MCP adoption would happen at an MCP adapter's translation layer, not in the base transport.
1204
- - **`peer_ping_action`** — `request_response`, `initiator: 'both'`, `auth: public`, `side_effects: false`. Input `PingActionInput = {nonce?, timeout_ms?}` (`with_default`, `{}` for an omitted input — the client's pre-send parse of a no-arg call); output `PingResponse = {nonce, protocol_version}`. The client→server invocation drives the **server→client** direction: the handler calls `ctx.request_client('peer/ping', {nonce})`, awaits the echo, validates it against `PingResponse` + checks the nonce, and returns it. A client's error reply reaches the caller as `parse_inbound_jsonrpc_error` reads it (a base-set code, else `internal_error`; a string message, else `'peer error'`; `data` as sent), as on the Rust spine. Over HTTP RPC (`ctx.request_client` absent) it refuses with `peer_no_transport`, so it's mounted on both the WS endpoint (via this bundle) and the HTTP RPC endpoint (the spine full mount). `timeout_ms` is clamped shorten-only. `data.reason` codes (`peer_timeout` / `peer_connection_gone` / `peer_no_transport` / `peer_too_many_in_flight` / `peer_ping_invalid_reply` / `peer_ping_nonce_mismatch`) + the `PingResponse` shape (whose `protocol_version` is `PEER_PROTOCOL_VERSION`) are the cross-impl wire contract (twins of the Rust `REASON_PEER_*`). The frontend half — `peer_ping_responder` (the echo a client sends back, wired into `FrontendWebsocketTransport`) — lives here too. `peer_ping_action` imports nothing from the dispatch core, so `protocol_action_specs` doesn't drag it into frontend bundles — same discipline as `heartbeat`/`cancel`. See `actions/peer_ping.ts`.
604
+ Wire-protocol actions shipped by fuz_app, not consumer domain logic:
605
+ `heartbeat_action` (`heartbeat.ts`, the client's activity-aware liveness
606
+ request), `cancel_action` (`cancel.ts`, a handler-less notification — cancel
607
+ is dispatcher-owned; snake_case `cancel` + `{request_id}`, not MCP's
608
+ `$/cancelRequest`), and `peer_ping_action` (`peer_ping.ts`, which drives the
609
+ server→client direction: the handler pings the calling client through
610
+ `ctx.request_client` and returns its echo; over HTTP it refuses
611
+ `peer_no_transport`). Their reason codes and `PingResponse` are the cross-impl
612
+ wire contract, on the modules' TSDoc.
613
+
614
+ A three-leg contract keeps them out of consumer surfaces: `protocol_actions`
615
+ (the server's handlers), `protocol_action_specs` (derived from it, for the
616
+ frontend `ActionRegistry`), and the codegen filter, all keyed by
617
+ `PROTOCOL_ACTION_METHODS` (`actions/action_codegen.ts`), which the action
618
+ manifest excludes too. `create_frontend_rpc_client` and `register_action_ws`
619
+ don't spread them — every registration site stays grep-traceable and can
620
+ override one; a `ws_endpoints` entry that omits `actions` does, via
621
+ `to_ws_actions`. None of them imports the dispatch core, so
622
+ `protocol_action_specs` doesn't drag it into frontend bundles.
1205
623
 
1206
624
  ## Event state machine
1207
625
 
1208
- Five modules (`action_event_types.ts`, `action_event_data.ts`,
1209
- `action_event_helpers.ts`, `action_event.ts`, `action_dispatcher.ts`) define a
1210
- discriminated-union-based state machine used by the reactive client to
1211
- track an action through its lifecycle. Per-symbol semantics on TSDoc;
1212
- high-level shapes that span modules:
1213
-
1214
- - **Discriminated union** — `ActionEventDataUnion<TMethod, TInput, TOutput>` across `kind` + `phase` + `step`, a variant per lifecycle point of each kind. Narrows `input` / `output` / `error` / `request` / `response` / `notification` / `progress` at each lifecycle point.
1215
- - **Step transitions** — `initial → parsed | failed`, `parsed → handling | failed`, `handling → handled | failed`, `handled`/`failed` terminal. `validate_step_transition(from, to)` throws on illegal moves.
1216
- - **Phase transitions** — chained: `send_request → receive_response`, `receive_request → send_response`; everything else terminal. `validate_phase_transition` enforces.
1217
- - **`ActionEvent.parse()`** — `initial → parsed` via `parse(spec.input, …)`. Input validation failures **fail immediately** without routing through an error phase (client-side programming errors, not runtime conditions with handlers); their `invalid_params` `data` is `{validation_errors, reason?}`, `reason` the declared `invalid_reason` the server would answer. Handler errors DO route through `send_error` / `receive_error`. On `receive_response` with error response, transitions to `receive_error` instead of failing; a success response's `result` is validated against `spec.output` (always, not DEV-only — it's inbound data; undeclared keys are dropped rather than refused, so an older client survives an added response field) and `output` becomes the parsed value, or the event moves to `receive_error` with an `internal_error` carrying `data: {reason: ERROR_RESPONSE_OUTPUT_INVALID, validation_errors}` — a remote contract break, deliberately distinct from the `invalid_params` / `validation_error` of bad caller input.
1218
- - **Handler throws** — `ThrownJsonrpcError` keeps code/message/data; any other throw becomes `internal_error` carrying the thrown message. When the error answers a remote caller (`receive_request` / `send_response`), the raw message goes through `dev_only` like the server dispatch core.
1219
- - **Protocol message creation is automatic** — transitioning `parsed → handling` on `send_request` materializes the outgoing `JsonrpcRequest` with a fresh `create_uuid()` id; on `send` (notification) it materializes the `JsonrpcNotification`.
1220
-
1221
- `ActionDispatcher` (`actions/action_dispatcher.ts`) is symmetric send + receive
1222
- over a `Transports` registry and `ActionEventEnvironment`. `default_send_options`
1223
- excludes `signal` deliberately — a shared signal would abort every subsequent
1224
- call after the first trip. `transport_name` and `queue` can be defaulted here
1225
- once to flip the dispatcher into client-authoritative mode. Diagnostics (failed
1226
- sends, inbound notifications that fail to parse or whose handler throws, unknown
1227
- methods) go to `environment.log`; unset falls back to `console_action_log`
1228
- (warn/error to `console`, debug dropped) so failures are never silent, and
1229
- `log: null` opts out (`resolve_action_log`). An inbound request or notification
1230
- reads its params through the server dispatch core's normalizer
1231
- (`to_input_params`): for a void input (`s.void`),
1232
- absent, `null`, and `{}` alike are the no-arg call; for any other input,
1233
- absent or `null` params are `{}` (so an all-optional object input accepts a
1234
- call that omits them).
1235
-
1236
- **Naming.** `ActionDispatcher` is the (frontend) send/receive coordinator class.
1237
- "ActionPeer" — unbackticked throughout the peer/ping + `request_client` docs — is
1238
- the _capability_ it participates in: the bidirectional peer request/response
1239
- feature. It's a concept, not a symbol. The server→client half of that capability
1240
- is `ConnectionRegistry.request_connection` + `PendingPeerRequests` (see
1241
- `actions/peer_request.ts`), not this class.
626
+ `action_event_types.ts`, `action_event_data.ts`, `action_event_helpers.ts`,
627
+ `action_event.ts` and `action_dispatcher.ts` define the discriminated-union
628
+ state machine (`ActionEventDataUnion`, over `kind` + `phase` + `step`) the
629
+ reactive client tracks an action through; `validate_step_transition` and
630
+ `validate_phase_transition` throw on illegal moves. Per-symbol semantics on
631
+ TSDoc. The rules a reader would miss:
632
+
633
+ - **Input validation fails immediately**, without an error phase — a
634
+ client-side programming error. Handler errors route through `send_error` /
635
+ `receive_error`.
636
+ - **A success response's `result` is validated always** (inbound data, not
637
+ DEV-only), undeclared keys dropped; a mismatch moves the event to
638
+ `receive_error` with `internal_error` and `ERROR_RESPONSE_OUTPUT_INVALID` —
639
+ a remote contract break, distinct from bad caller input.
640
+
641
+ `ActionDispatcher` is the frontend's symmetric send + receive coordinator over
642
+ `Transports`. `default_send_options` can fix `transport_name` and `queue`
643
+ once (client-authoritative mode) but excludes `signal`, which would abort
644
+ every later call. Diagnostics go to `environment.log`, `console_action_log`
645
+ when unset, nothing with `log: null`. Inbound params go through the server
646
+ core's normalizer (`to_input_params`). The server→client half of ActionPeer is
647
+ `ConnectionRegistry.request_connection`, not this class.
1242
648
 
1243
649
  ## Reactive frontend client
1244
650
 
1245
651
  ### `FrontendWebsocketClient` (`actions/socket.svelte.ts`)
1246
652
 
1247
- Portable, Svelte-reactive (`$state.raw` for `ws`, `status`, `reconnect_count`,
1248
- etc.). Plain class — no Cell inheritance, no app coupling. Implements
1249
- `WebsocketConnection` + `WebsocketRpcConnection`, and is `Disposable`.
1250
-
1251
- Ships three correctness primitives default-on:
1252
-
1253
- 1. **Promise-based `request`** — auto-assigned monotonic id; pending map keyed by id; resolved via intercept on the message path. Rejects `ThrownJsonrpcError` with specific codes (`unauthenticated`, `request_cancelled`, `queue_overflow`, `service_unavailable`, `internal_error`, or the server's wire code verbatim). The transport catch block preserves `.code` exactly so `FrontendWebsocketTransport` never collapses to `internal_error`.
1254
- 2. **Durable queue** — `request()` calls while disconnected buffer up to `DEFAULT_QUEUE_MAX_SIZE = 100` and flush on reopen. Overflow rejects `queue_overflow`. Pass `{queue: false}` to reject immediately (used internally by the heartbeat — it must not fight the queue for the disconnect-detection slot). Raw `send(data)` is **drop-on-disconnect** by design (fire-and-forget notifications want that).
1255
- 3. **Activity-aware heartbeat** — the shared `heartbeat` request fires when either direction has been idle past `DEFAULT_HEARTBEAT_INTERVAL = 30_000` (send-only silence would trip the server's detector, receive-only silence this client's). Receive-silence past the receive timeout closes with `WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT`. Tick runs at `interval / 2` so event-loop blockage pauses the timer itself — so a heartbeat can leave up to 1.5 × `interval` after the last receive, and `resolve_heartbeat_receive_timeout` raises the receive timeout (`DEFAULT_HEARTBEAT_RECEIVE_TIMEOUT = 60_000` unless given) to at least `HEARTBEAT_RECEIVE_TIMEOUT_MIN_FACTOR` (2) × `interval`. A long `interval` alone is therefore safe. At most one heartbeat is outstanding — an unanswered one is left to the receive timeout rather than repeated.
1256
-
1257
- `last_send_time` / `last_receive_time` are reactive epoch-ms stamps of the most
1258
- recent frame each way — every frame, including heartbeats and the responses
1259
- `request` consumes — for diagnostics UI.
1260
-
1261
- Reconnect policy (exponential backoff): `delay = DEFAULT_RECONNECT_DELAY * DEFAULT_BACKOFF_FACTOR ** (attempts-1)`,
1262
- capped at `DEFAULT_RECONNECT_DELAY_MAX`. Every other close reconnects —
1263
- `WS_CLOSE_OUTBOUND_OVERFLOW` included, the server's notice that this client
1264
- fell behind and missed messages. Three close codes never reconnect:
1265
-
1266
- - `WS_CLOSE_SESSION_REVOKED` is **terminal** — sets `revoked`, no reconnect
1267
- loop on 401, and `connect()` becomes a no-op. Pending and queued requests
1268
- reject `unauthenticated`.
1269
- - `WS_CLOSE_PERMISSION_REVOKED` is **closed until the user acts** too — status
1270
- `closed`, no reconnect scheduled (a reconnect would be refused at the role
1271
- gate), neither `revoked` nor `superseded` set (the credential is still
1272
- good), pending and queued requests reject `forbidden`. `last_close_code`
1273
- says why; `connect()` reopens.
1274
- - `WS_CLOSE_CONNECTION_LIMIT` is **closed until the user acts** — sets
1275
- `superseded` (reactive), status `closed`, no reconnect scheduled: the server
1276
- closed this socket to admit a newer one on the same account, and
1277
- reconnecting would close that one in turn, so clients past the cap would
1278
- close each other in a loop. The credential is still good, so `revoked` stays
1279
- `false` and an explicit `connect()` reopens and clears `superseded`. Pending
1280
- and queued requests reject `service_unavailable`; requests made while
1281
- superseded buffer in the durable queue like any call on a closed client. UI
1282
- reads `superseded` to say why the connection is closed and offer the
1283
- reconnect.
1284
-
1285
- Live policy swaps (behave like constructor — whole policy atomic, missing
1286
- fields fall back to defaults, not "keep current"): `set_reconnect`,
1287
- `set_heartbeat`, `cancel_reconnect`.
1288
-
1289
- `SocketStatus = 'initial' | 'connecting' | 'connected' | 'reconnecting' | 'closed'`.
1290
- `socket_status_to_async_status(status, revoked)` collapses to fuz_util's
1291
- 4-way `AsyncStatus`: `closed` reads `failure` when revoked and `initial`
1292
- otherwise — a `superseded` close included, since the client is not trying and
1293
- `connect()` reopens it.
653
+ Portable, Svelte-reactive, no app coupling; implements `WebsocketConnection`
654
+ + `WebsocketRpcConnection` and is `Disposable`. Three primitives, default-on:
1294
655
 
1295
- ## RPC client (`actions/rpc_client.ts`)
1296
-
1297
- `create_rpc_client({peer, environment, actions?, transport_for_method?})` —
1298
- returns a Proxy-based typed API. Per-kind dispatch:
1299
-
1300
- - **`local_call` sync** — `parse().handle_sync()`, return value directly. Throws on error (sync can't return `Result`). Ignores `signal`.
1301
- - **`local_call` async** — `parse().handle_async()`, return `Result<{value}, {error}>`. Pre-flight `signal.aborted` check short-circuits.
1302
- - **`request_response`** — builds `ActionEvent`, runs `parse().handle_async()` to produce the request, calls `peer.send(request, {transport_name, signal, queue})`, transitions to `receive_response`, wires the response, parses (may transition to `receive_error`), runs handler, extracts `Result`.
1303
- - **`remote_notification`** — builds event, creates notification, `peer.send(notification, {transport_name, signal, queue})`. Returns `Result<{value: void}, {error}>`.
656
+ 1. **Promise-based `request`** — rejects with a `ThrownJsonrpcError` whose code the transport preserves exactly (the codes on its TSDoc).
657
+ 2. **Durable queue** — `request()` while disconnected buffers (bounded, overflow rejects `queue_overflow`) and flushes on reopen; `{queue: false}` rejects at once. Raw `send(data)` drops while disconnected.
658
+ 3. **Activity-aware heartbeat** — the `heartbeat` request fires when either direction has been idle past the interval; receive-silence past the receive timeout closes with `WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT`. The receive timeout is raised to cover the interval, so a long interval alone is safe.
1304
659
 
1305
- `RpcClientCallOptions extends ActionDispatcherSendOptions` — `{signal?, queue?, transport_name?}`.
1306
- `transport_for_method: (method) => TransportName | undefined` for per-method
1307
- selection. `on_action_event(event)` fires once per dispatched action with
1308
- the live `ActionEvent` (zzz wires reactive history here).
660
+ Every close reconnects with exponential backoff except three:
1309
661
 
1310
- ### Throwing variants
662
+ - `WS_CLOSE_SESSION_REVOKED` — **terminal**: sets `revoked`, `connect()` is a no-op, pending and queued requests reject `unauthenticated`.
663
+ - `WS_CLOSE_PERMISSION_REVOKED` — `closed` until `connect()` (a reconnect would meet the role gate); pending and queued requests reject `forbidden`.
664
+ - `WS_CLOSE_CONNECTION_LIMIT` — sets `superseded`, `closed` until `connect()`: reconnecting would evict the newer socket, so clients past the cap would close each other in a loop. Pending and queued requests reject `service_unavailable`; UI reads `superseded` to explain the close and offer the reconnect.
1311
665
 
1312
- - `create_throwing_rpc_call` — shape `(method, input?) => Promise<T>`. Use at adapter wiring (e.g. `ui/admin_rpc_adapters.ts`) — method comes from a map.
1313
- - `create_throwing_api` — typed Proxy over `FrontendActionsApi`. Use at direct call sites — `await api.foo(input)` keeps full inference.
666
+ `socket_status_to_async_status(status, revoked)` collapses `SocketStatus` to
667
+ fuz_util's `AsyncStatus` (`closed` reads `failure` only when revoked).
1314
668
 
1315
- **Layered design.** `Result` is the protocol primitive —
1316
- `create_rpc_client` returns `Result<{value}, {error}>` with no Error
1317
- allocation. The throwing wrappers sit _above_ it as ergonomic adapters;
1318
- both shapes share the same underlying transport and call sites pick
1319
- per-site. `Result` is preferable when the call site inspects
1320
- `error.data.reason` (no allocation, no try/catch) or when overhead matters
1321
- (reconnect storms, hot paths). Throwing is preferable when the call site
1322
- doesn't inspect — `await api.foo()` reads cleaner than `if (!r.ok) throw …`.
1323
-
1324
- Hardening on both: only `{code, data}` cross onto the Error, leaving
1325
- `name` / `stack` as the native Error's own so attacker-shaped
1326
- `result.error` payloads cannot overwrite them.
1327
-
1328
- `ThrowingApi<TApi>` (the mapped type returned by `create_throwing_api`)
1329
- strips `Promise<Result<{value: T}, {error: JsonrpcErrorObject}>>` to
1330
- `Promise<T>` on every method matching the `request_response` / async
1331
- `local_call` return shape; `remote_notification` and sync `local_call`
1332
- methods pass through. The Proxy inspects each call's result shape at
1333
- runtime and only unwraps when it sees a Result.
669
+ ## RPC client (`actions/rpc_client.ts`)
1334
670
 
1335
- Both helpers throw `"rpc method not found: <name>"` on invocation of an
1336
- unknown method. Symbol props and `then` stay `undefined` so the Proxy
1337
- doesn't get probed as a thenable by `await`.
671
+ `create_rpc_client({peer, environment, on_action_event?, transport_for_method?})`
672
+ returns a Proxy-based typed API, one method per spec: `request_response` and
673
+ `remote_notification` go through `peer.send`, async `local_call` runs locally,
674
+ each returning a `Result` with no Error allocation; a sync `local_call`
675
+ returns its value and throws. `on_action_event` fires once per dispatched
676
+ action with the live `ActionEvent` (zzz wires reactive history here);
677
+ `transport_for_method` picks a transport per method.
678
+
679
+ **Throwing variants** sit above the `Result` primitive:
680
+ `create_throwing_rpc_call` (`(method, input?) => Promise<T>`, for adapter
681
+ wiring like `ui/admin_rpc_adapters.ts`) and `create_throwing_api` (a typed
682
+ Proxy, `ThrowingApi<TApi>`, for direct call sites). Use `Result` where the
683
+ call site inspects `error.data.reason` or overhead matters, throwing where it
684
+ doesn't. Only `{code, data}` cross onto the thrown Error, so an
685
+ attacker-shaped `result.error` can't overwrite `name` or `stack`.
1338
686
 
1339
687
  ### Frontend factory (`actions/frontend_rpc_client.ts`)
1340
688
 
1341
- `create_frontend_rpc_client<TApi>({specs, path?, http_headers?, max_get_url_length?, ws?, transports?, transport_for_method?, on_action_event?, lookup_action_handler?, log?})`
1342
- bundles `ActionRegistry + ActionEventEnvironment + Transports + ActionDispatcher +
1343
- create_rpc_client + create_throwing_api` boilerplate every consumer
1344
- repeats — plus the `lookup_action_handler: () => undefined` stub (frontend
1345
- never registers `request_response` handlers; every method dispatches over
1346
- the wire).
1347
-
1348
- Returns both Proxy shapes from one factory call:
1349
-
1350
- - `api: ThrowingApi<TApi>` — typed throwing Proxy. Default for hot-path call sites.
1351
- - `api_result: TApi` — typed Result-shaped Proxy. For sites that inspect `error.data.reason` without try/catch.
1352
- - `peer`, `environment` — exposed for advanced consumers.
1353
- - `socket` — the `ws.client`, or `null`.
1354
-
1355
- Transports: a `FrontendHttpTransport` on `path ?? '/api/rpc'` over the
1356
- registry's `lookup_action_spec` (a hand-built transport passes its own
1357
- environment's), so a read goes as a GET; and, with `ws: {client, queue?, max_message_bytes?}`, a
1358
- `FrontendWebsocketTransport` over the caller's client, registered after it,
1359
- which every `request_response` method routes to unless `transport_for_method`
1360
- says otherwise (HTTP stays the fallback while the socket is down). The caller
1361
- builds and connects the client — `new
1362
- FrontendWebsocketClient(to_same_origin_ws_url('/api/ws'))` — so the factory
1363
- never imports `socket.svelte.ts` and an HTTP-only bundle stays socket-free.
1364
- `ws.queue` sets the peer's default `queue` (Queue routing above). Pass
1365
- `transports` to replace the built-ins (exclusive with `ws`, `http_headers`,
1366
- `max_get_url_length`). `local_call` specs in `specs` silently no-op because
1367
- `lookup_action_handler` always returns `undefined`.
1368
-
1369
- `all_standard_action_specs` (in `auth/standard_action_specs.ts`) is
1370
- transport-agnostic — when a consumer spreads `create_standard_rpc_actions`
1371
- into both `rpc_endpoints` AND `ws_endpoints`, `transport_for_method` can
1372
- route per-call (e.g. return `'frontend_websocket_rpc'` for `account_*` /
1373
- `admin_*` methods to bind them to the live WS connection). See
1374
- `auth/CLAUDE.md` §Standard RPC bundle.
689
+ `create_frontend_rpc_client<TApi>(options)` bundles the `ActionRegistry`,
690
+ environment, `Transports`, `ActionDispatcher`, `create_rpc_client` and
691
+ `create_throwing_api` boilerplate, returning `api` (throwing), `api_result`
692
+ (`Result`-shaped), `peer`, `environment` and `socket`. Its transports: a
693
+ `FrontendHttpTransport` on `path ?? '/api/rpc'`, and with
694
+ `ws: {client, queue?, max_message_bytes?}` a `FrontendWebsocketTransport`
695
+ over the caller's client, which `request_response` methods route to (HTTP
696
+ the fallback while the socket is down). The caller builds and connects the
697
+ client, so an HTTP-only bundle never imports `socket.svelte.ts`. `ws.queue`
698
+ sets the peer's default `queue` (§Transports). `transports` replaces the
699
+ built-ins.
700
+
701
+ `lookup_action_handler` defaults to `() => undefined`; pass one to receive
702
+ WS-pushed notifications (`'receive'`, what `RoomClient` relies on) or hook
703
+ `receive_error`. A `local_call` spec no-ops unless it resolves an
704
+ `'execute'` handler.
705
+
706
+ `all_standard_action_specs` (`auth/standard_action_specs.ts`) is
707
+ transport-agnostic: with the standard actions on both endpoints,
708
+ `transport_for_method` can bind `account_*` / `admin_*` methods to the live
709
+ WS connection (`auth/CLAUDE.md` §Standard RPC bundle).
1375
710
 
1376
711
  ## Broadcast API (`actions/broadcast_api.ts`)
1377
712
 
1378
- `create_broadcast_api({registry, specs, log?, should_deliver?})` — builds a
1379
- typed `{method: (input) => Promise<void>}` object from a list of action
1380
- specs. Counterpart to `register_action_ws`: that handles frontend-initiated
1381
- request-scoped dispatch, this handles backend-initiated broadcast.
1382
- Request-scoped streaming stays on `ctx.notify` inside a handler.
1383
-
1384
- Per-method call: validates input against `spec.input`
1385
- (`parse`; logs + returns on failure), wraps in `JsonrpcNotification`, and sends it on `registry` — a
1386
- `BroadcastTarget`, `Pick<ConnectionRegistry, 'broadcast' |
1387
- 'broadcast_filtered'>`, typically `app_server.ws_endpoints[path]` or the
1388
- registry a `WsEndpointSpec` supplies. No `Transports` collection and no fallback:
1389
- broadcast is 1→N over one named registry. No connections reaches nobody.
1390
-
1391
- `should_deliver: (identity, method, input) => boolean` — optional
1392
- per-connection ACL predicate. When set, fans out via
1393
- `registry.broadcast_filtered`; otherwise `registry.broadcast`. Errors logged
1394
- but never thrown — broadcasts are fire-and-forget.
1395
-
1396
- Typed surface: consumers declare an explicit `interface BackendActionsApi`
1397
- and pin via `create_broadcast_api<BackendActionsApi>({...})` — unchecked
1398
- cast, so interface and `specs` array must stay in sync (codegen is a
1399
- natural fit).
1400
-
1401
- ## Shared type surface (`actions/action_types.ts`)
1402
-
1403
- Sits above `action_spec.ts` (types and the kind enums) and below the dispatchers. Extracted
1404
- so composable primitives (e.g. `heartbeat_action`) can name the types
1405
- without pulling in server-only modules.
1406
-
1407
- - `Action<TSpec>` — `{spec: TSpec, handler?: ActionHandler}`. Polymorphic on `kind`: `request_response` specs require a handler for dispatch; `remote_notification` specs are dispatcher-handled (e.g. `cancel`, which has no handler); `local_call` specs never reach a network dispatcher.
1408
- - `ActionContext` + its narrowed tiers (`ActionAuthContext`, `ActionActorContext`), the handler signatures (`ActionHandler`, `AuthActionHandler`, `ActorActionHandler`), `HandlerForSpec`, and the `rpc_action` binder — the handler-side surface every action factory names. `actions/action_rpc.ts` keeps only `create_rpc_endpoint` + its options.
1409
- - `RpcAction` — `{spec: RequestResponseActionSpec, handler: ActionHandler}`, what the dispatchers accept (`create_rpc_endpoint`, `register_action_ws`) and the `rpc_action` binder produces.
713
+ `create_broadcast_api({registry, specs, log?, should_deliver?})` builds a
714
+ typed `{method: (input) => Promise<void>}` object for backend-initiated
715
+ broadcast — the counterpart to `register_action_ws`'s request-scoped
716
+ dispatch (request-scoped streaming stays on `ctx.notify`). Each call validates
717
+ input against `spec.input` (logging and returning on failure) and sends a
718
+ `JsonrpcNotification` on one `BroadcastTarget` registry
719
+ (`app_server.ws_endpoints[path]`), through `broadcast_filtered` when
720
+ `should_deliver` is set. Errors are logged, never thrown. Its return is
721
+ `Promise<void>`, not the `Result` the frontend API returns. Pin the type with
722
+ `create_broadcast_api<BackendActionsApi>` — an unchecked cast, so the
723
+ interface and `specs` must stay in sync (codegen's
724
+ `generate_backend_actions_api`).