@fuzdev/fuz_app 0.183.0 → 0.185.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/dist/actions/CLAUDE.md +538 -1223
  2. package/dist/actions/action_codegen.d.ts +1 -1
  3. package/dist/actions/action_codegen.d.ts.map +1 -1
  4. package/dist/actions/action_codegen.js +3 -2
  5. package/dist/actions/connection_closer.d.ts +11 -9
  6. package/dist/actions/connection_closer.d.ts.map +1 -1
  7. package/dist/actions/connection_closer.js +11 -9
  8. package/dist/actions/frontend_rpc_client.d.ts +1 -1
  9. package/dist/actions/register_action_ws.d.ts +21 -1
  10. package/dist/actions/register_action_ws.d.ts.map +1 -1
  11. package/dist/actions/register_action_ws.js +2 -1
  12. package/dist/actions/ws_socket_session.d.ts +25 -4
  13. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  14. package/dist/actions/ws_socket_session.js +81 -25
  15. package/dist/auth/CLAUDE.md +433 -1048
  16. package/dist/auth/account_queries.d.ts +1 -1
  17. package/dist/auth/account_queries.js +1 -1
  18. package/dist/auth/account_routes.d.ts +4 -5
  19. package/dist/auth/account_routes.d.ts.map +1 -1
  20. package/dist/auth/account_routes.js +8 -10
  21. package/dist/auth/admin_actions.d.ts.map +1 -1
  22. package/dist/auth/admin_actions.js +10 -11
  23. package/dist/auth/api_token.d.ts +20 -3
  24. package/dist/auth/api_token.d.ts.map +1 -1
  25. package/dist/auth/api_token.js +28 -9
  26. package/dist/auth/api_token_queries.d.ts +2 -2
  27. package/dist/auth/api_token_queries.js +2 -2
  28. package/dist/auth/audit_log_routes.d.ts +1 -1
  29. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  30. package/dist/auth/audit_log_routes.js +3 -2
  31. package/dist/auth/audit_log_schema.d.ts +15 -9
  32. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  33. package/dist/auth/audit_log_schema.js +1 -2
  34. package/dist/auth/auth_guard_resolver.d.ts +1 -1
  35. package/dist/auth/auth_guard_resolver.js +1 -1
  36. package/dist/auth/bearer_auth.d.ts +2 -5
  37. package/dist/auth/bearer_auth.d.ts.map +1 -1
  38. package/dist/auth/bearer_auth.js +4 -13
  39. package/dist/auth/bootstrap_account.d.ts +13 -15
  40. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  41. package/dist/auth/bootstrap_account.js +9 -11
  42. package/dist/auth/bootstrap_routes.d.ts +20 -21
  43. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  44. package/dist/auth/bootstrap_routes.js +21 -19
  45. package/dist/auth/bootstrap_token_store.d.ts +3 -4
  46. package/dist/auth/bootstrap_token_store.d.ts.map +1 -1
  47. package/dist/auth/bootstrap_token_store.js +1 -1
  48. package/dist/auth/cleanup.d.ts +34 -3
  49. package/dist/auth/cleanup.d.ts.map +1 -1
  50. package/dist/auth/cleanup.js +11 -3
  51. package/dist/auth/daemon_token.d.ts +5 -1
  52. package/dist/auth/daemon_token.d.ts.map +1 -1
  53. package/dist/auth/daemon_token_middleware.d.ts +12 -8
  54. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  55. package/dist/auth/daemon_token_middleware.js +15 -21
  56. package/dist/auth/deps.d.ts +11 -0
  57. package/dist/auth/deps.d.ts.map +1 -1
  58. package/dist/auth/invite_queries.d.ts +51 -3
  59. package/dist/auth/invite_queries.d.ts.map +1 -1
  60. package/dist/auth/invite_queries.js +81 -6
  61. package/dist/auth/invite_schema.d.ts +2 -1
  62. package/dist/auth/invite_schema.d.ts.map +1 -1
  63. package/dist/auth/middleware.d.ts +2 -3
  64. package/dist/auth/middleware.d.ts.map +1 -1
  65. package/dist/auth/middleware.js +3 -3
  66. package/dist/auth/request_context.d.ts +3 -3
  67. package/dist/auth/request_context.js +3 -3
  68. package/dist/auth/role_grant_offer_actions.d.ts +2 -2
  69. package/dist/auth/role_grant_offer_actions.js +2 -2
  70. package/dist/auth/session_cookie.d.ts +82 -174
  71. package/dist/auth/session_cookie.d.ts.map +1 -1
  72. package/dist/auth/session_cookie.js +80 -130
  73. package/dist/auth/session_middleware.d.ts +8 -17
  74. package/dist/auth/session_middleware.d.ts.map +1 -1
  75. package/dist/auth/session_middleware.js +14 -23
  76. package/dist/auth/session_queries.d.ts +9 -14
  77. package/dist/auth/session_queries.d.ts.map +1 -1
  78. package/dist/auth/session_queries.js +8 -9
  79. package/dist/auth/signup_routes.d.ts.map +1 -1
  80. package/dist/auth/signup_routes.js +4 -6
  81. package/dist/db/CLAUDE.md +5 -3
  82. package/dist/dev/setup.d.ts +3 -1
  83. package/dist/dev/setup.d.ts.map +1 -1
  84. package/dist/dev/setup.js +3 -1
  85. package/dist/http/CLAUDE.md +315 -768
  86. package/dist/http/db_routes.d.ts +1 -1
  87. package/dist/http/db_routes.js +1 -1
  88. package/dist/http/origin.d.ts +7 -8
  89. package/dist/http/origin.d.ts.map +1 -1
  90. package/dist/http/origin.js +7 -8
  91. package/dist/http/pending_effects.d.ts +82 -4
  92. package/dist/http/pending_effects.d.ts.map +1 -1
  93. package/dist/http/pending_effects.js +82 -4
  94. package/dist/http/route_result.d.ts +1 -1
  95. package/dist/http/route_spec.d.ts +17 -14
  96. package/dist/http/route_spec.d.ts.map +1 -1
  97. package/dist/realtime/audit_log_sse.d.ts +1 -1
  98. package/dist/realtime/sse.d.ts +6 -25
  99. package/dist/realtime/sse.d.ts.map +1 -1
  100. package/dist/realtime/sse.js +4 -25
  101. package/dist/realtime/sse_constants.d.ts +1 -1
  102. package/dist/realtime/sse_constants.js +1 -1
  103. package/dist/server/app_backend.d.ts +4 -5
  104. package/dist/server/app_backend.d.ts.map +1 -1
  105. package/dist/server/app_backend.js +3 -1
  106. package/dist/server/app_server.d.ts +87 -76
  107. package/dist/server/app_server.d.ts.map +1 -1
  108. package/dist/server/app_server.js +111 -91
  109. package/dist/server/app_server_context.d.ts +1 -2
  110. package/dist/server/app_server_context.d.ts.map +1 -1
  111. package/dist/server/env.js +2 -2
  112. package/dist/server/shutdown_drain.d.ts +69 -0
  113. package/dist/server/shutdown_drain.d.ts.map +1 -0
  114. package/dist/server/shutdown_drain.js +77 -0
  115. package/dist/testing/CLAUDE.md +89 -57
  116. package/dist/testing/admin_integration.d.ts +4 -5
  117. package/dist/testing/admin_integration.d.ts.map +1 -1
  118. package/dist/testing/admin_integration.js +39 -23
  119. package/dist/testing/app_server.d.ts +3 -8
  120. package/dist/testing/app_server.d.ts.map +1 -1
  121. package/dist/testing/app_server.js +10 -9
  122. package/dist/testing/attack_surface.d.ts +1 -1
  123. package/dist/testing/attack_surface.d.ts.map +1 -1
  124. package/dist/testing/audit_completeness.d.ts +2 -3
  125. package/dist/testing/audit_completeness.d.ts.map +1 -1
  126. package/dist/testing/audit_completeness.js +1 -1
  127. package/dist/testing/cross_backend/bootstrap_backend.d.ts +3 -1
  128. package/dist/testing/cross_backend/bootstrap_backend.d.ts.map +1 -1
  129. package/dist/testing/cross_backend/bootstrap_backend.js +5 -1
  130. package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -1
  131. package/dist/testing/cross_backend/capability_mounts.js +16 -11
  132. package/dist/testing/cross_backend/conformance_table.d.ts +5 -6
  133. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/conformance_table.js +4 -4
  135. package/dist/testing/cross_backend/cookie_attributes.js +1 -1
  136. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts +10 -1
  137. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts.map +1 -1
  138. package/dist/testing/cross_backend/create_dual_spawn_global_setup.js +33 -7
  139. package/dist/testing/cross_backend/default_backend_configs.d.ts +3 -3
  140. package/dist/testing/cross_backend/default_spine_surface.d.ts +0 -6
  141. package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/default_spine_surface.js +4 -9
  143. package/dist/testing/cross_backend/differential.d.ts +2 -3
  144. package/dist/testing/cross_backend/differential.d.ts.map +1 -1
  145. package/dist/testing/cross_backend/differential.js +1 -1
  146. package/dist/testing/cross_backend/full_spine_mount.d.ts +1 -42
  147. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  148. package/dist/testing/cross_backend/full_spine_mount.js +45 -4
  149. package/dist/testing/cross_backend/in_process_setup.d.ts +7 -8
  150. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  151. package/dist/testing/cross_backend/in_process_setup.js +10 -13
  152. package/dist/testing/cross_backend/rpc_success_fixtures.d.ts.map +1 -1
  153. package/dist/testing/cross_backend/rpc_success_fixtures.js +2 -1
  154. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +3 -4
  155. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  156. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -2
  157. package/dist/testing/cross_backend/setup.d.ts +1 -1
  158. package/dist/testing/cross_backend/spawn_backend.d.ts +14 -0
  159. package/dist/testing/cross_backend/spawn_backend.d.ts.map +1 -1
  160. package/dist/testing/cross_backend/spawn_backend.js +56 -8
  161. package/dist/testing/cross_backend/spine_suites.d.ts +18 -16
  162. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  163. package/dist/testing/cross_backend/spine_suites.js +38 -18
  164. package/dist/testing/cross_backend/standard.d.ts +19 -84
  165. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  166. package/dist/testing/cross_backend/standard.js +8 -23
  167. package/dist/testing/cross_backend/standard_auth.d.ts +74 -0
  168. package/dist/testing/cross_backend/standard_auth.d.ts.map +1 -0
  169. package/dist/testing/cross_backend/standard_auth.js +28 -0
  170. package/dist/testing/cross_backend/standard_bundle.d.ts +48 -0
  171. package/dist/testing/cross_backend/standard_bundle.d.ts.map +1 -0
  172. package/dist/testing/cross_backend/standard_bundle.js +43 -0
  173. package/dist/testing/cross_backend/testing_credential_read.d.ts +10 -11
  174. package/dist/testing/cross_backend/testing_credential_read.d.ts.map +1 -1
  175. package/dist/testing/cross_backend/testing_credential_read.js +12 -12
  176. package/dist/testing/cross_backend/testing_reset_actions.d.ts +46 -30
  177. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  178. package/dist/testing/cross_backend/testing_reset_actions.js +52 -31
  179. package/dist/testing/cross_backend/testing_server_bun.d.ts.map +1 -1
  180. package/dist/testing/cross_backend/testing_server_bun.js +5 -4
  181. package/dist/testing/cross_backend/testing_server_core.d.ts +16 -3
  182. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  183. package/dist/testing/cross_backend/testing_server_core.js +22 -7
  184. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +6 -2
  185. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  186. package/dist/testing/cross_backend/ts_spine_backend_config.js +7 -3
  187. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  188. package/dist/testing/daemon_token_rotation.js +2 -3
  189. package/dist/testing/error_coverage.d.ts +5 -0
  190. package/dist/testing/error_coverage.d.ts.map +1 -1
  191. package/dist/testing/error_coverage.js +2 -1
  192. package/dist/testing/integration.d.ts +6 -23
  193. package/dist/testing/integration.d.ts.map +1 -1
  194. package/dist/testing/integration.js +53 -83
  195. package/dist/testing/integration_helpers.d.ts +16 -0
  196. package/dist/testing/integration_helpers.d.ts.map +1 -1
  197. package/dist/testing/integration_helpers.js +29 -1
  198. package/dist/testing/middleware_gate_probes.d.ts +55 -1
  199. package/dist/testing/middleware_gate_probes.d.ts.map +1 -1
  200. package/dist/testing/middleware_gate_probes.js +69 -3
  201. package/dist/testing/rate_limiting.d.ts +2 -3
  202. package/dist/testing/rate_limiting.d.ts.map +1 -1
  203. package/dist/testing/rate_limiting.js +3 -3
  204. package/dist/testing/rpc_helpers.d.ts +1 -2
  205. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  206. package/dist/testing/rpc_helpers.js +3 -3
  207. package/dist/testing/rpc_round_trip.d.ts +2 -3
  208. package/dist/testing/rpc_round_trip.d.ts.map +1 -1
  209. package/dist/testing/rpc_round_trip.js +1 -1
  210. package/dist/testing/sse_round_trip.d.ts +2 -3
  211. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  212. package/dist/testing/sse_round_trip.js +2 -2
  213. package/dist/testing/stubs.d.ts +5 -6
  214. package/dist/testing/stubs.d.ts.map +1 -1
  215. package/dist/testing/stubs.js +10 -8
  216. package/dist/testing/test_app.d.ts +8 -5
  217. package/dist/testing/test_app.d.ts.map +1 -1
  218. package/dist/testing/test_app.js +7 -7
  219. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  220. package/dist/testing/ws_round_trip.js +3 -0
  221. package/dist/ui/ui_format.d.ts.map +1 -1
  222. package/dist/ui/ui_format.js +1 -2
  223. package/package.json +1 -1
@@ -10,530 +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. Takes its deps (`audit` among them) and the request's context (`BootstrapAccountContext`: the pool `db`, the effect queues, `client_ip` — a `RouteContext` satisfies it). One transaction holds the whole bootstrap: the lock, the account and grants, the session (`create_capped_session`) and its `Set-Cookie` line (formatted there, as login and signup format theirs, so a refused value rolls the bootstrap back), the `bootstrap` success audit row, 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 `set_cookie`, the line 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, 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), the IDOR-guarded `query_revoke_role_grant` (every revoke's one supersede rule: the revokee's incoming siblings and every offer its actor made, in-tx), 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`), on the database clock: `query_create_session` writes `NOW() + INTERVAL '2592000 seconds'` (`AUTH_SESSION_LIFETIME_SQL` — elapsed seconds, as a day interval would follow DST in the session time zone), the Rust insert's statement, so it sits a whole lifetime past the row's `created_at` (a test needing another expiry, past or future, inserts through `testing/db_entities.ts`'s `create_test_session_row`). `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 scope teardown in `role_grant_queries.ts` still _writes_ offer rows, which
107
- is exactly why the offer const and the shared CTE tail live in the DDL module.
108
- `query_revoke_role_grant` lives with the offer queries (as in the Rust twin):
109
- it takes the offer locks and both supersedes.
110
- Every const is pinned to the live schema by
111
- `src/test/db/column_projections.db.test.ts`. The Rust `fuz_auth` twin carries
112
- the same nine consts (names and order), projected through
113
- `fuz_db::qualify_columns` / `omit_columns`, decoded with compile-time
114
- name→index (`fuz_db::col!`), and pinned by its own
115
- `tests/columns.rs` registry; its narrow purpose rows (`AccountRow` is an
116
- `id, username` pair) keep private per-shape lists checked as subsets of the
117
- table const.
118
-
119
- `_unscoped` suffix on `query_session_revoke_by_hash_unscoped` and
120
- `query_invite_claim_unscoped` is the safety signal: SQL only checks row state,
121
- caller is responsible for scoping. Production scoping for invites is enforced
122
- upstream in `auth/signup_routes.ts` via `query_invite_find_unclaimed_match_for_update`
123
- (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.
124
83
 
125
84
  ### Audit emitter
126
85
 
127
- `auth/audit_emitter.ts` defines the `AuditEmitter` capability that lives on
128
- `AppDeps.audit`. Built once at backend assembly via the consumer's
129
- `audit_factory` callback over `create_audit_emitter`; closes over the pool +
130
- its registered listeners + optional `AuditLogConfig`. Its methods:
131
-
132
- - `emit(ctx, input)` — async, always awaited: a success row is written in the request's transaction (a failed INSERT rejects, and so does a success row with no transaction open); a failure 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`
133
- - `emit_role_grant_target(ctx, auth, input)` — lifts `actor_id` / `account_id` / `ip` boilerplate for role-grant-shape events; `input` is an `AuditEmitRoleGrantInput`
134
- - `emit_pool(input)` — awaitable pool write for code paths without a request (ad-hoc maintenance scripts; not for success audits paired with a mutation — those write in-tx). Writes, then notifies, whatever the outcome; a success row written here counts toward `get_audit_success_outside_transaction`, which `install_audit_drift_guard` holds at zero
135
- - `notify(event)` — fan out an already-written row to listeners (used by in-tx audit batches like `query_accept_offer.audit_events`)
136
- - `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
137
- - `listener_count()` — registered-listener count, for tests / diagnostics
138
- - `drain_inflight()` — waits until no pool write is in flight, writes started while waiting included. Every emitter counts them. `AppServer.close` awaits it, bounded by `shutdown_drain_timeout_ms`, before the database closes; it backs `_testing_drain_effects` (twin of Rust `AuditEmitter::drain_inflight`)
139
- - `inflight_count()` — pool writes in flight now; what a shutdown that gives up at its bound reports (twin of Rust `AuditEmitter::inflight_count`)
140
-
141
- Listeners are closure-private; they change only through `add_listener` and
142
- its removers. `create_app_server` registers the audit-log SSE listener and the
143
- one revocation guard (`create_revocation_guard`) via `add_listener`
144
- so SSE fan-out and revocation closes compose on top of the consumer's `on_audit_event` callback
145
- without shallow-copying `AppDeps`, and removes them when its assembly fails or
146
- `AppServer.close` runs — the emitter outlives any one server on its backend.
147
- `notify` iterates a snapshot so a listener registered mid-fan-out fires only on
148
- the next event, and one removed mid-fan-out still hears the in-flight event
149
- (converges with the Rust twin's cloned vec).
150
-
151
- **Where a row is written.** `emit` is async — always `await` it. A **success**
152
- row is written in the transaction of the change it reports
153
- (`ctx.db.in_transaction`: an action with `side_effects`, a route with
154
- `transaction: true` — `/logout`, `db_admin_row_delete` — or the transaction
155
- `/login`, `/password`, signup and bootstrap open around just their writes
156
- through `transaction_with_post_commit_rollback`, the row last before the
157
- commit), so the change and its row commit together; a failed INSERT rejects
158
- `emit` and the transaction rolls back. With no transaction open `emit` refuses
159
- a success row (throws, writes nothing, and counts it for the drift guard). A
160
- **failure** row is a fire-and-forget pool write, fail-open (logged, counted by
161
- `get_audit_write_failures`). The Rust spine's split is the same
162
- (`route_audit_emit`: `emit_in_tx` for every success row, REST and db-admin
163
- included, `emit` on the pool for failure rows). `seq` follows INSERT order,
164
- not commit order.
165
-
166
- **When listeners hear about a row.** The fan-out depends on the outcome: a
167
- **failure** row is announced as soon as it is written — the attempt happened
168
- whatever the transaction does; a **success** row is announced only after the
169
- request's transaction commits (a thunk on `ctx.post_commit_effects`) and never
170
- when it rolls back — a handler-owned transaction truncates the queue itself
171
- (`transaction_with_post_commit_rollback`), so a handler that catches its
172
- failure and answers a refusal announces nothing. The listeners act on a success row — the revocation guards
173
- close connections, the audit stream broadcasts it — so announcing one before
174
- its commit would close while the revoked credential still reads as valid, and
175
- a rolled-back revocation would close anyway. A route that runs without a
176
- request transaction and opens its own around just its writes (`/login`,
177
- `/password`) emits its success row after that transaction commits. The Rust
178
- spine follows the same order: a success row emitted inside a request
179
- transaction is written in it with its fan-out queued behind the commit, and
180
- `/login` and `/password` emit after their own commit. `AuditEmitterContext` is therefore
181
- `{db, pending_effects, post_commit_effects}` — `RouteContext` and `ActionContext`
182
- both satisfy it.
183
-
184
- **Revocation scopes** (`auth/audit_log_schema.ts`) —
185
- `audit_event_revocation_scopes` declares, per builtin event type, what a
186
- successful row invalidates (`RevocationScope`: `none` / `session` / `token` /
187
- `account` / `role`), and `to_revocation_scope(event_type)` reads it (an unknown
188
- event type is `none`). Typed over `AuditEventType`, so a new event type does not
189
- compile until it declares its scope. The revocation listener
190
- (`create_revocation_guard`, `actions/connection_closer.ts`) dispatches on it. Twin of the
191
- `revocation_scope` column on the Rust `AUDIT_EVENT_SPECS`.
192
-
193
- **Drift counters** (`auth/audit_log_queries.ts`) — `audit_metadata_validation_failures`
194
- and `audit_unknown_event_type_failures` are process-wide, fail-open
195
- (write the row anyway). Independent in implementation; under the factory
196
- they track the same config. Sample via `get_*`; `reset_*` are test-only.
197
- Another counter lives with the emitter (`auth/audit_emitter.ts`,
198
- `get_audit_write_failures` / `reset_audit_write_failures`): rows the bound
199
- emitter's pool write failed to insert. That write is fail-open too — logged,
200
- counted, the request proceeds — so the count is how a lost row is seen. A
201
- third, `get_audit_success_outside_transaction` /
202
- `reset_audit_success_outside_transaction`, counts success rows written
203
- outside a transaction (`emit` with none open, which also throws, and a success
204
- `emit_pool`); `install_audit_drift_guard` holds all of them at zero per test.
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.
205
118
 
206
119
  ### Routes
207
120
 
208
- - `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`.
209
- - `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.
210
- - `auth/signup_routes.ts` — `POST /signup` (open or invite-gated). The `signup` success row is written last in the signup transaction; every unclassified failure writes a `signup` failure row with reason `internal_error` — one before the transaction began (the settings load, the hash, a refused `BEGIN`) carries neither `invite_id` nor `open_signup`, as the Rust spine's pre-transaction row. A failure row's emit that throws is logged, never answered in place of the original error.
211
- - `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.
212
- - `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).
213
-
214
- **Hono-free route shapes.** Each cookie/SSE-coupled route module has a sibling
215
- `*_route_schema.ts` (`account_route_schema.ts`, `signup_route_schema.ts`,
216
- `audit_log_route_schema.ts`, `bootstrap_route_schema.ts`) holding the I/O
217
- schemas **and** the route _shapes_ (`Omit<RouteSpec, 'handler'>` —
218
- method/path/auth/io/errors, via `create_*_route_shapes(options)` or a static
219
- `*_route_shape` const). The `create_*_route_specs` factories spread a shape and
220
- attach the live (hono-coupled) handler; a cross-process surface builder spreads
221
- the same shape with a stub handler (surface generation never runs handlers).
222
- Single source of truth — the shape can't drift between the live route and the
223
- attack surface — and a backend-spawning consumer assembling its surface imports
224
- the shapes without dragging `hono/streaming` (and the optional `hono` peer)
225
- onto a Rust-only cross-process suite. Shared route-limit constants
226
- (`DEFAULT_MAX_SESSIONS` / `_TOKENS`) live in `account_route_schema.ts` for the
227
- same reason (the RPC `account_actions` reads `DEFAULT_MAX_TOKENS`). The
228
- account, signup and bootstrap shapes' schemas, error bodies included, are
229
- `@fuzdev/fuz_schema` schemas: `/login` takes `UsernameProvided` and
230
- `PasswordProvided`; the output `username` of `/logout`, `/signup` and
231
- `/bootstrap` is a `UsernameCanonical`; `/password`'s revoke counts are
232
- non-negative integers; `/bootstrap`'s `token` is 1 to
233
- `BOOTSTRAP_TOKEN_LENGTH_MAX` (4096, the token file's cap) UTF-16 code units,
234
- a longer one a `400 invalid_request_body` before the window check, with no
235
- audit row — twin of the Rust `BOOTSTRAP_TOKEN_LENGTH_MAX`.
236
-
237
- **`POST /login` timing floor.** Login 401s are floored to
238
- `DEFAULT_LOGIN_FAIL_FLOOR_MS` (250ms) + uniform jitter (±25ms) via
239
- `start_fail_floor` (`auth/fail_floor.ts`, shared with signup's 403 / 409
240
- floor; twin of the Rust `fuz_auth::timing`), started before the work and
241
- awaited after, so observed time is `max(work, delay)` and
242
- found-wrong-password and not-found paths converge. 429 stays fast by design;
243
- `verify_dummy` equalizes Argon2id timing on not-found. A floor of `0` or less
244
- is announced once per process on stderr by `warn_if_fail_floor_disabled`
245
- (`LOGIN_` / `SIGNUP_FAIL_FLOOR_DISABLED_BANNER`, the Rust spine's text).
246
-
247
- **`POST /password` revokes everything.** Revokes all sessions + all API
248
- tokens (force re-auth everywhere), then clears the session cookie. Declares
249
- `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
250
142
  §Credential-channel gating).
251
143
 
252
- **The routes close what they revoke, after the commit.** `/password` queues an
253
- account-wide close, `/logout` a session close for the session it ends (the
254
- account's other sessions and tokens stay valid, and their connections open),
255
- and `/login` a session close for each session its cap evicted (`queue_connection_close` on
256
- `deps.connection_closer`). The queue runs once the route's transaction has
257
- 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.
258
152
 
259
- REST-only post RPC migration: `/login`, `/logout`, `/password`, `/signup`,
260
- `/bootstrap`, optional `/audit/stream`.
261
- 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.
262
156
 
263
157
  ### Middleware
264
158
 
265
- - `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.
266
- - `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`.
267
- - `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.
268
- - `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`.
269
- - `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`.
270
- - `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.
271
- - `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.
272
-
273
- See root ../../../CLAUDE.md §Middleware Ordering for canonical assembly
274
- order. The auth-specific invariants are described below in §Cross-cutting
275
- 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.
276
173
 
277
174
  ### Cell layer
278
175
 
279
176
  The cell content primitive's wire schemas, RPC handlers, and authz live
280
- here; the schema + queries live in `db/` (see `db/CLAUDE.md` §Cell layer).
281
- Generic-only — no app vocabulary on the wire; per-kind shape is the
282
- consumer's `validate_data(kind, data)` callback on `CellActionDeps`, which
283
- accepts or throws and never rewrites (the handler stores the caller's `data`).
284
-
285
- - `auth/cell_data_schema.ts` — `CellData` base (a `@fuzdev/fuz_schema`
286
- `loose_object` with optional `label` / `summary`); a per-kind schema spreads
287
- its `def` (`loose_object({...CellData.def, ...})`). **`kind` is
288
- not in `data`** — it is a top-level `cell.kind` column (peer to
289
- `visibility` / `path`), the write-once capability/identity axis; a stray
290
- `kind` inside `data` is rejected fail-loud (`ERROR_CELL_KIND_IN_DATA`).
291
- - `auth/cell_action_specs.ts` — `CellVisibility` enum, `CellPath` brand,
292
- `CELL_KIND_LENGTH_MAX` (64 — the wire `kind` on `cell_create` and the
293
- `cell_list` filter; the tag is copied into the cell's audit rows),
294
- `CellJson`, `CellPolicy` (a root's contribution policy, a `loose_object`), the
295
- generic verb specs (`cell_create / get / update / delete / list / clone /
296
- moderate / policy_set`), error reasons, and `all_cell_action_specs`
297
- (spreads in the grant / field / item / audit registries so codegen + UI
298
- see one cell namespace). `CellJson` has no hub axis; `path` is global. The
299
- directory-tree columns `parent_id` / `root_id` (containment, immutable in v1)
300
- - the `moderation` lifecycle marker (`pending` / `approved` / `rejected`) are
301
- top-level `CellJson` keys, peer to `visibility` (set by the create authorizer's
302
- verdict + the `cell_moderate` verb, never in `data`).
303
- - `auth/cell_grant_action_specs.ts` / `cell_field_action_specs.ts` /
304
- `cell_item_action_specs.ts` / `cell_audit_action_specs.ts` — the
305
- `cell_grant_*` / `cell_field_*` / `cell_item_*` / `cell_audit_list`
306
- specs + their wire JSON shapes. Every cell wire schema is
307
- `@fuzdev/fuz_schema`.
308
- - `auth/cell_authorize.ts` — pure predicates over
309
- `(RequestContext | null, CellRow, grants)`: `can_view_cell`,
310
- `can_edit_cell`, and `can_manage_cell` (= admin ‖ owner, where owner is
311
- the `cell.created_by` actor field). The manage tier gates visibility
312
- writes, all grant management (`cell_grant_create` / `_list` /
313
- `_revoke`), and the per-cell audit timeline (`cell_audit_list`, D14 —
314
- it surfaces who-touched-the-cell); it is not a grant level and not
315
- delegable. Editor-grant holders edit content + relations but cannot
316
- manage grants or read the audit timeline. NULL
317
- `created_by` (system origin) is admin-only for edit/manage (explicit
318
- defense-in-depth). "Admin" on every tier is the **global** grant — a
319
- scoped `admin` row bypasses nothing. `can_view_cell`'s public and grant
320
- arms also require the cell's `moderation` to admit an audience
321
- (`db/cell_moderation.ts`: unmoderated or `approved`), so a pending or
322
- rejected contribution is its author's and admins' alone; `can_edit_cell`'s
323
- editor-grant arm requires the same admission. `can_steward_cell`
324
- is the separate moderator read: the governing root's manager on a pending or
325
- rejected contribution under a live root.
326
- - `auth/cell_steward.ts` — `cell_steward_admits(deps, auth, cell)`: the steward
327
- arm with its governing-root load, run only after `can_view_cell` denies. Its
328
- module doc names where the arm applies (`cell_get`, `cell_moderate`, the
329
- cell-scoped fact route, `cell_list`'s SQL) and where it must not (clone,
330
- contribution parents, relation reads, `shared_with`, grant recompute).
331
- - Strict relation-read visibility — every relation read drops edges whose far
332
- endpoint the caller can't view, so a viewer of a parent can't enumerate
333
- private linked cells by id. **Forward and reverse** `cell_field_list` /
334
- `cell_item_list` filter in SQL before their limit
335
- (`db/cell_view_sql.ts`'s `can_view_cell_sql`, bound through
336
- `cell_viewer_from_auth`), so a page is up to `limit` edges whose other end
337
- the caller can view — `CELL_RELATION_LIST_LIMIT_DEFAULT` (50) when omitted,
338
- `CELL_RELATION_LIST_LIMIT_MAX` (500) at most
339
- (`auth/cell_relation_list_limit.ts`), and hidden ends never crowd out
340
- visible ones. The `cell_get` bundle (whose `*_truncated` counts raw edges)
341
- and the clone walk read with `CELL_VIEWER_UNRESTRICTED` and filter after,
342
- through `auth/cell_relation_visibility.ts`'s `filter_visible_target_ids(deps,
343
- auth, ids)`: two queries for the whole id-set, the cells read through the
344
- narrow `CELL_VIEW_COLUMNS` projection (`query_cell_view_load_many`), never
345
- the payload.
346
- - `auth/cell_actions.ts` — `create_cell_actions(deps)`, the generic
347
- handlers. `cell_create` stamps `created_by` + writes the top-level `kind`
348
- column; `path` writes are admin-only. It also resolves the directory tree:
349
- `parent_id` (wire) → the governing `root_id` (`parent.root_id ?? parent.id`),
350
- **404**-masking a hidden parent. `cell_update` gates `visibility`
351
- writes on `can_manage_cell` (`ERROR_CELL_VISIBILITY_MANAGE_ONLY`) and
352
- **never touches `kind`** / `parent_id` / `root_id` / `moderation` (all
353
- write-once-at-birth or control-gated, never on the update patch).
354
- `cell_get` bundles visibility-filtered `fields` + `items` (one over the cap
355
- for truncation detection). `cell_clone` deep-walks viewable children only
356
- (each clone inherits its source's `kind`; clones are unparented), and runs
357
- the mounted `authorize_create` for **every** cell it writes as a parentless
358
- create — a denial is the same 403 `cell_create_forbidden`, so clone is no
359
- side door past the creation policy. The optional
360
- parent-aware `authorize_create` dep (`CellCreateAuthorize` — an object whose
361
- `authorize` takes a wider input `{kind, data, parent_id, parent_kind,
362
- root_id, root_policy}` than `validate_data` and returns a `CellCreateVerdict`
363
- `{allow:false} | {allow:true, moderation_required}`, and whose optional
364
- `validate_policy` accepts or refuses a root policy write)
365
- gates create by capability; it runs after the validator + the parent-resolve
366
- (which **404**s `cell_not_found` on a missing or soft-deleted root as on a
367
- missing parent, authorizer or not).
368
- A **viewable**-parent / root-creation deny is **403** `cell_create_forbidden`
369
- (the create-path **404** mask is reserved for a hidden parent); `Allow` folds
370
- the moderation outcome (born `pending`+private vs `approved`+author-visibility).
371
- The handler reads the governing root in-tx and hands its `policy` column
372
- over as `root_policy`, so a directory policy resolves `root_policy[kind]`
373
- without a DB read; an authorizer needing more reads through its third
374
- argument, the request `ctx` (`ctx.db` is the request transaction), and only
375
- reads. `None`/omitted = open
376
- create (the default; mirrors `validate_data`), and every non-null policy write
377
- refused `cell_policy_unsupported`. A root's `policy` (a JSON object, roots only
378
- by table CHECK, opaque to the spine, readable on `CellJson`) is set at a
379
- root's `cell_create` and changed only by `cell_policy_set` — the 404 mask, then
380
- manage-tier (403 `cell_policy_manage_only`, an editor grant included), then
381
- root-only (400 `cell_policy_root_only`), then the authorizer's
382
- `validate_policy`; audited with the new and the previous policy. `cell_update`
383
- never writes it (an editor can rewrite `data`, so a policy read from `data`
384
- would be the editor's to loosen), and a clone is born without one.
385
- `cell_moderate` is the `pending → approved | rejected` transition (plus
386
- `approved → rejected`, the takedown), gated on
387
- `can_manage_cell` of the **governing root** (admin / root owner — the author
388
- lands a 403, the anti-self-approval guard; a root owner reaches the check
389
- through the steward arm); approve flips
390
- `moderation → approved` + `visibility → public`, reject sets `rejected`
391
- (visibility untouched). The write carries the from-state: approve moves only
392
- a pending contribution, reject a pending or approved one (the takedown); any
393
- other transition answers 400 `cell_not_pending`.
394
- - `auth/cell_action_helpers.ts` — the cell verbs' shared gates, each loading
395
- the cell and 404-masking a miss and a denial alike
396
- (`require_viewable_cell` — `auth` may be `null`, which reads no grants —
397
- `require_editable_cell`, `require_manageable_cell`), plus
398
- `cell_not_found_error` and `emit_cell_audit(ctx, audit, auth, event_type,
399
- metadata)`. Twins of the Rust `fuz_cell_actions` helpers.
400
- - `auth/cell_ref_admission.ts` — `require_new_refs_held`, the
401
- possession gate `cell_create` / `cell_update` / `cell_clone` run last before
402
- their write: a non-admin write introducing a fact ref (beyond the cell's
403
- current refs on update, each cloned row's source refs on clone) that its
404
- acting actor holds no `fact_holder` row for is 403 `cell_ref_not_held`,
405
- answered from holder rows alone (stored and unstored hashes read the same);
406
- a schema without the fact chain refuses every new ref. Global admin bypasses;
407
- a scoped admin doesn't. Twin of the Rust `cell_ref_admission`.
408
- - `auth/cell_grant_actions.ts` / `cell_field_actions.ts` /
409
- `cell_item_actions.ts` / `cell_audit_actions.ts` — the relation + ACL +
410
- audit handlers, exporting `to_grant_json` / `to_field_json` /
411
- `to_item_json` reused by the `cell_get` bundle. `cell_grant_create` takes an
412
- optional `authorize_grant_create` (`CellGrantCreateAuthorize`), asked of a
413
- manager after the spine's gates and before the write (a level change too);
414
- `false` is 403 `cell_grant_not_authorized`, nothing written.
415
- `cell_grant_revoke` takes an optional `authorize_grant_revoke`
416
- (`CellGrantRevokeAuthorize`), the steward widening: asked only of a caller
417
- who neither manages the cell nor holds the grant, for a role-shaped grant
418
- with a `scope_id`; `true` revokes (audit `steward: true`) with a delete
419
- matching the level it saw, `false` keeps the 404 mask. Both callbacks, like
420
- the create authorizer and the offer callback, take the request `ctx` last —
421
- `ctx.db` is the request transaction — and must only read through it.
422
- - `auth/all_cell_actions.ts` — `create_all_cell_actions(deps, {roles})`, the
423
- handler-side twin of `all_cell_action_specs` and sibling of
424
- `create_standard_rpc_actions`: bundles all five cell factories (CRUD + grant
425
- - field + item + audit) into one list. Reach for this whenever a backend
426
- mounts the full cell layer — a single source so an HTTP-RPC mount and a WS
427
- mount (or two backends) can't diverge on which cell verbs they expose.
428
- Distinct from `create_cell_actions` (the CRUD-only factory it bundles).
429
- - `auth/cell_audit_metadata.ts` + `cell_grant_audit_metadata.ts` +
430
- `cell_field_audit_metadata.ts` + `cell_item_audit_metadata.ts` — audit
431
- metadata envelopes (IDs only), `@fuzdev/fuz_schema` `loose_object`s,
432
- registered via `extra_events:` on the consumer's `create_audit_log_config`.
433
- - `auth/cell_audit_events.ts` — `cell_audit_events`, the canonical
434
- `event_type → metadata` map bundling every cell-domain audit event.
435
- Consumers spread it into `extra_events` to register the whole layer in
436
- one call (aggregator by design, not a compat shim).
437
-
438
- The cell event types (`cell_create` / `_update` / `_delete` / `_clone` /
439
- `_moderate`, `cell_policy_set`, `cell_grant_create` / `_revoke`, `cell_field_set` / `_delete`,
440
- `cell_item_insert` / `_move` / `_delete`) are consumer-registered extras,
441
- 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).
442
215
 
443
216
  ## Cross-cutting invariants
444
217
 
445
- The things that span multiple files and don't fit on any one symbol's TSDoc.
446
-
447
218
  ### Two-phase identity
448
219
 
449
- **Authentication runs in middleware** (session / bearer / daemon token).
450
- Sets one `ResolvedAuth` (`RESOLVED_AUTH_KEY`) on a valid credential.
451
- Account-only — never loads actor or role_grants, never populates
452
- `REQUEST_CONTEXT_KEY`.
453
-
454
- **Authorization runs before input validation**, matching the dispatcher's
455
- 401 → authz → 403 → 400 phase order — the 429 is dispatcher-only (see `http/CLAUDE.md` §Validation
456
- pipeline). When the route's input declares `acting?: ActingActor` or its auth
457
- requires role_grants, the authorization phase calls `resolve_acting_actor` over
458
- the `acting` selector — the validated query value on GETs, read off the raw
459
- body on mutations — and builds an actor-bound `RequestContext`. A malformed
460
- selector reads as omitted (it only ever picks among actors the account already
461
- owns, and input validation rejects it a step later). Account-grain routes run
462
- with `RequestContext.actor: null`.
463
-
464
- `apply_authorization_phase` is pure data — returns `AuthorizationResult`
465
- (`{ok: true, request_context: RequestContext | null} | {ok: false, status, body}`)
466
- without touching the Hono context. Each transport binds the same failure to
467
- its wire shape: REST `c.json(body, status)`; HTTP RPC + WS fold into a
468
- JSON-RPC envelope where `error.message` is the reason string and
469
- `error.data: {reason, ...rest}` flattens diagnostic fields. The one 500
470
- reason is `no_actors_on_account` (signup invariant violation: a live account
471
- with no active actor). The phase builds on the account row the credential leg
472
- read, so an account deleted or purged after that read runs an account-grain
473
- handler on that row, as on the Rust spine. An actor-grain one finds no actor,
474
- and the one read that tells the two cases apart answers a removed account
475
- with the dead credential's 401 (`authentication_required`). `account_verify`
476
- re-reads the account live and answers the same 401.
477
-
478
- **Production-middleware invariant.** No production middleware on the auth
479
- path populates `REQUEST_CONTEXT_KEY`; it sets only `RESOLVED_AUTH_KEY`. Test
480
- harnesses pre-populate `REQUEST_CONTEXT_KEY` and set `TEST_CONTEXT_PRESET_KEY`
481
- to the `TEST_CONTEXT_PRESET` symbol to bypass DB-backed actor resolution
482
- (`has_test_context_preset` reads it; any other value, `true` or a string
483
- included, is unset); production code that reads `REQUEST_CONTEXT_KEY` is
484
- reading test escape-hatch state.
485
-
486
- **The session token key is fixed.** The session middleware writes the token
487
- under `SESSION_TOKEN_KEY` (`hono_context.ts`, `'auth_session_id'`) and the
488
- session leg reads it there; `SessionOptions` carries no context key, so the two
489
- 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.
490
250
 
491
251
  ### Row locks
492
252
 
493
253
  One class order in every transaction — accounts, then offers, then grants and
494
254
  actors — and id order within a class. Every writer of an account takes its row
495
255
  first (two mints of one account take turns there, so the caps hold); a
496
- multi-row write (credential deletes, offer cascades, the expiry sweeps) locks
497
- its rows in one id-ordered statement before writing. Each lock's strength and
498
- reason is on its query's TSDoc; the rule set: ../../../docs/security.md §Row
499
- 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).
500
260
 
501
261
  ### Wire timestamp shape
502
262
 
503
- Every timestamp on the wire is **second-precision UTC** —
504
- `YYYY-MM-DDTHH:MM:SSZ`, exactly 20 characters, the shape both spines emit.
505
- Timestamps read from a row get it from the SQL projection: each query module
506
- builds an `iso8601_timestamp_expr` override over its table const and passes
507
- it to `columns_sql` / `qualify_columns` (see `db/CLAUDE.md`), covering `account`, `actor`,
508
- `role_grant`, `role_grant_offer`, `auth_session`, `api_token`, `invite`,
509
- `app_settings`, `audit_log`, and the cell tables. Stamps minted in TS rather
510
- than read back — the `expires_at` on `account_token_create`'s output — use
511
- `to_iso8601_seconds` (`timestamp.ts`), so the mint and the later
512
- `account_token_list` read agree byte for byte.
513
-
514
- The `*Json` schemas type these as `Timestamp` (`iso_datetime`), which a
515
- millisecond stamp also satisfies — so the shape is pinned behaviorally by
516
- `assert_iso8601_seconds` (`testing/cross_backend/wire_shapes.ts`) inside the
517
- shared suites, on both backends.
518
-
519
- The alias costs one rule: **an `ORDER BY` in a projected SELECT qualifies
520
- its column** (`ORDER BY auth_session.created_at`) — bare, Postgres resolves
521
- it to the formatted output column, which ties rows written inside the same
522
- second and drops the btree index. Qualified, ordering stays exact and
523
- index-backed, matching the Rust twin (which aliases nothing, so its bare
524
- `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.
525
271
 
526
272
  ### Open-registry composition
527
273
 
528
- Four open string registries — `RoleName`, `ScopeKindName`,
529
- `CredentialTypeName`, `GrantPathName` — share the same factory shape:
530
- construction-time guards (name regex, duplicate detection, builtin-collision
531
- rejection), `ReadonlyMap` output, pass into `create_role_registry` for
532
- cross-axis validation. The four share one name grammar, runs of lowercase
533
- letters joined by single underscores, at most `NAME_LENGTH_MAX` characters
534
- (`auth/name_schema.ts`), which a token's `surface:` name holds too.
535
-
536
- 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:
537
279
 
538
280
  ```
539
281
  create_credential_type_registry()
@@ -541,387 +283,188 @@ create_scope_kind_registry() → create_role_registry({roles, options})
541
283
  create_grant_path_registry()
542
284
  ```
543
285
 
544
- `role_specs` drives downstream defaults:
545
-
546
- - `admin_actions.grantable_roles` ⊇ `{role : 'admin' ∈ grant_paths}`
547
- - `self_service_role_actions` default eligibility ⊇ `{role : 'self_service' ∈ grant_paths}`
548
-
549
- `AuditEventTypeName` is the fifth open registry but composes differently —
550
- 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.
551
290
 
552
291
  ### Audit `target_*_id` rules
553
292
 
554
- The two target columns on `AuditLogEvent` populate by a single rule:
555
293
  **`target_actor_id` is set when the event subject is bound to a specific
556
- actor**; `target_account_id` is always populated when there's an account
557
- subject. SSE/WS socket-close keys on `target_account_id ?? account_id`
558
- (sessions stay account-grain at the routing layer even after multi-actor).
559
-
560
- The full per-event-type table lives in `AuditLogEvent.target_actor_id`
561
- TSDoc. The pattern that spans emit sites:
562
-
563
- - **Role-grant-shape events** populate both targets (the grantee actor is
564
- the subject regardless of initiator). Use `audit.emit_role_grant_target`
565
- to lift the `actor_id` / `account_id` / `ip` boilerplate.
566
- - **Offer-shape events** (`role_grant_offer_create` / `_expire` / `_retract` /
567
- `_supersede`) populate `target_actor_id` only when the offer was
568
- 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).
569
302
  - **Account-shape events** (login, logout, signup, bootstrap, password
570
- change, session/token revoke, app_settings update) stay
571
- account-grain on **both** `target_actor_id` and `actor_id` — the
572
- operation is performed by the account, and a multi-actor user must be
573
- able to log out without first picking an acting actor.
574
- - **Invite events** carry the acting `actor_id` (the handlers are
575
- actor-grain) and no target — the `invite_delete` rows an account removal
576
- writes for the invites it voids too, the remover's. A delete of a missing
577
- invite writes an `outcome: 'failure'` row (`reason`, `attempted_invite_id`
578
- — a UUID probe key, unlike `invite_create`'s email and username refusals,
579
- which write none).
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).
580
315
 
581
316
  ### Audit event extensibility
582
317
 
583
- Consumers extend the closed `AUDIT_EVENT_TYPES` enum via
584
- `create_audit_log_config({extra_events})` — a `@fuzdev/fuz_schema` metadata
585
- schema or `null` per type; collisions with builtins, name-format failures
586
- and a value that is no schema throw at construction. `query_audit_log`
587
- validates through `parse`, and a dropped row's log line masks the
588
- `sensitivity: 'secret'` fields of an object metadata schema.
589
- The builtin `audit_metadata_schemas` are fuz_schema `loose_object`s
590
- (`nullable` where the event may carry none, `literal(null)` for `logout`). The
591
- DB column is `TEXT NOT NULL` (no enum), so consumer types round-trip through
592
- list queries, the `audit_log_list` RPC, and SSE identically to builtins.
593
-
594
- `AuditLogEvent.event_type` / `AuditLogEventJson.event_type` / the
595
- `audit_log_list` filter input are all `AuditEventTypeName` (regex-validated
596
- string, at most `NAME_LENGTH_MAX` characters) — widened from the closed enum so consumer rows round-trip. The
597
- write side (`AuditLogInput<T>`, `AuditMetadataMap`) stays closed-enum so a
598
- builtin event's metadata narrows by its type.
599
-
600
- ### `AUDIT_EVENT_TYPES` builtins
601
-
602
- For quick reference; the source-of-truth list is the `Object.freeze`d
603
- constant in `auth/audit_log_schema.ts`.
604
-
605
- ```
606
- login role_grant_create
607
- logout role_grant_revoke
608
- bootstrap role_grant_offer_create
609
- signup role_grant_offer_accept
610
- password_change role_grant_offer_decline
611
- session_revoke role_grant_offer_retract
612
- session_revoke_all role_grant_offer_expire
613
- token_create role_grant_offer_supersede
614
- token_revoke invite_create
615
- token_revoke_all invite_delete
616
- account_delete app_settings_update
617
- account_purge db_admin_row_delete
618
- account_undelete
619
- actor_delete
620
- actor_purge
621
- actor_undelete
622
- ```
623
-
624
- `account_delete` / `account_purge` / `account_undelete` snapshot
625
- `{username, email}` into metadata; `actor_delete` / `actor_purge` /
626
- `actor_undelete` snapshot `{name}`. The account-level handlers emit the
627
- account event plus one per-actor event (`delete` = soft, `purge` = hard,
628
- `undelete` = reactivation — see ../../../docs/security.md §Authorization,
629
- "Account-removal target guards").
630
-
631
- `role_grant_offer_supersede` carries
632
- `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)
633
- plus `cause_id` pointing to the row that triggered the supersede. The WS
634
- `role_grant_offer_supersede` notification's reason set is narrower —
635
- `sibling_accepted | role_grant_revoked | account_deleted`; `scope_destroyed`
636
- 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.
637
334
 
638
335
  ### Keeper auth shape
639
336
 
640
337
  Keeper is not a dedicated guard — it's a composable `RouteAuth` shape:
641
338
  `{account: 'required', actor: 'required', roles: ['keeper'], credential_types: ['daemon_token']}`.
642
- The two-part check is `require_credential_types(['daemon_token'])` (403
643
- `ERROR_CREDENTIAL_TYPE_REQUIRED`) followed by `require_role(['keeper'])`
644
- (403 `ERROR_INSUFFICIENT_PERMISSIONS`) — the channel gate lands
645
- pre-authorization and the role gate post-authorization, so a non-daemon
646
- credential is refused before the route resolves an actor for it. Same
647
- scope-aware semantics mirrored
648
- in the HTTP RPC dispatcher (`actions/action_rpc.ts`), the WS dispatcher
649
- (`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
650
345
  `auth/role_grant_offer_actions.ts`.
651
346
 
652
347
  ### Migrations
653
348
 
654
- Schema migrations live in `auth/migrations.ts` — a frozen, append-only chain
655
- (`full_auth_schema` first, every later change its own appended entry) under
656
- the single reserved namespace `'fuz_auth'` (`AUTH_MIGRATION_NS`), each
657
- entry twinned byte-for-byte by name on the Rust spine. `db/migrate.ts`'s
658
- `reserved_migration_namespaces` lists the spine's names (`fuz_auth`, `fuz_cell`,
659
- `fuz_facts`); `run_migrations` and `baseline` refuse a namespace bearing one
660
- unless it is the spine's own object (`AUTH_MIGRATION_NS`, `CELL_MIGRATION_NS`,
661
- `FACT_MIGRATION_NS`, each built by `create_spine_migration_namespace`). Runner contract, error vocabulary, and
662
- operator recipes (rename, mark applied, reset, baseline) are in
663
- ../../../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.
664
355
 
665
356
  ## RPC action surfaces
666
357
 
667
- Each registry splits across `*_action_specs.ts` (schemas + specs + registry,
668
- codegen-importable) and `*_actions.ts` (`create_*_actions(deps, options)`
669
- factory with handlers). Client codegen imports the specs and skips the
670
- 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.
671
363
 
672
- - `create_admin_actions` — registry `all_admin_action_specs` — bundled in `create_standard_rpc_actions`.
673
- - `create_role_grant_offer_actions` — registry `all_role_grant_offer_action_specs` — bundled.
674
- - `create_account_actions` — registry `all_account_action_specs` — bundled.
675
- - `create_self_service_role_actions` — registry `all_self_service_role_action_specs` — not bundled (`eligible_roles` is app-specific).
676
- - `create_actor_lookup_actions` — registry `all_actor_lookup_action_specs` — not bundled (opt-in batched id → label resolver).
677
- - `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).
678
370
 
679
- `auth/all_action_spec_registries.ts` exposes `all_fuz_auth_action_spec_registries`
680
- for registry-wide invariant tests. Not a mounting surface; protocol specs
681
- 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.
682
374
 
683
375
  ### Authorization patterns
684
376
 
685
- - **Spec-level enforcement.** Every admin spec declares
686
- `auth: {account: 'required', actor: 'required', roles: ['admin']}`; the
687
- dispatcher checks per-spec, so mixed-auth bundles compose cleanly
688
- (`role_grant_revoke` uses the admin gate alongside non-admin offer
689
- siblings in the same factory).
690
- - **Input-dependent elevation.** `role_grant_offer_list` and `_history` use
691
- `side_effects: false` so they're GET-addressable. Spec-level auth is
692
- `{account: 'required', actor: 'required'}` so any caller reaches their
693
- own inbox; the handler additionally requires admin when `{account_id}`
694
- refers to another account. The spec can't express this because auth runs
695
- 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.
696
386
  - **Account-grain self-service.** `account_*` specs declare
697
- `auth: {account: 'required', actor: 'none'}` — no `acting` on input, so
698
- the actor axis stays `'none'` per registry-time invariant 2. IDOR via
699
- `query_session_revoke_for_account` / `query_revoke_api_token_for_account`.
700
- - **Credential-channel gating.** `account_token_create` / `_revoke`,
701
- `account_session_revoke` / `_revoke_all`, and REST `POST /password` all
702
- declare `credential_types: ['session']`. `account_session_revoke` is
703
- gated alongside `_revoke_all` because a leaked bearer can otherwise
704
- compose `account_session_list` + N×revoke to reach the same lockout.
705
- `role_grant_offer_accept` and `self_service_role_set` carry the gate for
706
- the privilege-pivot shape — both move the caller's own authority, and the
707
- resulting grant outlives revoking the token. `role_grant_offer_create`
708
- carries it for the same pivot onto another account (a leaked bearer offers a
709
- role to an account its holder controls); scripted conferral is
710
- `role_grant_assign`'s.
711
- REST `POST /logout` also declares `credential_types: ['session']`, but
712
- for forensic fidelity rather than a threat — a bearer / daemon token
713
- holds no session to end, so the gate refuses it instead of returning a
714
- misleading 200 + a phantom `logout` audit row. `GET /audit/stream` carries
715
- it so the stream stays closable (SSE subscribers are keyed by session
716
- hash, so `token_revoke` could not close a bearer's stream).
717
- Admin token/session revoke specs deliberately stay unrestricted (admin
718
- scripting from CLI/bearer is legitimate operator workflow). See
719
- ../../../docs/security.md §Credential-channel gating.
720
- - **Rate-limit posture.** Admin specs and authed-spam-prone surfaces
721
- (`role_grant_offer_create`, `role_grant_revoke`, `account_token_create`,
722
- `self_service_role_set`, `actor_lookup`, `actor_search`) declare
723
- `rate_limit: 'account'`. Throttle-requests semantics — every invocation
724
- records, regardless of outcome. Default
725
- `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).
726
397
 
727
398
  ### Admin actions
728
399
 
729
400
  `create_admin_actions(deps, options?)` in `auth/admin_actions.ts`.
730
401
 
731
- Three of these — `account_delete` / `account_purge` / `account_undelete` —
732
- carry `account_*` method names (not `admin_`): privilege lives in the auth
733
- spec, not the name, so soft-delete stays self-service-capable. They sit in
734
- the admin factory because their `actor: 'required'` shape + account-management
735
- queries match the rest of this registry (mixed-auth in one factory is
736
- fine — same as `role_grant_revoke`). `account_undelete` is admin-only —
737
- reactivation has no self path because a soft-deleted account can't
738
- authenticate.
739
-
740
- - `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.
741
- - `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.
742
- - `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`).
743
- - `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.
744
- - `admin_session_list_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{sessions}`.
745
- - `admin_session_revoke_all_action_spec` — mutation; input `{account_id}`; output `{ok, count}`.
746
- - `admin_token_revoke_all_action_spec` — mutation; input `{account_id}`; output `{ok, count}`.
747
- - `audit_log_list_action_spec` — read; input `{event_type?, outcome?, account_id?, limit?, offset?, since_seq?}`; output `{events}`.
748
- - `audit_log_role_grant_history_action_spec` — read; input `{limit?, offset?}`; output `{events}`.
749
- - `invite_create_action_spec` — mutation; input `{email?, username?}`; output `{ok, invite}`.
750
- - `invite_list_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{invites}`.
751
- - `invite_delete_action_spec` — mutation; input `{invite_id}`; output `{ok}`.
752
- - `app_settings_get_action_spec` — read; input `{acting?}` (an omitted input reads as `{}`); output `{settings}`.
753
- - `app_settings_update_action_spec` — mutation; input `{open_signup}`; output `{ok, settings}`.
754
-
755
- Constants: `AUDIT_LOG_LIST_LIMIT_MAX = 200`, `ADMIN_ACCOUNT_LIST_DEFAULT_LIMIT = 50`,
756
- `ADMIN_ACCOUNT_LIST_LIMIT_MAX = 200`.
757
-
758
- Error reasons via `error.data.reason`: `ERROR_ACCOUNT_NOT_FOUND` (404 via
759
- `jsonrpc_errors.not_found`) on admin revoke-all + account delete/purge,
760
- `ERROR_INSUFFICIENT_PERMISSIONS` (403) when `account_delete` targets another
761
- account without admin, `ERROR_PURGE_NOT_CONFIRMED` (400) when `account_purge`
762
- omits `confirm: true`, `ERROR_CANNOT_DELETE_KEEPER` (403) when `account_delete` /
763
- `account_purge` targets a keeper-role account (the keeper account is never
764
- API-removable — auth + daemon-token both pivot on it),
765
- `ERROR_CANNOT_DELETE_LAST_ADMIN` (403) when `account_delete` / `account_purge`
766
- targets the sole remaining active admin (soft-deleted admins don't count; the
767
- count locks its rows, so concurrent removals can't both pass), `ERROR_INVITE_ACCOUNT_EXISTS_USERNAME` /
768
- `_EMAIL` / `ERROR_INVITE_DUPLICATE` on invite create, `ERROR_INVITE_NOT_FOUND`
769
- on invite delete (with a failure-audit row). `invite_create` empty input is rejected at the schema by a
770
- `check` and surfaces as `invalid_params` with `error.data.issues` (DEV-only `WireIssue`s).
771
-
772
- Closure state:
773
-
774
- - `grantable_roles` derived once from `options.roles?.role_specs ?? builtin_role_specs`
775
- via `list_roles_with_grant_path(_, GRANT_PATH_ADMIN)`.
776
- - `app_settings_get`/`_update` handlers are always wired and read/write the DB
777
- directly (`query_app_settings_load`/`query_app_settings_update`);
778
- `auth/signup_routes.ts` reads the current value fresh per request. There is no
779
- `options.app_settings` ref.
780
- - `deps.connection_closer` (required, `RevokingActionFactoryDeps`) —
781
- `admin_session_revoke_all` / `admin_token_revoke_all` / `account_delete` /
782
- `account_purge` queue a close of the target account's live connections
783
- (`queue_connection_close`), run after the handler's transaction commits and
784
- dropped if it throws. The close does not depend on the audit write; the
785
- audit listeners repeat it on the announced row. Failure outcomes queue no
786
- close.
787
-
788
- Failure-outcome audit rows: `admin_session_revoke_all` and `_token_revoke_all`
789
- emit an `outcome: 'failure'` row on `ERROR_ACCOUNT_NOT_FOUND` for forensic
790
- visibility — `target_account_id` is null (FK rejects missing ids), and the
791
- probed id is preserved under `metadata.attempted_account_id`. Every gated
792
- 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.
793
426
 
794
427
  ### Role-grant-offer actions
795
428
 
796
429
  `create_role_grant_offer_actions(deps, options?)` in
797
- `auth/role_grant_offer_actions.ts`.
798
-
799
- > **Hazard — admin `role_grant_offer_create` does not auto-accept.** The
800
- > action returns `{offer}` only. Acceptance is a separate
801
- > `role_grant_offer_accept` call; admin-side tests that materialize a
802
- > role_grant drive the full offer + accept RPCs (see
803
- > `testing/admin_integration.ts` §`offer_and_accept`), or skip the consent
804
- > path entirely via `create_test_role_grant_direct` from
805
- > `testing/db_entities.ts` when the test focuses on revoke / isolation
806
- > rather than the grant path itself. The v0.31 CHANGELOG entry was the
807
- > first signal of this two-step flow; consumers reading the standard admin
808
- > suite assume auto-accept and have to redesign their tests when they
809
- > discover otherwise.
810
-
811
- The specs' inputs and outputs are `@fuzdev/fuz_schema` schemas
812
- (`auth/role_grant_offer_action_specs.ts`), every object refusing unknown keys,
813
- `role` a `RoleName`, `scope_kind` a `ScopeKindName`.
814
- The create and assign inputs end in a `check` of `is_grant_scope_paired`
815
- (`GRANT_SCOPE_PAIRED_MESSAGE`), run only on an input whose fields all passed;
816
- the list and history inputs read an omitted input as a fresh `{}`
817
- (`with_default_fn`); history's `offset` is held to `Number.MAX_SAFE_INTEGER`.
818
-
819
- - `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.
820
- - `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.
821
- - `role_grant_offer_decline_action_spec` — input `{offer_id, reason?}`; output `{offer}` (the declined offer, as accept answers its own).
822
- - `role_grant_offer_retract_action_spec` — input `{offer_id}`; output `{offer}` (the retracted offer).
823
- - `role_grant_offer_list_action_spec` — input `{account_id?}`; output `{offers}`.
824
- - `role_grant_offer_history_action_spec` — input `{account_id?, limit?, offset?}`; output `{offers}`.
825
- - `role_grant_revoke_action_spec` — input `{actor_id, role_grant_id, reason?}`; output `{ok, revoked}`.
826
- A global `admin` grant is guarded: the keeper account's is refused
827
- (`ERROR_CANNOT_REVOKE_KEEPER_ADMIN`, 403) and so is one whose revoke would
828
- leave no active admin account (`ERROR_CANNOT_REVOKE_LAST_ADMIN`, 403, under
829
- the locked count `query_count_active_accounts_with_global_role_locked`,
830
- which leaves the revoked grant out — §Row locks). Besides the revokee's
831
- incoming sibling offers, the revoke supersedes every pending offer the
832
- revokee's actor made — the rule `query_revoke_role_grant` holds for every
833
- revoke, the self-service disable's too;
834
- `account_delete` / `account_purge` supersede both directions for the whole
835
- account (`reason: 'account_deleted'`). Every supersede cascade returns —
836
- and audits and notifies — its rows ordered by `created_at, id`; a revoke's
837
- is two such runs, its incoming siblings then its outgoing offers. Who is
838
- told: §WS notifications.
839
- - `role_grant_assign_action_spec` — global-admin-only immediate conferral (no
840
- consent step); input `{to_account_id, to_actor_id?, role, scope_kind?, scope_id?}`
841
- (the pair as on offer-create); output `{ok, role_grant_id}`. The handler:
842
- - re-checks the global admin grant behind the dispatcher gate;
843
- - runs the same admin-grant-path gate as offer-create, and refuses a scoped
844
- `admin` (`invalid_params` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`; a scoped
845
- `keeper` stays 403 `ERROR_ROLE_NOT_WEB_GRANTABLE`, since `keeper` is never
846
- web-grantable);
847
- - runs the consumer's `RoleGrantOfferCreateAuthorize` callback (the offer
848
- policy binds the consent-free path too — a refusal is 403
849
- `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`, failure-audited);
850
- - resolves the target actor (named `to_actor_id` ∈ the account's active
851
- actors, else its sole active actor — multi-actor → `invalid_params`,
852
- actorless → 404);
853
- - writes the `(scope_kind, scope_id)` pair via the idempotent
854
- `query_create_role_grant`, and emits a `role_grant_create` audit row
855
- (metadata carries `scope_kind`, success and failure).
856
-
857
- No WS notification in v1. Reasons: `ERROR_INSUFFICIENT_PERMISSIONS`,
858
- `ERROR_ROLE_NOT_WEB_GRANTABLE`, `ERROR_ROLE_GRANT_BUILTIN_SCOPED`,
859
- `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`,
860
- `ERROR_ROLE_GRANT_OFFER_ACTOR_ACCOUNT_MISMATCH`.
861
-
862
- Every input carries `acting?: ActingActor` (registry-time invariant 2).
863
- `role_grant_revoke` keys on **`actor_id`**, not `account_id` — role_grants
864
- are actor-scoped and deriving actor from account collapses under multi-actor
865
- accounts.
866
-
867
- `role_grant_offer_create` runs the **admin-grantability gate first** (offered
868
- role's `RoleSpec.grant_paths` must include `'admin'`), then the
869
- `RoleGrantOfferCreateAuthorize` callback. **Default `default_authorize`: the
870
- caller must hold a _global_ `admin` grant** — conferral is admin-only, with no
871
- holder-propagation (holding the offered role confers no power to offer it). The
872
- global check (`has_scoped_role(_, ROLE_ADMIN, null)`) stops a scoped `admin`
873
- escalating into global authority over the offer surface. A consumer needing
874
- scope-aware delegation (e.g. a classroom teacher offering within their own
875
- scope) supplies a custom `authorize` callback. The callback receives
876
- `{to_account_id, role, scope_kind, scope_id}` and the request `ctx` (`ctx.db` is
877
- the request transaction, for read-only checks), and also gates
878
- `role_grant_assign`.
879
-
880
- **Builtin roles (`admin` / `keeper`) are global-only**, decided by the spine
881
- ahead of any callback. Offer-create refuses a scoped `admin`
882
- (`invalid_params` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`; `keeper`, scoped or not,
883
- stays 403 `ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE` at the grant-path gate)
884
- and a builtin offered by
885
- a caller without a global `admin` (`ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`), so
886
- a consumer callback only ever sees app roles or a global admin's unscoped
887
- builtin offer. Accept (`query_accept_offer`, the chokepoint where an offer
888
- becomes a grant) refuses a `keeper` offer (`ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE`),
889
- a scoped `admin` offer (`invalid_request` + `ERROR_ROLE_GRANT_BUILTIN_SCOPED`), and a
890
- builtin offer whose grantor no longer holds an active global `admin` on an
891
- active actor of an active account (`ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`,
892
- read under the grantor's account lock) — via
893
- `RoleGrantOfferBuiltinRefusedError` (`refusal: BuiltinOfferRefusal`). Each
894
- refusal leaves the offer pending and is audited as a failed
895
- `role_grant_offer_accept` with `{offer_id, role, scope_id, reason}`. The
896
- grantor re-check is builtin-only: an app-role offer's authority was the
897
- callback's call at create time.
898
-
899
- Error reasons (`as const` literals):
900
-
901
- - `ERROR_ROLE_GRANT_OFFER_SELF_TARGET`
902
- - `ERROR_ROLE_GRANT_OFFER_TERMINAL`
903
- - `ERROR_ROLE_GRANT_OFFER_EXPIRED`
904
- - `ERROR_ROLE_GRANT_OFFER_NOT_FOUND` (404-over-403 IDOR mask)
905
- - `ERROR_ROLE_GRANT_OFFER_ROLE_NOT_GRANTABLE`
906
- - `ERROR_ROLE_GRANT_OFFER_NOT_AUTHORIZED`
907
- - `ERROR_ROLE_GRANT_OFFER_ACTOR_ACCOUNT_MISMATCH` (supplied `to_actor_id` doesn't belong to `to_account_id`)
908
- - `ERROR_ROLE_GRANT_OFFER_ACTOR_MISMATCH` (actor-targeted offer accepted by wrong actor)
909
- - `ERROR_ROLE_GRANT_BUILTIN_SCOPED` (a grant path asked to bind `admin` / `keeper` to a scope)
910
-
911
- Plus re-uses from `http/error_schemas.ts`: `ERROR_ROLE_GRANT_NOT_FOUND`,
912
- `ERROR_ROLE_NOT_WEB_GRANTABLE`, `ERROR_INSUFFICIENT_PERMISSIONS`,
913
- `ERROR_ACCOUNT_NOT_FOUND`. Each spec declares the reason codes its handler
914
- may surface via `spec.error_reasons`; drift is caught per-module by
915
- ../../test/auth/role_grant_offer_actions.error_reasons.test.ts.
916
-
917
- Failure-outcome audits use `emit_create_failure_audit` /
918
- `emit_revoke_failure_audit` so all denial paths land uniform rows; the
919
- admin-role-denied path (pre-IDOR) on `role_grant_revoke` emits no audit,
920
- 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.
921
462
 
922
463
  #### WS notifications
923
464
 
924
- 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):
925
468
 
926
469
  - Create — `role_grant_offer_received` → recipient.
927
470
  - Retract — `role_grant_offer_retracted` → recipient.
@@ -929,247 +472,89 @@ Post-commit via `emit_after_commit` (see `http/CLAUDE.md` §Pending Effects):
929
472
  - Decline — `role_grant_offer_declined` → grantor.
930
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.
931
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).
932
- - Self-service disable — `_supersede` per superseded offer (the caller's incoming siblings and its own outgoing offers), each to its grantor and its recipient, as the admin revoke (the caller's answer lists no offers).
933
-
934
- `queue_supersede_notifications(ctx, offers, reason, audience)` sends them in
935
- the cascade's row order, grantor before recipient; the `SupersedeAudience`
936
- names the `cause_id` each told party gets (a recipient told of its grantor's
937
- removal gets the grantor's actor, never its account id — TSDoc on
938
- `SupersedeAudience`). Their audit rows go through `emit_supersede_audits`
939
- (`auth/role_grant_offer_actions.ts`), shared by both revokes and account
940
- removal, as the Rust twin's.
941
-
942
- Spec module is `auth/role_grant_offer_notifications.ts` —
943
- `RemoteNotificationActionSpec`s with `@fuzdev/fuz_schema` params schemas and
944
- notification builders. `role_grant_revoked`'s params are
945
- `{role_grant_id, role, scope_kind, scope_id, reason}`, the grant's
946
- `scope_kind` and `scope_id` both `null` for a global grant, every key
947
- required. `role_grant_offer_notification_actions` holds the specs as
948
- handler-less actions: `to_ws_actions` (`actions/protocol.ts`) appends them to
949
- the WS action set of an RPC list holding `role_grant_offer_create`, so the WS
950
- endpoint's surface lists them as `remote_notification` methods. The revokee's
951
- notification is `role_grant_revoked`, not the admin action's
952
- `role_grant_revoke`, so the two methods never collide. They never reach
953
- dispatch: an inbound frame for one is answered `method_not_found`. They are not SSE events; `role_grant_offer_notification_specs`
954
- holds them as `EventSpec`s for a consumer that broadcasts them on an SSE
955
- channel of its own. Handlers send through `ctx.notification_sender`
956
- (`actions/CLAUDE.md` §Notification sender) with `queue_offer_notification` /
957
- `queue_supersede_notifications`, each queued post-commit.
958
-
959
- Deps: `RevokingActionFactoryDeps`.
960
- `role_grant_revoke` of a global grant queues a close of the revokee account's
961
- connections gated on the role (`queue_connection_close`, `{kind: 'role'}`),
962
- run after the transaction commits and independent of the audit row's
963
- announcement; the revocation guard repeats it on the announced row. A scoped revoke
964
- closes nothing — a role gate admits on global grants alone.
965
- Target account travels via the send argument, not the payload — `revoked_by`
966
- is deliberately not in the `role_grant_revoked` payload (the revokee doesn't
967
- need to learn the admin's identity).
968
-
969
- Options: `roles?: RoleRegistry` (drives admin-grant-path lookup),
970
- `default_ttl_ms?` (defaults to `ROLE_GRANT_OFFER_DEFAULT_TTL_MS` = 30 days),
971
- `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.
972
487
 
973
488
  ### Account actions — self-service
974
489
 
975
- `create_account_actions(deps, options?)` in `auth/account_actions.ts`.
976
-
977
- - `account_verify_action_spec` — read; input fuz_schema's `void`; output `SessionAccountJson`.
978
- - `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).
979
- - `account_session_revoke_action_spec` — mutation; input `{session_id}`; output `{ok, revoked}`.
980
- - `account_session_revoke_all_action_spec` — mutation; input fuz_schema's `void`; output `{ok, count}`, `count` a non-negative integer.
981
- - `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.
982
- - `account_token_list_action_spec` — read; input fuz_schema's `void`; output `{tokens}`, each a `ClientApiTokenJson`.
983
- - `account_token_revoke_action_spec` — mutation; input `{token_id}`; output `{ok, revoked}`.
984
-
985
- `account_verify` is the credential probe on both spines: it returns
986
- `SessionAccountJson`, and a narrowed token that names it may call it.
987
- `GET /status` answers a narrowed token as the anonymous caller. There is no
988
- REST probe (an nginx `auth_request` gate would need one mounted on both
989
- spines).
990
-
991
- `session_id` validates as `SessionId`, the fuz_schema `Blake3Hash` branded;
992
- `token_id` as `ApiTokenId` (`tok_[A-Za-z0-9_-]{12}`). Every input and output
993
- is a `@fuzdev/fuz_schema` schema.
994
-
995
- Audit events via `deps.audit.emit` with `ip: ctx.client_ip`:
996
- `session_revoke`, `session_revoke_all`, `token_create`, `token_revoke`. Every
997
- gated event also records `credential_type` in metadata (mirrors REST
998
- `password_change`).
999
-
1000
- Options: `max_tokens?: number | null` (defaults to `DEFAULT_MAX_TOKENS`;
1001
- `null` disables). Deps: `RevokingActionFactoryDeps` — `log`, `audit`, and the
1002
- required `connection_closer`. Each revoking handler queues its close
1003
- (`queue_connection_close`: one session, one token, or the account), which runs
1004
- after the handler's transaction commits and is dropped if it throws;
1005
- `account_token_create` queues a token close for each token its cap evicts.
1006
- Failure outcomes (`revoked: false`) queue no close — mirrors the listeners'
1007
- `outcome === 'success'` guard so attacker-guessable ids can't target
1008
- 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.
1009
506
 
1010
507
  ### Standard RPC bundle
1011
508
 
1012
- `create_standard_rpc_actions(deps, options)` in `auth/standard_rpc_actions.ts`
1013
- spreads `create_admin_actions`, `create_role_grant_offer_actions`, and
1014
- `create_account_actions` into a single `Array<RpcAction>` — the canonical
1015
- fuz_app "standard" surface (admin + role-grant-offer + account; the two
1016
- app-settings methods are always wired). Frontend mirror is
1017
- `all_standard_action_specs` in `auth/standard_action_specs.ts`.
1018
-
1019
- Option routing — `roles` is shared between admin + role-grant-offer;
1020
- `default_ttl_ms` + `authorize` → role-grant-offer
1021
- only; `max_tokens` → account only. On `deps`: `connection_closer`
1022
- (required) → admin, account, and role-grant-offer (the role revoke's close).
1023
- The notification sender is on every action's context, not on `deps`.
1024
-
1025
- Pair with `create_app_server`'s `rpc_endpoints` factory form
1026
- `(ctx) => Array<RpcEndpointSpec>` so the combined action list gets
1027
- `ctx.deps`. `create_app_server` auto-mounts the
1028
- endpoint via `create_rpc_endpoint`. To expose the standard surface over
1029
- WebSocket as well, spread `protocol_actions` and the same factory into
1030
- `ws_endpoints` — per-message authorization and rate limiting fire
1031
- identically across HTTP RPC and WS.
1032
-
1033
- Bundling account actions into the "standard" surface is deliberate: the
1034
- admin integration suite exercises `account_token_create` / `_revoke` for
1035
- cross-account isolation, so a consumer wiring the admin surface without
1036
- 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.
1037
515
 
1038
- ### 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).
1039
520
 
1040
- `create_self_service_role_actions(deps, {eligible_roles?, roles?})` in
1041
- `auth/self_service_role_actions.ts`. One static action
1042
- `self_service_role_set({role, enabled})` toggles a global role_grant on the
1043
- caller. Idempotent in both directions (`changed: false` when the post-call
1044
- state already matched). Its input and output are `@fuzdev/fuz_schema`
1045
- `object`s, refusing unknown keys, `role` a `RoleName`.
1046
-
1047
- Audit metadata carries `self_service: true` so admin reviewers can
1048
- distinguish self-toggled role_grants. Eligibility derives from
1049
- `roles.role_specs` by selecting roles with `'self_service' ∈ grant_paths`;
1050
- override via `eligible_roles`. Roles outside the eligible set are rejected
1051
- with `ERROR_ROLE_NOT_SELF_SERVICE_ELIGIBLE`. The eligible set is validated at
1052
- construction (`validate_self_service_eligible_roles`): a builtin role or a name
1053
- outside the `RoleName` grammar throws — self-toggling a builtin would hand any
1054
- account instance-wide authority.
1055
-
1056
- A disable revokes through `query_revoke_role_grant`, so it ends what the admin
1057
- revoke ends: the caller's pending offers of the role and every offer its actor
1058
- made, whatever the role, each audited (`role_grant_offer_supersede`,
1059
- `role_grant_revoked`, the grant as cause) and told to both parties.
1060
-
1061
- Deps are `RevokingActionFactoryDeps`: a disable that revokes queues a close of
1062
- the caller's connections gated on the role (`queue_connection_close`,
1063
- `{kind: 'role'}`), after the commit and independent of the audit write.
1064
-
1065
- Method name is static (`role` lives in input, not method) — per-role
1066
- parameterized methods would break the `satisfies RequestResponseActionSpec`
1067
- codegen invariant.
1068
-
1069
- Bundle **not** included in `create_standard_rpc_actions` — `eligible_roles`
1070
- 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`.
1071
524
 
1072
- ### Actor lookup / actor search
1073
-
1074
- Two opt-in helpers for surfaces that stamp actor ids (bylines, owner
1075
- columns, grantor labels, picker UIs):
1076
-
1077
- - `create_actor_lookup_actions(deps)` — `actor_lookup({ids}) → {actors}`,
1078
- batched id → label resolver. `ACTOR_LOOKUP_IDS_MAX = 50`.
1079
- - `create_actor_search_actions(deps)` — `actor_search({query, scope_ids?, limit?}) → {actors}`,
1080
- prefix search. Default limit `ACTOR_SEARCH_LIMIT_DEFAULT = 20`, cap
1081
- `_MAX = 50`. Non-admin callers must pass `scope_ids` (filtered to actors
1082
- holding active role_grants on those scopes); admin-only when `scope_ids`
1083
- is empty. `ERROR_ACTOR_SEARCH_SCOPE_REQUIRED` on non-admin + empty
1084
- `scope_ids`.
1085
-
1086
- Both: `auth: {account: 'required', actor: 'none'}` + `rate_limit: 'account'`,
1087
- pure reads (no audit, no side effects), their input and output schemas
1088
- `@fuzdev/fuz_schema` `object`s, which refuse unknown keys. `ActorLookupEntryJson` deliberately
1089
- omits `account_id`, `email`, credentials, timestamps, and role state —
1090
- control-plane details, timing-oracle avoidance, separation of concern. LIKE
1091
- wildcards in the user-supplied query are escaped at the JS layer so
1092
- `%xyz`-style inputs can't widen the per-call cap.
525
+ ### Self-service role toggle
1093
526
 
1094
- 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.
1095
536
 
1096
- ### `admin_rpc_adapters.ts` (in `ui/`)
537
+ ### Actor lookup / actor search
1097
538
 
1098
- `create_admin_rpc_adapters(api)` + `provide_admin_rpc_contexts(adapters)` —
1099
- single-call wiring for the four admin RPC contexts (`admin_accounts`,
1100
- `admin_invites`, `audit_log`, `app_settings`). One line at the admin shell
1101
- drops the hand-maintained method-name mappings:
1102
- `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.
1103
547
 
1104
548
  ## Cleanup
1105
549
 
1106
- `auth/cleanup.ts` — twin of the Rust `fuz_auth::auth_cleanup` module.
1107
-
1108
- - `run_auth_cleanup(deps)` — one pass: `cleanup_expired_sessions`, then
1109
- `cleanup_expired_role_grant_offers`; returns `AuthCleanupResult`
1110
- (`{expired_sessions, expired_offers}`, the same shape on both spines).
1111
- Re-throws the first sweep's error. Expired offer rows are preserved (audit
1112
- value for the history view).
1113
- - `start_auth_cleanup(deps, {interval_ms?})` → `{stop}` — the scheduler: a
1114
- pass at once, then one per interval (`DEFAULT_AUTH_CLEANUP_INTERVAL_MS`, ten
1115
- minutes), until `stop()`. `create_app_server`'s `auth_cleanup` option calls
1116
- it with `backend.deps` and chains `stop` into `AppServer.close`. **Off by
1117
- default** there; a production server turns it on, and an in-process test
1118
- harness leaves it off (a background pass deletes rows and writes audit rows
1119
- mid-test).
1120
-
1121
- `AuthCleanupDeps` is `{db, log, audit, connection_closer}`, all required —
1122
- `AppDeps` satisfies it. Tests pass `create_test_audit_emitter()` from
1123
- `testing/stubs.ts` and, where nothing is to be closed, `noop_connection_closer`.
1124
- The sweep belongs in the process that holds the connections: run from another
1125
- process against a live server's database, it deletes the rows that server's
1126
- own pass would have closed for.
1127
-
1128
- **The session sweep closes what it sweeps.** A connection never re-reads its
1129
- session, and once the sweep deletes an expired row `account_session_revoke`
1130
- has nothing left to close for — so `cleanup_expired_sessions` closes each
1131
- swept session's connections itself, by session id
1132
- (`connection_closer.close_connections` with a `session` target), which is why
1133
- `query_session_cleanup_expired` returns the deleted ids. The close repeats
1134
- one already made: every connection closes at its credential's deadline
1135
- (`auth/credential_deadline.ts`) in the process holding it, sweep or no sweep.
1136
- An expired API token's row is not swept; its connections close at their
1137
- deadline (`account_token_revoke` still finds the row).
1138
-
1139
- - The delete runs in its own transaction and the closes follow the commit —
1140
- the rule every revocation close keeps (`actions/CLAUDE.md` §Connection
1141
- closer).
1142
- - A transaction that fails once the delete has answered still closes: the
1143
- sessions are expired either way, the error is thrown after the closes, and
1144
- the next pass deletes the rows the commit left.
1145
- - A closer that throws for one session is logged and the rest still close.
1146
- - No audit row is written for a swept session, so no listener repeats the
1147
- close.
1148
-
1149
- **The schedule** is `start_periodic` (`periodic.ts`, twin of the Rust
1150
- `fuz_sys::periodic::spawn_periodic`), which owns the loop's rules:
1151
- `start_auth_cleanup` is that loop over `run_auth_cleanup` plus the swept-counts
1152
- log. Passes never overlap, and a pass that overruns its interval delays the
1153
- next one (which starts when the slow one ends, the one after a full interval
1154
- later) rather than bursting. A failed pass is logged at `warn` with its error
1155
- and retried on the next interval. The timer is unref'd. An interval that is
1156
- not a positive finite number, or exceeds `PERIODIC_INTERVAL_MS_MAX` (the
1157
- largest delay a timer honors), throws at the call. **Shutdown differs from
1158
- Rust**: its task drops a pass in progress; `stop()` ends the schedule at once
1159
- and its promise resolves when the pass in progress has finished — await it
1160
- before closing the database. The wait has no bound of its own.
1161
-
1162
- **Offer idempotency.** `cleanup_expired_role_grant_offers` runs one transaction:
1163
- `query_role_grant_offer_sweep_expired` claims the expired pending offers not
1164
- yet audited by stamping `role_grant_offer.expire_audited_at` (`UPDATE …
1165
- RETURNING`), and each claimed row's `role_grant_offer_expire` audit row is
1166
- inserted in the same transaction; events fan out via `audit.notify` after the
1167
- commit. Each expiry is audited exactly once — a second run finds nothing, and
1168
- concurrent runs claim disjoint rows (a row another sweep holds blocks on its
1169
- row lock, then fails the re-checked stamp). A failed audit insert rolls the
1170
- stamps back and the next run retries, so the offer sweep can throw. The stamp
1171
- is not a lifecycle state (outside the terminal CHECK and the pending
1172
- predicate) and stays off the wire (`to_role_grant_offer_json` drops it); the
1173
- create upsert's re-offer clears it, so a refreshed offer's own expiry is
1174
- audited too. The `role_grant_offer_expire_sweep` partial index serves the
1175
- 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`).
554
+ `create_app_server`'s `auth_cleanup` is required, an `AuthCleanupSchedule`
555
+ (`{every_ms}` or `'off'`, twin of the Rust `fuz_auth::AuthCleanupSchedule`);
556
+ `AppServer.close` waits for a pass in progress within its drain bound and
557
+ counts one still running at the bound (`ShutdownDrainGivenUp.upkeep`). Run it
558
+ in the process that holds the connections, never from another process
559
+ against a live server's database. The rules are the module TSDoc and `periodic.ts`'s (whose `stop()` differs
560
+ from the Rust shutdown); wiring is ../../../docs/usage.md §Auth cleanup.