@fuzdev/fuz_app 0.182.0 → 0.184.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 (295) hide show
  1. package/README.md +2 -0
  2. package/dist/actions/CLAUDE.md +535 -1223
  3. package/dist/actions/action_codegen.d.ts +1 -1
  4. package/dist/actions/action_codegen.d.ts.map +1 -1
  5. package/dist/actions/action_codegen.js +3 -2
  6. package/dist/actions/connection_closer.d.ts +11 -9
  7. package/dist/actions/connection_closer.d.ts.map +1 -1
  8. package/dist/actions/connection_closer.js +11 -9
  9. package/dist/actions/frontend_rpc_client.d.ts +1 -1
  10. package/dist/actions/register_action_ws.d.ts +14 -1
  11. package/dist/actions/register_action_ws.d.ts.map +1 -1
  12. package/dist/actions/register_action_ws.js +2 -1
  13. package/dist/actions/ws_socket_session.d.ts +9 -1
  14. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  15. package/dist/actions/ws_socket_session.js +43 -19
  16. package/dist/auth/CLAUDE.md +430 -1024
  17. package/dist/auth/account_queries.d.ts +1 -1
  18. package/dist/auth/account_queries.js +1 -1
  19. package/dist/auth/account_routes.d.ts +9 -8
  20. package/dist/auth/account_routes.d.ts.map +1 -1
  21. package/dist/auth/account_routes.js +78 -75
  22. package/dist/auth/admin_actions.d.ts.map +1 -1
  23. package/dist/auth/admin_actions.js +32 -28
  24. package/dist/auth/api_token.d.ts +20 -3
  25. package/dist/auth/api_token.d.ts.map +1 -1
  26. package/dist/auth/api_token.js +28 -9
  27. package/dist/auth/api_token_queries.d.ts +2 -2
  28. package/dist/auth/api_token_queries.js +2 -2
  29. package/dist/auth/audit_emitter.d.ts +75 -84
  30. package/dist/auth/audit_emitter.d.ts.map +1 -1
  31. package/dist/auth/audit_emitter.js +83 -71
  32. package/dist/auth/audit_log_schema.d.ts +25 -14
  33. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  34. package/dist/auth/audit_log_schema.js +23 -8
  35. package/dist/auth/auth_guard_resolver.d.ts +1 -1
  36. package/dist/auth/auth_guard_resolver.js +1 -1
  37. package/dist/auth/bearer_auth.d.ts +2 -5
  38. package/dist/auth/bearer_auth.d.ts.map +1 -1
  39. package/dist/auth/bearer_auth.js +4 -13
  40. package/dist/auth/bootstrap_account.d.ts +42 -26
  41. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  42. package/dist/auth/bootstrap_account.js +36 -19
  43. package/dist/auth/bootstrap_routes.d.ts +20 -21
  44. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  45. package/dist/auth/bootstrap_routes.js +26 -31
  46. package/dist/auth/bootstrap_token_store.d.ts +3 -4
  47. package/dist/auth/bootstrap_token_store.d.ts.map +1 -1
  48. package/dist/auth/bootstrap_token_store.js +1 -1
  49. package/dist/auth/daemon_token.d.ts +5 -1
  50. package/dist/auth/daemon_token.d.ts.map +1 -1
  51. package/dist/auth/daemon_token_middleware.d.ts +12 -8
  52. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  53. package/dist/auth/daemon_token_middleware.js +15 -21
  54. package/dist/auth/deps.d.ts +19 -5
  55. package/dist/auth/deps.d.ts.map +1 -1
  56. package/dist/auth/deps.js +3 -2
  57. package/dist/auth/invite_queries.d.ts +51 -3
  58. package/dist/auth/invite_queries.d.ts.map +1 -1
  59. package/dist/auth/invite_queries.js +81 -6
  60. package/dist/auth/invite_schema.d.ts +2 -1
  61. package/dist/auth/invite_schema.d.ts.map +1 -1
  62. package/dist/auth/middleware.d.ts +2 -3
  63. package/dist/auth/middleware.d.ts.map +1 -1
  64. package/dist/auth/middleware.js +3 -3
  65. package/dist/auth/request_context.d.ts +3 -3
  66. package/dist/auth/request_context.js +3 -3
  67. package/dist/auth/resolved_auth.d.ts +7 -7
  68. package/dist/auth/resolved_auth.d.ts.map +1 -1
  69. package/dist/auth/resolved_auth.js +4 -4
  70. package/dist/auth/role_grant_offer_actions.d.ts +27 -3
  71. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  72. package/dist/auth/role_grant_offer_actions.js +42 -35
  73. package/dist/auth/role_grant_offer_queries.d.ts +60 -4
  74. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  75. package/dist/auth/role_grant_offer_queries.js +79 -5
  76. package/dist/auth/role_grant_queries.d.ts +3 -52
  77. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  78. package/dist/auth/role_grant_queries.js +5 -80
  79. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  80. package/dist/auth/self_service_role_actions.js +11 -22
  81. package/dist/auth/session_cookie.d.ts +82 -174
  82. package/dist/auth/session_cookie.d.ts.map +1 -1
  83. package/dist/auth/session_cookie.js +80 -130
  84. package/dist/auth/session_middleware.d.ts +8 -17
  85. package/dist/auth/session_middleware.d.ts.map +1 -1
  86. package/dist/auth/session_middleware.js +14 -23
  87. package/dist/auth/session_queries.d.ts +15 -17
  88. package/dist/auth/session_queries.d.ts.map +1 -1
  89. package/dist/auth/session_queries.js +28 -20
  90. package/dist/auth/signup_routes.d.ts.map +1 -1
  91. package/dist/auth/signup_routes.js +93 -43
  92. package/dist/db/CLAUDE.md +5 -3
  93. package/dist/db/sql_columns.d.ts +1 -1
  94. package/dist/db/sql_columns.js +1 -1
  95. package/dist/dev/setup.d.ts +3 -1
  96. package/dist/dev/setup.d.ts.map +1 -1
  97. package/dist/dev/setup.js +3 -1
  98. package/dist/http/CLAUDE.md +315 -763
  99. package/dist/http/db_routes.d.ts +8 -23
  100. package/dist/http/db_routes.d.ts.map +1 -1
  101. package/dist/http/db_routes.js +73 -73
  102. package/dist/http/origin.d.ts +7 -8
  103. package/dist/http/origin.d.ts.map +1 -1
  104. package/dist/http/origin.js +7 -8
  105. package/dist/http/pending_effects.d.ts +118 -6
  106. package/dist/http/pending_effects.d.ts.map +1 -1
  107. package/dist/http/pending_effects.js +114 -6
  108. package/dist/http/route_result.d.ts +1 -1
  109. package/dist/http/route_spec.d.ts +14 -11
  110. package/dist/http/route_spec.d.ts.map +1 -1
  111. package/dist/realtime/sse.d.ts +4 -23
  112. package/dist/realtime/sse.d.ts.map +1 -1
  113. package/dist/realtime/sse.js +4 -25
  114. package/dist/server/app_backend.d.ts +4 -5
  115. package/dist/server/app_backend.d.ts.map +1 -1
  116. package/dist/server/app_backend.js +3 -1
  117. package/dist/server/app_server.d.ts +80 -16
  118. package/dist/server/app_server.d.ts.map +1 -1
  119. package/dist/server/app_server.js +113 -31
  120. package/dist/server/app_server_context.d.ts +1 -2
  121. package/dist/server/app_server_context.d.ts.map +1 -1
  122. package/dist/server/env.js +2 -2
  123. package/dist/testing/CLAUDE.md +265 -796
  124. package/dist/testing/admin_integration.d.ts +2 -3
  125. package/dist/testing/admin_integration.d.ts.map +1 -1
  126. package/dist/testing/admin_integration.js +3 -3
  127. package/dist/testing/adversarial_404.d.ts +6 -1
  128. package/dist/testing/adversarial_404.d.ts.map +1 -1
  129. package/dist/testing/adversarial_404.js +38 -17
  130. package/dist/testing/app_server.d.ts +23 -148
  131. package/dist/testing/app_server.d.ts.map +1 -1
  132. package/dist/testing/app_server.js +53 -131
  133. package/dist/testing/attack_surface.d.ts +1 -1
  134. package/dist/testing/attack_surface.d.ts.map +1 -1
  135. package/dist/testing/audit_completeness.d.ts +2 -3
  136. package/dist/testing/audit_completeness.d.ts.map +1 -1
  137. package/dist/testing/audit_completeness.js +1 -1
  138. package/dist/testing/audit_drift_guard.d.ts +11 -6
  139. package/dist/testing/audit_drift_guard.d.ts.map +1 -1
  140. package/dist/testing/audit_drift_guard.js +15 -8
  141. package/dist/testing/cross_backend/audit_cross_helpers.d.ts +12 -9
  142. package/dist/testing/cross_backend/audit_cross_helpers.d.ts.map +1 -1
  143. package/dist/testing/cross_backend/audit_cross_helpers.js +13 -14
  144. package/dist/testing/cross_backend/capabilities.d.ts +9 -6
  145. package/dist/testing/cross_backend/capabilities.d.ts.map +1 -1
  146. package/dist/testing/cross_backend/capabilities.js +11 -7
  147. package/dist/testing/cross_backend/capability_mounts.d.ts +103 -0
  148. package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -0
  149. package/dist/testing/cross_backend/capability_mounts.js +428 -0
  150. package/dist/testing/cross_backend/cell_moderate.js +2 -2
  151. package/dist/testing/cross_backend/cell_relations.d.ts.map +1 -1
  152. package/dist/testing/cross_backend/cell_relations.js +12 -11
  153. package/dist/testing/cross_backend/conformance_principal.d.ts +54 -0
  154. package/dist/testing/cross_backend/conformance_principal.d.ts.map +1 -0
  155. package/dist/testing/cross_backend/conformance_principal.js +283 -0
  156. package/dist/testing/cross_backend/conformance_table.d.ts +7 -56
  157. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  158. package/dist/testing/cross_backend/conformance_table.js +6 -274
  159. package/dist/testing/cross_backend/cookie_attributes.js +1 -1
  160. package/dist/testing/cross_backend/credential_deadline.d.ts.map +1 -1
  161. package/dist/testing/cross_backend/credential_deadline.js +2 -0
  162. package/dist/testing/cross_backend/credential_wire.d.ts +1 -1
  163. package/dist/testing/cross_backend/credential_wire.d.ts.map +1 -1
  164. package/dist/testing/cross_backend/db_state_diff.d.ts +72 -0
  165. package/dist/testing/cross_backend/db_state_diff.d.ts.map +1 -0
  166. package/dist/testing/cross_backend/db_state_diff.js +444 -0
  167. package/dist/testing/cross_backend/declared_skips.d.ts +68 -0
  168. package/dist/testing/cross_backend/declared_skips.d.ts.map +1 -0
  169. package/dist/testing/cross_backend/declared_skips.js +132 -0
  170. package/dist/testing/cross_backend/default_backend_configs.d.ts +3 -3
  171. package/dist/testing/cross_backend/default_spine_surface.d.ts +0 -6
  172. package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
  173. package/dist/testing/cross_backend/default_spine_surface.js +4 -9
  174. package/dist/testing/cross_backend/differential.d.ts +13 -5
  175. package/dist/testing/cross_backend/differential.d.ts.map +1 -1
  176. package/dist/testing/cross_backend/differential.js +35 -11
  177. package/dist/testing/cross_backend/differential_normalize.d.ts +12 -0
  178. package/dist/testing/cross_backend/differential_normalize.d.ts.map +1 -1
  179. package/dist/testing/cross_backend/differential_normalize.js +16 -0
  180. package/dist/testing/cross_backend/full_spine_mount.d.ts +1 -42
  181. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  182. package/dist/testing/cross_backend/full_spine_mount.js +45 -4
  183. package/dist/testing/cross_backend/in_process_setup.d.ts +28 -19
  184. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  185. package/dist/testing/cross_backend/in_process_setup.js +156 -142
  186. package/dist/testing/cross_backend/login_security.d.ts +12 -0
  187. package/dist/testing/cross_backend/login_security.d.ts.map +1 -1
  188. package/dist/testing/cross_backend/login_security.js +21 -4
  189. package/dist/testing/cross_backend/request_target_conformance_wire.d.ts +0 -2
  190. package/dist/testing/cross_backend/request_target_conformance_wire.d.ts.map +1 -1
  191. package/dist/testing/cross_backend/request_target_conformance_wire.js +3 -1
  192. package/dist/testing/cross_backend/revocation_drivers.d.ts +18 -5
  193. package/dist/testing/cross_backend/revocation_drivers.d.ts.map +1 -1
  194. package/dist/testing/cross_backend/revocation_drivers.js +18 -10
  195. package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts +1 -1
  196. package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts.map +1 -1
  197. package/dist/testing/cross_backend/role_grant_offer_lifecycle.d.ts.map +1 -1
  198. package/dist/testing/cross_backend/role_grant_offer_lifecycle.js +33 -1
  199. package/dist/testing/cross_backend/role_grant_participation.js +4 -4
  200. package/dist/testing/cross_backend/rpc_adversarial.js +1 -1
  201. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +3 -4
  202. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  203. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -2
  204. package/dist/testing/cross_backend/session_cap.d.ts +2 -2
  205. package/dist/testing/cross_backend/session_cap.d.ts.map +1 -1
  206. package/dist/testing/cross_backend/session_cap.js +22 -11
  207. package/dist/testing/cross_backend/setup.d.ts +32 -2
  208. package/dist/testing/cross_backend/setup.d.ts.map +1 -1
  209. package/dist/testing/cross_backend/setup.js +32 -1
  210. package/dist/testing/cross_backend/spine_suites.d.ts +125 -15
  211. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  212. package/dist/testing/cross_backend/spine_suites.js +459 -62
  213. package/dist/testing/cross_backend/spine_surface_constants.d.ts +1 -1
  214. package/dist/testing/cross_backend/spine_surface_constants.d.ts.map +1 -1
  215. package/dist/testing/cross_backend/spine_surface_constants.js +1 -0
  216. package/dist/testing/cross_backend/sse_round_trip.d.ts +9 -1
  217. package/dist/testing/cross_backend/sse_round_trip.d.ts.map +1 -1
  218. package/dist/testing/cross_backend/sse_round_trip.js +123 -27
  219. package/dist/testing/cross_backend/standard.d.ts +2 -3
  220. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  221. package/dist/testing/cross_backend/standard.js +3 -3
  222. package/dist/testing/cross_backend/testing_backdoor.d.ts.map +1 -1
  223. package/dist/testing/cross_backend/testing_backdoor.js +4 -2
  224. package/dist/testing/cross_backend/testing_credential_read.d.ts +10 -11
  225. package/dist/testing/cross_backend/testing_credential_read.d.ts.map +1 -1
  226. package/dist/testing/cross_backend/testing_credential_read.js +12 -12
  227. package/dist/testing/cross_backend/testing_reset_actions.d.ts +84 -47
  228. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  229. package/dist/testing/cross_backend/testing_reset_actions.js +95 -63
  230. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  231. package/dist/testing/cross_backend/testing_server_core.js +2 -3
  232. package/dist/testing/cross_backend/transport_composition.d.ts +1 -1
  233. package/dist/testing/cross_backend/transport_composition.d.ts.map +1 -1
  234. package/dist/testing/cross_backend/transport_composition.js +7 -3
  235. package/dist/testing/cross_backend/ws_round_trip.d.ts +5 -0
  236. package/dist/testing/cross_backend/ws_round_trip.d.ts.map +1 -1
  237. package/dist/testing/cross_backend/ws_round_trip.js +54 -8
  238. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  239. package/dist/testing/daemon_token_rotation.js +2 -3
  240. package/dist/testing/data_exposure.d.ts.map +1 -1
  241. package/dist/testing/data_exposure.js +3 -0
  242. package/dist/testing/db.d.ts +0 -32
  243. package/dist/testing/db.d.ts.map +1 -1
  244. package/dist/testing/db.js +0 -86
  245. package/dist/testing/db_entities.d.ts +14 -0
  246. package/dist/testing/db_entities.d.ts.map +1 -1
  247. package/dist/testing/db_entities.js +17 -0
  248. package/dist/testing/db_invariant_queries.d.ts +259 -0
  249. package/dist/testing/db_invariant_queries.d.ts.map +1 -0
  250. package/dist/testing/db_invariant_queries.js +400 -0
  251. package/dist/testing/db_invariants.d.ts +106 -0
  252. package/dist/testing/db_invariants.d.ts.map +1 -0
  253. package/dist/testing/db_invariants.gen.sql.d.ts +11 -0
  254. package/dist/testing/db_invariants.gen.sql.d.ts.map +1 -0
  255. package/dist/testing/db_invariants.gen.sql.js +13 -0
  256. package/dist/testing/db_invariants.js +141 -0
  257. package/dist/testing/db_invariants.sql +152 -0
  258. package/dist/testing/describe_db.d.ts +36 -0
  259. package/dist/testing/describe_db.d.ts.map +1 -0
  260. package/dist/testing/describe_db.js +71 -0
  261. package/dist/testing/integration.d.ts +8 -12
  262. package/dist/testing/integration.d.ts.map +1 -1
  263. package/dist/testing/integration.js +13 -17
  264. package/dist/testing/integration_helpers.d.ts +1 -1
  265. package/dist/testing/integration_helpers.d.ts.map +1 -1
  266. package/dist/testing/rate_limiting.d.ts +3 -4
  267. package/dist/testing/rate_limiting.d.ts.map +1 -1
  268. package/dist/testing/rate_limiting.js +6 -5
  269. package/dist/testing/role_grant_helpers.d.ts +1 -1
  270. package/dist/testing/role_grant_helpers.d.ts.map +1 -1
  271. package/dist/testing/round_trip.d.ts.map +1 -1
  272. package/dist/testing/round_trip.js +3 -0
  273. package/dist/testing/rpc_attack_surface.d.ts +8 -6
  274. package/dist/testing/rpc_attack_surface.d.ts.map +1 -1
  275. package/dist/testing/rpc_attack_surface.js +69 -6
  276. package/dist/testing/rpc_helpers.d.ts +1 -2
  277. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  278. package/dist/testing/rpc_helpers.js +3 -3
  279. package/dist/testing/rpc_round_trip.d.ts +3 -4
  280. package/dist/testing/rpc_round_trip.d.ts.map +1 -1
  281. package/dist/testing/rpc_round_trip.js +4 -1
  282. package/dist/testing/sse_round_trip.d.ts +3 -4
  283. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  284. package/dist/testing/sse_round_trip.js +15 -6
  285. package/dist/testing/stubs.d.ts +9 -8
  286. package/dist/testing/stubs.d.ts.map +1 -1
  287. package/dist/testing/stubs.js +20 -13
  288. package/dist/testing/test_app.d.ts +168 -0
  289. package/dist/testing/test_app.d.ts.map +1 -0
  290. package/dist/testing/test_app.js +123 -0
  291. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  292. package/dist/testing/ws_round_trip.js +3 -0
  293. package/dist/ui/ui_format.d.ts.map +1 -1
  294. package/dist/ui/ui_format.js +1 -2
  295. package/package.json +1 -1
@@ -10,521 +10,272 @@ runner contract + operator recipes: ../../../docs/migrations.md. For
10
10
  workspace-wide DI vocabulary: Skill(fuz-stack) `dependency-injection.md`.
11
11
 
12
12
  **CLAUDE.md is a map; TSDoc is the detail.** Per-symbol semantics
13
- (parameters, error shapes, invariants, fire-and-forget contracts) live on
14
- TSDoc next to the code. This file orients you across the modules and
15
- documents the cross-cutting invariants that don't fit on any single symbol.
13
+ (parameters, error shapes, invariants, timing contracts) live on TSDoc next
14
+ to the code. This file orients you across the modules and documents the
15
+ cross-cutting invariants that don't fit on any single symbol.
16
16
 
17
17
  ## AppDeps split
18
18
 
19
- - **Capabilities** — `AppDeps` — stateless, injectable per env: `keyring`, `password`, `db`, `log`, `audit`, `connection_closer` (the `RealtimeCloser` every revocation handler closes live connections through — `actions/CLAUDE.md` §Connection closer), `notification_sender` (the `RealtimeNotificationSender` the dispatchers put on every `ActionContext` — `actions/CLAUDE.md` §Notification sender).
20
- - **Route caps** — `RouteFactoryDeps` — `Omit<AppDeps, 'db'>`; handlers get `db` via `RouteContext`.
21
- - **Action caps** — `ActionFactoryDeps` (`auth/deps.ts`) — the `{log, audit}` shape action factories take; `RouteFactoryDeps`/`AppDeps` satisfy it structurally. The factories whose handlers end credentials or revoke roles (`create_account_actions`, `create_admin_actions`, `create_role_grant_offer_actions`, `create_self_service_role_actions`, and the standard bundle) take `RevokingActionFactoryDeps` — `ActionFactoryDeps` plus a required `connection_closer`. The two pure-read actor factories (`actor_lookup`/`actor_search`) take only `{log: Logger}`.
22
- - **Parameters** — `*Options` — static startup values, per-factory.
23
- - **Runtime state** — inline ref — mutable values: `bootstrap_status`, `DaemonTokenState`. NOT in deps or options.
19
+ The categories are root ../../../CLAUDE.md §AppDeps Vocabulary. What auth adds:
24
20
 
25
- `audit: AuditEmitter` is the bound emitter built once at backend assembly by
26
- the consumer's `audit_factory` callback over `create_audit_emitter`; closes
27
- over the pool so rows persist when request transactions roll back. See root
28
- ../../../CLAUDE.md §AppDeps Vocabulary for the workspace-wide split.
21
+ - **Action caps** — `ActionFactoryDeps` (`auth/deps.ts`), the `{log, audit}` shape action factories take; `RouteFactoryDeps` / `AppDeps` satisfy it structurally. The factories whose handlers end credentials or revoke roles (`create_account_actions`, `create_admin_actions`, `create_role_grant_offer_actions`, `create_self_service_role_actions`, and the standard bundle) take `RevokingActionFactoryDeps` — `ActionFactoryDeps` plus a required `connection_closer` (`actions/CLAUDE.md` §Connection closer). The pure-read actor factories (`actor_lookup` / `actor_search`) take only `{log}`.
22
+ - **Runtime state** — `bootstrap_status` and `DaemonTokenState` are inline refs, never deps or options. `DaemonTokenState.keeper_account_id` is resolved by `create_app_server` at assembly when null, and set by the bootstrap route after its commit (and by `_testing_reset`); the daemon leg never re-reads it.
29
23
 
30
24
  ## Module map
31
25
 
32
26
  ### Crypto primitives (pure, I/O-free)
33
27
 
34
- - `auth/keyring.ts` — `Keyring`, `create_keyring` (validates — the one way to build a `Keyring`), `validate_keyring`.
35
- - `auth/session_cookie.ts` — `SessionOptions<T>`, `parse_session`, `process_session_cookie` (`'none' | 'clear'` — no refresh action; the 30-day lifetime is an absolute cap signed once at mint; a value that is present and does not verify, the empty string included, is `'clear'`, and only an absent cookie is `'none'`), `create_session_cookie_value`, `create_session_config`, `fuz_session_config`, `SESSION_AGE_MAX`. The cookie's attributes are fixed — `SESSION_COOKIE_ATTRIBUTES` (`Path=/; HttpOnly; Secure; SameSite=Strict`), no option weakens them — and `format_session_set_cookie` / `format_session_clear_cookie` (and `session_cookie_header` / `clear_session_cookie_header`, the same lines from a `SessionOptions`, for a route's success result — the Rust `route_helpers`' names; the TS form takes the signed value, the Rust one signs the token itself) write the exact `Set-Cookie` strings the Rust spine writes, the value raw (never percent-encoded), refusing a name or value outside RFC 6265 (`is_cookie_name`, `is_cookie_value`) by throwing, so a consumer's `encode_identity` must emit cookie-octets.
36
- - `auth/credential_headers.ts` — the grammar of the three credential headers as pure readers over header lines (`get_header_lines` of `http/header_lines.ts`): `read_session_cookie_value` (several `Cookie` lines read as their `; ` join; split on `;`, SP and HTAB stripped from each pair, the first pair beginning `<name>=` wins, its value verbatim — an invalid first pair is not skipped for a later one), `read_bearer_token` and `read_daemon_token` (exactly one line, exact shape; a header sent twice is discarded). Hono-free. Twin of the Rust `fuz_auth::credential_headers`; `testing/cross_backend/credential_conformance.json` holds both to the same rows.
37
- - `auth/password.ts` — `Password`, `PasswordProvided` (`@fuzdev/fuz_schema` schemas), `PasswordHashDeps`, `PASSWORD_LENGTH_MIN` (12, OWASP), `PASSWORD_LENGTH_MAX` (300).
38
- - `auth/password_argon2.ts` — `hash_password`, `verify_password`, `verify_dummy`, `argon2_password_deps`.
39
- - `auth/api_token.ts` — `API_TOKEN_PREFIX` (`secret_fuz_token_`), `ApiTokenId` (the public id, `pipe(string, regex(API_TOKEN_ID_REGEX))`, a `@fuzdev/fuz_schema` schema), `hash_api_token`, `generate_api_token`, and the shape precheck `is_api_token_shaped` (`API_TOKEN_REGEX`: the prefix plus exactly `API_TOKEN_BODY_LENGTH` = 43 base64url chars).
40
- - `auth/daemon_token.ts` — `DaemonToken`, `DAEMON_TOKEN_REGEX` + the shape precheck `is_daemon_token_shaped` (43 base64url chars), `DAEMON_TOKEN_HEADER` (`X-Daemon-Token`), `generate_daemon_token`, `validate_daemon_token`, `DaemonTokenState`.
41
- - `auth/bootstrap_account.ts` — `bootstrap_account` (one-shot, `bootstrap_lock`-protected) + `read_bootstrap_token`, the read both it and `check_bootstrap_status` use: the secure read less one trailing LF, a token under `BOOTSTRAP_TOKEN_MIN_BYTES` (32) refused as unreadable with an error log. One transaction holds the whole bootstrap: the lock, the account and grants, the session (`create_capped_session`), and last the burn of the token (`token_store.burn_token`) — a failed burn throws out of the transaction (`BootstrapTokenBurnError`) and answers `token_file_undeletable` with nothing created; the success carries `session_cookie_value`, the signed cookie the route sets. `BootstrapAccountCreated` is what `on_bootstrap` receives.
42
- - `auth/bootstrap_token_store.ts` — `BootstrapTokenStore` (`path`, `read_token`, `burn_token`), the one seam to the token file, and `create_file_bootstrap_token_store(deps, path)` over the runtime's secure read and burn. Its read asks the secure read for a single hard link (`require_single_link`): a token file with a second link would outlive its burn under the other name, so it is refused as unreadable, at boot and on a request alike. Twin of the Rust `BootstrapTokenStore` trait, which carries no path (its availability check is handed one).
43
-
44
- Cross-cutting notes that don't live on any single symbol:
45
-
46
- - **Password schemas are split deliberately.** `Password` (length min 12)
47
- gates creation + change; `PasswordProvided` (length min 1) gates
48
- login/verify so tightening creation rules doesn't lock out existing
49
- accounts. Both carry `sensitivity: 'secret'` meta.
50
- - **Argon2id parameters** track OWASP guidance (`memoryCost: 19456`,
51
- `timeCost: 2`, `parallelism: 1`); `verify_dummy` equalizes timing on
52
- account-lookup miss.
53
- - **API token format** `secret_fuz_token_<base64url>` — prefix enables
54
- secret scanning (GitHub, TruffleHog); public `id` is `tok_<12 chars>`;
55
- storage key is the blake3 hash. Raw token returned once.
28
+ - `auth/keyring.ts` — `Keyring`; `create_keyring` validates and is the one way to build one.
29
+ - `auth/session_cookie.ts` — the signed session cookie, named by a bare `session_cookie_name` (`SESSION_COOKIE_NAME` the default), as on the Rust spine: `parse_session_from_cookies` reads it off the `Cookie` lines as `SessionCookieRead` — `absent`, `invalid` (a present cookie that fails to verify, the empty value included) or `valid` with its token and signed expiry; no refresh, the lifetime is an absolute cap signed at mint — and the `Set-Cookie` writers for a route's result (`sign_session_cookie` over a minted token, `format_session_clear_cookie`). The attributes are fixed (`SESSION_COOKIE_ATTRIBUTES`, no option weakens them), and the writers throw on a name or value outside RFC 6265's grammar. The strings and names match the Rust spine's byte for byte.
30
+ - `auth/credential_headers.ts` — the grammar of the three credential headers as pure readers over header lines (`read_session_cookie_value`, `read_bearer_token`, `read_daemon_token`; a credential header sent twice is discarded). Hono-free; twin of the Rust `fuz_auth::credential_headers`, both held to `testing/cross_backend/credential_conformance.json`.
31
+ - `auth/password.ts` — `Password` (creation and change) vs `PasswordProvided` (login and verify): split so tightening creation rules never locks out an existing account. Both carry `sensitivity: 'secret'`.
32
+ - `auth/password_argon2.ts` — `argon2_password_deps` (Argon2id at OWASP parameters); `verify_dummy` equalizes timing on an account-lookup miss.
33
+ - `auth/api_token.ts` — the API token format: the `secret_fuz_token_` prefix exists for secret scanning; the public id (`ApiTokenId`, `to_api_token_id`) is derived from the token; storage is the blake3 hash; the raw token is returned once. `is_api_token_shaped` is the precheck that keeps a malformed bearer from costing a query.
34
+ - `auth/daemon_token.ts` — `DaemonToken`, its shape precheck, `DAEMON_TOKEN_HEADER`, `DaemonTokenState`.
35
+ - `auth/bootstrap_account.ts` — `bootstrap_account`, the one-shot keeper bootstrap: one transaction holds the `bootstrap_lock`, the account and grants, the session and its cookie line, the success row, and last the token burn — a failed burn (`BootstrapTokenBurnError`) rolls everything back and answers `token_file_undeletable`. `read_bootstrap_token` is the read it and `is_bootstrap_available` share. Its success (`BootstrapAccountSuccess`, internal) is the Rust `BootstrapSuccess`: the session token, the account and actor, and the signed `Set-Cookie` line.
36
+ - `auth/bootstrap_token_store.ts` — `BootstrapTokenStore`, the one seam to the token file. Its read refuses a file with a second hard link, which would outlive the burn under the other name. Twin of the Rust trait.
56
37
 
57
38
  ### Schemas, types, DDL
58
39
 
59
- Convention — `*_schema.ts` holds a domain's `@fuzdev/fuz_schema` schemas; `*_ddl.ts` holds DDL strings.
60
-
61
- - `auth/account_schema.ts` — `Account`, `Actor`, `RoleGrant`, `AuthSession`, `ApiToken` + client-safe JSON shapes, `@fuzdev/fuz_schema` schemas: `SessionId` (`brand(Blake3Hash, 'SessionId')`, minted by `hash_session_token`), `SessionAccountJson` and `AdminAccountJson` (their `username` `UsernameCanonical`, so a username in another case fails), `AuthSessionJson`, `RoleGrantSummaryJson` and `PendingOfferSummaryJson` (`role` a `RoleName`, `scope_kind` a `ScopeKindName` or `null`), `ActorSummaryJson`, `AdminAccountEntryJson`, `ClientApiTokenJson` (`id` an `ApiTokenId`); every timestamp a `Timestamp`. Grant predicates over wire fields: `is_role_grant_active` (not revoked, not expired) and `has_global_role(role_grants, role, now?)` (an active grant of the role with `scope_id === null` — the bare-list form of `has_scoped_role(ctx, role, null)`, used client-side by `AuthState`).
62
- - `auth/name_schema.ts` — the name grammar the auth vocabularies share: `NAME_REGEX` (runs of lowercase letters joined by single underscores), `NAME_LENGTH_MAX` (64), `is_valid_name`, `create_name_schema(label)` (the `@fuzdev/fuz_schema` schema, `pipe(bounded_string, message(regex))`: a string too long and off the grammar gets the one length issue, a value that is no string fuz_schema's message; its JSON Schema `maxLength` and `pattern`) and the message builders `format_name_length_message` / `format_name_pattern_message`, so each domain keeps its own label in its messages. `RoleName`, `ScopeKindName`, `GrantPathName`, `CredentialTypeName` and a token's `surface:` name (`is_route_scope_capability`) hold it; `AuditEventTypeName` takes its cap over its own grammar. Twin of the Rust `fuz_auth::is_valid_name` / `NAME_LENGTH_MAX`.
63
- - `auth/role_schema.ts` — `RoleName` (`create_name_schema('Role')`: lowercase letters and underscores, no leading, trailing or consecutive underscores, at most `NAME_LENGTH_MAX` = 64 characters — the grammar every `role` input and every registered role holds, twin of the Rust `is_valid_name`), its messages (`ROLE_NAME_LENGTH_MESSAGE`, `ROLE_NAME_PATTERN_MESSAGE`), `RoleSpec`, `ROLE_KEEPER`, `ROLE_ADMIN`, `BUILTIN_ROLES` and its type `BuiltinRole`, `is_builtin_role`, `create_role_registry` (returns `{role_specs}`), `builtin_role_specs`, `role_has_grant_path`, `list_roles_with_grant_path`. Pinned by the vector table of `role_schema.name.test.ts`.
64
- - `auth/scope_kind_schema.ts` — `ScopeKindName`, the constants its messages come from (`SCOPE_KIND_NAME_LENGTH_MESSAGE`, `SCOPE_KIND_NAME_PATTERN_MESSAGE`), `create_scope_kind_registry` (open registry, no builtins; returns `{scope_kinds}`). `ScopeKindName` (`create_name_schema('Scope-kind')`, grammar and cap) checks a registered name and the `scope_kind` on `role_grant_offer_create` / `role_grant_assign`, which is copied into the row and its audit metadata; off the grammar is the partial unique indexes' `'GLOBAL'` token. Pinned by the vector table of `scope_kind_schema.name.test.ts`.
65
- - `auth/credential_type_schema.ts` — `CredentialTypeName` (`create_name_schema('Credential-type')`), `CREDENTIAL_TYPE_SESSION` / `_API_TOKEN` / `_DAEMON_TOKEN`, `BUILTIN_CREDENTIAL_TYPES` and its type `BuiltinCredentialType`, `create_credential_type_registry` (returns `{credential_types}`).
66
- - `auth/grant_path_schema.ts` — `GrantPathName` (`create_name_schema('Grant-path')`), `GRANT_PATH_ADMIN` / `_SELF_SERVICE` / `_SYSTEM` / `_BOOTSTRAP`, `BUILTIN_GRANT_PATHS` and its type `BuiltinGrantPath`, `create_grant_path_registry` (returns `{grant_paths}`).
67
- - `auth/token_lifetime.ts` — the temporal axis of a minted token: `TokenLifetimeInput` (required `variant` on `account_token_create` — `{kind:'eternal'}` or `{kind:'ttl', days}`, a `@fuzdev/fuz_schema` schema), `token_lifetime_to_expires_at`, `TOKEN_TTL_DAYS_MAX`. No default — `expires_at IS NULL` always means "deliberately eternal".
68
- - `auth/token_scope.ts` — per-credential authority narrowing stored on `api_token.scope`: `TokenScope` / `TokenScopeInput` (`@fuzdev/fuz_schema` `variant`s of strict `object` arms) + constructors, `parse_stored_token_scope` (fail-closed; the `MAX_TOKEN_SCOPE_BYTES` cap counts UTF-8 bytes of the compact document at mint and at read, as the Rust spine does), `token_scope_admits_method` / `_non_rpc`, and the `<section>:<id>` capability vocabulary (`token_scope_method_capability` for the dispatcher's `rpc:<method>`, `is_route_scope_capability` for the `surface:<name>` a `RouteAuth.required_scope` may declare, `token_scope_denied_body`, `TOKEN_SURFACES`). Not an open registry — see ../../../docs/security.md §Token scoping for why the identifier half is deliberately unregistered.
69
- - `auth/auth_ddl.ts` — `CREATE TABLE` / index / seed strings for the core identity tables.
70
- - `auth/audit_log_schema.ts` — `@fuzdev/fuz_schema` throughout: `AUDIT_EVENT_TYPES` (the builtin event types) and the type `AuditEventType` (`(typeof AUDIT_EVENT_TYPES)[number]`), `AuditEventTypeName` (`pipe(bounded_string, message(regex))`, `AUDIT_EVENT_TYPE_NAME_REGEX` under `NAME_LENGTH_MAX`, with `AUDIT_EVENT_TYPE_NAME_LENGTH_MESSAGE` / `AUDIT_EVENT_TYPE_NAME_PATTERN_MESSAGE`; a name too long and off the grammar gets the one length issue), `AuditOutcome` (`one_of(['success', 'failure'])`), `audit_metadata_schemas`, `AuditLogEvent`, `AuditLogInput`, `AuditLogConfig`, `create_audit_log_config` (refuses an `extra_events` key off `AuditEventTypeName` with its first issue's message), and the wire rows `AuditLogEventJson` (`seq` `pipe(number, safe_integer)`, `created_at` a `Timestamp`), `AuditLogEventWithUsernamesJson`, `RoleGrantHistoryEventJson` and `AdminSessionJson`. `audit_log_list`'s input declares `AuditEventTypeName` and `AuditOutcome`. Pinned by the vector tables of `audit_log_schema.names.test.ts`.
71
- - `auth/audit_log_ddl.ts` — `audit_log` table DDL with `seq BIGSERIAL` for cursor-based gap fill (BIGSERIAL converges with the Rust spine; `create_db` registers a `pg.types` int8 parser so `seq` still reads as a JS number).
72
- - `auth/invite_schema.ts` — `Invite`, `CreateInviteInput`, and the `@fuzdev/fuz_schema` rows `InviteJson` (`username` a `UsernameCanonical` or `null`, timestamps `Timestamp`s) and `InviteWithUsernamesJson`, whose resolved names are plain strings.
73
- - `auth/app_settings_schema.ts` — `AppSettings` (single-row via `CHECK (id = 1)`) and its `@fuzdev/fuz_schema` schemas `AppSettingsJson` and `AppSettingsWithUsernameJson`.
74
- - `auth/role_grant_offer_schema.ts` — `RoleGrantOffer`, `RoleGrantOfferJson` (a `@fuzdev/fuz_schema` `object`: `role` a `RoleName`, `scope_kind` a `ScopeKindName` or `null`, so an offer row holding a name off either grammar fails it), `to_role_grant_offer_json`.
75
- - `auth/role_grant_offer_ddl.ts` — `role_grant_offer` table + indexes + `ROLE_GRANT_OFFER_SCOPE_SENTINEL_UUID` / `_GLOBAL_TOKEN` + `ROLE_GRANT_OFFER_COLUMNS` and the shared `ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT` CTE tail (homed here per the placement rule in `db/sql_columns.ts`).
76
- - `auth/role_grant_sql.ts` — the liveness predicates every grant and offer read shares: `role_grant_active_sql(alias)` (not revoked, not expired) and `offer_pending_predicate(alias)` (every `OFFER_TERMINAL_COLUMNS` entry null), twins of the Rust spine's. The frozen partial-index DDL keeps its literal text.
77
- - `auth/role_grant_offer_notifications.ts` — the WS notification specs for the consentful-grant lifecycle, their `@fuzdev/fuz_schema` params, builders, `role_grant_offer_notification_actions`, `role_grant_offer_notification_specs`, the post-commit send helpers `queue_offer_notification` / `queue_supersede_notifications` (`SupersedeAudience`, `SupersedeCause`), and `create_validated_notification_sender`.
40
+ Convention — `*_schema.ts` holds a domain's `@fuzdev/fuz_schema` schemas;
41
+ `*_ddl.ts` holds DDL strings. Every wire shape in auth is a fuz_schema
42
+ schema, its timestamps `Timestamp`s, its usernames `UsernameCanonical` on
43
+ output.
44
+
45
+ - `auth/account_schema.ts` — `Account`, `Actor`, `RoleGrant`, `AuthSession`, `ApiToken` and their client-safe `*Json` shapes; `SessionId` (the blake3 session hash, branded); the grant predicates `is_role_grant_active` and `has_global_role` (the client-side bare-list form of `has_scoped_role(_, role, null)`).
46
+ - `auth/name_schema.ts` — the one name grammar the auth vocabularies share (runs of lowercase letters joined by single underscores, capped at `NAME_LENGTH_MAX`) and `create_name_schema(label)`, so each domain keeps its own label in messages. Twin of the Rust `fuz_auth::is_valid_name`.
47
+ - `auth/role_schema.ts` — `RoleName`, `RoleSpec`, the builtins (`ROLE_KEEPER`, `ROLE_ADMIN`, `is_builtin_role`), `create_role_registry`, and the grant-path lookups (`role_has_grant_path`, `list_roles_with_grant_path`).
48
+ - `auth/scope_kind_schema.ts`, `auth/credential_type_schema.ts`, `auth/grant_path_schema.ts` — the other open name registries (§Open-registry composition) and their builtins. A `scope_kind` is copied into the row and its audit metadata; the grammar keeps out the partial unique indexes' `'GLOBAL'` token.
49
+ - `auth/token_lifetime.ts` — `TokenLifetimeInput` (`eternal` or `ttl`), required on `account_token_create`: no default, so `expires_at IS NULL` always means deliberately eternal.
50
+ - `auth/token_scope.ts` — per-credential authority narrowing on `api_token.scope`: `TokenScope` / `TokenScopeInput`, `parse_stored_token_scope` (fail-closed, byte-capped at mint and read as on the Rust spine), and the `<section>:<id>` capability vocabulary (`rpc:<method>`, `surface:<name>`). Not an open registry — ../../../docs/security.md §Token scoping says why.
51
+ - `auth/auth_ddl.ts` — DDL and seeds for the core identity tables.
52
+ - `auth/audit_log_schema.ts` — `AUDIT_EVENT_TYPES` (the builtins; read the frozen constant, not a copy), `AuditEventTypeName`, `audit_metadata_schemas`, `AuditLogEvent` (its `actor_id` / `target_actor_id` TSDoc is the per-event table), `create_audit_log_config`, the revocation scopes (§Audit emitter), and the wire rows.
53
+ - `auth/audit_log_ddl.ts` — the `audit_log` table; `seq BIGSERIAL` for cursor-based gap fill (`create_db` parses int8 so `seq` reads as a number).
54
+ - `auth/invite_schema.ts`, `auth/app_settings_schema.ts` (a single-row table, `CHECK (id = 1)`) — rows and wire shapes.
55
+ - `auth/role_grant_offer_schema.ts` — `RoleGrantOffer`, `RoleGrantOfferJson`, `to_role_grant_offer_json`.
56
+ - `auth/role_grant_offer_ddl.ts` — the offer table and indexes, `ROLE_GRANT_OFFER_SCOPE_SENTINEL_UUID` / `ROLE_GRANT_OFFER_SCOPE_KIND_GLOBAL_TOKEN`, `ROLE_GRANT_OFFER_COLUMNS` and the shared `ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT` CTE tail (homed here, not with the queries, because `role_grant_queries.ts` writes offer rows too and must not import the offer queries).
57
+ - `auth/role_grant_sql.ts` — the liveness predicates every grant and offer read shares (`role_grant_active_sql`, `offer_pending_predicate`), twins of the Rust spine's.
58
+ - `auth/role_grant_offer_notifications.ts` — the offer-lifecycle WS notification specs and their post-commit send helpers (§WS notifications).
78
59
 
79
60
  ### Queries
80
61
 
81
- All take `deps: QueryDeps = {db}` first; `query_validate_api_token` adds `log` and returns a `ValidatedApiToken` — the row with `scope` parsed, refusing (returning `undefined` for) a row whose stored scope is unreadable.
82
-
83
- - `auth/account_queries.ts` — account CRUD, actor resolution, password update with verify-write race guard, paged `query_admin_account_list`, and the account-row locks every writer of an account takes first (§Row locks): `query_account_lock_verified` (login) and `query_account_lock_live` (token create), `query_account_lock_live_many` (offer and invite create), `query_account_lock_for_offer_accept`, `query_account_lock_for_revoke`, and the purge's `query_account_lock_admins_for_purge` then `query_account_lock_for_purge`.
84
- - `auth/actor_lookup_queries.ts` — batched `actor` ⨝ `account` for the labels arc; active actors of active accounts only.
85
- - `auth/actor_search_queries.ts` — case-insensitive prefix search on `actor.name`, scope-filtered when not admin; active actors of active accounts only.
86
- - `auth/role_grant_queries.ts` — idempotent create, IDOR-guarded revoke (with in-tx supersede), scope-aware lookup, role/account predicates, `query_role_grant_revoke_for_scope` parent-scope cascade.
87
- - `auth/role_grant_offer_queries.ts` — offer create/decline/retract/list/history/sweep, atomic `query_accept_offer` with sibling supersede (a recipient deleted in flight answers the dead credential's 401), and the offer-row lockers `query_role_grant_offer_lock_for_account_removal` / `_for_revoke` over `offer_rows_locked_in_id_order` (`role_grant_sql.ts`; §Row locks); error classes `RoleGrantOfferSelfTargetError` / `_AlreadyTerminalError` / `_ExpiredError` / `_NotFoundError` / `_ActorAccountMismatchError` / `_ActorMismatchError`.
88
- - `auth/session_queries.ts` — server-side sessions (blake3-hashed), `create_capped_session` (the one session minter: the row, the cap's evictions, and the signed cookie value — Hono-free, so the bootstrap transaction mints through it; twin of the Rust `create_capped_session`), `query_session_revoke_by_hash_unscoped` (logout only), `query_session_enforce_limit` (transaction-required; returns the evicted sessions' ids — their token hashes — so the caller closes their connections after the commit), `query_session_cleanup_expired` (returns the swept sessions' ids for the same close — `cleanup_expired_sessions` is its caller). No touch/renewal query — `expires_at` is an absolute cap set at mint (`AUTH_SESSION_LIFETIME_MS`). `query_session_is_live(id, account_id)` is the re-read `account_token_create` runs after the account lock: the session that authorized the mint must still exist.
89
- - `auth/api_token_queries.ts` — token validation (`query_validate_api_token`, which records nothing) and the separate fire-and-forget usage record (`query_api_token_touch`, which the bearer leg runs only once the token's account is found live), `query_api_token_live_account` (the by-id, no-touch re-check read; shares the `API_TOKEN_IS_LIVE` predicate with the validate query so the two can't drift), IDOR-guarded revoke, `query_api_token_enforce_limit` (transaction-required; returns the evicted tokens' ids for the same post-commit close).
90
- - `auth/invite_queries.ts` — invite create/find/claim/list/delete; `query_invite_claim_unscoped` (scoping enforced upstream by `_find_unclaimed_match_for_update`, which runs inside the signup tx with `FOR UPDATE` so find + claim are atomic).
91
- - `auth/app_settings_queries.ts` — load/update for the single-row settings table.
92
- - `auth/audit_log_queries.ts` — `query_audit_log` (in-tx insert), `_list` / `_list_with_usernames` / `_list_role_grant_history` / `_cleanup_before`, drift counters (`get_audit_metadata_validation_failures` / `get_audit_unknown_event_type_failures`).
93
-
94
- **Named projections** (rationale + helpers: ../../../docs/architecture.md
95
- §Query Modules). The consts on this side: `ACCOUNT_COLUMNS` + `ACTOR_COLUMNS`
96
- (`account_queries.ts` owns both tables; its admin listing derives an
97
- active-grant subset from `ROLE_GRANT_COLUMNS`), `AUTH_SESSION_COLUMNS`,
98
- `INVITE_COLUMNS`, `AUDIT_LOG_COLUMNS` (shared with `db/cell_audit_queries.ts`),
99
- `API_TOKEN_COLUMNS` (the client listing derives `minus token_hash`),
100
- `ROLE_GRANT_COLUMNS`, `ROLE_GRANT_OFFER_COLUMNS` (in `role_grant_offer_ddl.ts`),
101
- `APP_SETTINGS_COLUMNS` (reads omit the constant singleton `id`; the one const
102
- without a `satisfies keyof Row` clause, since `AppSettings` deliberately
103
- doesn't carry `id`). Module direction: `role_grant_offer_queries.ts` imports
104
- `role_grant_queries.ts` (the accept path writes through
105
- `query_create_role_grant` / `query_role_grant_by_id`) and not the reverse —
106
- the revoke cascades in `role_grant_queries.ts` still _write_ offer rows, which
107
- is exactly why the offer const and the shared CTE tail live in the DDL module.
108
- Every const is pinned to the live schema by
109
- `src/test/db/column_projections.db.test.ts`. The Rust `fuz_auth` twin carries
110
- the same nine consts (names and order), projected through
111
- `fuz_db::qualify_columns` / `omit_columns`, decoded with compile-time
112
- name→index (`fuz_db::col!`), and pinned by its own
113
- `tests/columns.rs` registry; its narrow purpose rows (`AccountRow` is an
114
- `id, username` pair) keep private per-shape lists checked as subsets of the
115
- table const.
116
-
117
- `_unscoped` suffix on `query_session_revoke_by_hash_unscoped` and
118
- `query_invite_claim_unscoped` is the safety signal: SQL only checks row state,
119
- caller is responsible for scoping. Production scoping for invites is enforced
120
- upstream in `auth/signup_routes.ts` via `query_invite_find_unclaimed_match_for_update`
121
- (SELECT … FOR UPDATE inside the signup tx — find + claim atomic on the row lock).
62
+ All take `deps: QueryDeps = {db}` first. Module direction:
63
+ `role_grant_offer_queries.ts` imports `role_grant_queries.ts`, never the
64
+ reverse; `query_revoke_role_grant` lives with the offer queries (as in the
65
+ Rust twin) because it takes the offer locks and both supersedes. Every
66
+ read projects through its table's `*_COLUMNS` const (../../../docs/architecture.md
67
+ §Query Modules), pinned to the live schema by
68
+ `src/test/db/column_projections.db.test.ts`.
69
+
70
+ - `auth/account_queries.ts` — account CRUD, actor resolution, password update with a verify-write race guard, the admin listing, and the account-row locks every writer of an account takes first (§Row locks).
71
+ - `auth/actor_lookup_queries.ts` / `auth/actor_search_queries.ts` — batched id → label and prefix search; active actors of active accounts only.
72
+ - `auth/role_grant_queries.ts` — idempotent create, scope-aware lookups, `query_role_grant_revoke_for_scope` (parent-scope cascade).
73
+ - `auth/role_grant_offer_queries.ts` — the offer lifecycle, atomic `query_accept_offer` with sibling supersede, `query_revoke_role_grant` (every revoke's one supersede rule: the revokee's incoming siblings and every offer its actor made), the offer-row lockers, and the `RoleGrantOffer*Error` classes.
74
+ - `auth/session_queries.ts` — server-side sessions (blake3-hashed). `create_capped_session` is the one session minter (row, cap evictions, the raw token the caller signs with `sign_session_cookie`; Hono-free; twin of the Rust one). No touch or renewal: `expires_at` is an absolute cap on the database clock. The cap and the expiry sweep return the ids they remove, so the caller closes their connections after the commit.
75
+ - `auth/api_token_queries.ts` — `query_validate_api_token` (records nothing, refuses an unreadable stored scope) and the separate usage touch the bearer leg runs only once the account is found live; `query_api_token_live_account`, the no-touch re-check sharing the validate query's liveness predicate; the token cap.
76
+ - `auth/invite_queries.ts`, `auth/app_settings_queries.ts`.
77
+ - `auth/audit_log_queries.ts` — `query_audit_log` (the insert), the list and history reads, the retention cleanup, and the drift counters.
78
+
79
+ `_unscoped` (`query_session_revoke_by_hash_unscoped`, logout only;
80
+ `query_invite_claim_unscoped`) is the safety signal: the SQL checks row
81
+ state, the caller owns scoping. Signup scopes the invite claim with
82
+ `query_invite_find_unclaimed_match_for_update` in the same transaction.
122
83
 
123
84
  ### Audit emitter
124
85
 
125
- `auth/audit_emitter.ts` defines the `AuditEmitter` capability that lives on
126
- `AppDeps.audit`. Built once at backend assembly via the consumer's
127
- `audit_factory` callback over `create_audit_emitter`; closes over the pool +
128
- its registered listeners + optional `AuditLogConfig`. Its methods:
129
-
130
- - `emit(ctx, input)` — async, always awaited: a success row inside a request transaction is written in it (a failed INSERT rejects); any other row is a fire-and-forget pool write pushed to `ctx.pending_effects`; a success row's listener fan-out goes on `ctx.post_commit_effects`
131
- - `emit_role_grant_target(ctx, auth, input)` — lifts `actor_id` / `account_id` / `ip` boilerplate for role-grant-shape events; `input` is an `AuditEmitRoleGrantInput`
132
- - `emit_pool(input)` — awaitable pool write for code paths without a request transaction (ad-hoc maintenance scripts, a post-commit thunk; not for success audits paired with a mutation — those write in-tx and `notify` post-commit). Writes, then notifies, whatever the outcome
133
- - `notify(event)` — fan out an already-written row to listeners (used by in-tx audit batches like `query_accept_offer.audit_events`)
134
- - `add_listener(listener)` — listener registration, returning a remover for that registration (idempotent; the same function registered twice is two registrations, each with its own remover). Twin of Rust `fuz_auth` `AuditEmitter::add_listener` in firing order and snapshot-at-notify
135
- - `listener_count()` — registered-listener count, for tests / diagnostics
136
- - `drain_inflight()` — test-binary barrier: waits until no `emit` write is in flight, writes started while waiting included. Only an emitter built with `track_inflight: true` tracks; otherwise it resolves at once (production never tracks). Backs `_testing_drain_effects` (twin of Rust `AuditEmitter::drain_inflight` / `new_with_inflight_tracking`)
137
- - `is_tracking_inflight()` — whether the emitter was built with `track_inflight: true`, i.e. whether `drain_inflight` can wait on anything. `_testing_drain_effects` reports it as `tracked`, and `cross_drain_effects` (every `list_audit_events` read) refuses `false` (twin of Rust `AuditEmitter::is_tracking_inflight`)
138
-
139
- Listeners are closure-private; they change only through `add_listener` and
140
- its removers. `create_app_server` registers the audit-log SSE listener and the
141
- one revocation guard (`create_revocation_guard`) via `add_listener`
142
- so SSE fan-out and revocation closes compose on top of the consumer's `on_audit_event` callback
143
- without shallow-copying `AppDeps`, and removes them when its assembly fails or
144
- `AppServer.close` runs — the emitter outlives any one server on its backend.
145
- `notify` iterates a snapshot so a listener registered mid-fan-out fires only on
146
- the next event, and one removed mid-fan-out still hears the in-flight event
147
- (converges with the Rust twin's cloned vec).
148
-
149
- **Where a row is written.** `emit` is async — always `await` it. A **success**
150
- row emitted inside a request transaction (`ctx.db.in_transaction`: an action
151
- with `side_effects`, a route with `transaction: true`) is written in that
152
- transaction, so the change and its row commit together; a failed INSERT
153
- rejects `emit` and the handler's transaction rolls back. A **failure** row, and
154
- a success row with no request transaction open (`/login`, `/password`,
155
- signup, bootstrap — which emit after their own transaction commits), is a
156
- fire-and-forget pool write, fail-open (logged, counted by
157
- `get_audit_write_failures`). The Rust spine's split is the same
158
- (`route_audit_emit`: `emit_in_tx` for an action's success row, `emit` on the
159
- pool otherwise); the TS `/logout` runs in a route transaction, so its row is
160
- in-transaction where Rust's is pooled. `db_admin_row_delete` is written on the
161
- pool after its commit on both twins (TS: `emit_pool` from a post-commit
162
- thunk).
163
-
164
- **When listeners hear about a row.** The fan-out depends on the outcome: a
165
- **failure** row is announced as soon as it is written — the attempt happened
166
- whatever the transaction does; a **success** row is announced only after the
167
- request's transaction commits (a thunk on `ctx.post_commit_effects`; after the
168
- handler returns, on a route without one) and never when the handler throws. The listeners act on a success row — the revocation guards
169
- close connections, the audit stream broadcasts it — so announcing one before
170
- its commit would close while the revoked credential still reads as valid, and
171
- a rolled-back revocation would close anyway. A route that runs without a
172
- request transaction and opens its own around just its writes (`/login`,
173
- `/password`) emits its success row after that transaction commits. The Rust
174
- spine follows the same order: a success row emitted inside a request
175
- transaction is written in it with its fan-out queued behind the commit, and
176
- `/login` and `/password` emit after their own commit. `AuditEmitterContext` is therefore
177
- `{db, pending_effects, post_commit_effects}` — `RouteContext` and `ActionContext`
178
- both satisfy it.
179
-
180
- **Revocation scopes** (`auth/audit_log_schema.ts`) —
181
- `audit_event_revocation_scopes` declares, per builtin event type, what a
182
- successful row invalidates (`RevocationScope`: `none` / `session` / `token` /
183
- `account` / `role`), and `to_revocation_scope(event_type)` reads it (an unknown
184
- event type is `none`). Typed over `AuditEventType`, so a new event type does not
185
- compile until it declares its scope. The revocation listener
186
- (`create_revocation_guard`, `actions/connection_closer.ts`) dispatches on it. Twin of the
187
- `revocation_scope` column on the Rust `AUDIT_EVENT_SPECS`.
188
-
189
- **Drift counters** (`auth/audit_log_queries.ts`) — `audit_metadata_validation_failures`
190
- and `audit_unknown_event_type_failures` are process-wide, fail-open
191
- (write the row anyway). Independent in implementation; under the factory
192
- they track the same config. Sample via `get_*`; `reset_*` are test-only.
193
- Another counter lives with the emitter (`auth/audit_emitter.ts`,
194
- `get_audit_write_failures` / `reset_audit_write_failures`): rows the bound
195
- emitter's pool write failed to insert. That write is fail-open too — logged,
196
- counted, the request proceeds — so the count is how a lost row is seen.
86
+ `auth/audit_emitter.ts` defines `AuditEmitter`, the capability on
87
+ `AppDeps.audit`, built once by the consumer's `audit_factory` over
88
+ `create_audit_emitter`. Its module doc owns the rules ("Where a row is
89
+ written", "When listeners hear about a row"); in short:
90
+
91
+ - `emit` is async — always `await` it. A **success** row is written in the
92
+ transaction of the change it reports, last before the commit; a refused
93
+ INSERT fails the change, and with no transaction open `emit` throws. A
94
+ **failure** row is a fail-open pool write that survives the rollback.
95
+ - Listeners hear a failure row when it is written and a success row only
96
+ after its transaction commits — never on a rollback. The revocation guard
97
+ and the audit stream act on success rows, so announcing one early would
98
+ close connections for a revocation that might not land.
99
+ - `emit_role_grant_target` lifts the actor/account/ip boilerplate for
100
+ role-grant-shape rows; `emit_pool` is for code with no request (never a
101
+ success row paired with a mutation); `notify` announces rows a query wrote
102
+ in its own transaction; `drain_inflight` is what `AppServer.close` and
103
+ `_testing_drain_effects` wait on.
104
+ - `create_app_server` registers the audit-stream listener and the one
105
+ revocation guard through `add_listener`, and removes them on a failed
106
+ assembly or `AppServer.close` — the emitter outlives any one server.
107
+ - The drift counters (metadata validation, unknown event type, failed pool
108
+ write, success row outside a transaction) are process-wide and fail-open;
109
+ `install_audit_drift_guard` holds them at zero per test.
110
+
111
+ **Revocation scopes** — `audit_event_revocation_scopes`
112
+ (`auth/audit_log_schema.ts`) declares, per builtin event type, what a
113
+ successful row invalidates (`none` / `session` / `token` / `account` /
114
+ `role`), read by `to_revocation_scope` and dispatched on by
115
+ `create_revocation_guard`. Typed over `AuditEventType`, so a new builtin
116
+ does not compile until it declares its scope. Twin of the Rust
117
+ `AUDIT_EVENT_SPECS` `revocation_scope` column.
197
118
 
198
119
  ### Routes
199
120
 
200
- - `auth/account_routes.ts` — `POST /login` / `/logout` / `/password`, `GET /api/account/status`. Constants: `DEFAULT_MAX_SESSIONS = 5`, `DEFAULT_MAX_TOKENS = 10`, `DEFAULT_LOGIN_FAIL_FLOOR_MS = 250`, `DEFAULT_LOGIN_FAIL_JITTER_MS = 25`.
201
- - `auth/bootstrap_routes.ts` — `POST /bootstrap` + `check_bootstrap_status` (the boot report: the lock read first; a token file left on a bootstrapped database and an unreadable one on an open window each warn; a missing lock row reads unavailable); `BootstrapStatus` runtime ref (`{available}`); `OnBootstrap`, the post-commit callback over what was created. A failed burn answers 500 `token_file_undeletable` with the window left open; the lock race loser closes its window with no audit row and no charge.
202
- - `auth/signup_routes.ts` — `POST /signup` (open or invite-gated).
203
- - `auth/audit_log_routes.ts` — optional `GET /audit/stream` (SSE); list/history are on the RPC surface. Takes `stream: {registry, log}` (an `AuditLogSse` satisfies it). The handler admits the stream in two phases — register pending on the `SseRegistry`, re-read the credential (`revalidate_resolved_auth`) and the acting actor's role grants, admit — so a revocation racing the request opens no stream: 401 / 403 from the re-reads, or a 200 whose body is the connect comment alone when the pending registration was closed.
204
- - `auth/auth_guard_resolver.ts` — `fuz_auth_guard_resolver` injected into `apply_route_specs` so the framework stays auth-agnostic. Maps each `RouteAuth` axis to a guard and is the single site every route spec traverses, so it also carries the two invariants the auth shape alone can't (a `required_scope` that isn't a well-formed capability, and one on an unrestricted route).
205
-
206
- **Hono-free route shapes.** Each cookie/SSE-coupled route module has a sibling
207
- `*_route_schema.ts` (`account_route_schema.ts`, `signup_route_schema.ts`,
208
- `audit_log_route_schema.ts`, `bootstrap_route_schema.ts`) holding the I/O
209
- schemas **and** the route _shapes_ (`Omit<RouteSpec, 'handler'>` —
210
- method/path/auth/io/errors, via `create_*_route_shapes(options)` or a static
211
- `*_route_shape` const). The `create_*_route_specs` factories spread a shape and
212
- attach the live (hono-coupled) handler; a cross-process surface builder spreads
213
- the same shape with a stub handler (surface generation never runs handlers).
214
- Single source of truth — the shape can't drift between the live route and the
215
- attack surface — and a backend-spawning consumer assembling its surface imports
216
- the shapes without dragging `hono/streaming` (and the optional `hono` peer)
217
- onto a Rust-only cross-process suite. Shared route-limit constants
218
- (`DEFAULT_MAX_SESSIONS` / `_TOKENS`) live in `account_route_schema.ts` for the
219
- same reason (the RPC `account_actions` reads `DEFAULT_MAX_TOKENS`). The
220
- account, signup and bootstrap shapes' schemas, error bodies included, are
221
- `@fuzdev/fuz_schema` schemas: `/login` takes `UsernameProvided` and
222
- `PasswordProvided`; the output `username` of `/logout`, `/signup` and
223
- `/bootstrap` is a `UsernameCanonical`; `/password`'s revoke counts are
224
- non-negative integers; `/bootstrap`'s `token` is 1 to
225
- `BOOTSTRAP_TOKEN_LENGTH_MAX` (4096, the token file's cap) UTF-16 code units,
226
- a longer one a `400 invalid_request_body` before the window check, with no
227
- audit row — twin of the Rust `BOOTSTRAP_TOKEN_LENGTH_MAX`.
228
-
229
- **`POST /login` timing floor.** Login 401s are floored to
230
- `DEFAULT_LOGIN_FAIL_FLOOR_MS` (250ms) + uniform jitter (±25ms) via
231
- `start_fail_floor` (`auth/fail_floor.ts`, shared with signup's 403 / 409
232
- floor; twin of the Rust `fuz_auth::timing`), started before the work and
233
- awaited after, so observed time is `max(work, delay)` and
234
- found-wrong-password and not-found paths converge. 429 stays fast by design;
235
- `verify_dummy` equalizes Argon2id timing on not-found. A floor of `0` or less
236
- is announced once per process on stderr by `warn_if_fail_floor_disabled`
237
- (`LOGIN_` / `SIGNUP_FAIL_FLOOR_DISABLED_BANNER`, the Rust spine's text).
238
-
239
- **`POST /password` revokes everything.** Revokes all sessions + all API
240
- tokens (force re-auth everywhere), then clears the session cookie. Declares
241
- `credential_types: ['session']` (see ../../../docs/security.md
121
+ - `auth/account_routes.ts` — `POST /login`, `/logout`, `/password`, `GET /status`. Rules on `create_account_route_specs`; the close-after-commit split is below.
122
+ - `auth/bootstrap_routes.ts` — `POST /bootstrap`, `is_bootstrap_available` (the boot report), the `BootstrapStatus` ref. A success sets the daemon-token keeper (`daemon_token_state`) after its commit. The lock-race loser answers with no audit row.
123
+ - `auth/signup_routes.ts` — `POST /signup`, open or invite-gated; the success row last in its transaction, an unclassified failure a `signup` failure row with reason `internal_error`.
124
+ - `auth/audit_log_routes.ts` — the optional `GET /audit/stream` (SSE); list and history are RPC. Admission is two-phase (register pending, re-read the credential and role grants, admit), so a revocation racing the request opens no stream.
125
+ - `auth/auth_guard_resolver.ts` — `fuz_auth_guard_resolver`, injected into `apply_route_specs` so `http/` stays auth-agnostic; the one site every route spec passes, so it also refuses a malformed `required_scope` and one on an unrestricted route.
126
+
127
+ **Hono-free route shapes.** Each cookie- or SSE-coupled route module has a
128
+ sibling `*_route_schema.ts` holding its I/O schemas and route _shapes_
129
+ (`Omit<RouteSpec, 'handler'>`). The live factory attaches the handler; a
130
+ cross-process surface builder attaches a stub. One source for the live route
131
+ and the attack surface, and a Rust-only cross-process suite imports the
132
+ shapes without the `hono` peer. Shared limits (`DEFAULT_MAX_SESSIONS` /
133
+ `_TOKENS`) live in `account_route_schema.ts` for the same reason.
134
+
135
+ **`POST /login` timing floor.** Login 401s are floored (`start_fail_floor`,
136
+ `auth/fail_floor.ts`, shared with signup's 403 / 409; twin of the Rust
137
+ `fuz_auth::timing`) so found-wrong-password and not-found converge; 429
138
+ stays fast by design. A disabled floor is announced once per process.
139
+
140
+ **`POST /password` revokes everything** — every session and API token —
141
+ then clears the cookie. Session-only (../../../docs/security.md
242
142
  §Credential-channel gating).
243
143
 
244
- **The routes close what they revoke, after the commit.** `/logout` and
245
- `/password` queue an account-wide close, and `/login` queues a session close
246
- for each session its cap evicted (`queue_connection_close` on
247
- `deps.connection_closer`). The queue runs once the route's transaction has
248
- committed and is dropped if the handler throws.
144
+ **The routes close what they revoke, after the commit.** `/logout` closes
145
+ the one session it ends (the account's other sessions and tokens stay
146
+ valid) through the route transaction's post-commit queue
147
+ (`queue_connection_close`). `/login` (the sessions its cap evicts) and
148
+ `/password` (the account) open their own transaction around just their
149
+ writes and close straight after it commits
150
+ (`close_connections_after_commit`), so a later throw can't drop a close a
151
+ committed revocation owes.
249
152
 
250
- REST-only post RPC migration: `/login`, `/logout`, `/password`, `/signup`,
251
- `/bootstrap`, optional `/audit/stream`.
252
- Everything else listed under §RPC action surfaces.
153
+ Of the auth surface only `/login`, `/logout`, `/password`, `/status`,
154
+ `/signup`, `/bootstrap` and the optional `/audit/stream` are REST;
155
+ everything else is under §RPC action surfaces.
253
156
 
254
157
  ### Middleware
255
158
 
256
- - `auth/middleware.ts` — `create_auth_middleware_specs(deps, options)` assembles `[origin, daemon_token?, session, request_context, bearer_auth]`, the `daemon_token` layer only when given a `daemon_token_state` — the credential legs in the Rust spine's `resolve_auth_from_headers` order, daemon token → session cookie → bearer, the first that authenticates setting `ResolvedAuth` and the later ones skipping. The chain starts from a clean slate: the first leg composed — the daemon token's, else the session's (`create_request_context_middleware`'s `starts_chain`, which the stack sets `false` behind the daemon leg) — clears `RESOLVED_AUTH_KEY` on entry, so a layer mounted before the stack can't pre-set an identity every leg would skip past, and debug-logs a clear that finds one — the trace of a hand-built chain whose session leg sits behind its own earlier leg without `starts_chain: false` (the content-type refusal isn't a middleware: `apply_route_specs` checks every `POST` route, see `http/simple_request.ts`). The origin check mounts on every path (`ORIGIN_MIDDLEWARE_PATH`, `'*'`), less its `origin_carve_outs` — each a `MiddlewareCarveOut` (`{path, reason}`, copied and frozen at assembly by `freeze_origin_carve_outs`, refused by `assert_origin_carve_outs_valid` without a reason or when it overlaps the auth scope — `middleware_paths_overlap` against `AUTH_MIDDLEWARE_PATH`, which holds every credential-reading and credential-minting route — and recorded on the origin spec so the surface leaves its `403` off the carved routes); `AUTH_MIDDLEWARE_PATH` (`'/api/*'`) is where `create_app_server` mounts the rest of the stack; assembly asserts lean on it: `assert_endpoint_in_auth_scope` (an `rpc_endpoints` / `ws_endpoints` path, or the bootstrap route under `bootstrap.route_prefix`, must sit inside it — so no carve-out can reach one), `assert_credential_routes_in_auth_scope(route_specs)` (every registered route that reads a credential — `auth.account` not `'none'`, or marked `reads_credential`, as account status is — or is marked `mints_credential` — login, signup, bootstrap — must sit inside it too, so a consumer prefixing the relative account or signup specs outside `/api/` is refused), and `assert_middleware_stack_mounted(stack_specs, middleware_specs)`, run on a `transform_middleware` result against the pre-transform stack (`[host?, proxy, ...auth]`) — each stack spec, matched by its `handler` closure (not its spoofable `name`), mounted exactly once at its original path (`'*'` for the host gate, the trusted proxy and the origin check, `AUTH_MIDDLEWARE_PATH` for the rest of auth), in its original order; other specs may sit anywhere, including before the proxy and between the auth layers. The proxy is in the stack because dropping it turns every `get_client_ip` into `'unknown'`, one shared bucket for every IP-keyed limiter. The transform receives shallow copies in a fresh array, so an in-place mutation can't rewrite the originals the check reads. The check pins where those layers sit, not what added layers do — a layer you add runs with full context access. Both run in `create_test_app_surface_spec` too.
257
- - `auth/request_context.ts` — `RequestContext`, `resolve_acting_actor`, `build_request_context`, predicates (`has_scoped_role`, `has_any_scoped_role` — the dispatcher's role gate and every builtin-role check read the **global** grant via `has_scoped_role(_, role, null)` / `has_any_scoped_role(_, roles, null)`), guards (`require_auth`, `require_role`, `require_credential_types`, `require_token_scope`), `token_scope_surface_denial` (the direct-call form, for surfaces that aren't route specs), `get_public_account(route)` (the account a `reads_credential` route may read, off the route context's `credential` — `null` for a scope-narrowed token, which such a route answers as anonymous; twin of the Rust `AuthGate::public_request_context` downgrade), `RequestContextForAuth` (the request context a spec's `auth` promises its handler — the one narrowing a route handler's `route.auth` and an action handler's `ctx.auth` share), `refresh_role_grants`.
258
- - `auth/session_middleware.ts` — `create_session_middleware` (reads the cookie through `read_session_cookie_value`, never a framework cookie parser; puts the clear for a cookie that is present and invalid on the context's prepared headers before the handler runs, so every response built through the context carries it once — every route result, which the spine emits there after the commit, ahead of the success's own cookie lines, and the middleware's and error handlers' answers. It never reads or rewrites a response: doing so changes framing and content type on the runtimes' own `Response` classes. What still carries no clear is what the route system doesn't build — a consumer's own middleware or raw Hono route answering with a `Response` it made or replacing the context's `Set-Cookie`, and an accepted WebSocket upgrade's placeholder — where the Rust stack's cookie-clear layer clears every non-`101`. The middleware records the clear line it wrote (`EXPECTED_FIRST_SET_COOKIE_KEY`), and in DEV an answer that doesn't lead with it is logged (`http/dev_set_cookie_check.ts`), the upgrade excepted), `get_session_cookie`. A route sets or clears the session cookie on its success result (`route_ok(value, {set_cookie})`) with `session_cookie_header` / `clear_session_cookie_header` of `auth/session_cookie.ts`; nothing in fuz_app writes a cookie on the context but the middleware's clear. Login, signup and bootstrap each mint through `create_capped_session` (`auth/session_queries.ts`) inside a transaction of their own.
259
- - `auth/resolved_auth.ts` — `ResolvedAuth`, the resolved credential as one value — a union on `credential_type`, each arm carrying only its own fields: `session` (`account`, `session_hash`, `credential_deadline`), `api_token` (`account`, `api_token_id`, `scope`, `credential_deadline`), `daemon_token` (`account`, `credential_deadline: null`) — `account` the row the credential leg read, which the authorization phase builds on rather than reading the account again, as the Rust `ResolvedAuth::account` does (the daemon leg reads the keeper's row per request); `get_resolved_auth(c)` (reads it off `RESOLVED_AUTH_KEY`, the one context key every auth leg writes); the accessors `resolved_auth_scope` (an API token's scope, `full` for a session or daemon token, `null` for anonymous — every token-scope gate reads it), `resolved_auth_session_hash`, and `resolved_auth_api_token_id`; and `revalidate_resolved_auth(deps, resolved)`, the no-touch re-read a long-lived connection runs once it is registered: session row / token row (by id) still live and still on the account, account not soft-deleted; a daemon token re-reads its account only. Reuses the middleware's own queries and predicates. Called by the WS socket session (`actions/ws_socket_session.ts`) and the audit SSE route between registering a connection pending and admitting it. Twin of the Rust `revalidate_resolved_auth`.
260
- - `auth/credential_deadline.ts` — when a resolved credential stops authenticating, which a WebSocket or audit stream opened on it closes at (expiry writes nothing a revocation listener hears): `credential_deadline_after` (the earliest remaining lifetime, anchored to `performance.now()`), `EXPIRES_IN_MS_SQL` (a row's `expires_at - NOW()`, read on the database clock in the statement that checks it, so the session and token validation queries return `expires_in_ms`), and `schedule_credential_deadline` (a chain of timers of at most `CREDENTIAL_DEADLINE_TIMER_CAP_MS`, an hour — a 30-day session is past `setTimeout`'s ceiling — each wake-up also checking a wall-clock copy of the deadline, so a host suspend, which stops the monotonic clock, delays the close by at most one timer after the resume). The middleware sets it on `ResolvedAuth.credential_deadline`: session — the earlier of the cookie's signed expiry (`SESSION_COOKIE_EXPIRES_AT_KEY`, set by the session middleware) and the row's; bearer — the row's, none for an eternal token; daemon token — none. Twin of the Rust `ResolvedAuth::credential_deadline`.
261
- - `auth/bearer_auth.ts` — soft-fail bearer middleware; reads the header through `read_bearer_token` (one line, `Bearer` in any case, one SP, an `is_api_token_shaped` value — anything else, a repeated `Authorization` line included, is no credential and costs no query), and discards the token when the request carries any `Origin` or `Referer` line, an empty one included (browser context, `is_browser_context`). The scope it sets is the one the query parsed — there is no fallback. The last credential leg: it skips before reading the header when the daemon token or a session already resolved the request, so a bearer sent beside one is never looked up and its `last_used_at` / `last_used_ip` never move. A token whose account is tombstoned is no credential either — the anonymous answer, no use recorded.
262
- - `auth/daemon_token_middleware.ts` — `create_daemon_token_middleware(state, deps, log)` — the credential **consumer** only (soft-fail validation, keeper account resolution). The producer (`write_daemon_token` / `start_daemon_token_rotation`) lives in `testing/daemon_token_rotation.ts` behind the dev-env guard — no production assembly mints daemon tokens, mirroring the Rust spine's `fuz_testing`-confined producer. Soft-fails — discards the credential (pass-through, no own 401/503) on **every** non-success path: browser context (any `Origin` or `Referer` line, an empty one included), malformed/invalid token (anything `read_daemon_token` does not read: off-shape, or the header sent twice), and valid-token-but-no-keeper all `next()` through to the dispatcher's `credential_type_required` (403) gate, mirroring the bearer guard and the Rust spine's `resolve.rs`. Daemon tokens are loopback-only, so browser context never arises in practice — the discard is defense-in-depth. The first credential leg, so it clears `RESOLVED_AUTH_KEY` on entry; a valid daemon token sets the `daemon_token` arm, and the session and bearer legs after it skip, so a cookie or bearer sent beside it is never looked up — as on the Rust spine, whose resolve walk never reads the cookie (its cookie-clear layer still verifies one, to clear it when invalid — as the session middleware here does). A discarded daemon token falls through to them.
263
-
264
- See root ../../../CLAUDE.md §Middleware Ordering for canonical assembly
265
- order. The auth-specific invariants are described below in §Cross-cutting
266
- invariants.
159
+ The credential legs, their order, the chain reset, the origin carve-outs and
160
+ the assembly asserts (`assert_endpoint_in_auth_scope`,
161
+ `assert_credential_routes_in_auth_scope`, `assert_middleware_stack_mounted`)
162
+ are root ../../../CLAUDE.md §Middleware Ordering — its origin-verification
163
+ and credential-leg layers (daemon token, session parsing, request context,
164
+ bearer auth) and the `transform_middleware` paragraph. The modules:
165
+
166
+ - `auth/middleware.ts` — `create_auth_middleware_specs(deps, options)`, the stack `create_app_server` mounts at `AUTH_MIDDLEWARE_PATH` (the origin check at `'*'`), and the assembly asserts above.
167
+ - `auth/session_middleware.ts` — the session leg's cookie read and the clear of a present, invalid cookie. A route sets or clears the cookie only on its success result (`route_ok(value, {set_cookie})` with `sign_session_cookie` / `format_session_clear_cookie`); nothing writes a cookie on the context but the middleware's clear.
168
+ - `auth/request_context.ts` — `RequestContext`, `resolve_acting_actor`, `apply_authorization_phase`, the predicates (`has_scoped_role`, `has_any_scoped_role` — builtin-role checks read the **global** grant, `scope_id` null), the guards (`require_auth`, `require_role`, `require_credential_types`, `require_token_scope`), `get_public_account` (what a `reads_credential` route may read — `null` for a scope-narrowed token), and `RequestContextForAuth`, the narrowing a route's `route.auth` and an action's `ctx.auth` share.
169
+ - `auth/resolved_auth.ts` — `ResolvedAuth`, the resolved credential as one union on `credential_type`, carrying the account row the leg read (the authorization phase builds on it rather than reading again). `revalidate_resolved_auth` is the no-touch re-read a long-lived connection (WS, the audit stream) runs between registering pending and admitting.
170
+ - `auth/credential_deadline.ts` — when a resolved credential stops authenticating, which an open WebSocket or audit stream closes at (expiry writes nothing a revocation listener hears). Survives host suspend and `setTimeout`'s ceiling; rules in its TSDoc.
171
+ - `auth/bearer_auth.ts` — the soft-fail bearer leg; a request with any `Origin` or `Referer` line discards the token.
172
+ - `auth/daemon_token_middleware.ts` — the daemon token **consumer** only, soft-fail on every non-success path. The producer (`write_daemon_token`, `start_daemon_token_rotation`) is in `testing/daemon_token_rotation.ts` behind the dev-env guard — no production assembly mints daemon tokens, as on the Rust spine.
267
173
 
268
174
  ### Cell layer
269
175
 
270
176
  The cell content primitive's wire schemas, RPC handlers, and authz live
271
- here; the schema + queries live in `db/` (see `db/CLAUDE.md` §Cell layer).
272
- Generic-only — no app vocabulary on the wire; per-kind shape is the
273
- consumer's `validate_data(kind, data)` callback on `CellActionDeps`, which
274
- accepts or throws and never rewrites (the handler stores the caller's `data`).
275
-
276
- - `auth/cell_data_schema.ts` — `CellData` base (a `@fuzdev/fuz_schema`
277
- `loose_object` with optional `label` / `summary`); a per-kind schema spreads
278
- its `def` (`loose_object({...CellData.def, ...})`). **`kind` is
279
- not in `data`** — it is a top-level `cell.kind` column (peer to
280
- `visibility` / `path`), the write-once capability/identity axis; a stray
281
- `kind` inside `data` is rejected fail-loud (`ERROR_CELL_KIND_IN_DATA`).
282
- - `auth/cell_action_specs.ts` — `CellVisibility` enum, `CellPath` brand,
283
- `CELL_KIND_LENGTH_MAX` (64 — the wire `kind` on `cell_create` and the
284
- `cell_list` filter; the tag is copied into the cell's audit rows),
285
- `CellJson`, `CellPolicy` (a root's contribution policy, a `loose_object`), the
286
- generic verb specs (`cell_create / get / update / delete / list / clone /
287
- moderate / policy_set`), error reasons, and `all_cell_action_specs`
288
- (spreads in the grant / field / item / audit registries so codegen + UI
289
- see one cell namespace). `CellJson` has no hub axis; `path` is global. The
290
- directory-tree columns `parent_id` / `root_id` (containment, immutable in v1)
291
- - the `moderation` lifecycle marker (`pending` / `approved` / `rejected`) are
292
- top-level `CellJson` keys, peer to `visibility` (set by the create authorizer's
293
- verdict + the `cell_moderate` verb, never in `data`).
294
- - `auth/cell_grant_action_specs.ts` / `cell_field_action_specs.ts` /
295
- `cell_item_action_specs.ts` / `cell_audit_action_specs.ts` — the
296
- `cell_grant_*` / `cell_field_*` / `cell_item_*` / `cell_audit_list`
297
- specs + their wire JSON shapes. Every cell wire schema is
298
- `@fuzdev/fuz_schema`.
299
- - `auth/cell_authorize.ts` — pure predicates over
300
- `(RequestContext | null, CellRow, grants)`: `can_view_cell`,
301
- `can_edit_cell`, and `can_manage_cell` (= admin ‖ owner, where owner is
302
- the `cell.created_by` actor field). The manage tier gates visibility
303
- writes, all grant management (`cell_grant_create` / `_list` /
304
- `_revoke`), and the per-cell audit timeline (`cell_audit_list`, D14 —
305
- it surfaces who-touched-the-cell); it is not a grant level and not
306
- delegable. Editor-grant holders edit content + relations but cannot
307
- manage grants or read the audit timeline. NULL
308
- `created_by` (system origin) is admin-only for edit/manage (explicit
309
- defense-in-depth). "Admin" on every tier is the **global** grant — a
310
- scoped `admin` row bypasses nothing. `can_view_cell`'s public and grant
311
- arms also require the cell's `moderation` to admit an audience
312
- (`db/cell_moderation.ts`: unmoderated or `approved`), so a pending or
313
- rejected contribution is its author's and admins' alone; `can_edit_cell`'s
314
- editor-grant arm requires the same admission. `can_steward_cell`
315
- is the separate moderator read: the governing root's manager on a pending or
316
- rejected contribution under a live root.
317
- - `auth/cell_steward.ts` — `cell_steward_admits(deps, auth, cell)`: the steward
318
- arm with its governing-root load, run only after `can_view_cell` denies. Its
319
- module doc names where the arm applies (`cell_get`, `cell_moderate`, the
320
- cell-scoped fact route, `cell_list`'s SQL) and where it must not (clone,
321
- contribution parents, relation reads, `shared_with`, grant recompute).
322
- - Strict relation-read visibility — every relation read drops edges whose far
323
- endpoint the caller can't view, so a viewer of a parent can't enumerate
324
- private linked cells by id. **Forward and reverse** `cell_field_list` /
325
- `cell_item_list` filter in SQL before their limit
326
- (`db/cell_view_sql.ts`'s `can_view_cell_sql`, bound through
327
- `cell_viewer_from_auth`), so a page is up to `limit` edges whose other end
328
- the caller can view — `CELL_RELATION_LIST_LIMIT_DEFAULT` (50) when omitted,
329
- `CELL_RELATION_LIST_LIMIT_MAX` (500) at most
330
- (`auth/cell_relation_list_limit.ts`), and hidden ends never crowd out
331
- visible ones. The `cell_get` bundle (whose `*_truncated` counts raw edges)
332
- and the clone walk read with `CELL_VIEWER_UNRESTRICTED` and filter after,
333
- through `auth/cell_relation_visibility.ts`'s `filter_visible_target_ids(deps,
334
- auth, ids)`: two queries for the whole id-set, the cells read through the
335
- narrow `CELL_VIEW_COLUMNS` projection (`query_cell_view_load_many`), never
336
- the payload.
337
- - `auth/cell_actions.ts` — `create_cell_actions(deps)`, the generic
338
- handlers. `cell_create` stamps `created_by` + writes the top-level `kind`
339
- column; `path` writes are admin-only. It also resolves the directory tree:
340
- `parent_id` (wire) → the governing `root_id` (`parent.root_id ?? parent.id`),
341
- **404**-masking a hidden parent. `cell_update` gates `visibility`
342
- writes on `can_manage_cell` (`ERROR_CELL_VISIBILITY_MANAGE_ONLY`) and
343
- **never touches `kind`** / `parent_id` / `root_id` / `moderation` (all
344
- write-once-at-birth or control-gated, never on the update patch).
345
- `cell_get` bundles visibility-filtered `fields` + `items` (one over the cap
346
- for truncation detection). `cell_clone` deep-walks viewable children only
347
- (each clone inherits its source's `kind`; clones are unparented), and runs
348
- the mounted `authorize_create` for **every** cell it writes as a parentless
349
- create — a denial is the same 403 `cell_create_forbidden`, so clone is no
350
- side door past the creation policy. The optional
351
- parent-aware `authorize_create` dep (`CellCreateAuthorize` — an object whose
352
- `authorize` takes a wider input `{kind, data, parent_id, parent_kind,
353
- root_id, root_policy}` than `validate_data` and returns a `CellCreateVerdict`
354
- `{allow:false} | {allow:true, moderation_required}`, and whose optional
355
- `validate_policy` accepts or refuses a root policy write)
356
- gates create by capability; it runs after the validator + the parent-resolve
357
- (which **404**s `cell_not_found` on a missing or soft-deleted root as on a
358
- missing parent, authorizer or not).
359
- A **viewable**-parent / root-creation deny is **403** `cell_create_forbidden`
360
- (the create-path **404** mask is reserved for a hidden parent); `Allow` folds
361
- the moderation outcome (born `pending`+private vs `approved`+author-visibility).
362
- The handler reads the governing root in-tx and hands its `policy` column
363
- over as `root_policy`, so a directory policy resolves `root_policy[kind]`
364
- without a DB read; an authorizer needing more reads through its third
365
- argument, the request `ctx` (`ctx.db` is the request transaction), and only
366
- reads. `None`/omitted = open
367
- create (the default; mirrors `validate_data`), and every non-null policy write
368
- refused `cell_policy_unsupported`. A root's `policy` (a JSON object, roots only
369
- by table CHECK, opaque to the spine, readable on `CellJson`) is set at a
370
- root's `cell_create` and changed only by `cell_policy_set` — the 404 mask, then
371
- manage-tier (403 `cell_policy_manage_only`, an editor grant included), then
372
- root-only (400 `cell_policy_root_only`), then the authorizer's
373
- `validate_policy`; audited with the new and the previous policy. `cell_update`
374
- never writes it (an editor can rewrite `data`, so a policy read from `data`
375
- would be the editor's to loosen), and a clone is born without one.
376
- `cell_moderate` is the `pending → approved | rejected` transition (plus
377
- `approved → rejected`, the takedown), gated on
378
- `can_manage_cell` of the **governing root** (admin / root owner — the author
379
- lands a 403, the anti-self-approval guard; a root owner reaches the check
380
- through the steward arm); approve flips
381
- `moderation → approved` + `visibility → public`, reject sets `rejected`
382
- (visibility untouched). The write carries the from-state: approve moves only
383
- a pending contribution, reject a pending or approved one (the takedown); any
384
- other transition answers 400 `cell_not_pending`.
385
- - `auth/cell_action_helpers.ts` — the cell verbs' shared gates, each loading
386
- the cell and 404-masking a miss and a denial alike
387
- (`require_viewable_cell` — `auth` may be `null`, which reads no grants —
388
- `require_editable_cell`, `require_manageable_cell`), plus
389
- `cell_not_found_error` and `emit_cell_audit(ctx, audit, auth, event_type,
390
- metadata)`. Twins of the Rust `fuz_cell_actions` helpers.
391
- - `auth/cell_ref_admission.ts` — `require_new_refs_held`, the
392
- possession gate `cell_create` / `cell_update` / `cell_clone` run last before
393
- their write: a non-admin write introducing a fact ref (beyond the cell's
394
- current refs on update, each cloned row's source refs on clone) that its
395
- acting actor holds no `fact_holder` row for is 403 `cell_ref_not_held`,
396
- answered from holder rows alone (stored and unstored hashes read the same);
397
- a schema without the fact chain refuses every new ref. Global admin bypasses;
398
- a scoped admin doesn't. Twin of the Rust `cell_ref_admission`.
399
- - `auth/cell_grant_actions.ts` / `cell_field_actions.ts` /
400
- `cell_item_actions.ts` / `cell_audit_actions.ts` — the relation + ACL +
401
- audit handlers, exporting `to_grant_json` / `to_field_json` /
402
- `to_item_json` reused by the `cell_get` bundle. `cell_grant_create` takes an
403
- optional `authorize_grant_create` (`CellGrantCreateAuthorize`), asked of a
404
- manager after the spine's gates and before the write (a level change too);
405
- `false` is 403 `cell_grant_not_authorized`, nothing written.
406
- `cell_grant_revoke` takes an optional `authorize_grant_revoke`
407
- (`CellGrantRevokeAuthorize`), the steward widening: asked only of a caller
408
- who neither manages the cell nor holds the grant, for a role-shaped grant
409
- with a `scope_id`; `true` revokes (audit `steward: true`) with a delete
410
- matching the level it saw, `false` keeps the 404 mask. Both callbacks, like
411
- the create authorizer and the offer callback, take the request `ctx` last —
412
- `ctx.db` is the request transaction — and must only read through it.
413
- - `auth/all_cell_actions.ts` — `create_all_cell_actions(deps, {roles})`, the
414
- handler-side twin of `all_cell_action_specs` and sibling of
415
- `create_standard_rpc_actions`: bundles all five cell factories (CRUD + grant
416
- - field + item + audit) into one list. Reach for this whenever a backend
417
- mounts the full cell layer — a single source so an HTTP-RPC mount and a WS
418
- mount (or two backends) can't diverge on which cell verbs they expose.
419
- Distinct from `create_cell_actions` (the CRUD-only factory it bundles).
420
- - `auth/cell_audit_metadata.ts` + `cell_grant_audit_metadata.ts` +
421
- `cell_field_audit_metadata.ts` + `cell_item_audit_metadata.ts` — audit
422
- metadata envelopes (IDs only), `@fuzdev/fuz_schema` `loose_object`s,
423
- registered via `extra_events:` on the consumer's `create_audit_log_config`.
424
- - `auth/cell_audit_events.ts` — `cell_audit_events`, the canonical
425
- `event_type → metadata` map bundling every cell-domain audit event.
426
- Consumers spread it into `extra_events` to register the whole layer in
427
- one call (aggregator by design, not a compat shim).
428
-
429
- The cell event types (`cell_create` / `_update` / `_delete` / `_clone` /
430
- `_moderate`, `cell_policy_set`, `cell_grant_create` / `_revoke`, `cell_field_set` / `_delete`,
431
- `cell_item_insert` / `_move` / `_delete`) are consumer-registered extras,
432
- not built-ins — see §Audit event extensibility.
177
+ here; the schema and queries live in `db/` (`db/CLAUDE.md` §Cell layer). The
178
+ handler semantics are `auth/cell_actions.ts`'s module TSDoc; the model for
179
+ consumers is ../../../docs/usage.md §Cell data layer, and the security
180
+ properties (moderation gates reads, root policy is manage-tier) are
181
+ ../../../docs/security.md §Authorization.
182
+
183
+ Rules a caller would miss:
184
+
185
+ - **Generic only** — no app vocabulary on the wire. Per-kind shape is the
186
+ consumer's `validate_data(kind, data)` on `CellActionDeps`, which accepts or
187
+ throws and never rewrites.
188
+ - **`kind` is not in `data`** — it is the top-level, write-once `cell.kind`
189
+ column; a stray `kind` in `data` is refused (`ERROR_CELL_KIND_IN_DATA`).
190
+ `parent_id` / `root_id` / `moderation` are likewise top-level and never on
191
+ the update patch.
192
+ - **Consumer callbacks only read.** `authorize_create`,
193
+ `authorize_grant_create`, `authorize_grant_revoke` (and the offer
194
+ `authorize`) take the request `ctx` last; `ctx.db` is the request
195
+ transaction.
196
+ - **A clone is no side door**: it runs `authorize_create` for every cell it
197
+ writes as a parentless create.
198
+ - **Every miss and denial on a gated read is a 404**, so a private cell's
199
+ existence doesn't leak.
200
+
201
+ Modules:
202
+
203
+ - `auth/cell_data_schema.ts` — `CellData`, the base a per-kind schema spreads.
204
+ - `auth/cell_action_specs.ts` — `CellJson`, `CellPolicy`, the generic verb specs (`cell_create / get / update / delete / list / clone / moderate / policy_set`), and `all_cell_action_specs`, which spreads the grant, field, item and audit registries in so codegen sees one cell namespace.
205
+ - `auth/cell_grant_action_specs.ts` / `cell_field_action_specs.ts` / `cell_item_action_specs.ts` / `cell_audit_action_specs.ts` — the relation, ACL and audit-timeline specs.
206
+ - `auth/cell_authorize.ts` — the pure view / edit / manage predicates. Manage (global admin or the `created_by` actor) is not a grant level and not delegable; "admin" is always the **global** grant. `can_steward_cell` is the separate moderator read.
207
+ - `auth/cell_steward.ts` — `cell_steward_admits`; its module doc names where the steward arm applies and where it must not.
208
+ - `auth/cell_relation_visibility.ts`, `auth/cell_relation_list_limit.ts` — strict relation-read visibility: every relation read drops edges whose far endpoint the caller can't view.
209
+ - `auth/cell_actions.ts` — `create_cell_actions(deps)`, the CRUD, clone, moderate and policy handlers.
210
+ - `auth/cell_action_helpers.ts` — the shared load-and-404-mask gates and `emit_cell_audit`; twins of the Rust `fuz_cell_actions` helpers.
211
+ - `auth/cell_ref_admission.ts` — `require_new_refs_held`: a non-admin write introducing a fact ref its actor holds no `fact_holder` row for is 403 `cell_ref_not_held`. Twin of the Rust `cell_ref_admission`.
212
+ - `auth/cell_grant_actions.ts` / `cell_field_actions.ts` / `cell_item_actions.ts` / `cell_audit_actions.ts` — the relation, ACL and audit handlers.
213
+ - `auth/all_cell_actions.ts` — `create_all_cell_actions(deps, {roles})`, the handler twin of `all_cell_action_specs`. Reach for it whenever a backend mounts the full cell layer, so an HTTP-RPC mount and a WS mount can't diverge.
214
+ - `auth/cell_audit_events.ts` (and the `cell_*_audit_metadata.ts` modules) — `cell_audit_events`, the cell event types' metadata map; consumers spread it into `extra_events`. The cell events are consumer-registered extras, not builtins (§Audit event extensibility).
433
215
 
434
216
  ## Cross-cutting invariants
435
217
 
436
- The things that span multiple files and don't fit on any one symbol's TSDoc.
437
-
438
218
  ### Two-phase identity
439
219
 
440
- **Authentication runs in middleware** (session / bearer / daemon token).
441
- Sets one `ResolvedAuth` (`RESOLVED_AUTH_KEY`) on a valid credential.
442
- Account-only — never loads actor or role_grants, never populates
443
- `REQUEST_CONTEXT_KEY`.
444
-
445
- **Authorization runs before input validation**, matching the dispatcher's
446
- 401 → authz → 403 → 400 phase order — the 429 is dispatcher-only (see `http/CLAUDE.md` §Validation
447
- pipeline). When the route's input declares `acting?: ActingActor` or its auth
448
- requires role_grants, the authorization phase calls `resolve_acting_actor` over
449
- the `acting` selector — the validated query value on GETs, read off the raw
450
- body on mutations — and builds an actor-bound `RequestContext`. A malformed
451
- selector reads as omitted (it only ever picks among actors the account already
452
- owns, and input validation rejects it a step later). Account-grain routes run
453
- with `RequestContext.actor: null`.
454
-
455
- `apply_authorization_phase` is pure data — returns `AuthorizationResult`
456
- (`{ok: true, request_context: RequestContext | null} | {ok: false, status, body}`)
457
- without touching the Hono context. Each transport binds the same failure to
458
- its wire shape: REST `c.json(body, status)`; HTTP RPC + WS fold into a
459
- JSON-RPC envelope where `error.message` is the reason string and
460
- `error.data: {reason, ...rest}` flattens diagnostic fields. The one 500
461
- reason is `no_actors_on_account` (signup invariant violation: a live account
462
- with no active actor). The phase builds on the account row the credential leg
463
- read, so an account deleted or purged after that read runs an account-grain
464
- handler on that row, as on the Rust spine. An actor-grain one finds no actor,
465
- and the one read that tells the two cases apart answers a removed account
466
- with the dead credential's 401 (`authentication_required`). `account_verify`
467
- re-reads the account live and answers the same 401.
468
-
469
- **Production-middleware invariant.** No production middleware on the auth
470
- path populates `REQUEST_CONTEXT_KEY`; it sets only `RESOLVED_AUTH_KEY`. Test
471
- harnesses pre-populate `REQUEST_CONTEXT_KEY` and set `TEST_CONTEXT_PRESET_KEY`
472
- to the `TEST_CONTEXT_PRESET` symbol to bypass DB-backed actor resolution
473
- (`has_test_context_preset` reads it; any other value, `true` or a string
474
- included, is unset); production code that reads `REQUEST_CONTEXT_KEY` is
475
- reading test escape-hatch state.
476
-
477
- **The session token key is fixed.** The session middleware writes the token
478
- under `SESSION_TOKEN_KEY` (`hono_context.ts`, `'auth_session_id'`) and the
479
- session leg reads it there; `SessionOptions` carries no context key, so the two
480
- cannot disagree and the token cannot land on another spine key.
220
+ **Authentication runs in middleware** (daemon token / session / bearer) and
221
+ sets one `ResolvedAuth` (`RESOLVED_AUTH_KEY`) on a valid credential.
222
+ Account-only — never loads actor or role_grants.
223
+
224
+ **Authorization runs before input validation**, per route and per action
225
+ (`http/CLAUDE.md` §Validation pipeline for the full phase order). When the
226
+ input declares `acting?: ActingActor` or the auth requires role_grants,
227
+ the authorization phase resolves the acting actor and builds an actor-bound
228
+ `RequestContext`; a malformed selector reads as omitted (it only ever picks
229
+ among actors the account owns, and validation rejects it a step later).
230
+ Account-grain routes run with `RequestContext.actor: null`, so a multi-actor
231
+ account can log out without picking a persona.
232
+
233
+ `apply_authorization_phase` is pure data — it returns `AuthorizationResult`
234
+ and each transport binds a failure to its wire shape. The one 500 is
235
+ `no_actors_on_account` (a live account with no active actor). It builds on
236
+ the credential leg's account row: an account removed after that read runs an
237
+ account-grain handler on the row, while an actor-grain one finds no actor and
238
+ answers the dead credential's 401, as on the Rust spine.
239
+
240
+ **Production-middleware invariant.** The credential legs set only
241
+ `RESOLVED_AUTH_KEY`. The route pipeline's authorization phase writes the
242
+ actor-bound context to `REQUEST_CONTEXT_KEY`, which `require_role` reads.
243
+ Test harnesses pre-set `REQUEST_CONTEXT_KEY` and set
244
+ `TEST_CONTEXT_PRESET_KEY` to the `TEST_CONTEXT_PRESET` symbol to skip
245
+ DB-backed resolution (`has_test_context_preset`; any other value is unset).
246
+
247
+ **The session token key is fixed** (`SESSION_TOKEN_KEY`): the session
248
+ middleware takes only the cookie's name, no context key, so it and the leg
249
+ cannot disagree.
481
250
 
482
251
  ### Row locks
483
252
 
484
253
  One class order in every transaction — accounts, then offers, then grants and
485
254
  actors — and id order within a class. Every writer of an account takes its row
486
255
  first (two mints of one account take turns there, so the caps hold); a
487
- multi-row write (credential deletes, offer cascades, the expiry sweeps) locks
488
- its rows in one id-ordered statement before writing. Each lock's strength and
489
- reason is on its query's TSDoc; the rule set: ../../../docs/security.md §Row
490
- Locks. `lock_pins.cross.test.ts` pins them on both spines (../../test/CLAUDE.md).
256
+ multi-row write locks its rows in one id-ordered statement before writing.
257
+ Each lock's strength and reason is on its query's TSDoc; the rule set:
258
+ ../../../docs/security.md §Row Locks. `lock_pins.cross.test.ts` pins them on
259
+ both spines (../../test/CLAUDE.md).
491
260
 
492
261
  ### Wire timestamp shape
493
262
 
494
- Every timestamp on the wire is **second-precision UTC** —
495
- `YYYY-MM-DDTHH:MM:SSZ`, exactly 20 characters, the shape both spines emit.
496
- Timestamps read from a row get it from the SQL projection: each query module
497
- builds an `iso8601_timestamp_expr` override over its table const and passes
498
- it to `columns_sql` / `qualify_columns` (see `db/CLAUDE.md`), covering `account`, `actor`,
499
- `role_grant`, `role_grant_offer`, `auth_session`, `api_token`, `invite`,
500
- `app_settings`, `audit_log`, and the cell tables. Stamps minted in TS rather
501
- than read back — the `expires_at` on `account_token_create`'s output — use
502
- `to_iso8601_seconds` (`timestamp.ts`), so the mint and the later
503
- `account_token_list` read agree byte for byte.
504
-
505
- The `*Json` schemas type these as `Timestamp` (`iso_datetime`), which a
506
- millisecond stamp also satisfies — so the shape is pinned behaviorally by
507
- `assert_iso8601_seconds` (`testing/cross_backend/wire_shapes.ts`) inside the
508
- shared suites, on both backends.
509
-
510
- The alias costs one rule: **an `ORDER BY` in a projected SELECT qualifies
511
- its column** (`ORDER BY auth_session.created_at`) — bare, Postgres resolves
512
- it to the formatted output column, which ties rows written inside the same
513
- second and drops the btree index. Qualified, ordering stays exact and
514
- index-backed, matching the Rust twin (which aliases nothing, so its bare
515
- `ORDER BY created_at` already means the column).
263
+ Every wire timestamp is second-precision UTC, the shape both spines emit
264
+ (`timestamp.ts`). Rows get it from the SQL projection
265
+ (`iso8601_timestamp_column`, `db/sql_columns.ts`, which also owns the one
266
+ rule it costs: an `ORDER BY` in a projected SELECT qualifies its column);
267
+ stamps minted in TS use `to_iso8601_seconds`. `Timestamp` also admits
268
+ milliseconds, so the shape is pinned behaviorally by
269
+ `assert_iso8601_seconds` (`testing/cross_backend/wire_shapes.ts`) on both
270
+ backends.
516
271
 
517
272
  ### Open-registry composition
518
273
 
519
- Four open string registries — `RoleName`, `ScopeKindName`,
520
- `CredentialTypeName`, `GrantPathName` — share the same factory shape:
521
- construction-time guards (name regex, duplicate detection, builtin-collision
522
- rejection), `ReadonlyMap` output, pass into `create_role_registry` for
523
- cross-axis validation. The four share one name grammar, runs of lowercase
524
- letters joined by single underscores, at most `NAME_LENGTH_MAX` characters
525
- (`auth/name_schema.ts`), which a token's `surface:` name holds too.
526
-
527
- Dependency flow:
274
+ Four open name registries — `RoleName`, `ScopeKindName`,
275
+ `CredentialTypeName`, `GrantPathName` — share one factory shape
276
+ (construction-time grammar, duplicate and builtin-collision checks,
277
+ `ReadonlyMap` output) and one name grammar (`auth/name_schema.ts`), and
278
+ compose into `create_role_registry` for cross-axis validation:
528
279
 
529
280
  ```
530
281
  create_credential_type_registry()
@@ -532,379 +283,188 @@ create_scope_kind_registry() → create_role_registry({roles, options})
532
283
  create_grant_path_registry()
533
284
  ```
534
285
 
535
- `role_specs` drives downstream defaults:
536
-
537
- - `admin_actions.grantable_roles` ⊇ `{role : 'admin' ∈ grant_paths}`
538
- - `self_service_role_actions` default eligibility ⊇ `{role : 'self_service' ∈ grant_paths}`
539
-
540
- `AuditEventTypeName` is the fifth open registry but composes differently —
541
- via `create_audit_log_config({extra_events})` into the bound emitter.
286
+ `role_specs` drives the defaults: `admin_actions.grantable_roles` (roles with
287
+ the `admin` grant path) and the self-service eligible set (roles with
288
+ `self_service`). `AuditEventTypeName` is a fifth open registry that composes
289
+ differently — `create_audit_log_config({extra_events})` into the emitter.
542
290
 
543
291
  ### Audit `target_*_id` rules
544
292
 
545
- The two target columns on `AuditLogEvent` populate by a single rule:
546
293
  **`target_actor_id` is set when the event subject is bound to a specific
547
- actor**; `target_account_id` is always populated when there's an account
548
- subject. SSE/WS socket-close keys on `target_account_id ?? account_id`
549
- (sessions stay account-grain at the routing layer even after multi-actor).
550
-
551
- The full per-event-type table lives in `AuditLogEvent.target_actor_id`
552
- TSDoc. The pattern that spans emit sites:
553
-
554
- - **Role-grant-shape events** populate both targets (the grantee actor is
555
- the subject regardless of initiator). Use `audit.emit_role_grant_target`
556
- to lift the `actor_id` / `account_id` / `ip` boilerplate.
557
- - **Offer-shape events** (`role_grant_offer_create` / `_expire` / `_retract` /
558
- `_supersede`) populate `target_actor_id` only when the offer was
559
- actor-targeted at create time (`role_grant_offer.to_actor_id` set).
294
+ actor**; `target_account_id` whenever there is an account subject. The full
295
+ per-event table is the `AuditLogEvent.actor_id` / `target_actor_id` TSDoc.
296
+ The pattern across emit sites:
297
+
298
+ - **Role-grant-shape events** populate both targets — the grantee actor is
299
+ the subject whoever initiated. Use `audit.emit_role_grant_target`.
300
+ - **Offer-shape events** populate `target_actor_id` only when the offer was
301
+ actor-targeted (`role_grant_offer.to_actor_id` set).
560
302
  - **Account-shape events** (login, logout, signup, bootstrap, password
561
- change, session/token revoke, app_settings update, invite events) stay
562
- account-grain on **both** `target_actor_id` and `actor_id` — the
563
- operation is performed by the account, and a multi-actor user must be
564
- able to log out without first picking an acting actor.
303
+ change, session/token revoke, app_settings_update) stay account-grain on
304
+ `target_actor_id`. `actor_id` is null except on signup and bootstrap, which
305
+ name the actor they create.
306
+ - **Invite events** carry the acting `actor_id` and no target. A delete of a
307
+ missing invite writes a failure row with `attempted_invite_id`.
308
+ - **Account removal** writes the account event plus one per actor
309
+ (`actor_delete` / `_purge` / `_undelete`, `target_actor_id` the actor), each
310
+ snapshotting the identity into metadata, since `audit_log` ids carry no FK.
311
+
312
+ A connection close keyed on an audit row follows the row's revocation scope:
313
+ `account` and `role` key on `target_account_id ?? account_id`, `session` and
314
+ `token` on the row's metadata (`actions/CLAUDE.md` §Revocation guard).
565
315
 
566
316
  ### Audit event extensibility
567
317
 
568
- Consumers extend the closed `AUDIT_EVENT_TYPES` enum via
569
- `create_audit_log_config({extra_events})` — a `@fuzdev/fuz_schema` metadata
570
- schema or `null` per type; collisions with builtins, name-format failures
571
- and a value that is no schema throw at construction. `query_audit_log`
572
- validates through `parse`, and a dropped row's log line masks the
573
- `sensitivity: 'secret'` fields of an object metadata schema.
574
- The builtin `audit_metadata_schemas` are fuz_schema `loose_object`s
575
- (`nullable` where the event may carry none, `literal(null)` for `logout`). The
576
- DB column is `TEXT NOT NULL` (no enum), so consumer types round-trip through
577
- list queries, the `audit_log_list` RPC, and SSE identically to builtins.
578
-
579
- `AuditLogEvent.event_type` / `AuditLogEventJson.event_type` / the
580
- `audit_log_list` filter input are all `AuditEventTypeName` (regex-validated
581
- string, at most `NAME_LENGTH_MAX` characters) — widened from the closed enum so consumer rows round-trip. The
582
- write side (`AuditLogInput<T>`, `AuditMetadataMap`) stays closed-enum so a
583
- builtin event's metadata narrows by its type.
584
-
585
- ### `AUDIT_EVENT_TYPES` builtins
586
-
587
- For quick reference; the source-of-truth list is the `Object.freeze`d
588
- constant in `auth/audit_log_schema.ts`.
589
-
590
- ```
591
- login role_grant_create
592
- logout role_grant_revoke
593
- bootstrap role_grant_offer_create
594
- signup role_grant_offer_accept
595
- password_change role_grant_offer_decline
596
- session_revoke role_grant_offer_retract
597
- session_revoke_all role_grant_offer_expire
598
- token_create role_grant_offer_supersede
599
- token_revoke invite_create
600
- token_revoke_all invite_delete
601
- account_delete app_settings_update
602
- account_purge db_admin_row_delete
603
- account_undelete
604
- actor_delete
605
- actor_purge
606
- actor_undelete
607
- ```
608
-
609
- `account_delete` / `account_purge` / `account_undelete` snapshot
610
- `{username, email}` into metadata; `actor_delete` / `actor_purge` /
611
- `actor_undelete` snapshot `{name}`. The account-level handlers emit the
612
- account event plus one per-actor event (`delete` = soft, `purge` = hard,
613
- `undelete` = reactivation — see ../../../docs/security.md §Authorization,
614
- "Account-removal target guards").
615
-
616
- `role_grant_offer_supersede` carries
617
- `reason: 'sibling_accepted' | 'role_grant_revoked' | 'scope_destroyed' | 'account_deleted'` (for `account_deleted`, `cause_id` is the removed account, the grantor's or the recipient's)
618
- plus `cause_id` pointing to the row that triggered the supersede. The WS
619
- `role_grant_offer_supersede` notification's reason set is narrower —
620
- `sibling_accepted | role_grant_revoked | account_deleted`; `scope_destroyed`
621
- is an audit reason only (a consumer's own cascade writes it).
318
+ Consumers extend the closed `AUDIT_EVENT_TYPES` via
319
+ `create_audit_log_config({extra_events})` — a fuz_schema metadata schema or
320
+ `null` per type; a collision with a builtin, an off-grammar name, or a value
321
+ that is no schema throws at construction. The DB column is `TEXT NOT NULL`,
322
+ and the read side (`AuditLogEvent.event_type`, the wire row, the
323
+ `audit_log_list` filter) is the widened `AuditEventTypeName`, so consumer
324
+ rows round-trip like builtins. The write side (`AuditLogInput<T>`,
325
+ `AuditMetadataMap`) stays closed so a builtin's metadata narrows by its
326
+ type. An unknown type or a metadata mismatch is logged and counted, and the
327
+ row written anyway; a failed pool write logs the lost row with its secret
328
+ fields masked.
329
+
330
+ `role_grant_offer_supersede` carries `reason` (`sibling_accepted` /
331
+ `role_grant_revoked` / `scope_destroyed` / `account_deleted`) and `cause_id`,
332
+ the row that triggered it. `scope_destroyed` is an audit reason only (a
333
+ consumer's own cascade writes it); the WS notification's set omits it.
622
334
 
623
335
  ### Keeper auth shape
624
336
 
625
337
  Keeper is not a dedicated guard — it's a composable `RouteAuth` shape:
626
338
  `{account: 'required', actor: 'required', roles: ['keeper'], credential_types: ['daemon_token']}`.
627
- The two-part check is `require_credential_types(['daemon_token'])` (403
628
- `ERROR_CREDENTIAL_TYPE_REQUIRED`) followed by `require_role(['keeper'])`
629
- (403 `ERROR_INSUFFICIENT_PERMISSIONS`) — the channel gate lands
630
- pre-authorization and the role gate post-authorization, so a non-daemon
631
- credential is refused before the route resolves an actor for it. Same
632
- scope-aware semantics mirrored
633
- in the HTTP RPC dispatcher (`actions/action_rpc.ts`), the WS dispatcher
634
- (`actions/register_action_ws.ts`), and the admin bypasses inside
339
+ The channel gate (`require_credential_types`, 403
340
+ `ERROR_CREDENTIAL_TYPE_REQUIRED`) runs pre-authorization and the role gate
341
+ (`require_role`, 403 `ERROR_INSUFFICIENT_PERMISSIONS`) post-authorization,
342
+ so a non-daemon credential is refused before the route resolves an actor
343
+ for it. The same scope-aware check runs for actions in
344
+ `actions/perform_action.ts` (both dispatchers) and in the admin bypasses of
635
345
  `auth/role_grant_offer_actions.ts`.
636
346
 
637
347
  ### Migrations
638
348
 
639
- Schema migrations live in `auth/migrations.ts` — a frozen, append-only chain
640
- (`full_auth_schema` first, every later change its own appended entry) under
641
- the single reserved namespace `'fuz_auth'` (`AUTH_MIGRATION_NS`), each
642
- entry twinned byte-for-byte by name on the Rust spine. `db/migrate.ts`'s
643
- `reserved_migration_namespaces` lists the spine's names (`fuz_auth`, `fuz_cell`,
644
- `fuz_facts`); `run_migrations` and `baseline` refuse a namespace bearing one
645
- unless it is the spine's own object (`AUTH_MIGRATION_NS`, `CELL_MIGRATION_NS`,
646
- `FACT_MIGRATION_NS`, each built by `create_spine_migration_namespace`). Runner contract, error vocabulary, and
647
- operator recipes (rename, mark applied, reset, baseline) are in
648
- ../../../docs/migrations.md.
349
+ `auth/migrations.ts` — a frozen, append-only chain (`full_auth_schema`
350
+ first) under the reserved namespace `'fuz_auth'` (`AUTH_MIGRATION_NS`), each
351
+ entry twinned by name on the Rust spine. The reserved names are
352
+ `reserved_migration_namespaces` in `db/migrate.ts`, a consumer namespace under
353
+ one refused as `namespace-reserved`; that refusal, the runner contract, and the
354
+ operator recipes are ../../../docs/migrations.md.
649
355
 
650
356
  ## RPC action surfaces
651
357
 
652
- Each registry splits across `*_action_specs.ts` (schemas + specs + registry,
653
- codegen-importable) and `*_actions.ts` (`create_*_actions(deps, options)`
654
- factory with handlers). Client codegen imports the specs and skips the
655
- handler module's transitive query-layer deps.
358
+ Each registry splits across `*_action_specs.ts` (schemas, specs, registry —
359
+ what client codegen imports, without the handlers' query-layer deps) and
360
+ `*_actions.ts` (`create_*_actions(deps, options)`). The spec modules carry
361
+ each action's input, output, auth and `error_reasons`; the handler modules'
362
+ TSDoc carries their semantics. This section keeps what spans actions.
656
363
 
657
- - `create_admin_actions` — registry `all_admin_action_specs` — bundled in `create_standard_rpc_actions`.
658
- - `create_role_grant_offer_actions` — registry `all_role_grant_offer_action_specs` — bundled.
659
- - `create_account_actions` — registry `all_account_action_specs` — bundled.
660
- - `create_self_service_role_actions` — registry `all_self_service_role_action_specs` — not bundled (`eligible_roles` is app-specific).
661
- - `create_actor_lookup_actions` — registry `all_actor_lookup_action_specs` — not bundled (opt-in batched id → label resolver).
662
- - `create_actor_search_actions` — registry `all_actor_search_action_specs` — not bundled (opt-in prefix-search picker).
364
+ - `create_admin_actions` — `all_admin_action_specs` — bundled in `create_standard_rpc_actions`.
365
+ - `create_role_grant_offer_actions` — `all_role_grant_offer_action_specs` — bundled.
366
+ - `create_account_actions` — `all_account_action_specs` — bundled.
367
+ - `create_self_service_role_actions` — `all_self_service_role_action_specs` — not bundled (`eligible_roles` is app-specific).
368
+ - `create_actor_lookup_actions` — `all_actor_lookup_action_specs` — not bundled (opt-in id → label resolver).
369
+ - `create_actor_search_actions` — `all_actor_search_action_specs` — not bundled (opt-in prefix-search picker).
663
370
 
664
- `auth/all_action_spec_registries.ts` exposes `all_fuz_auth_action_spec_registries`
665
- for registry-wide invariant tests. Not a mounting surface; protocol specs
666
- are excluded.
371
+ `auth/all_action_spec_registries.ts` exposes
372
+ `all_fuz_auth_action_spec_registries` for registry-wide invariant tests — not
373
+ a mounting surface; protocol specs excluded.
667
374
 
668
375
  ### Authorization patterns
669
376
 
670
- - **Spec-level enforcement.** Every admin spec declares
671
- `auth: {account: 'required', actor: 'required', roles: ['admin']}`; the
672
- dispatcher checks per-spec, so mixed-auth bundles compose cleanly
673
- (`role_grant_revoke` uses the admin gate alongside non-admin offer
674
- siblings in the same factory).
675
- - **Input-dependent elevation.** `role_grant_offer_list` and `_history` use
676
- `side_effects: false` so they're GET-addressable. Spec-level auth is
677
- `{account: 'required', actor: 'required'}` so any caller reaches their
678
- own inbox; the handler additionally requires admin when `{account_id}`
679
- refers to another account. The spec can't express this because auth runs
680
- before input parsing.
377
+ - **Spec-level enforcement.** Admin specs declare
378
+ `auth: {account: 'required', actor: 'required', roles: ['admin']}`, checked
379
+ per spec, so mixed-auth factories compose (`role_grant_revoke` is
380
+ admin-gated beside non-admin offer siblings).
381
+ - **Input-dependent elevation.** `role_grant_offer_list` / `_history` (GET
382
+ addressable, `side_effects: false`) admit any caller to its own inbox; the
383
+ handler requires admin when `account_id` names another account — auth runs
384
+ before input parsing, so the spec can't say it. `account_delete`'s self
385
+ path is session-only the same way.
681
386
  - **Account-grain self-service.** `account_*` specs declare
682
- `auth: {account: 'required', actor: 'none'}` — no `acting` on input, so
683
- the actor axis stays `'none'` per registry-time invariant 2. IDOR via
684
- `query_session_revoke_for_account` / `query_revoke_api_token_for_account`.
685
- - **Credential-channel gating.** `account_token_create` / `_revoke`,
686
- `account_session_revoke` / `_revoke_all`, and REST `POST /password` all
687
- declare `credential_types: ['session']`. `account_session_revoke` is
688
- gated alongside `_revoke_all` because a leaked bearer can otherwise
689
- compose `account_session_list` + N×revoke to reach the same lockout.
690
- `role_grant_offer_accept` and `self_service_role_set` carry the gate for
691
- the privilege-pivot shape — both move the caller's own authority, and the
692
- resulting grant outlives revoking the token. `role_grant_offer_create`
693
- carries it for the same pivot onto another account (a leaked bearer offers a
694
- role to an account its holder controls); scripted conferral is
695
- `role_grant_assign`'s.
696
- REST `POST /logout` also declares `credential_types: ['session']`, but
697
- for forensic fidelity rather than a threat — a bearer / daemon token
698
- holds no session to end, so the gate refuses it instead of returning a
699
- misleading 200 + a phantom `logout` audit row. `GET /audit/stream` carries
700
- it so the stream stays closable (SSE subscribers are keyed by session
701
- hash, so `token_revoke` could not close a bearer's stream).
702
- Admin token/session revoke specs deliberately stay unrestricted (admin
703
- scripting from CLI/bearer is legitimate operator workflow). See
704
- ../../../docs/security.md §Credential-channel gating.
705
- - **Rate-limit posture.** Admin specs and authed-spam-prone surfaces
706
- (`role_grant_offer_create`, `role_grant_revoke`, `account_token_create`,
707
- `self_service_role_set`, `actor_lookup`, `actor_search`) declare
708
- `rate_limit: 'account'`. Throttle-requests semantics — every invocation
709
- records, regardless of outcome. Default
710
- `default_action_account_rate_limit` is 1200/15min per actor.
387
+ `actor: 'none'`, with no `acting` on the input; IDOR is the account-scoped
388
+ queries.
389
+ - **Credential-channel gating** — which specs and routes are session-only,
390
+ and why (`/logout` for forensic fidelity; `/audit/stream` because a
391
+ long-lived admin feed is not handed to a channel the deployment never
392
+ chose): ../../../docs/security.md §Credential-channel gating. Every gated
393
+ event records `credential_type` in its metadata.
394
+ - **Rate limits.** Admin specs and the spam-prone surfaces declare
395
+ `rate_limit: 'account'`, which records every invocation whatever its
396
+ outcome (`default_action_account_rate_limit`, keyed per account).
711
397
 
712
398
  ### Admin actions
713
399
 
714
400
  `create_admin_actions(deps, options?)` in `auth/admin_actions.ts`.
715
401
 
716
- Three of these — `account_delete` / `account_purge` / `account_undelete` —
717
- carry `account_*` method names (not `admin_`): privilege lives in the auth
718
- spec, not the name, so soft-delete stays self-service-capable. They sit in
719
- the admin factory because their `actor: 'required'` shape + account-management
720
- queries match the rest of this registry (mixed-auth in one factory is
721
- fine — same as `role_grant_revoke`). `account_undelete` is admin-only —
722
- reactivation has no self path because a soft-deleted account can't
723
- authenticate.
724
-
725
- - `admin_account_list_action_spec` — read; input `{limit?, offset?, include_deleted?}`; output `{accounts, grantable_roles}`. On it and the other paged reads (`audit_log_list`, `audit_log_role_grant_history`, `role_grant_offer_history`) `limit` / `offset` declare `invalid_reason` `ERROR_LIMIT_INVALID` / `ERROR_OFFSET_INVALID` (`http/error_schemas.ts`), and `audit_log_list`'s `since_seq` / `outcome` `ERROR_SINCE_SEQ_INVALID` / `ERROR_OUTCOME_INVALID`: every refusal of the field carries it. `include_deleted` (default false) surfaces soft-deleted rows (with `account.deleted_at` set) for the admin UI's reactivation view.
726
- - `account_delete_action_spec` — mutation (soft delete); self-or-admin (`{account, actor}`, handler elevates to admin when `account_id` ≠ self); the self path is session-only, handler-enforced ahead of the target guards (an API or daemon token gets the dispatcher's `ERROR_CREDENTIAL_TYPE_REQUIRED` 403 via `credential_type_required_error`), while an admin deleting another account keeps any credential; input `{account_id?}`; output `{ok, deleted}`. Tombstones account + actor(s), supersedes every pending offer the account made and every pending offer made to it (`reason: 'account_deleted'`, an audit row each), revokes sessions/tokens, deletes the unclaimed invites the account issued (an `invite_delete` row each), emits `account_delete` + per-actor `actor_delete`. Role grants are kept — inert while the account is tombstoned. Refuses a keeper-role target (`ERROR_CANNOT_DELETE_KEEPER`) or the sole active admin (`ERROR_CANNOT_DELETE_LAST_ADMIN`) — both fail-loud with a failure-audit row.
727
- - `account_purge_action_spec` — mutation (hard purge); keeper-only (`credential_types: ['daemon_token']` + `roles: ['keeper']`) + `confirm: true` + WARN; input `{account_id, confirm?}`; output `{ok, purged}`. Supersedes the offers the account made and those made to it (audited and notified, as `account_delete` does), deletes the unclaimed invites it issued, revokes its sessions and tokens, then the cascading delete (its locks: §Row locks); emits `account_purge` + per-actor `actor_purge` (identity snapshot survives in metadata since `audit_log` ids carry no FK). Refuses a keeper-role target (`ERROR_CANNOT_DELETE_KEEPER`) or the sole active admin (`ERROR_CANNOT_DELETE_LAST_ADMIN`).
728
- - `account_undelete_action_spec` — mutation (reactivation, inverse of soft delete); admin-only (`roles: ['admin']` — no self path, a tombstoned account can't authenticate); input `{account_id}`; output `{ok, undeleted}`. Clears the `deleted_at` tombstone on the account + its actor(s), emits `account_undelete` + per-actor `actor_undelete`. Restores the account, its actors and its role grants as they were; does not restore revoked sessions/tokens, superseded offers, or deleted invites.
729
- - `admin_session_list_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{sessions}`.
730
- - `admin_session_revoke_all_action_spec` — mutation; input `{account_id}`; output `{ok, count}`.
731
- - `admin_token_revoke_all_action_spec` — mutation; input `{account_id}`; output `{ok, count}`.
732
- - `audit_log_list_action_spec` — read; input `{event_type?, outcome?, account_id?, limit?, offset?, since_seq?}`; output `{events}`.
733
- - `audit_log_role_grant_history_action_spec` — read; input `{limit?, offset?}`; output `{events}`.
734
- - `invite_create_action_spec` — mutation; input `{email?, username?}`; output `{ok, invite}`.
735
- - `invite_list_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{invites}`.
736
- - `invite_delete_action_spec` — mutation; input `{invite_id}`; output `{ok}`.
737
- - `app_settings_get_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{settings}`.
738
- - `app_settings_update_action_spec` — mutation; input `{open_signup}`; output `{ok, settings}`.
739
-
740
- Constants: `AUDIT_LOG_LIST_LIMIT_MAX = 200`, `ADMIN_ACCOUNT_LIST_DEFAULT_LIMIT = 50`,
741
- `ADMIN_ACCOUNT_LIST_LIMIT_MAX = 200`.
742
-
743
- Error reasons via `error.data.reason`: `ERROR_ACCOUNT_NOT_FOUND` (404 via
744
- `jsonrpc_errors.not_found`) on admin revoke-all + account delete/purge,
745
- `ERROR_INSUFFICIENT_PERMISSIONS` (403) when `account_delete` targets another
746
- account without admin, `ERROR_PURGE_NOT_CONFIRMED` (400) when `account_purge`
747
- omits `confirm: true`, `ERROR_CANNOT_DELETE_KEEPER` (403) when `account_delete` /
748
- `account_purge` targets a keeper-role account (the keeper account is never
749
- API-removable — auth + daemon-token both pivot on it),
750
- `ERROR_CANNOT_DELETE_LAST_ADMIN` (403) when `account_delete` / `account_purge`
751
- targets the sole remaining active admin (soft-deleted admins don't count; the
752
- count locks its rows, so concurrent removals can't both pass), `ERROR_INVITE_ACCOUNT_EXISTS_USERNAME` /
753
- `_EMAIL` / `ERROR_INVITE_DUPLICATE` on invite create, `ERROR_INVITE_NOT_FOUND`
754
- on invite delete. `invite_create` empty input is rejected at the schema by a
755
- `check` and surfaces as `invalid_params` with `error.data.issues` (DEV-only `WireIssue`s).
756
-
757
- Closure state:
758
-
759
- - `grantable_roles` derived once from `options.roles?.role_specs ?? builtin_role_specs`
760
- via `list_roles_with_grant_path(_, GRANT_PATH_ADMIN)`.
761
- - `app_settings_get`/`_update` handlers are always wired and read/write the DB
762
- directly (`query_app_settings_load`/`query_app_settings_update`);
763
- `auth/signup_routes.ts` reads the current value fresh per request. There is no
764
- `options.app_settings` ref.
765
- - `deps.connection_closer` (required, `RevokingActionFactoryDeps`) —
766
- `admin_session_revoke_all` / `admin_token_revoke_all` / `account_delete` /
767
- `account_purge` queue a close of the target account's live connections
768
- (`queue_connection_close`), run after the handler's transaction commits and
769
- dropped if it throws. The close does not depend on the audit write; the
770
- audit listeners repeat it on the announced row. Failure outcomes queue no
771
- close.
772
-
773
- Failure-outcome audit rows: `admin_session_revoke_all` and `_token_revoke_all`
774
- emit an `outcome: 'failure'` row on `ERROR_ACCOUNT_NOT_FOUND` for forensic
775
- visibility — `target_account_id` is null (FK rejects missing ids), and the
776
- probed id is preserved under `metadata.attempted_account_id`. Every gated
777
- event additionally records `credential_type` in metadata (defense in depth).
402
+ - **`account_delete` / `account_purge` / `account_undelete` carry `account_*`
403
+ names**, not `admin_`: privilege lives in the auth spec, so soft delete
404
+ stays self-service. They sit in the admin factory because their actor-grain
405
+ shape and queries match it. `account_undelete` is admin-only — a tombstoned
406
+ account can't authenticate, so there is no self path.
407
+ - **Account removal** (delete and purge alike) supersedes every pending offer
408
+ the account made and every one made to it (`account_deleted`, audited and
409
+ notified), deletes the unclaimed invites it issued, revokes its sessions and
410
+ tokens, and writes the account row plus one per actor. Delete keeps the role
411
+ grants, inert; purge is the keeper-only cascading delete with
412
+ `confirm: true`. The target guards (never a keeper account, never the last
413
+ active admin) and what an undelete restores are ../../../docs/security.md
414
+ §Authorization.
415
+ - **Failure rows on a miss.** `admin_session_revoke_all`,
416
+ `admin_token_revoke_all`, account delete / purge and `invite_delete` write
417
+ a failure row on a missing target, the probed id in metadata
418
+ (`attempted_account_id`, `attempted_invite_id`) since the FK rejects it.
419
+ - **Closure state.** `grantable_roles` is derived once from
420
+ `options.roles?.role_specs ?? builtin_role_specs`. App settings are read and
421
+ written in the database; signup reads `open_signup` fresh per request, so
422
+ there is no shared in-memory ref.
423
+ - **Closes.** The revoke-alls and the account removals queue a close of the
424
+ target account's connections (`queue_connection_close`), after the commit
425
+ and independent of the audit row; failure outcomes queue none.
778
426
 
779
427
  ### Role-grant-offer actions
780
428
 
781
429
  `create_role_grant_offer_actions(deps, options?)` in
782
- `auth/role_grant_offer_actions.ts`.
783
-
784
- > **Hazard — admin `role_grant_offer_create` does not auto-accept.** The
785
- > action returns `{offer}` only. Acceptance is a separate
786
- > `role_grant_offer_accept` call; admin-side tests that materialize a
787
- > role_grant drive the full offer + accept RPCs (see
788
- > `testing/admin_integration.ts` §`offer_and_accept`), or skip the consent
789
- > path entirely via `create_test_role_grant_direct` from
790
- > `testing/db_entities.ts` when the test focuses on revoke / isolation
791
- > rather than the grant path itself. The v0.31 CHANGELOG entry was the
792
- > first signal of this two-step flow; consumers reading the standard admin
793
- > suite assume auto-accept and have to redesign their tests when they
794
- > discover otherwise.
795
-
796
- The specs' inputs and outputs are `@fuzdev/fuz_schema` schemas
797
- (`auth/role_grant_offer_action_specs.ts`), every object refusing unknown keys,
798
- `role` a `RoleName`, `scope_kind` a `ScopeKindName`.
799
- The create and assign inputs end in a `check` of `is_grant_scope_paired`
800
- (`GRANT_SCOPE_PAIRED_MESSAGE`), run only on an input whose fields all passed;
801
- the list and history inputs read an omitted input as a fresh `{}`
802
- (`with_default_fn`); history's `offset` is held to `Number.MAX_SAFE_INTEGER`.
803
-
804
- - `role_grant_offer_create_action_spec` — session-only; input `{to_account_id, to_actor_id?, role, scope_kind?, scope_id?, message?}` (`scope_kind` a `ScopeKindName`; `scope_kind` + `scope_id` paired — both or neither, else `invalid_params`); output `{offer}`. The create query itself (`query_role_grant_offer_create`) refuses a recipient that is not an active account — deleted or missing alike, answered as `role_grant_assign` answers them: 404 `not_found` (message `account not found`, no `data.reason`), or 400 `role_grant_offer_actor_account_mismatch` when an actor is named — after the self-target check and after the handler's authority gates, and a grantor that is no longer active (deleted mid-request: the dead-credential 401, no audit row). It takes `FOR SHARE` on both accounts first, so a delete of either party in flight is ordered against it.
805
- - `role_grant_offer_accept_action_spec` — session-only; input `{offer_id}`; output `{role_grant_id, offer, superseded_offer_ids}`. Refuses a builtin-role offer that must not mint (see below), leaving it pending.
806
- - `role_grant_offer_decline_action_spec` — input `{offer_id, reason?}`; output `{offer}` (the declined offer, as accept answers its own).
807
- - `role_grant_offer_retract_action_spec` — input `{offer_id}`; output `{offer}` (the retracted offer).
808
- - `role_grant_offer_list_action_spec` — input `{account_id?}`; output `{offers}`.
809
- - `role_grant_offer_history_action_spec` — input `{account_id?, limit?, offset?}`; output `{offers}`.
810
- - `role_grant_revoke_action_spec` — input `{actor_id, role_grant_id, reason?}`; output `{ok, revoked}`.
811
- A global `admin` grant is guarded: the keeper account's is refused
812
- (`ERROR_CANNOT_REVOKE_KEEPER_ADMIN`, 403) and so is one whose revoke would
813
- leave no active admin account (`ERROR_CANNOT_REVOKE_LAST_ADMIN`, 403, under
814
- the locked count `query_count_active_accounts_with_global_role_locked`,
815
- which leaves the revoked grant out — §Row locks). Besides the revokee's
816
- incoming sibling offers, the revoke supersedes every pending offer the
817
- revokee's actor made (`query_role_grant_offer_supersede_outgoing`);
818
- `account_delete` / `account_purge` supersede both directions for the whole
819
- account (`reason: 'account_deleted'`). Every supersede cascade returns —
820
- and audits and notifies — its rows ordered by `created_at, id`; who is
821
- told: §WS notifications.
822
- - `role_grant_assign_action_spec` — global-admin-only immediate conferral (no
823
- consent step); input `{to_account_id, to_actor_id?, role, scope_kind?, scope_id?}`
824
- (the pair as on offer-create); output `{ok, role_grant_id}`. The handler:
825
- - re-checks the global admin grant behind the dispatcher gate;
826
- - runs the same admin-grant-path gate as offer-create, and refuses a scoped
827
- `admin` (`invalid_params` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`; a scoped
828
- `keeper` stays 403 `ERROR_ROLE_NOT_WEB_GRANTABLE`, since `keeper` is never
829
- web-grantable);
830
- - runs the consumer's `RoleGrantOfferCreateAuthorize` callback (the offer
831
- policy binds the consent-free path too — a refusal is 403
832
- `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`, failure-audited);
833
- - resolves the target actor (named `to_actor_id` ∈ the account's active
834
- actors, else its sole active actor — multi-actor → `invalid_params`,
835
- actorless → 404);
836
- - writes the `(scope_kind, scope_id)` pair via the idempotent
837
- `query_create_role_grant`, and emits a `role_grant_create` audit row
838
- (metadata carries `scope_kind`, success and failure).
839
-
840
- No WS notification in v1. Reasons: `ERROR_INSUFFICIENT_PERMISSIONS`,
841
- `ERROR_ROLE_NOT_WEB_GRANTABLE`, `ERROR_ROLE_GRANT_BUILTIN_SCOPED`,
842
- `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`,
843
- `ERROR_ROLE_GRANT_OFFER_ACTOR_ACCOUNT_MISMATCH`.
844
-
845
- Every input carries `acting?: ActingActor` (registry-time invariant 2).
846
- `role_grant_revoke` keys on **`actor_id`**, not `account_id` — role_grants
847
- are actor-scoped and deriving actor from account collapses under multi-actor
848
- accounts.
849
-
850
- `role_grant_offer_create` runs the **admin-grantability gate first** (offered
851
- role's `RoleSpec.grant_paths` must include `'admin'`), then the
852
- `RoleGrantOfferCreateAuthorize` callback. **Default `default_authorize`: the
853
- caller must hold a _global_ `admin` grant** — conferral is admin-only, with no
854
- holder-propagation (holding the offered role confers no power to offer it). The
855
- global check (`has_scoped_role(_, ROLE_ADMIN, null)`) stops a scoped `admin`
856
- escalating into global authority over the offer surface. A consumer needing
857
- scope-aware delegation (e.g. a classroom teacher offering within their own
858
- scope) supplies a custom `authorize` callback. The callback receives
859
- `{to_account_id, role, scope_kind, scope_id}` and the request `ctx` (`ctx.db` is
860
- the request transaction, for read-only checks), and also gates
861
- `role_grant_assign`.
862
-
863
- **Builtin roles (`admin` / `keeper`) are global-only**, decided by the spine
864
- ahead of any callback. Offer-create refuses a scoped `admin`
865
- (`invalid_params` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`; `keeper`, scoped or not,
866
- stays 403 `ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE` at the grant-path gate)
867
- and a builtin offered by
868
- a caller without a global `admin` (`ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`), so
869
- a consumer callback only ever sees app roles or a global admin's unscoped
870
- builtin offer. Accept (`query_accept_offer`, the chokepoint where an offer
871
- becomes a grant) refuses a `keeper` offer (`ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE`),
872
- a scoped `admin` offer (`invalid_request` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`), and a
873
- builtin offer whose grantor no longer holds an active global `admin` on an
874
- active actor of an active account (`ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`,
875
- read under the grantor's account lock) — via
876
- `RoleGrantOfferBuiltinRefusedError` (`refusal: BuiltinOfferRefusal`). Each
877
- refusal leaves the offer pending and is audited as a failed
878
- `role_grant_offer_accept` with `{offer_id, role, scope_id, reason}`. The
879
- grantor re-check is builtin-only: an app-role offer's authority was the
880
- callback's call at create time.
881
-
882
- Error reasons (`as const` literals):
883
-
884
- - `ERROR_ROLE_GRANT_OFFER_SELF_TARGET`
885
- - `ERROR_ROLE_GRANT_OFFER_TERMINAL`
886
- - `ERROR_ROLE_GRANT_OFFER_EXPIRED`
887
- - `ERROR_ROLE_GRANT_OFFER_NOT_FOUND` (404-over-403 IDOR mask)
888
- - `ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE`
889
- - `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`
890
- - `ERROR_ROLE_GRANT_OFFER_ACTOR_ACCOUNT_MISMATCH` (supplied `to_actor_id` doesn't belong to `to_account_id`)
891
- - `ERROR_ROLE_GRANT_OFFER_ACTOR_MISMATCH` (actor-targeted offer accepted by wrong actor)
892
- - `ERROR_ROLE_GRANT_BUILTIN_SCOPED` (a grant path asked to bind `admin` / `keeper` to a scope)
893
-
894
- Plus re-uses from `http/error_schemas.ts`: `ERROR_ROLE_GRANT_NOT_FOUND`,
895
- `ERROR_ROLE_NOT_WEB_GRANTABLE`, `ERROR_INSUFFICIENT_PERMISSIONS`,
896
- `ERROR_ACCOUNT_NOT_FOUND`. Each spec declares the reason codes its handler
897
- may surface via `spec.error_reasons`; drift is caught per-module by
898
- ../../test/auth/role_grant_offer_actions.error_reasons.test.ts.
899
-
900
- Failure-outcome audits use `emit_create_failure_audit` /
901
- `emit_revoke_failure_audit` so all denial paths land uniform rows; the
902
- admin-role-denied path (pre-IDOR) on `role_grant_revoke` emits no audit,
903
- matching the middleware auth-guard precedent.
430
+ `auth/role_grant_offer_actions.ts`; the authorization rules per action are
431
+ its module TSDoc, the threat model ../../../docs/security.md §Authorization
432
+ (builtin roles global-only, consentful grants, the supersede cascade).
433
+
434
+ > **Hazard — `role_grant_offer_create` does not auto-accept**, admin or not.
435
+ > It returns `{offer}`; acceptance is a separate `role_grant_offer_accept`.
436
+ > A test that needs a grant drives offer + accept (`testing/admin_integration.ts`
437
+ > `offer_and_accept`) or skips the consent path with
438
+ > `create_test_role_grant_direct` (`testing/db_entities.ts`).
439
+
440
+ - **Default `authorize`: the caller holds a _global_ `admin` grant.** No
441
+ holder-propagation — holding a role confers no power to offer it. A
442
+ consumer needing scope-aware delegation (a teacher offering within their
443
+ classroom) supplies `authorize` (`RoleGrantOfferCreateAuthorize`), which
444
+ also gates `role_grant_assign`. It runs after the admin-grant-path gate and
445
+ only ever sees app roles or a global admin's unscoped builtin offer — the
446
+ builtin rules are decided first.
447
+ - **`role_grant_revoke` keys on `actor_id`**, not `account_id`: grants are
448
+ actor-scoped, and deriving the actor collapses under multi-actor accounts.
449
+ A revoke supersedes the revokee's incoming siblings and every offer its
450
+ actor made (`query_revoke_role_grant`, shared with the self-service
451
+ disable). A global grant's revoke queues a role-gated close of the
452
+ revokee's connections; a scoped revoke closes nothing, since a role gate
453
+ admits on global grants alone.
454
+ - **`role_grant_assign`** is the global-admin-only consent-free path; it
455
+ sends no WS notification.
456
+ - **Denials are audited uniformly** as failure rows; the admin-role denial on
457
+ `role_grant_revoke` (pre-IDOR) writes none, as an auth-guard refusal
458
+ doesn't. Supersede rows go through `emit_supersede_audits`, shared by both
459
+ revokes and account removal, as in the Rust twin.
460
+ - `error_reasons` drift is pinned per module by
461
+ ../../test/auth/role_grant_offer_actions.error_reasons.test.ts.
904
462
 
905
463
  #### WS notifications
906
464
 
907
- Post-commit via `emit_after_commit` (see `http/CLAUDE.md` §Pending Effects):
465
+ Post-commit via `emit_after_commit` (`http/CLAUDE.md` §Pending Effects),
466
+ through `ctx.notification_sender` (`actions/CLAUDE.md` §Notification
467
+ sender):
908
468
 
909
469
  - Create — `role_grant_offer_received` → recipient.
910
470
  - Retract — `role_grant_offer_retracted` → recipient.
@@ -912,240 +472,86 @@ Post-commit via `emit_after_commit` (see `http/CLAUDE.md` §Pending Effects):
912
472
  - Decline — `role_grant_offer_declined` → grantor.
913
473
  - Revoke (`role_grant_revoke`) — `role_grant_revoked` → revokee + `_supersede` per superseded offer (the revokee's incoming siblings and its own outgoing offers), each to its grantor and its recipient.
914
474
  - Delete / purge (`account_delete`, `account_purge`) — `_supersede` (`account_deleted`) per superseded offer to the live party: the recipient of each offer the account made, the grantor of each offer made to it. The removed account hears nothing (its sockets close).
915
- - Self-service disable — `_supersede` per incoming sibling, to its grantor and to the caller (its answer lists no offers).
916
-
917
- `queue_supersede_notifications(ctx, offers, reason, audience)` sends them in
918
- the cascade's row order, grantor before recipient; the `SupersedeAudience`
919
- names the `cause_id` each told party gets (a recipient told of its grantor's
920
- removal gets the grantor's actor, never its account id — TSDoc on
921
- `SupersedeAudience`).
922
-
923
- Spec module is `auth/role_grant_offer_notifications.ts` —
924
- `RemoteNotificationActionSpec`s with `@fuzdev/fuz_schema` params schemas and
925
- notification builders. `role_grant_revoked`'s params are
926
- `{role_grant_id, role, scope_kind, scope_id, reason}`, the grant's
927
- `scope_kind` and `scope_id` both `null` for a global grant, every key
928
- required. `role_grant_offer_notification_actions` holds the specs as
929
- handler-less actions: `to_ws_actions` (`actions/protocol.ts`) appends them to
930
- the WS action set of an RPC list holding `role_grant_offer_create`, so the WS
931
- endpoint's surface lists them as `remote_notification` methods. The revokee's
932
- notification is `role_grant_revoked`, not the admin action's
933
- `role_grant_revoke`, so the two methods never collide. They never reach
934
- dispatch: an inbound frame for one is answered `method_not_found`. They are not SSE events; `role_grant_offer_notification_specs`
935
- holds them as `EventSpec`s for a consumer that broadcasts them on an SSE
936
- channel of its own. Handlers send through `ctx.notification_sender`
937
- (`actions/CLAUDE.md` §Notification sender) with `queue_offer_notification` /
938
- `queue_supersede_notifications`, each queued post-commit.
939
-
940
- Deps: `RevokingActionFactoryDeps`.
941
- `role_grant_revoke` of a global grant queues a close of the revokee account's
942
- connections gated on the role (`queue_connection_close`, `{kind: 'role'}`),
943
- run after the transaction commits and independent of the audit row's
944
- announcement; the revocation guard repeats it on the announced row. A scoped revoke
945
- closes nothing — a role gate admits on global grants alone.
946
- Target account travels via the send argument, not the payload — `revoked_by`
947
- is deliberately not in the `role_grant_revoked` payload (the revokee doesn't
948
- need to learn the admin's identity).
949
-
950
- Options: `roles?: RoleRegistry` (drives admin-grant-path lookup),
951
- `default_ttl_ms?` (defaults to `ROLE_GRANT_OFFER_DEFAULT_TTL_MS` = 30 days),
952
- `authorize?: RoleGrantOfferCreateAuthorize`.
475
+ - Self-service disable — `_supersede` per superseded offer, each to its grantor and its recipient, as the admin revoke (the caller's answer lists no offers).
476
+
477
+ `queue_supersede_notifications` sends in the cascade's row order
478
+ (`created_at, id`), grantor before recipient; `SupersedeAudience` names the
479
+ `cause_id` each party gets (a recipient never learns its grantor's account
480
+ id). The specs are `auth/role_grant_offer_notifications.ts`'s handler-less
481
+ `remote_notification` actions: `to_ws_actions` lists them on a WS endpoint
482
+ holding `role_grant_offer_create`, and an inbound frame for one is
483
+ `method_not_found`. The revokee's method is `role_grant_revoked`, never the
484
+ admin action's `role_grant_revoke`, and its payload omits who revoked.
485
+ `role_grant_offer_notification_specs` holds them as `EventSpec`s for a
486
+ consumer broadcasting them over SSE of its own.
953
487
 
954
488
  ### Account actions — self-service
955
489
 
956
- `create_account_actions(deps, options?)` in `auth/account_actions.ts`.
957
-
958
- - `account_verify_action_spec` — read; input fuz_schema's `void`; output `SessionAccountJson`.
959
- - `account_session_list_action_spec` — read; input fuz_schema's `void`; output `{sessions}`, each with `is_current` (the session the request authenticated with; `false` on every row for a bearer or daemon-token caller).
960
- - `account_session_revoke_action_spec` — mutation; input `{session_id}`; output `{ok, revoked}`.
961
- - `account_session_revoke_all_action_spec` — mutation; input fuz_schema's `void`; output `{ok, count}`, `count` a non-negative integer.
962
- - `account_token_create_action_spec` — mutation; input `{name?, scope, lifetime}` (both `scope` and `lifetime` required — default-deny at mint on both axes; `name` at most `API_TOKEN_NAME_LENGTH_MAX` = 255 characters, since it is copied into the audit row); output `{ok, token, id, name, expires_at}`, `expires_at` a `Timestamp` or `null`. `scope` / `lifetime` declare `invalid_reason` `ERROR_TOKEN_SCOPE_INVALID` / `ERROR_TOKEN_LIFETIME_INVALID`, so every refusal of either carries it — the handler's over-cap scope refusal included.
963
- - `account_token_list_action_spec` — read; input fuz_schema's `void`; output `{tokens}`, each a `ClientApiTokenJson`.
964
- - `account_token_revoke_action_spec` — mutation; input `{token_id}`; output `{ok, revoked}`.
965
-
966
- `account_verify` is the credential probe on both spines: it returns
967
- `SessionAccountJson`, and a narrowed token that names it may call it.
968
- `GET /status` answers a narrowed token as the anonymous caller. There is no
969
- REST probe (an nginx `auth_request` gate would need one mounted on both
970
- spines).
971
-
972
- `session_id` validates as `SessionId`, the fuz_schema `Blake3Hash` branded;
973
- `token_id` as `ApiTokenId` (`tok_[A-Za-z0-9_-]{12}`). Every input and output
974
- is a `@fuzdev/fuz_schema` schema.
975
-
976
- Audit events via `deps.audit.emit` with `ip: ctx.client_ip`:
977
- `session_revoke`, `session_revoke_all`, `token_create`, `token_revoke`. Every
978
- gated event also records `credential_type` in metadata (mirrors REST
979
- `password_change`).
980
-
981
- Options: `max_tokens?: number | null` (defaults to `DEFAULT_MAX_TOKENS`;
982
- `null` disables). Deps: `RevokingActionFactoryDeps` — `log`, `audit`, and the
983
- required `connection_closer`. Each revoking handler queues its close
984
- (`queue_connection_close`: one session, one token, or the account), which runs
985
- after the handler's transaction commits and is dropped if it throws;
986
- `account_token_create` queues a token close for each token its cap evicts.
987
- Failure outcomes (`revoked: false`) queue no close — mirrors the listeners'
988
- `outcome === 'success'` guard so attacker-guessable ids can't target
989
- arbitrary connections.
490
+ `create_account_actions(deps, options?)` in `auth/account_actions.ts`
491
+ (session and token list / revoke / revoke-all, token create, and
492
+ `account_verify`).
493
+
494
+ - **`account_verify` is the credential probe** on both spines, callable by a
495
+ narrowed token that names it. There is no REST probe; `GET /status`
496
+ answers a narrowed token as anonymous.
497
+ - **`account_token_create` is default-deny at mint**: `scope` and `lifetime`
498
+ are both required. The token cap (`max_tokens`, `DEFAULT_MAX_TOKENS`,
499
+ `null` disables) evicts the oldest, closing each evicted token's
500
+ connections.
501
+ - **Each revoking handler queues its close** (one session, one token, or the
502
+ account) after the commit. A failure outcome (`revoked: false`) queues
503
+ none, so an attacker-guessable id can't target another user's
504
+ connections — the same reason the revocation guard acts only on success
505
+ rows.
990
506
 
991
507
  ### Standard RPC bundle
992
508
 
993
- `create_standard_rpc_actions(deps, options)` in `auth/standard_rpc_actions.ts`
994
- spreads `create_admin_actions`, `create_role_grant_offer_actions`, and
995
- `create_account_actions` into a single `Array<RpcAction>` — the canonical
996
- fuz_app "standard" surface (admin + role-grant-offer + account; the two
997
- app-settings methods are always wired). Frontend mirror is
998
- `all_standard_action_specs` in `auth/standard_action_specs.ts`.
999
-
1000
- Option routing — `roles` is shared between admin + role-grant-offer;
1001
- `default_ttl_ms` + `authorize` → role-grant-offer
1002
- only; `max_tokens` → account only. On `deps`: `connection_closer`
1003
- (required) → admin, account, and role-grant-offer (the role revoke's close).
1004
- The notification sender is on every action's context, not on `deps`.
1005
-
1006
- Pair with `create_app_server`'s `rpc_endpoints` factory form
1007
- `(ctx) => Array<RpcEndpointSpec>` so the combined action list gets
1008
- `ctx.deps`. `create_app_server` auto-mounts the
1009
- endpoint via `create_rpc_endpoint`. To expose the standard surface over
1010
- WebSocket as well, spread `protocol_actions` and the same factory into
1011
- `ws_endpoints` — per-message authorization and rate limiting fire
1012
- identically across HTTP RPC and WS.
1013
-
1014
- Bundling account actions into the "standard" surface is deliberate: the
1015
- admin integration suite exercises `account_token_create` / `_revoke` for
1016
- cross-account isolation, so a consumer wiring the admin surface without
1017
- account actions hits `method_not_found` on first admin-suite run.
509
+ `create_standard_rpc_actions(deps, options)` (`auth/standard_rpc_actions.ts`)
510
+ spreads the admin, role-grant-offer and account factories into one
511
+ `Array<RpcAction>`; the frontend mirror is `all_standard_action_specs`
512
+ (`auth/standard_action_specs.ts`). Option routing: `roles` → admin and
513
+ role-grant-offer; `default_ttl_ms` and `authorize` → role-grant-offer;
514
+ `max_tokens` → account. `deps.connection_closer` reaches all three.
1018
515
 
1019
- ### Self-service role toggle
516
+ Mount it through `create_app_server`'s `rpc_endpoints` factory form
517
+ `(ctx) => Array<RpcEndpointSpec>` so the handlers get `ctx.deps`; over
518
+ WebSocket, the same list goes in `ws_endpoints` (root ../../../CLAUDE.md
519
+ §Action Registries).
1020
520
 
1021
- `create_self_service_role_actions(deps, {eligible_roles?, roles?})` in
1022
- `auth/self_service_role_actions.ts`. One static action
1023
- `self_service_role_set({role, enabled})` toggles a global role_grant on the
1024
- caller. Idempotent in both directions (`changed: false` when the post-call
1025
- state already matched). Its input and output are `@fuzdev/fuz_schema`
1026
- `object`s, refusing unknown keys, `role` a `RoleName`.
1027
-
1028
- Audit metadata carries `self_service: true` so admin reviewers can
1029
- distinguish self-toggled role_grants. Eligibility derives from
1030
- `roles.role_specs` by selecting roles with `'self_service' ∈ grant_paths`;
1031
- override via `eligible_roles`. Roles outside the eligible set are rejected
1032
- with `ERROR_ROLE_NOT_SELF_SERVICE_ELIGIBLE`. The eligible set is validated at
1033
- construction (`validate_self_service_eligible_roles`): a builtin role or a name
1034
- outside the `RoleName` grammar throws — self-toggling a builtin would hand any
1035
- account instance-wide authority.
1036
-
1037
- Deps are `RevokingActionFactoryDeps`: a disable that revokes queues a close of
1038
- the caller's connections gated on the role (`queue_connection_close`,
1039
- `{kind: 'role'}`), after the commit and independent of the audit write.
1040
-
1041
- Method name is static (`role` lives in input, not method) — per-role
1042
- parameterized methods would break the `satisfies RequestResponseActionSpec`
1043
- codegen invariant.
1044
-
1045
- Bundle **not** included in `create_standard_rpc_actions` — `eligible_roles`
1046
- is app-specific.
521
+ Bundling the account actions is deliberate: the admin integration suite
522
+ exercises `account_token_create` / `_revoke` for cross-account isolation, so
523
+ a consumer mounting admin without account hits `method_not_found`.
1047
524
 
1048
- ### Actor lookup / actor search
1049
-
1050
- Two opt-in helpers for surfaces that stamp actor ids (bylines, owner
1051
- columns, grantor labels, picker UIs):
1052
-
1053
- - `create_actor_lookup_actions(deps)` — `actor_lookup({ids}) → {actors}`,
1054
- batched id → label resolver. `ACTOR_LOOKUP_IDS_MAX = 50`.
1055
- - `create_actor_search_actions(deps)` — `actor_search({query, scope_ids?, limit?}) → {actors}`,
1056
- prefix search. Default limit `ACTOR_SEARCH_LIMIT_DEFAULT = 20`, cap
1057
- `_MAX = 50`. Non-admin callers must pass `scope_ids` (filtered to actors
1058
- holding active role_grants on those scopes); admin-only when `scope_ids`
1059
- is empty. `ERROR_ACTOR_SEARCH_SCOPE_REQUIRED` on non-admin + empty
1060
- `scope_ids`.
1061
-
1062
- Both: `auth: {account: 'required', actor: 'none'}` + `rate_limit: 'account'`,
1063
- pure reads (no audit, no side effects), their input and output schemas
1064
- `@fuzdev/fuz_schema` `object`s, which refuse unknown keys. `ActorLookupEntryJson` deliberately
1065
- omits `account_id`, `email`, credentials, timestamps, and role state —
1066
- control-plane details, timing-oracle avoidance, separation of concern. LIKE
1067
- wildcards in the user-supplied query are escaped at the JS layer so
1068
- `%xyz`-style inputs can't widen the per-call cap.
525
+ ### Self-service role toggle
1069
526
 
1070
- Bundle **not** included in `create_standard_rpc_actions`.
527
+ `create_self_service_role_actions(deps, {eligible_roles?, roles?})` —
528
+ `self_service_role_set({role, enabled})`, idempotent both ways, audited with
529
+ `self_service: true`. Eligibility defaults to roles with the `self_service`
530
+ grant path; a builtin or off-grammar name in `eligible_roles` throws at
531
+ construction, since self-toggling a builtin would hand any account
532
+ instance-wide authority. A disable revokes through `query_revoke_role_grant`,
533
+ so it supersedes what the admin revoke does and queues the same role-gated
534
+ close. The method is static (`role` is input) so codegen's
535
+ `satisfies RequestResponseActionSpec` holds.
1071
536
 
1072
- ### `admin_rpc_adapters.ts` (in `ui/`)
537
+ ### Actor lookup / actor search
1073
538
 
1074
- `create_admin_rpc_adapters(api)` + `provide_admin_rpc_contexts(adapters)` —
1075
- single-call wiring for the four admin RPC contexts (`admin_accounts`,
1076
- `admin_invites`, `audit_log`, `app_settings`). One line at the admin shell
1077
- drops the hand-maintained method-name mappings:
1078
- `provide_admin_rpc_contexts(create_admin_rpc_adapters(api))`.
539
+ Two opt-in, account-grain, rate-limited pure reads for surfaces that stamp
540
+ actor ids (bylines, grantor labels, pickers): `create_actor_lookup_actions`
541
+ (`actor_lookup({ids})`, batched) and `create_actor_search_actions`
542
+ (`actor_search({query, scope_ids?, limit?})`, prefix). A non-admin search
543
+ must pass `scope_ids` (`ERROR_ACTOR_SEARCH_SCOPE_REQUIRED`). The entry shape
544
+ deliberately omits `account_id`, email, credentials, timestamps and role
545
+ state, and LIKE wildcards in the query are escaped so `%`-inputs can't widen
546
+ a call. Caps and limits are on the spec modules.
1079
547
 
1080
548
  ## Cleanup
1081
549
 
1082
- `auth/cleanup.ts` — twin of the Rust `fuz_auth::auth_cleanup` module.
1083
-
1084
- - `run_auth_cleanup(deps)` — one pass: `cleanup_expired_sessions`, then
1085
- `cleanup_expired_role_grant_offers`; returns `AuthCleanupResult`
1086
- (`{expired_sessions, expired_offers}`, the same shape on both spines).
1087
- Re-throws the first sweep's error. Expired offer rows are preserved (audit
1088
- value for the history view).
1089
- - `start_auth_cleanup(deps, {interval_ms?})` → `{stop}` — the scheduler: a
1090
- pass at once, then one per interval (`DEFAULT_AUTH_CLEANUP_INTERVAL_MS`, ten
1091
- minutes), until `stop()`. `create_app_server`'s `auth_cleanup` option calls
1092
- it with `backend.deps` and chains `stop` into `AppServer.close`. **Off by
1093
- default** there; a production server turns it on, and an in-process test
1094
- harness leaves it off (a background pass deletes rows and writes audit rows
1095
- mid-test).
1096
-
1097
- `AuthCleanupDeps` is `{db, log, audit, connection_closer}`, all required —
1098
- `AppDeps` satisfies it. Tests pass `create_test_audit_emitter()` from
1099
- `testing/stubs.ts` and, where nothing is to be closed, `noop_connection_closer`.
1100
- The sweep belongs in the process that holds the connections: run from another
1101
- process against a live server's database, it deletes the rows that server's
1102
- own pass would have closed for.
1103
-
1104
- **The session sweep closes what it sweeps.** A connection never re-reads its
1105
- session, and once the sweep deletes an expired row `account_session_revoke`
1106
- has nothing left to close for — so `cleanup_expired_sessions` closes each
1107
- swept session's connections itself, by session id
1108
- (`connection_closer.close_connections` with a `session` target), which is why
1109
- `query_session_cleanup_expired` returns the deleted ids. The close repeats
1110
- one already made: every connection closes at its credential's deadline
1111
- (`auth/credential_deadline.ts`) in the process holding it, sweep or no sweep.
1112
- An expired API token's row is not swept; its connections close at their
1113
- deadline (`account_token_revoke` still finds the row).
1114
-
1115
- - The delete runs in its own transaction and the closes follow the commit —
1116
- the rule every revocation close keeps (`actions/CLAUDE.md` §Connection
1117
- closer).
1118
- - A transaction that fails once the delete has answered still closes: the
1119
- sessions are expired either way, the error is thrown after the closes, and
1120
- the next pass deletes the rows the commit left.
1121
- - A closer that throws for one session is logged and the rest still close.
1122
- - No audit row is written for a swept session, so no listener repeats the
1123
- close.
1124
-
1125
- **The schedule** is `start_periodic` (`periodic.ts`, twin of the Rust
1126
- `fuz_sys::periodic::spawn_periodic`), which owns the loop's rules:
1127
- `start_auth_cleanup` is that loop over `run_auth_cleanup` plus the swept-counts
1128
- log. Passes never overlap, and a pass that overruns its interval delays the
1129
- next one (which starts when the slow one ends, the one after a full interval
1130
- later) rather than bursting. A failed pass is logged at `warn` with its error
1131
- and retried on the next interval. The timer is unref'd. An interval that is
1132
- not a positive finite number, or exceeds `PERIODIC_INTERVAL_MS_MAX` (the
1133
- largest delay a timer honors), throws at the call. **Shutdown differs from
1134
- Rust**: its task drops a pass in progress; `stop()` ends the schedule at once
1135
- and its promise resolves when the pass in progress has finished — await it
1136
- before closing the database. The wait has no bound of its own.
1137
-
1138
- **Offer idempotency.** `cleanup_expired_role_grant_offers` runs one transaction:
1139
- `query_role_grant_offer_sweep_expired` claims the expired pending offers not
1140
- yet audited by stamping `role_grant_offer.expire_audited_at` (`UPDATE …
1141
- RETURNING`), and each claimed row's `role_grant_offer_expire` audit row is
1142
- inserted in the same transaction; events fan out via `audit.notify` after the
1143
- commit. Each expiry is audited exactly once — a second run finds nothing, and
1144
- concurrent runs claim disjoint rows (a row another sweep holds blocks on its
1145
- row lock, then fails the re-checked stamp). A failed audit insert rolls the
1146
- stamps back and the next run retries, so the offer sweep can throw. The stamp
1147
- is not a lifecycle state (outside the terminal CHECK and the pending
1148
- predicate) and stays off the wire (`to_role_grant_offer_json` drops it); the
1149
- create upsert's re-offer clears it, so a refreshed offer's own expiry is
1150
- audited too. The `role_grant_offer_expire_sweep` partial index serves the
1151
- claim.
550
+ `auth/cleanup.ts`, twin of the Rust `fuz_auth::auth_cleanup`:
551
+ `run_auth_cleanup` (one pass — the session sweep, which closes the swept
552
+ sessions' connections, then the offer-expiry sweep, audited exactly once)
553
+ and `start_auth_cleanup` (scheduled on `start_periodic`, `periodic.ts`). Off
554
+ by default in `create_app_server`; run it in the process that holds the
555
+ connections, never from another process against a live server's database.
556
+ The rules are the module TSDoc and `periodic.ts`'s (whose `stop()` differs
557
+ from the Rust shutdown); wiring is ../../../docs/usage.md §Auth cleanup.