@fuzdev/fuz_app 0.182.0 → 0.184.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/actions/CLAUDE.md +535 -1223
- package/dist/actions/action_codegen.d.ts +1 -1
- package/dist/actions/action_codegen.d.ts.map +1 -1
- package/dist/actions/action_codegen.js +3 -2
- package/dist/actions/connection_closer.d.ts +11 -9
- package/dist/actions/connection_closer.d.ts.map +1 -1
- package/dist/actions/connection_closer.js +11 -9
- package/dist/actions/frontend_rpc_client.d.ts +1 -1
- package/dist/actions/register_action_ws.d.ts +14 -1
- package/dist/actions/register_action_ws.d.ts.map +1 -1
- package/dist/actions/register_action_ws.js +2 -1
- package/dist/actions/ws_socket_session.d.ts +9 -1
- package/dist/actions/ws_socket_session.d.ts.map +1 -1
- package/dist/actions/ws_socket_session.js +43 -19
- package/dist/auth/CLAUDE.md +430 -1024
- package/dist/auth/account_queries.d.ts +1 -1
- package/dist/auth/account_queries.js +1 -1
- package/dist/auth/account_routes.d.ts +9 -8
- package/dist/auth/account_routes.d.ts.map +1 -1
- package/dist/auth/account_routes.js +78 -75
- package/dist/auth/admin_actions.d.ts.map +1 -1
- package/dist/auth/admin_actions.js +32 -28
- package/dist/auth/api_token.d.ts +20 -3
- package/dist/auth/api_token.d.ts.map +1 -1
- package/dist/auth/api_token.js +28 -9
- package/dist/auth/api_token_queries.d.ts +2 -2
- package/dist/auth/api_token_queries.js +2 -2
- package/dist/auth/audit_emitter.d.ts +75 -84
- package/dist/auth/audit_emitter.d.ts.map +1 -1
- package/dist/auth/audit_emitter.js +83 -71
- package/dist/auth/audit_log_schema.d.ts +25 -14
- package/dist/auth/audit_log_schema.d.ts.map +1 -1
- package/dist/auth/audit_log_schema.js +23 -8
- package/dist/auth/auth_guard_resolver.d.ts +1 -1
- package/dist/auth/auth_guard_resolver.js +1 -1
- package/dist/auth/bearer_auth.d.ts +2 -5
- package/dist/auth/bearer_auth.d.ts.map +1 -1
- package/dist/auth/bearer_auth.js +4 -13
- package/dist/auth/bootstrap_account.d.ts +42 -26
- package/dist/auth/bootstrap_account.d.ts.map +1 -1
- package/dist/auth/bootstrap_account.js +36 -19
- package/dist/auth/bootstrap_routes.d.ts +20 -21
- package/dist/auth/bootstrap_routes.d.ts.map +1 -1
- package/dist/auth/bootstrap_routes.js +26 -31
- package/dist/auth/bootstrap_token_store.d.ts +3 -4
- package/dist/auth/bootstrap_token_store.d.ts.map +1 -1
- package/dist/auth/bootstrap_token_store.js +1 -1
- package/dist/auth/daemon_token.d.ts +5 -1
- package/dist/auth/daemon_token.d.ts.map +1 -1
- package/dist/auth/daemon_token_middleware.d.ts +12 -8
- package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
- package/dist/auth/daemon_token_middleware.js +15 -21
- package/dist/auth/deps.d.ts +19 -5
- package/dist/auth/deps.d.ts.map +1 -1
- package/dist/auth/deps.js +3 -2
- package/dist/auth/invite_queries.d.ts +51 -3
- package/dist/auth/invite_queries.d.ts.map +1 -1
- package/dist/auth/invite_queries.js +81 -6
- package/dist/auth/invite_schema.d.ts +2 -1
- package/dist/auth/invite_schema.d.ts.map +1 -1
- package/dist/auth/middleware.d.ts +2 -3
- package/dist/auth/middleware.d.ts.map +1 -1
- package/dist/auth/middleware.js +3 -3
- package/dist/auth/request_context.d.ts +3 -3
- package/dist/auth/request_context.js +3 -3
- package/dist/auth/resolved_auth.d.ts +7 -7
- package/dist/auth/resolved_auth.d.ts.map +1 -1
- package/dist/auth/resolved_auth.js +4 -4
- package/dist/auth/role_grant_offer_actions.d.ts +27 -3
- package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
- package/dist/auth/role_grant_offer_actions.js +42 -35
- package/dist/auth/role_grant_offer_queries.d.ts +60 -4
- package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
- package/dist/auth/role_grant_offer_queries.js +79 -5
- package/dist/auth/role_grant_queries.d.ts +3 -52
- package/dist/auth/role_grant_queries.d.ts.map +1 -1
- package/dist/auth/role_grant_queries.js +5 -80
- package/dist/auth/self_service_role_actions.d.ts.map +1 -1
- package/dist/auth/self_service_role_actions.js +11 -22
- package/dist/auth/session_cookie.d.ts +82 -174
- package/dist/auth/session_cookie.d.ts.map +1 -1
- package/dist/auth/session_cookie.js +80 -130
- package/dist/auth/session_middleware.d.ts +8 -17
- package/dist/auth/session_middleware.d.ts.map +1 -1
- package/dist/auth/session_middleware.js +14 -23
- package/dist/auth/session_queries.d.ts +15 -17
- package/dist/auth/session_queries.d.ts.map +1 -1
- package/dist/auth/session_queries.js +28 -20
- package/dist/auth/signup_routes.d.ts.map +1 -1
- package/dist/auth/signup_routes.js +93 -43
- package/dist/db/CLAUDE.md +5 -3
- package/dist/db/sql_columns.d.ts +1 -1
- package/dist/db/sql_columns.js +1 -1
- package/dist/dev/setup.d.ts +3 -1
- package/dist/dev/setup.d.ts.map +1 -1
- package/dist/dev/setup.js +3 -1
- package/dist/http/CLAUDE.md +315 -763
- package/dist/http/db_routes.d.ts +8 -23
- package/dist/http/db_routes.d.ts.map +1 -1
- package/dist/http/db_routes.js +73 -73
- package/dist/http/origin.d.ts +7 -8
- package/dist/http/origin.d.ts.map +1 -1
- package/dist/http/origin.js +7 -8
- package/dist/http/pending_effects.d.ts +118 -6
- package/dist/http/pending_effects.d.ts.map +1 -1
- package/dist/http/pending_effects.js +114 -6
- package/dist/http/route_result.d.ts +1 -1
- package/dist/http/route_spec.d.ts +14 -11
- package/dist/http/route_spec.d.ts.map +1 -1
- package/dist/realtime/sse.d.ts +4 -23
- package/dist/realtime/sse.d.ts.map +1 -1
- package/dist/realtime/sse.js +4 -25
- package/dist/server/app_backend.d.ts +4 -5
- package/dist/server/app_backend.d.ts.map +1 -1
- package/dist/server/app_backend.js +3 -1
- package/dist/server/app_server.d.ts +80 -16
- package/dist/server/app_server.d.ts.map +1 -1
- package/dist/server/app_server.js +113 -31
- package/dist/server/app_server_context.d.ts +1 -2
- package/dist/server/app_server_context.d.ts.map +1 -1
- package/dist/server/env.js +2 -2
- package/dist/testing/CLAUDE.md +265 -796
- package/dist/testing/admin_integration.d.ts +2 -3
- package/dist/testing/admin_integration.d.ts.map +1 -1
- package/dist/testing/admin_integration.js +3 -3
- package/dist/testing/adversarial_404.d.ts +6 -1
- package/dist/testing/adversarial_404.d.ts.map +1 -1
- package/dist/testing/adversarial_404.js +38 -17
- package/dist/testing/app_server.d.ts +23 -148
- package/dist/testing/app_server.d.ts.map +1 -1
- package/dist/testing/app_server.js +53 -131
- package/dist/testing/attack_surface.d.ts +1 -1
- package/dist/testing/attack_surface.d.ts.map +1 -1
- package/dist/testing/audit_completeness.d.ts +2 -3
- package/dist/testing/audit_completeness.d.ts.map +1 -1
- package/dist/testing/audit_completeness.js +1 -1
- package/dist/testing/audit_drift_guard.d.ts +11 -6
- package/dist/testing/audit_drift_guard.d.ts.map +1 -1
- package/dist/testing/audit_drift_guard.js +15 -8
- package/dist/testing/cross_backend/audit_cross_helpers.d.ts +12 -9
- package/dist/testing/cross_backend/audit_cross_helpers.d.ts.map +1 -1
- package/dist/testing/cross_backend/audit_cross_helpers.js +13 -14
- package/dist/testing/cross_backend/capabilities.d.ts +9 -6
- package/dist/testing/cross_backend/capabilities.d.ts.map +1 -1
- package/dist/testing/cross_backend/capabilities.js +11 -7
- package/dist/testing/cross_backend/capability_mounts.d.ts +103 -0
- package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -0
- package/dist/testing/cross_backend/capability_mounts.js +428 -0
- package/dist/testing/cross_backend/cell_moderate.js +2 -2
- package/dist/testing/cross_backend/cell_relations.d.ts.map +1 -1
- package/dist/testing/cross_backend/cell_relations.js +12 -11
- package/dist/testing/cross_backend/conformance_principal.d.ts +54 -0
- package/dist/testing/cross_backend/conformance_principal.d.ts.map +1 -0
- package/dist/testing/cross_backend/conformance_principal.js +283 -0
- package/dist/testing/cross_backend/conformance_table.d.ts +7 -56
- package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
- package/dist/testing/cross_backend/conformance_table.js +6 -274
- package/dist/testing/cross_backend/cookie_attributes.js +1 -1
- package/dist/testing/cross_backend/credential_deadline.d.ts.map +1 -1
- package/dist/testing/cross_backend/credential_deadline.js +2 -0
- package/dist/testing/cross_backend/credential_wire.d.ts +1 -1
- package/dist/testing/cross_backend/credential_wire.d.ts.map +1 -1
- package/dist/testing/cross_backend/db_state_diff.d.ts +72 -0
- package/dist/testing/cross_backend/db_state_diff.d.ts.map +1 -0
- package/dist/testing/cross_backend/db_state_diff.js +444 -0
- package/dist/testing/cross_backend/declared_skips.d.ts +68 -0
- package/dist/testing/cross_backend/declared_skips.d.ts.map +1 -0
- package/dist/testing/cross_backend/declared_skips.js +132 -0
- package/dist/testing/cross_backend/default_backend_configs.d.ts +3 -3
- package/dist/testing/cross_backend/default_spine_surface.d.ts +0 -6
- package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
- package/dist/testing/cross_backend/default_spine_surface.js +4 -9
- package/dist/testing/cross_backend/differential.d.ts +13 -5
- package/dist/testing/cross_backend/differential.d.ts.map +1 -1
- package/dist/testing/cross_backend/differential.js +35 -11
- package/dist/testing/cross_backend/differential_normalize.d.ts +12 -0
- package/dist/testing/cross_backend/differential_normalize.d.ts.map +1 -1
- package/dist/testing/cross_backend/differential_normalize.js +16 -0
- package/dist/testing/cross_backend/full_spine_mount.d.ts +1 -42
- package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
- package/dist/testing/cross_backend/full_spine_mount.js +45 -4
- package/dist/testing/cross_backend/in_process_setup.d.ts +28 -19
- package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
- package/dist/testing/cross_backend/in_process_setup.js +156 -142
- package/dist/testing/cross_backend/login_security.d.ts +12 -0
- package/dist/testing/cross_backend/login_security.d.ts.map +1 -1
- package/dist/testing/cross_backend/login_security.js +21 -4
- package/dist/testing/cross_backend/request_target_conformance_wire.d.ts +0 -2
- package/dist/testing/cross_backend/request_target_conformance_wire.d.ts.map +1 -1
- package/dist/testing/cross_backend/request_target_conformance_wire.js +3 -1
- package/dist/testing/cross_backend/revocation_drivers.d.ts +18 -5
- package/dist/testing/cross_backend/revocation_drivers.d.ts.map +1 -1
- package/dist/testing/cross_backend/revocation_drivers.js +18 -10
- package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts +1 -1
- package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts.map +1 -1
- package/dist/testing/cross_backend/role_grant_offer_lifecycle.d.ts.map +1 -1
- package/dist/testing/cross_backend/role_grant_offer_lifecycle.js +33 -1
- package/dist/testing/cross_backend/role_grant_participation.js +4 -4
- package/dist/testing/cross_backend/rpc_adversarial.js +1 -1
- package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +3 -4
- package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
- package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -2
- package/dist/testing/cross_backend/session_cap.d.ts +2 -2
- package/dist/testing/cross_backend/session_cap.d.ts.map +1 -1
- package/dist/testing/cross_backend/session_cap.js +22 -11
- package/dist/testing/cross_backend/setup.d.ts +32 -2
- package/dist/testing/cross_backend/setup.d.ts.map +1 -1
- package/dist/testing/cross_backend/setup.js +32 -1
- package/dist/testing/cross_backend/spine_suites.d.ts +125 -15
- package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
- package/dist/testing/cross_backend/spine_suites.js +459 -62
- package/dist/testing/cross_backend/spine_surface_constants.d.ts +1 -1
- package/dist/testing/cross_backend/spine_surface_constants.d.ts.map +1 -1
- package/dist/testing/cross_backend/spine_surface_constants.js +1 -0
- package/dist/testing/cross_backend/sse_round_trip.d.ts +9 -1
- package/dist/testing/cross_backend/sse_round_trip.d.ts.map +1 -1
- package/dist/testing/cross_backend/sse_round_trip.js +123 -27
- package/dist/testing/cross_backend/standard.d.ts +2 -3
- package/dist/testing/cross_backend/standard.d.ts.map +1 -1
- package/dist/testing/cross_backend/standard.js +3 -3
- package/dist/testing/cross_backend/testing_backdoor.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_backdoor.js +4 -2
- package/dist/testing/cross_backend/testing_credential_read.d.ts +10 -11
- package/dist/testing/cross_backend/testing_credential_read.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_credential_read.js +12 -12
- package/dist/testing/cross_backend/testing_reset_actions.d.ts +84 -47
- package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_reset_actions.js +95 -63
- package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_server_core.js +2 -3
- package/dist/testing/cross_backend/transport_composition.d.ts +1 -1
- package/dist/testing/cross_backend/transport_composition.d.ts.map +1 -1
- package/dist/testing/cross_backend/transport_composition.js +7 -3
- package/dist/testing/cross_backend/ws_round_trip.d.ts +5 -0
- package/dist/testing/cross_backend/ws_round_trip.d.ts.map +1 -1
- package/dist/testing/cross_backend/ws_round_trip.js +54 -8
- package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
- package/dist/testing/daemon_token_rotation.js +2 -3
- package/dist/testing/data_exposure.d.ts.map +1 -1
- package/dist/testing/data_exposure.js +3 -0
- package/dist/testing/db.d.ts +0 -32
- package/dist/testing/db.d.ts.map +1 -1
- package/dist/testing/db.js +0 -86
- package/dist/testing/db_entities.d.ts +14 -0
- package/dist/testing/db_entities.d.ts.map +1 -1
- package/dist/testing/db_entities.js +17 -0
- package/dist/testing/db_invariant_queries.d.ts +259 -0
- package/dist/testing/db_invariant_queries.d.ts.map +1 -0
- package/dist/testing/db_invariant_queries.js +400 -0
- package/dist/testing/db_invariants.d.ts +106 -0
- package/dist/testing/db_invariants.d.ts.map +1 -0
- package/dist/testing/db_invariants.gen.sql.d.ts +11 -0
- package/dist/testing/db_invariants.gen.sql.d.ts.map +1 -0
- package/dist/testing/db_invariants.gen.sql.js +13 -0
- package/dist/testing/db_invariants.js +141 -0
- package/dist/testing/db_invariants.sql +152 -0
- package/dist/testing/describe_db.d.ts +36 -0
- package/dist/testing/describe_db.d.ts.map +1 -0
- package/dist/testing/describe_db.js +71 -0
- package/dist/testing/integration.d.ts +8 -12
- package/dist/testing/integration.d.ts.map +1 -1
- package/dist/testing/integration.js +13 -17
- package/dist/testing/integration_helpers.d.ts +1 -1
- package/dist/testing/integration_helpers.d.ts.map +1 -1
- package/dist/testing/rate_limiting.d.ts +3 -4
- package/dist/testing/rate_limiting.d.ts.map +1 -1
- package/dist/testing/rate_limiting.js +6 -5
- package/dist/testing/role_grant_helpers.d.ts +1 -1
- package/dist/testing/role_grant_helpers.d.ts.map +1 -1
- package/dist/testing/round_trip.d.ts.map +1 -1
- package/dist/testing/round_trip.js +3 -0
- package/dist/testing/rpc_attack_surface.d.ts +8 -6
- package/dist/testing/rpc_attack_surface.d.ts.map +1 -1
- package/dist/testing/rpc_attack_surface.js +69 -6
- package/dist/testing/rpc_helpers.d.ts +1 -2
- package/dist/testing/rpc_helpers.d.ts.map +1 -1
- package/dist/testing/rpc_helpers.js +3 -3
- package/dist/testing/rpc_round_trip.d.ts +3 -4
- package/dist/testing/rpc_round_trip.d.ts.map +1 -1
- package/dist/testing/rpc_round_trip.js +4 -1
- package/dist/testing/sse_round_trip.d.ts +3 -4
- package/dist/testing/sse_round_trip.d.ts.map +1 -1
- package/dist/testing/sse_round_trip.js +15 -6
- package/dist/testing/stubs.d.ts +9 -8
- package/dist/testing/stubs.d.ts.map +1 -1
- package/dist/testing/stubs.js +20 -13
- package/dist/testing/test_app.d.ts +168 -0
- package/dist/testing/test_app.d.ts.map +1 -0
- package/dist/testing/test_app.js +123 -0
- package/dist/testing/ws_round_trip.d.ts.map +1 -1
- package/dist/testing/ws_round_trip.js +3 -0
- package/dist/ui/ui_format.d.ts.map +1 -1
- package/dist/ui/ui_format.js +1 -2
- package/package.json +1 -1
package/dist/http/CLAUDE.md
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Generic HTTP framework infrastructure — route specs, error schemas, attack
|
|
4
4
|
surface introspection, JSON-RPC envelope + error taxonomy, proxy/origin
|
|
5
|
-
middleware primitives, post-commit effect
|
|
5
|
+
middleware primitives, the post-commit effect queues, generic admin route
|
|
6
|
+
specs.
|
|
6
7
|
|
|
7
8
|
**No auth logic lives in this directory.** Auth middleware, routes, and
|
|
8
9
|
guards live in `auth/` and consume these primitives; the route context names
|
|
@@ -10,856 +11,407 @@ the auth domain's types (`RequestContext`, `ResolvedAuth`) as types only, as
|
|
|
10
11
|
`hono_context.ts` does. Routes and actions in other domains should do the
|
|
11
12
|
same — extend, don't special-case.
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
This file is the home of the route pipeline, the route error map's
|
|
15
|
+
derivation, and the pending and post-commit effects. Design rationale for
|
|
16
|
+
declarative routes and DEV-only validation is in
|
|
17
|
+
../../../docs/architecture.md; per-symbol rules are each module's TSDoc.
|
|
16
18
|
|
|
17
19
|
## Module Map
|
|
18
20
|
|
|
19
|
-
- `http/route_spec.ts` — `RouteSpec` + `apply_route_specs
|
|
21
|
+
- `http/route_spec.ts` — `RouteSpec` + `apply_route_specs` (the validation pipeline, transactions); `define_route`, `define_route_shape` + `attach_route_handler`; `prepare_route_response` + `emit_route_response` (the one place a route result becomes a `Response`); `RouteContext`.
|
|
20
22
|
- `http/route_result.ts` — what a handler returns, all of it data: `route_ok`, `route_fail`, `route_raw`, `route_sse` (`RouteResult`), and `ROUTE_RAW_REFUSED_HEADERS`. Imports nothing from Hono.
|
|
21
|
-
- `http/auth_shape.ts` — canonical `RouteAuth` type
|
|
22
|
-
- `http/error_schemas.ts` — `ERROR_*` constants, the
|
|
23
|
+
- `http/auth_shape.ts` — the canonical `RouteAuth` type, `AuthAxisState`, the per-route predicates (`is_public_auth`, `is_keeper_auth`, …, `needs_actor`), `parse_acting` / `input_schema_declares_acting`, and the registration-time checks `assert_route_auth_invariants` (invariants 1, 3, 4) and `assert_route_auth_acting_biconditional` (invariant 2), both run by `apply_route_specs` and `compile_action_registry` on every spec.
|
|
24
|
+
- `http/error_schemas.ts` — the `ERROR_*` constants (the catalog of codes), the REST error definitions (`rest_error`, `REST_*`), `derive_route_errors`, `to_error_schemas`.
|
|
23
25
|
- `http/route_errors.ts` — the route error map: `RouteErrorMap`, `resolve_route_error_map`, `resolve_app_route_error_maps`, `get_route_error_map`.
|
|
24
|
-
- `http/route_error_check.ts` — `check_route_error
|
|
25
|
-
- `http/dev_route_error_check.ts` — `create_dev_route_error_check
|
|
26
|
-
- `http/dev_set_cookie_check.ts` — `create_dev_set_cookie_check
|
|
27
|
-
- `http/schema_helpers.ts` — shared schema introspection (
|
|
28
|
-
- `http/json_text.ts` — `parse_json_text
|
|
29
|
-
- `http/middleware_spec.ts` — `MiddlewareSpec`
|
|
30
|
-
- `http/body_limit.ts` — `
|
|
31
|
-
- `http/surface.ts` — `AppSurface`, `AppSurfaceSpec`, `generate_app_surface`, diagnostics.
|
|
26
|
+
- `http/route_error_check.ts` — `check_route_error`, the rule the DEV error check and `assert_response_matches_spec` share (`ALWAYS_ACCEPTED_ERRORS`), `is_json_response`, and the hono-free route lookup the test helpers use (`find_mounted_route` and its template readers, matching as Hono's RegExpRouter does). Hono-free and `esm-env`-free.
|
|
27
|
+
- `http/dev_route_error_check.ts` — `create_dev_route_error_check`, the DEV-only outer error check (`null` outside DEV), finding the route with Hono's own router (`create_route_lookup`).
|
|
28
|
+
- `http/dev_set_cookie_check.ts` — `create_dev_set_cookie_check`, the DEV-only outer check that a response leads with the `Set-Cookie` line a middleware recorded (`EXPECTED_FIRST_SET_COOKIE_KEY`). Knows nothing of sessions.
|
|
29
|
+
- `http/schema_helpers.ts` — shared schema introspection (§Schema Helpers).
|
|
30
|
+
- `http/json_text.ts` — `parse_json_text`, JSON read as the Rust spine's `serde_json` reads it (refusing a lone escaped surrogate, an out-of-range number, nesting past `JSON_DEPTH_LIMIT`), and `read_json_body`, the once-per-request body read the authorization phase and input validation share. Every body and frame parse runs it. Hono-free.
|
|
31
|
+
- `http/middleware_spec.ts` — `MiddlewareSpec`, `MiddlewareCarveOut`.
|
|
32
|
+
- `http/body_limit.ts` — `create_body_limit_middleware_spec(max_size)`, the `'*'` body cap `create_app_server` mounts ahead of everything else (absent with `max_body_size: null`): 413 `payload_too_large` past the cap and 400 `invalid_content_length` on an unreadable length, both with `Connection: close`, declared through its hono-free shape (`body_limit_schema.ts`) so every route's error map carries them. The per-runtime behavior and tested floors are its module TSDoc; the threat is ../../../docs/security.md §Body Size Limiting.
|
|
33
|
+
- `http/surface.ts` — `AppSurface`, `AppSurfaceSpec`, `generate_app_surface`, `env_schema_to_surface`, `events_to_surface`, diagnostics.
|
|
32
34
|
- `http/surface_query.ts` — pure filters/groupings over `AppSurface`.
|
|
33
|
-
- `http/proxy.ts` — trusted-proxy middleware
|
|
34
|
-
- `http/client_ip.ts` — `get_client_ip(c)
|
|
35
|
-
- `http/ip_canonical.ts` — RFC 5952 IPv6 canonicalization
|
|
36
|
-
- `http/header_lines.ts` — `get_header_lines(c, name)`: a request header as the lines the client sent
|
|
37
|
-
- `http/request_headers.ts` — the gates' header grammar as pure readers over header lines
|
|
38
|
-
- `http/simple_request.ts` — the 415 gate on every `POST` route (`is_post_content_type_refused`
|
|
39
|
-
- `http/request_target.ts` — the strict
|
|
40
|
-
- `http/origin.ts` — origin allowlist: the strict pattern grammar shared with the Rust spine, typed refusals,
|
|
41
|
-
- `http/
|
|
42
|
-
- `http/
|
|
43
|
-
- `http/
|
|
44
|
-
- `http/
|
|
45
|
-
- `http/
|
|
46
|
-
- `http/
|
|
47
|
-
- `http/
|
|
48
|
-
- `http/
|
|
35
|
+
- `http/proxy.ts` — the trusted-proxy middleware: CIDR parsing, rightmost-first XFF resolution, and the socket peer it read (`CONNECTION_IP_KEY`, what `RouteContext.connection_ip` answers). Pulls `hono/utils/ipaddr`.
|
|
36
|
+
- `http/client_ip.ts` — `get_client_ip(c)`, the resolved IP off the context; split from `proxy.ts` so modules that only read the IP stay hono-free.
|
|
37
|
+
- `http/ip_canonical.ts` — RFC 5952 IPv6 canonicalization, IPv4-mapped collapse, `rate_limit_ip_key` (an IPv6 client's `/64`), and IP parsers with the grammar of Rust's `IpAddr::from_str`. Imports nothing (`src/test/hono_free_modules.test.ts` walks every module's graph).
|
|
38
|
+
- `http/header_lines.ts` — `get_header_lines(c, name)`: a request header as the lines the client sent (Node's raw header list where `@hono/node-server` provides it, else the Fetch value as one line), and `trim_optional_whitespace`. What the credential and gate readers read, so a header sent twice or empty is seen as such.
|
|
39
|
+
- `http/request_headers.ts` — the gates' header grammar as pure readers over header lines: `read_origin`, `read_host`, `read_content_type` (each `absent`, `one` well-formed line, or `refused`) and `is_browser_context`. Twin of the Rust `fuz_http::request_headers`, both held to `testing/cross_backend/request_header_conformance.json`. `src/test/request_reads_census.test.ts` holds every raw request read in `src/lib` to a per-module allowlist.
|
|
40
|
+
- `http/simple_request.ts` — the 415 gate on every `POST` route (`is_post_content_type_refused`): a JSON route takes only `application/json`, a `raw_body` route any well-formed type that isn't CORS-safelisted (../../../docs/security.md §CSRF Protection).
|
|
41
|
+
- `http/request_target.ts` — the strict request-target readers: `read_query_pairs` and `read_path_segment` refuse an escape that doesn't decode (`PercentDecodeError`), never leaving it literal or replacing it; `query_first`, `to_query_record`; the Hono-bound `read_request_query_pairs` / `read_request_route_params` every query and param read goes through; `get_request_path`, the raw path the router matches. Twin of the Rust `fuz_http::request_target`, held to `testing/cross_backend/request_target_conformance.json`.
|
|
42
|
+
- `http/origin.ts` — origin allowlist: the strict pattern grammar shared with the Rust spine, typed refusals, the Origin-only middleware.
|
|
43
|
+
- `http/origin_wildcard.ts` — the wildcard-entry policy: `origin_wildcard_kind`, `origin_wildcard_warning` (the Rust text word for word), `admit_origin_wildcards` (a wildcard boots only with `FUZ_ALLOW_ORIGIN_WILDCARDS=true`; an unbranded matcher is refused).
|
|
44
|
+
- `http/host.ts` — the host gate (DNS rebinding): `is_loopback_host`, `allows_host`, `create_host_gate_middleware_spec` (`'*'`, 403 `forbidden_host`, on by default). Twin of the Rust `fuz_http::host`, pinned by `origin_conformance.json` and `request_header_conformance.json` (../../../docs/security.md §DNS Rebinding (Host Gate)).
|
|
45
|
+
- `http/jsonrpc.ts` — JSON-RPC 2.0 envelope schemas (MCP superset), `JsonrpcErrorCode`.
|
|
46
|
+
- `http/jsonrpc_errors.ts` — `ThrownJsonrpcError`, `jsonrpc_errors` throwers, status mappings, `register_jsonrpc_error_code`.
|
|
47
|
+
- `http/jsonrpc_helpers.ts` — builders, type guards, normalizers, and `classify_jsonrpc_message`, the one envelope classifier both transports run.
|
|
48
|
+
- `http/health_schema.ts` — `HEALTH_PATH` + `HealthResponse`, browser-safe, shared by the health route and `ui/backend_probe.svelte.ts`.
|
|
49
|
+
- `http/common_routes.ts` — health, readiness (`/ready`) and server-status route specs.
|
|
50
|
+
- `http/db_routes.ts` — the keeper-only, allowlisted table browser.
|
|
51
|
+
- `http/pending_effects.ts` — the two effect queues (§Pending Effects): `emit_after_commit`, `dispatch_with_post_commit_rollback`, `transaction_with_post_commit_rollback`, `flush_request_effects` over `flush_pending_effects` + `flush_post_commit_effects`, `RequestTracker` / `AcceptedRequest` (`create_request_tracker`, `create_request_tracker_view`), `RequestEffectsContext`, `EmitAfterCommitContext`, `EffectErrorContext`.
|
|
49
52
|
|
|
50
53
|
## Route Spec System
|
|
51
54
|
|
|
52
55
|
`RouteSpec` (in `http/route_spec.ts`) is the unit of the attack surface —
|
|
53
56
|
routes are **data**, registered with Hono by `apply_route_specs` and
|
|
54
|
-
introspected by `generate_app_surface`.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
- `
|
|
60
|
-
- `
|
|
61
|
-
- `
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
- `mints_credential?: boolean` — the route issues a session cookie while declaring no auth (login, signup, bootstrap); assembly refuses it outside `AUTH_MIDDLEWARE_PATH`, as it does any route whose `auth.account` is not `'none'` (`assert_credential_routes_in_auth_scope` in `auth/middleware.ts`)
|
|
69
|
-
- `reads_credential?: boolean` — the handler reads the resolved account while the route declares no auth gate, answering an anonymous caller itself (account status, the cell-scoped fact read, `create_rpc_endpoint`'s pair, whose dispatcher gates per action); held inside `AUTH_MIDDLEWARE_PATH` by the same assertion. Such a handler reads the account through `get_public_account` (`auth/request_context.ts`), which answers a scope-narrowed token as anonymous — the RPC pair excepted, its dispatcher gating each method
|
|
70
|
-
- `rate_limit?: RateLimitKey` — metadata only (`'ip' | 'account' | 'both'`); auto-derives 429
|
|
71
|
-
- `errors?: ReadonlyArray<RestErrorDef>` — the handler's own error definitions (`rest_error`); joins the route error map beside the derived and middleware ones
|
|
72
|
-
- `jsonrpc?: boolean` — the route answers JSON-RPC envelopes, not REST bodies; set by `create_rpc_endpoint`, read by the DEV error check and `assert_response_matches_spec`
|
|
73
|
-
- `response_headers?: Record<string, string>` — static headers every answer of the route carries once a request reaches it: its own validation and guard refusals, the handler's result of any kind, and the error catch's 500 and 503. Checked at registration by the raw result's header rules, and refusing the names a body or the framing owns (`ROUTE_RAW_REFUSED_HEADERS`, `Content-Type`, `Content-Length`). A result that names one of them itself is refused at the prepare. Listed on `AppSurfaceRoute`. For a header true of every answer — the RPC `GET`'s `Cache-Control: no-store` — not for a success's own (the fact routes' hardening headers stay on the bytes answer)
|
|
74
|
-
- `transaction?: boolean` — declarative transaction wrapping (see below)
|
|
75
|
-
|
|
76
|
-
Every schema field takes a `@fuzdev/fuz_schema` schema (`AnySchema`),
|
|
77
|
-
validated through `parse`, its refusals answered with `to_wire_issues`'s
|
|
78
|
-
`WireIssue`s. A slot holding a value that is no schema throws at registration, naming the route
|
|
79
|
-
and the slot (`assert_validation_schema`) — in an assembled app, surface
|
|
80
|
-
generation (`schema_to_surface`) reads most slots first and throws the same
|
|
81
|
-
refusal; `params`, `query` and an `errors` entry
|
|
82
|
-
may be absent. A `params` or `query` must be an object schema
|
|
83
|
-
under any wrappers (`get_schema_entries`); `apply_route_specs` throws naming
|
|
84
|
-
the route on one that isn't. Input/output naming mirrors SAES `ActionSpec`. Use a strict object for
|
|
85
|
-
inputs — fuz_schema's `object` — the surface diagnostic warns on non-strict
|
|
86
|
-
objects because unknown keys are silently stripped by `strip_object` and
|
|
87
|
-
kept by `loose_object`.
|
|
57
|
+
introspected by `generate_app_surface`. The fields are on the interface's
|
|
58
|
+
TSDoc; the rules a caller misses:
|
|
59
|
+
|
|
60
|
+
- `auth: RouteAuth` — `{account, actor, roles?, credential_types?, required_scope?}`, the same shape as `ActionSpec.auth` (`actions/CLAUDE.md`). `required_scope` is route-only: a `surface:<name>` capability a narrowed api token must admit (an `rpc:<method>` throws at registration; the dispatcher derives that one per action).
|
|
61
|
+
- `mints_credential` (login, signup, bootstrap) and `reads_credential` (a handler that reads the account behind no auth gate, through `get_public_account`) — assembly refuses either outside `AUTH_MIDDLEWARE_PATH`, as it does any route whose `auth.account` isn't `'none'` (`assert_credential_routes_in_auth_scope`).
|
|
62
|
+
- `input` is `literal(null)` for no body and on every `GET` (any other throws). `raw_body` routes take the body as a stream (`route.request`).
|
|
63
|
+
- `response_headers` are static headers on every answer the route gives once a request reaches it — its refusals, the handler's result, the error catch's — never a name the body or framing owns.
|
|
64
|
+
- `rate_limit` is metadata that derives the 429; the limiter itself is wired in the handler.
|
|
65
|
+
|
|
66
|
+
Every schema slot takes a `@fuzdev/fuz_schema` schema; a slot holding none
|
|
67
|
+
throws at registration naming the route and slot (`assert_validation_schema`),
|
|
68
|
+
and a `params` or `query` must be an object schema. Use a strict `object` for
|
|
69
|
+
inputs — the surface warns on `strip_object` / `loose_object`. Input/output
|
|
70
|
+
naming mirrors SAES `ActionSpec`.
|
|
88
71
|
|
|
89
72
|
### Handlers and results
|
|
90
73
|
|
|
91
|
-
A handler returns a result — data, never
|
|
92
|
-
the response in two steps around the commit
|
|
93
|
-
inside any wrapping transaction and checks
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
- `
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
refused, rolled back by a failed commit, or asked for by `HEAD`.
|
|
126
|
-
- `route_sse(stream)` — an event stream the handler opened with
|
|
127
|
-
`route.open_sse(options)`, so it exists before the handler admits it to a
|
|
128
|
-
registry. Opening writes nothing on the context: the response is built at
|
|
129
|
-
the emit with `SSE_RESPONSE_HEADERS`, and a stream the route opened and
|
|
130
|
-
did not answer with (another result, a throw) is closed. A stream another
|
|
131
|
-
request opened is refused.
|
|
132
|
-
|
|
133
|
-
**`HEAD`.** Hono serves `HEAD` by running the `GET` handler and dropping the
|
|
134
|
-
body unread, so the spine releases what a stream holds: the emit cancels a
|
|
135
|
-
raw stream body and closes an SSE stream (its `on_close` listeners run, its
|
|
136
|
-
registry drops it), then answers the prepared status and headers with no
|
|
137
|
-
body — an SSE answer without its `Connection: keep-alive`, so the
|
|
138
|
-
connection can end. A handler has no `HEAD` branch to write.
|
|
139
|
-
|
|
140
|
-
A response that can't be built after the commit — the runtime refusing what
|
|
141
|
-
the prepare let through — is logged naming the route and answered by the
|
|
142
|
-
error catch's 500; the work stays committed. A handler holds no Hono
|
|
143
|
-
context, so it writes nothing on one: what a response carries is the
|
|
144
|
-
result, the spec's `response_headers`, and what middleware prepared
|
|
145
|
-
(`src/test/route_modules_hono_free.test.ts` holds every module that defines
|
|
146
|
-
a route to importing nothing from Hono and building no `Response`). A failure is plain data
|
|
147
|
-
(`ok: false`), so domain code and shared helpers fail without the context and
|
|
148
|
-
a handler forwards one (`if (!result.ok) return result`). A thrown error is
|
|
149
|
-
still the error catch's.
|
|
150
|
-
|
|
151
|
-
A spec is made by `define_route(spec)`, or by `attach_route_handler(shape,
|
|
152
|
-
handler)` over a `define_route_shape(shape)` — the split the hono-free
|
|
153
|
-
`*_route_schema.ts` shapes use. Each checks the handler at the definition
|
|
154
|
-
(`TypedRouteHandler`): `route_ok`'s value against the input side of `output`
|
|
155
|
-
(made readonly at every depth, `ReadonlyJson`, so `route_ok` keeps literals as
|
|
156
|
-
written), and each `route_fail` against what the route allows — its `errors`,
|
|
157
|
-
the derived codes a handler may itself give (`RouteHandlerDerivedErrors`: the
|
|
158
|
-
401 and the auth 403s its `auth` derives, the 429 of a `rate_limit`), and the
|
|
159
|
-
catch layers' 500 `internal_error` and 503 `service_unavailable`
|
|
160
|
-
(`RouteAlwaysErrors`). A failure is allowed when an allowed definition at the
|
|
161
|
-
same status and code accepts its body, so the bare 401 passes where
|
|
162
|
-
`REST_AUTHENTICATION_REQUIRED_BOOTSTRAP` is declared, and the reverse. An
|
|
163
|
-
`errors` list typed `Array<RestErrorDef>` is refused (`KnownRouteErrors`).
|
|
164
|
-
`RouteSpec` carries a phantom brand, in the types only, that just these two
|
|
165
|
-
mint, so a spec literal doesn't typecheck; a spread of a spec keeps the brand
|
|
166
|
-
and is not checked again (the DEV error check covers a rewritten `auth` or
|
|
167
|
-
`errors`). At runtime they return the spec, or the shape with its handler.
|
|
74
|
+
A handler takes the route context alone and returns a result — data, never
|
|
75
|
+
a `Response`. The spine builds the response in two steps around the commit:
|
|
76
|
+
`prepare_route_response` runs inside any wrapping transaction and checks
|
|
77
|
+
everything that could fail (a bare `Response`, a result no factory made, a
|
|
78
|
+
body `JSON.stringify` refuses, a raw result breaking its rules), so a bad
|
|
79
|
+
result throws, rolls back, and discards the post-commit effects;
|
|
80
|
+
`emit_route_response` runs after the commit, through the context, so its
|
|
81
|
+
prepared headers — the clearing `Set-Cookie` for an invalid session cookie —
|
|
82
|
+
are on every response. Nothing a handler returned reaches the wire for work
|
|
83
|
+
that didn't commit: a login whose commit fails answers its 500 with no cookie.
|
|
84
|
+
|
|
85
|
+
- `route_ok(value, {set_cookie?})` — JSON at 200; `set_cookie` lines follow the context's.
|
|
86
|
+
- `route_fail(def, fields?)` — `{error: def.code, ...fields}` at `def.status`, with the headers `def` derives (`Retry-After`). A failure is plain data, so domain code fails without the context and a handler forwards one (`if (!result.ok) return result`).
|
|
87
|
+
- `route_raw({status, headers?, body?})` — an answer the route spells itself (empty, text, bytes, a stream, a JSON-RPC envelope). The prepare refuses what wouldn't send as written; the rules are `route_raw`'s TSDoc. The one a caller must honor: a stream body's `cancel` releases its source, since the spine cancels a stream it doesn't send (refused, rolled back, or a `HEAD`).
|
|
88
|
+
- `route_sse(stream)` — a stream opened with `route.open_sse(options)`, so it exists before the handler admits it to a registry; one the route opened and didn't answer with is closed.
|
|
89
|
+
|
|
90
|
+
**`HEAD`** runs the `GET` handler; the emit cancels a raw stream body or
|
|
91
|
+
closes an SSE stream and answers status and headers alone. A handler has no
|
|
92
|
+
`HEAD` branch to write.
|
|
93
|
+
|
|
94
|
+
A response that can't be built after the commit is logged naming the route
|
|
95
|
+
and answered by the error catch's 500; the work stays committed. A thrown
|
|
96
|
+
error is still the error catch's. `src/test/route_modules_hono_free.test.ts`
|
|
97
|
+
holds every route-defining module to importing nothing from Hono and building
|
|
98
|
+
no `Response`.
|
|
99
|
+
|
|
100
|
+
A spec is minted by `define_route(spec)` or `attach_route_handler(shape,
|
|
101
|
+
handler)` over `define_route_shape(shape)` (the split the hono-free
|
|
102
|
+
`*_route_schema.ts` shapes use). Both type the handler against the route
|
|
103
|
+
(`TypedRouteHandler`): `route_ok`'s value against `output`, each `route_fail`
|
|
104
|
+
against what the route allows (its `errors`, the 401/403s its `auth` derives,
|
|
105
|
+
the 429 of a `rate_limit`, and the catch layers' 500 and 503). `RouteSpec`
|
|
106
|
+
carries a phantom brand only these mint, so a spec literal doesn't typecheck;
|
|
107
|
+
a spread keeps the brand unchecked (the DEV error check covers it).
|
|
168
108
|
|
|
169
109
|
### `RouteContext` — what a handler gets
|
|
170
110
|
|
|
171
111
|
The handler's one argument, built by `apply_route_specs` from the Hono
|
|
172
|
-
context
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
query: TQuery; // validated query; undefined without a `query` schema
|
|
189
|
-
has_test_context_preset: boolean; // a harness pre-built `auth`; never in production
|
|
190
|
-
request: Request; // the raw request: a `raw_body` stream, the undecoded URL
|
|
191
|
-
query_pairs: QueryPairsRead; // the query decoded strictly, or why it doesn't decode; a key read with `query_first(pairs, key)`
|
|
192
|
-
read_json_body: () => Promise<JsonBodyResult>; // the once-per-request JSON read
|
|
193
|
-
header_lines: (name: string) => Array<string>; // a header as the lines sent
|
|
194
|
-
close_connection: () => void; // answer with `Connection: close`
|
|
195
|
-
open_sse: <T = unknown>(options?: RouteOpenSseOptions) => SseStream<T>; // the stream a `route_sse` answers with
|
|
196
|
-
}
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
- **Typed from the spec.** `define_route` and `attach_route_handler` type
|
|
200
|
-
`input`, `params` and `query` from the route's schemas (`TypedRouteContext`),
|
|
201
|
-
so `route.params.x` on a route with no `params` is a type error, and
|
|
202
|
-
`auth` from the route's `auth` through `RequestContextForAuth`
|
|
203
|
-
(`auth/request_context.ts`) — the one conditional `rpc_action`'s
|
|
204
|
-
`HandlerForSpec` also narrows by: an actor-required route gets a
|
|
205
|
-
`RequestActorContext`, an account-required one a `RequestContext`,
|
|
206
|
-
anything else `RequestContext | null`. A handler of a required tier is
|
|
207
|
-
wrapped where it is defined and throws rather than run without the
|
|
208
|
-
context its type promises (a spread spec whose `auth` was loosened
|
|
209
|
-
answers 500, not a handler running on `null`).
|
|
210
|
-
- **`route.credential`** is the whole resolved credential. A
|
|
211
|
-
`reads_credential` route never reads the account off it: it calls
|
|
212
|
-
`get_public_account(route)` (`auth/request_context.ts`), which answers
|
|
213
|
-
a scope-narrowed API token as the anonymous caller
|
|
214
|
-
(`src/test/auth/token_scope_surface_census.test.ts` holds every route
|
|
215
|
-
module to that).
|
|
216
|
-
- **`route.connection_ip`** is the TCP peer, never a forwarded address, and
|
|
217
|
-
not normalized (`::ffff:127.0.0.1` stays that) — for a route that admits
|
|
218
|
-
loopback callers only. `null` when the trusted-proxy middleware isn't
|
|
219
|
-
mounted.
|
|
220
|
-
- **Reading the request.** `query_pairs` is the query string read by
|
|
221
|
-
`read_query_pairs` (`http/request_target.ts`): every pair percent-decoded,
|
|
222
|
-
or the reason it doesn't decode — a handler that reads an undeclared key
|
|
223
|
-
refuses an undecodable query in its own shape (the RPC `GET` its envelope)
|
|
224
|
-
and reads a key with `query_first(pairs, key)` — first occurrence, `''`
|
|
225
|
-
for a key with no value, the cross-implementation contract the
|
|
226
|
-
`query_shape` suite pins;
|
|
227
|
-
`read_json_body()` shares the one body read with the authorization phase
|
|
228
|
-
and input validation; `request` is the raw `Request`, whose body is
|
|
229
|
-
already used on a route the pipeline read a JSON input for.
|
|
230
|
-
- **`route.close_connection()`** makes the spine answer with
|
|
231
|
-
`Connection: close` whatever the result, the error catch's answer
|
|
232
|
-
included, so the runtime drops a connection whose request body nothing
|
|
233
|
-
will read. A raw result can't carry the header itself, and an SSE answer
|
|
234
|
-
after it is refused.
|
|
235
|
-
- **`route.db`** — handler's main DB work. Wrapped in a transaction when `transaction: true` (default for non-GET); routes that opt out (`transaction: false`, e.g. signup / bootstrap) get the pool here directly and may call `route.db.transaction(...)` for their own scope.
|
|
236
|
-
- **`route.pending_effects`** — direct push for eager fire-and-forget pool writes (audit, api-token usage tracking).
|
|
237
|
-
- **`route.post_commit_effects`** — do not push directly; reach for `emit_after_commit` from `http/pending_effects.ts`. The helper pushes a thunk that the flush middleware invokes after the handler returns, closing the microtask-ordering window that an eager `Promise.resolve().then(fn)` leaves open inside the wrapping `db.transaction`.
|
|
238
|
-
- **`route.open_sse(options)`** — opens the event stream the route answers with (`route_sse(stream)`) through the opener `apply_route_specs` was given (`create_sse_stream`, wired by `create_app_server`). It writes nothing on the context; a stream not answered with is closed. Without an opener it throws.
|
|
239
|
-
|
|
240
|
-
Middleware, the authorization phase and the WebSocket upgrade still run on
|
|
241
|
-
the Hono context and read it through their own helpers (`get_client_ip(c)`,
|
|
112
|
+
context; the fields are the interface's TSDoc. Shared with `ActionContext`
|
|
113
|
+
(same names and types): `auth`, `client_ip`, `signal`, `db`,
|
|
114
|
+
`pending_effects`, `post_commit_effects`. REST's own: `credential`,
|
|
115
|
+
`connection_ip`, `input`, `params`, `query`, `has_test_context_preset`,
|
|
116
|
+
`request`, `query_pairs`, `read_json_body`, `header_lines`,
|
|
117
|
+
`close_connection`, `open_sse`.
|
|
118
|
+
|
|
119
|
+
- **Typed from the spec.** `define_route` types `input`, `params` and `query` from the route's schemas, and `auth` through `RequestContextForAuth` (`auth/request_context.ts`, the conditional `rpc_action` also narrows by). A handler of a required tier throws rather than run without the context its type promises.
|
|
120
|
+
- **`route.credential`** is the whole resolved credential. A `reads_credential` route reads the account through `get_public_account(route)`, which answers a scope-narrowed token as anonymous (`src/test/auth/token_scope_surface_census.test.ts`).
|
|
121
|
+
- **`route.connection_ip`** is the TCP peer, never forwarded and not normalized — for loopback-only routes; `null` without the trusted-proxy middleware.
|
|
122
|
+
- **`route.query_pairs`** is the strictly decoded query or why it doesn't decode; read a key with `query_first(pairs, key)` (first occurrence wins). `request`'s body is already consumed on a route the pipeline read JSON input for.
|
|
123
|
+
- **`route.close_connection()`** answers with `Connection: close` whatever the result, so the runtime drops a connection whose body nothing will read.
|
|
124
|
+
- **`route.db`** is the transaction when `transaction: true`, the pool otherwise; a `transaction: false` handler opens its own scope (§Pending Effects for the wrapper it must use).
|
|
125
|
+
|
|
126
|
+
Middleware, the authorization phase and the WebSocket upgrade run on the
|
|
127
|
+
Hono context and read it through their own helpers (`get_client_ip(c)`,
|
|
242
128
|
`get_resolved_auth(c)`, `get_header_lines(c, name)`).
|
|
243
129
|
|
|
244
|
-
Audit rows
|
|
245
|
-
`
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
lands even when the handler's transaction rolls back.
|
|
130
|
+
Audit rows go through the bound `AppDeps.audit`:
|
|
131
|
+
`await deps.audit.emit(route, input)` writes a success row in the
|
|
132
|
+
transaction of its change (refused when none is open) and a failure row on
|
|
133
|
+
the pool; `auth/CLAUDE.md` §Audit emitter.
|
|
249
134
|
|
|
250
135
|
### Declarative transactions
|
|
251
136
|
|
|
252
|
-
`RouteSpec.transaction` defaults
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
- All mutations (POST, PUT, DELETE, PATCH) → `true`
|
|
256
|
-
|
|
257
|
-
Override explicitly when a mutation route must manage its own transactions
|
|
258
|
-
(e.g. signup, which does a multi-step flow that can't live inside a single
|
|
259
|
-
wrapper). See `auth/signup_routes.ts`.
|
|
137
|
+
`RouteSpec.transaction` defaults to `false` on `GET` and `true` on every
|
|
138
|
+
mutation. Override it when a mutation manages its own transactions (login,
|
|
139
|
+
password, signup, bootstrap — see `auth/signup_routes.ts`).
|
|
260
140
|
|
|
261
141
|
### Validation pipeline (per-route middleware order)
|
|
262
142
|
|
|
263
|
-
`apply_route_specs(app, specs, resolve_auth_guards, log, db, {authorize?, open_sse?})`
|
|
264
|
-
|
|
265
|
-
`
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
Params and query still validate first: they are part of addressing the route,
|
|
288
|
-
not of its payload, and the authorization phase reads `acting` off the query on
|
|
289
|
-
GETs.
|
|
143
|
+
`apply_route_specs(app, specs, resolve_auth_guards, log, db, {authorize?, open_sse?})`
|
|
144
|
+
assembles this chain per spec, behind one stage that writes the spec's
|
|
145
|
+
`response_headers` on the context:
|
|
146
|
+
|
|
147
|
+
0. **Content type** — every `POST`: 415 `unsupported_content_type` before any credential or body read (`http/simple_request.ts`).
|
|
148
|
+
1. **Params** — decoded strictly from the raw target (`read_request_route_params`), then `spec.params`; 400 `invalid_route_params` (with `issues` on a schema failure).
|
|
149
|
+
2. **Query** — decoded strictly (`read_request_query_pairs`), then `spec.query`; 400 `invalid_query_params`.
|
|
150
|
+
3. **Pre-authorization guards** — the gates that read only what the auth middleware set, coarse to fine: `require_auth` (401) when the account or actor is required; `require_credential_types` (403 `credential_type_required`); `require_token_scope` (403 `token_scope_required`). Before any body parse, so a refused caller learns no route shape, and before actor resolution, so a wrong channel costs no DB work. The `AuthGuardResolver` (`fuz_auth_guard_resolver`) returns them as `pre_authorization`.
|
|
151
|
+
4. **Authorization phase** — when `auth.actor !== 'none'`, resolves the acting actor against the credential's account plus the `acting` selector (query on `GET`, raw body on mutations, since body validation comes later) and builds the `RequestContext`; an account-only context when only the account is declared. Refusals: 400 `actor_required` (with `available`) / `actor_not_on_account`, 500 `no_actors_on_account`, 401 when the account was removed after the credential leg read it. Public routes skip it.
|
|
152
|
+
5. **Post-authorization guards** — `require_role` (403 `insufficient_permissions`), the one gate that reads the context step 4 built; multi-role specs admit any-of.
|
|
153
|
+
6. **Input validation** — `read_json_body` + `spec.input`; 400 `invalid_json_body` or `invalid_request_body` (`issues` as `WireIssue`s, DEV only). Skipped on a null input.
|
|
154
|
+
7. **Handler** — in a transaction when the spec says so; its result prepared inside it and emitted after the commit.
|
|
155
|
+
8. **Error catch** — a thrown `ThrownJsonrpcError` (recognized by `to_thrown_jsonrpc_error`) → its HTTP status and the flat REST body `{error: <reason>, message?, ...data}`, the reason from `err.data.reason` or the code's name; anything else → 500 `internal_error` (message in DEV only). The JSON-RPC dispatcher keeps its own envelope on the RPC mount.
|
|
156
|
+
9. **DEV-only output validation** — a 2xx JSON body against `spec.output`.
|
|
157
|
+
|
|
158
|
+
**Ordering: 401 → authz → 403 → 400 → handler**, the RPC dispatcher's order
|
|
159
|
+
(`actions/action_rpc.ts`) and the Rust spine's, except that the dispatcher
|
|
160
|
+
adds its per-action 429 between 403 and 400. Within the 403s the two
|
|
161
|
+
differ: REST runs its credential-type and token-scope gates ahead of the
|
|
162
|
+
authorization phase (step 3), while the dispatcher (`actions/perform_action.ts`)
|
|
163
|
+
runs them after it, beside the role gate. Body validation runs last so a
|
|
164
|
+
caller the authority gates refuse learns nothing of the input shape; params
|
|
165
|
+
and query validate first because they address the route, and the
|
|
166
|
+
authorization phase reads `acting` off the query on `GET`.
|
|
290
167
|
|
|
291
168
|
Duplicate `method path` pairs throw at registration.
|
|
292
169
|
|
|
293
|
-
A handler reads the validated values as `route.input`, `route.params` and
|
|
294
|
-
`route.query`, typed from the spec's schemas.
|
|
295
|
-
|
|
296
170
|
### DEV-only output + error validation
|
|
297
171
|
|
|
298
|
-
|
|
299
|
-
|
|
172
|
+
Inputs are validated unconditionally; outputs and errors under `DEV`
|
|
173
|
+
(`esm-env`) only, each at one mount:
|
|
300
174
|
|
|
301
|
-
**Output
|
|
302
|
-
`
|
|
175
|
+
- **Output** — `wrap_output_validation`, per route: a 2xx JSON body against `spec.output`.
|
|
176
|
+
- **Errors** — `create_dev_route_error_check`, mounted outermost by `create_app_server`, so it sees every layer's refusal; checks a JSON body at 400+ against the route's error map (`check_route_error`). A 500 `internal_error` and a 503 `service_unavailable` are always accepted; a JSON-RPC envelope on a `jsonrpc` route, non-JSON responses, and requests no route matches are skipped.
|
|
177
|
+
- **The first `Set-Cookie`** — `create_dev_set_cookie_check`, beside it, reaching what the route system doesn't build (a consumer middleware, a raw Hono route).
|
|
303
178
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
- **Logs on mismatch, returns the response unchanged** — never throws (a throw inside the error check, its logger's included, is swallowed), never mutates the body
|
|
308
|
-
|
|
309
|
-
Production short-circuits: `wrap_output_validation` returns the handler
|
|
310
|
-
unwrapped and `create_dev_route_error_check` returns `null`, so nothing is
|
|
311
|
-
mounted — no parse work on the hot path. Uniform across all three
|
|
312
|
-
action-handler surfaces (REST, RPC, WS); see ../../../docs/architecture.md
|
|
313
|
-
§DEV-only Output Validation.
|
|
179
|
+
Each logs a mismatch and returns the response unchanged, never throwing.
|
|
180
|
+
Production mounts none of them. Rationale and the action-side check:
|
|
181
|
+
../../../docs/architecture.md §DEV-only Output Validation.
|
|
314
182
|
|
|
315
183
|
### Helpers
|
|
316
184
|
|
|
317
|
-
- `apply_middleware_specs(app, specs)` — registers middleware specs
|
|
318
|
-
- `prefix_route_specs(prefix, specs)` — prepends a path prefix
|
|
185
|
+
- `apply_middleware_specs(app, specs)` — registers middleware specs by `{name, path, handler}`
|
|
186
|
+
- `prefix_route_specs(prefix, specs)` — prepends a path prefix; `/` collapses to the bare prefix
|
|
319
187
|
|
|
320
188
|
## Error Schemas
|
|
321
189
|
|
|
322
|
-
`http/error_schemas.ts` is the
|
|
323
|
-
|
|
324
|
-
- `ERROR_*` `snake_case` string constants (`ERROR_FORBIDDEN_HOST` / `REST_FORBIDDEN_HOST` the host gate's) — single source of truth for codes; they double as JSON-RPC `data.reason`s, so they carry no HTTP status
|
|
325
|
-
- `rest_error(status, code, fields?, headers?)` → `RestErrorDef<S, C, F>` — one code at one status; the code must be a code, `REST_ERROR_CODE_PATTERN` (`^[a-z][a-z0-9_]*$`, `is_rest_error_code`) — a throw at definition, and a literal plainly off it (prose, uppercase, a leading digit) a type error — so prose goes in `message`; its body `loose_object({error: literal(code), ...fields})` as `.schema`; `headers` derives response headers from a body (`Retry-After`). Status and code must be literals. One `REST_*` definition per code a route or middleware answers (`REST_TABLE_NOT_FOUND`, `REST_RATE_LIMIT_EXCEEDED`, …); a code with a second body shape gets a second definition (`REST_AUTHENTICATION_REQUIRED_BOOTSTRAP`, `/account/status`'s 401 with `bootstrap_available`)
|
|
326
|
-
- `to_error_schemas(defs)` — a status map from definitions: one schema at a status maps to it, more to a `union` in list order
|
|
327
|
-
- `ErrorSchemas = Record<number, AnySchema>` — a status map, what `to_error_schemas` groups definitions into: one schema at a status, or a `union` of them
|
|
328
|
-
- `same_rest_error(a, b)` / `dedupe_rest_errors(defs)` — a definition is the same as another when it is the same object, or the same status, code, `headers`, and field schemas; a list keeps the first of each
|
|
329
|
-
- `RateLimitKey` (`rate_limiter.ts`) — `'ip' | 'account' | 'both'`
|
|
330
|
-
|
|
331
|
-
`RouteSpec.errors` and `MiddlewareSpec.errors` are lists of definitions
|
|
332
|
-
(`ReadonlyArray<RestErrorDef>`), so a bare schema is impossible by type, and
|
|
333
|
-
`apply_route_specs` refuses anything else at registration.
|
|
190
|
+
`http/error_schemas.ts` is the declarative error surface:
|
|
334
191
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
`
|
|
339
|
-
`required_credential_types`, `retry_after`, `message`) are diagnostic.
|
|
192
|
+
- `ERROR_*` — `snake_case` code constants, the catalog of every code; they double as JSON-RPC `data.reason`s, so they carry no status.
|
|
193
|
+
- `rest_error(status, code, fields?, headers?)` → `RestErrorDef` — one code at one status. The code must match `REST_ERROR_CODE_PATTERN` (`^[a-z][a-z0-9_]*$`), a throw at definition and a type error for a plainly-off literal, so prose goes in `message`. The body is `loose_object({error: literal(code), ...fields})` (`.schema`); `headers` derives response headers from a body. One `REST_*` per code; a code with a second body shape gets a second definition (`REST_AUTHENTICATION_REQUIRED_BOOTSTRAP`).
|
|
194
|
+
- `to_error_schemas(defs)` — a status map (`ErrorSchemas`), a `union` where a status has several.
|
|
195
|
+
- `same_rest_error` / `dedupe_rest_errors` — identity by object, or by status, code, `headers` and field schemas.
|
|
340
196
|
|
|
341
|
-
|
|
197
|
+
`RouteSpec.errors` and `MiddlewareSpec.errors` are lists of definitions, so a
|
|
198
|
+
bare schema is impossible by type and refused at registration. Every body is
|
|
199
|
+
a loose object: several producers can answer one status with different extra
|
|
200
|
+
fields, and a thrown error flattens its `data` into the body. The `error` code
|
|
201
|
+
is the contract; extra keys are diagnostic.
|
|
342
202
|
|
|
343
203
|
### The route error map
|
|
344
204
|
|
|
345
|
-
A route's declared errors are **one map**,
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
(`
|
|
351
|
-
are both kept, a union of their bodies. The result, `RouteErrorMap`, holds the
|
|
352
|
-
definitions (`defs`) and the status map they group into (`schemas`):
|
|
205
|
+
A route's declared errors are **one map**, `resolve_route_error_map(spec,
|
|
206
|
+
middleware_specs?)` (`http/route_errors.ts`): the union of three layers in
|
|
207
|
+
order, where nothing replaces anything — a definition at a status another
|
|
208
|
+
layer declares is one more branch there, a repeat counts once, and two shapes
|
|
209
|
+
of one code at one status are both kept. `RouteErrorMap` holds the
|
|
210
|
+
definitions (`defs`) and the status map they group into (`schemas`).
|
|
353
211
|
|
|
354
212
|
1. **Derived** — `derive_route_errors({method, auth, has_input?, has_params?, has_query?, rate_limit?})`, narrowed to the slots the route has:
|
|
355
|
-
- a body
|
|
213
|
+
- a body (input not null, not `GET`) → 400 `invalid_request_body`, `invalid_json_body`
|
|
356
214
|
- `params` → 400 `invalid_route_params`; `query` → 400 `invalid_query_params`
|
|
357
|
-
- `auth.actor !== 'none'` → 400 `actor_required`, `actor_not_on_account`, 500 `no_actors_on_account`, 401 `authentication_required` (
|
|
358
|
-
-
|
|
359
|
-
- `
|
|
360
|
-
- `rate_limit` → 429 `rate_limit_exceeded`
|
|
215
|
+
- `auth.actor !== 'none'` → 400 `actor_required`, `actor_not_on_account`, 500 `no_actors_on_account`, 401 `authentication_required` (declared on an actor-optional route too)
|
|
216
|
+
- account or actor required → 401 `authentication_required`
|
|
217
|
+
- `required_scope` → 403 `token_scope_required`; `credential_types` → 403 `credential_type_required`; `roles` → 403 `insufficient_permissions`
|
|
218
|
+
- `rate_limit` → 429 `rate_limit_exceeded`
|
|
361
219
|
- every `POST` → 415 `unsupported_content_type`
|
|
362
|
-
2. **Middleware** — the definitions of each `MiddlewareSpec` that runs on the route (`middleware_spec_applies`: its path, less its carve-outs)
|
|
363
|
-
3. **Explicit** — `RouteSpec.errors`, the handler's own codes (a 404, a 409, a second 401)
|
|
364
|
-
|
|
365
|
-
`resolve_app_route_error_maps
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
`
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
registry-time invariant 2 (`actor !== 'none' ⟺ input declares acting?: ActingActor`),
|
|
382
|
-
the auth-shape axis is the single source of truth.
|
|
383
|
-
|
|
384
|
-
**Framework-emitted vs consumer-authored.** The error-schema derivation
|
|
385
|
-
above is sound because the framework authors the errors at fixed
|
|
386
|
-
middleware sites — 401 from `require_auth`, 400 from
|
|
387
|
-
`create_input_validation`, 403 from `require_role` /
|
|
388
|
-
`require_credential_types`, 429 from rate limiters — and narrows each to
|
|
389
|
-
the slots that reach those sites. Auto-derivation documents the framework's
|
|
390
|
-
own emissions; consumers add their handler's codes in `RouteSpec.errors`,
|
|
391
|
-
beside them.
|
|
392
|
-
|
|
393
|
-
The same auto-derivation pattern is **not** appropriate for
|
|
394
|
-
consumer-authored inputs (or handler outputs). A consumer's spec declares
|
|
395
|
-
the exact `acting?: ActingActor` slot (`ActingActor` of `primitive_schemas.ts`),
|
|
396
|
-
and the framework
|
|
397
|
-
reads it back via reference-equality to drive the authorization phase — auto-extending
|
|
398
|
-
schemas at registration time would obscure the source of truth ("did the
|
|
399
|
-
spec declare this, or did the framework graft it on?") and quietly shadow
|
|
400
|
-
consumer fields named `acting` that aren't the canonical `ActingActor`.
|
|
401
|
-
The asymmetry is the design rule: derive what the framework emits, never
|
|
402
|
-
what the consumer authors. The keeper `db_routes` bug (an early consumer
|
|
403
|
-
registration failure caught by invariant 2's throw) was the empirical
|
|
404
|
-
confirmation.
|
|
405
|
-
|
|
406
|
-
### `ERROR_*` constants by category
|
|
407
|
-
|
|
408
|
-
- **Validation**: `ERROR_INVALID_REQUEST_BODY`, `ERROR_INVALID_JSON_BODY`, `ERROR_INVALID_ROUTE_PARAMS`, `ERROR_INVALID_QUERY_PARAMS`, `ERROR_PARAMS_PROTO_KEY` + `ERROR_PARAMS_NUL` (RPC params)
|
|
409
|
-
- **Auth**: `ERROR_AUTHENTICATION_REQUIRED`, `ERROR_INSUFFICIENT_PERMISSIONS`, `ERROR_CREDENTIAL_TYPE_REQUIRED`, `ERROR_RATE_LIMIT_EXCEEDED`, `ERROR_INVALID_CREDENTIALS`, `ERROR_PAYLOAD_TOO_LARGE`, `ERROR_INVALID_CONTENT_LENGTH`
|
|
410
|
-
- **Origin + bearer**: `ERROR_FORBIDDEN_ORIGIN`, `ERROR_INVALID_TOKEN`, `ERROR_ACCOUNT_NOT_FOUND`
|
|
411
|
-
- **Keeper/daemon**: `ERROR_KEEPER_ACCOUNT_NOT_FOUND`
|
|
412
|
-
- **Routing + gates**: `ERROR_METHOD_NOT_ALLOWED`, `ERROR_ROUTE_NOT_FOUND` (+ `NOT_FOUND_TEXT`, the plain-text 404 outside `/api/`), `ERROR_FORBIDDEN_HOST`, `ERROR_UNSUPPORTED_CONTENT_TYPE`
|
|
413
|
-
- **Bootstrap**: `ERROR_ALREADY_BOOTSTRAPPED`, `ERROR_TOKEN_FILE_MISSING`
|
|
414
|
-
- **Signup/invites**: `ERROR_NO_MATCHING_INVITE`, `ERROR_SIGNUP_CONFLICT`, `ERROR_INVITE_NOT_FOUND`, `ERROR_INVITE_DUPLICATE`, `ERROR_INVITE_ACCOUNT_EXISTS_USERNAME`, `ERROR_INVITE_ACCOUNT_EXISTS_EMAIL`
|
|
415
|
-
- **Admin**: `ERROR_ROLE_NOT_WEB_GRANTABLE`, `ERROR_ROLE_GRANT_NOT_FOUND`, `ERROR_INVALID_EVENT_TYPE`
|
|
416
|
-
- **DB browser**: `ERROR_FOREIGN_KEY_VIOLATION`, `ERROR_TABLE_NOT_FOUND`, `ERROR_TABLE_NO_PRIMARY_KEY`, `ERROR_TABLE_NOT_DELETABLE`, `ERROR_ROW_NOT_FOUND`
|
|
220
|
+
2. **Middleware** — the definitions of each `MiddlewareSpec` that runs on the route (`middleware_spec_applies`: its path, less its carve-outs): the body limit's 413 and 400, the origin check's 403 `forbidden_origin`, a consumer layer's own. The bearer and daemon-token layers soft-fail and declare none.
|
|
221
|
+
3. **Explicit** — `RouteSpec.errors`, the handler's own codes (a 404, a 409, a second 401).
|
|
222
|
+
|
|
223
|
+
`resolve_app_route_error_maps` builds every route's map keyed `METHOD path`
|
|
224
|
+
(`format_route_key`); `create_app_surface_spec` carries it as
|
|
225
|
+
`AppSurfaceSpec.route_error_maps` and `create_app_server` hands the same maps
|
|
226
|
+
to the DEV error check. Every reader reads that one map: the surface (an
|
|
227
|
+
`anyOf` per status), the DEV error check, `assert_response_matches_spec`,
|
|
228
|
+
error coverage, and the adversarial suites. An error a route answers that its
|
|
229
|
+
map doesn't declare fails each of them; 500 `internal_error` and 503
|
|
230
|
+
`service_unavailable` are answerable everywhere and declared by none. Run
|
|
231
|
+
against the Rust spine over the cross-process round trip, this is REST
|
|
232
|
+
error-code parity between the spines. `get_route_error_map` reads a map entry
|
|
233
|
+
or resolves the route alone, and throws on a map missing the route.
|
|
234
|
+
|
|
235
|
+
**Derive what the framework emits, never what the consumer authors.** The
|
|
236
|
+
derived codes are the framework's own fixed sites; a consumer's input
|
|
237
|
+
declares its `acting?: ActingActor` slot itself, and the framework reads it
|
|
238
|
+
back by reference (invariant 2) rather than grafting it on.
|
|
417
239
|
|
|
418
240
|
## Schema Helpers
|
|
419
241
|
|
|
420
|
-
`http/schema_helpers.ts`
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
`
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
- `is_null_schema(schema)` — a `literal(null)` (a kind check, not parse-null, to avoid false positives from `nullable(string)`)
|
|
432
|
-
- `is_void_schema(schema)` — a `literal(undefined)` (what `s.void` is, a `meta` copy included; a kind check like `is_null_schema`, so an optional schema is not void); a void input declares a parameterless RPC method
|
|
433
|
-
- `to_void_params(raw_params)` — reads absent, `null`, and `{}` params of a void input as the no-arg call (`undefined`), passing any other shape through for the void schema to refuse — the twin of the Rust spine's `require_void_params`
|
|
434
|
-
- `to_input_params(input, raw_params)` — the one params normalizer every receiving end runs before the input parse (`parse`): `to_void_params` for a void input, else absent/`null` → `{}`; used by both the server dispatch core (`perform_action`) and the peer receive path (`ActionDispatcher`)
|
|
435
|
-
- `scan_json_value(value)` → `JsonValueScan` (`{proto_key, nul}`) — one iterative walk (no recursion — `JSON.parse` nests deeper than the call stack) of a parsed JSON value for an own `__proto__` key in any object and U+0000 in any string or key; the dispatcher refuses such params with `ERROR_PARAMS_PROTO_KEY`, then `ERROR_PARAMS_NUL`, and route input validation a NUL body with `invalid_request_body`. Reads the parsed value, so of duplicate keys only the kept one counts. Twin of the Rust `fuz_http::scan_json_value`
|
|
436
|
-
- `safe_parse_dropping_unknown_keys(schema, value)` — the forward-compatible read of a remote-authored payload, returning `parse`'s `{ok, value}` / `{ok: false, issues}`: while every issue is an unknown key (`unknown_key_targets`), strips them from a copy and reparses — after the first parse that reports unknown keys, one schema-guided pass deletes every key a strict `object` doesn't name anywhere the schema reaches (entries, array items, record values, the `variant` option), as a parse reports at most a hundred issues; a key under a `union` is never stripped (the union fails as one issue of its own), and a later `pipe` stage is stripped only as reported — until nothing is left to strip, capped at `UNKNOWN_KEY_PASSES_MAX` passes (the last failure returned past it); any other issue still fails. Used for response `result`s (`ActionEvent`) and peer replies (`peer/ping`); matches serde's ignore-unknown-fields default on the Rust spine
|
|
437
|
-
- `is_strict_object_schema(schema)` — detects an `object` (not `strip_object` / `loose_object`); a `pipe` is read through to its first schema when no stage is a `transform` (so a refined `object` reads strict)
|
|
438
|
-
- `schema_to_surface(schema, {io?, source?, on_unrepresentable?}?)` — throws first on a value that is no schema (`assert_validation_schema`, naming `source`, so an assembled app's slot holding none fails boot as registration would refuse it, not as an unwritable JSON Schema); a schema → JSON Schema (`to_json_schema`), on the side `io` names (`'output'` by default), with `$schema` and `default` keys stripped recursively (defaults may be non-deterministic; `$schema` is snapshot noise). `null` for a null or void schema. A part JSON Schema can't say (an output-side transform, a `check`) is left out or written as `{}` (`unrepresentable: 'any'`) and reported to `on_unrepresentable`; a schema with nothing describable (`{}` from a schema other than `unknown`) or one the emitter refuses outright throws, prefixed with `source` — so a root-level transform output fails server assembly. It never answers `null` for a failure, which would read as "no input" and drop the schema from every suite that reads the surface
|
|
439
|
-
- `SchemaFieldInfo` — one field of an object schema (`name`, `base_type` — a `SchemaFieldBaseType`, the innermost fuz_schema kind —, `required`, `has_default`, `nullable`), what the testing generators' `to_object_schema_view` produces
|
|
440
|
-
- `middleware_applies(mw_path, route_path)` — Hono pattern matching: `'*'`, exact, `'/api/*'` prefix (handles `prefix.slice(0, -1)` so `/api/*` also matches the bare `/api`)
|
|
441
|
-
- `middleware_carves_out(spec, route_path)` — one of the layer's `carve_outs` applies to the route; the carve-out half of `middleware_spec_applies`, which `assert_full_middleware_stack` reads to relax a carved-out route's expected stack
|
|
442
|
-
- `middleware_spec_applies(spec, route_path)` — the layer runs on the route: its `path` applies and none of its `carve_outs` does; what the route error map takes middleware definitions by
|
|
242
|
+
`http/schema_helpers.ts` holds the shared schema introspection, split out to
|
|
243
|
+
break the `route_spec.ts` ↔ `surface.ts` cycle — import these from here, and
|
|
244
|
+
the route error map from `http/route_errors.ts`. Each function's rules are its
|
|
245
|
+
TSDoc:
|
|
246
|
+
|
|
247
|
+
- `is_null_schema`, `is_void_schema` (kind checks, not parses), `is_strict_object_schema`, `SchemaFieldInfo`
|
|
248
|
+
- `to_void_params`, `to_input_params` — the one params normalizer every receiving end runs before the input parse (twin of the Rust `require_void_params`)
|
|
249
|
+
- `scan_json_value` — the `__proto__`-key and NUL scan behind `ERROR_PARAMS_PROTO_KEY` / `ERROR_PARAMS_NUL` (twin of `fuz_http::scan_json_value`)
|
|
250
|
+
- `safe_parse_dropping_unknown_keys` — the forward-compatible read of a remote-authored payload (response `result`s, peer replies), matching serde's ignore-unknown-fields default
|
|
251
|
+
- `schema_to_surface` — a schema → JSON Schema for the surface; throws on what it can't write rather than answering `null`, which would read as "no input"
|
|
252
|
+
- `middleware_applies`, `middleware_paths_overlap`, `middleware_carves_out`, `middleware_spec_applies`
|
|
443
253
|
|
|
444
254
|
## Surface Generation
|
|
445
255
|
|
|
446
|
-
`http/surface.ts` produces a JSON-serializable attack surface from
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
policy invariants.
|
|
450
|
-
|
|
451
|
-
### Types
|
|
452
|
-
|
|
453
|
-
- `AppSurface` — JSON-serializable output (`middleware`, `routes`, `rpc_endpoints`, `ws_endpoints`, `env`, `events`, `diagnostics`)
|
|
454
|
-
- `AppSurfaceSpec` — the surface bundled with the **source specs** (`surface`, `route_specs`, `middleware_specs`, `rpc_endpoints`, `ws_endpoints`). Runtime-only — use for tests and introspection
|
|
455
|
-
- `AppSurfaceRoute`, `AppSurfaceMiddleware`, `AppSurfaceEnv`, `AppSurfaceEvent`, `AppSurfaceRpcEndpoint`, `AppSurfaceRpcMethod` — per-entity entries
|
|
456
|
-
- `AppSurfaceDiagnostic` — `{level: 'warning' | 'info'; category; message; source?}`
|
|
457
|
-
- `RpcEndpointSpec` — `{path, actions: Array<RpcAction>}`; fed into `generate_app_surface` so RPC endpoints appear in the surface without coupling to `create_rpc_endpoint`
|
|
458
|
-
- `GenerateAppSurfaceOptions` — `{route_specs, middleware_specs, env_schema?, event_specs?, rpc_endpoints?, ws_endpoints?}`; `ws_endpoints` takes `ResolvedWsEndpointSpec`s (`allowed_origins` filled in by `resolve_ws_endpoints`), so the surface records the patterns the upgrade gate matches
|
|
459
|
-
|
|
460
|
-
`generate_app_surface(options)` emits a `warning` diagnostic for every
|
|
461
|
-
input schema that's not strict (unknown keys silently strip under
|
|
462
|
-
`strip_object`), writes every schema through `schema_to_surface` — inputs,
|
|
463
|
-
params and query on the input side (what the server accepts, so a
|
|
464
|
-
`Username` transform keeps its bounds and pattern), outputs, error bodies and
|
|
465
|
-
event params on the output side — with an `info` diagnostic (category
|
|
466
|
-
`schema`, `source` naming the route or method and side) for each schema
|
|
467
|
-
part of which is left out or written as `{}`, throws naming the same source for one
|
|
468
|
-
that can't be written, writes each route's error map (`route_error_maps`) status by status, derives `is_mutation`
|
|
469
|
-
and `transaction` from method/spec, and surfaces RPC methods with their
|
|
470
|
-
`RouteAuth` directly (same shape on both `ActionSpec.auth` and
|
|
471
|
-
`RouteSpec.auth`, no translation step).
|
|
472
|
-
|
|
473
|
-
`create_app_surface_spec(options)` = `generate_app_surface(options)` plus
|
|
474
|
-
the source specs, for tests that need to iterate over raw specs.
|
|
256
|
+
`http/surface.ts` produces a JSON-serializable attack surface from middleware,
|
|
257
|
+
route, RPC, WS, env and event specs — for startup logging, snapshot tests, the
|
|
258
|
+
surface explorer, adversarial test generation, and policy invariants.
|
|
475
259
|
|
|
476
|
-
|
|
260
|
+
- `AppSurface` (`middleware`, `routes`, `rpc_endpoints`, `ws_endpoints`, `env`, `events`, `diagnostics`) and its per-entity entries (`AppSurfaceRoute`, `AppSurfaceRpcMethod`, `AppSurfaceWsEndpoint`, …).
|
|
261
|
+
- `AppSurfaceSpec` — the surface plus its source specs and `route_error_maps`; runtime-only, for tests and introspection.
|
|
262
|
+
- `GenerateAppSurfaceOptions` — the inputs; `ws_endpoints` takes resolved specs, so the surface records the origin patterns the upgrade gate matches. `RpcEndpointSpec` (`{path, actions}`) puts RPC endpoints on the surface without coupling to `create_rpc_endpoint`.
|
|
477
263
|
|
|
478
|
-
|
|
264
|
+
`generate_app_surface` warns on every non-strict input, writes every schema
|
|
265
|
+
through `schema_to_surface` (inputs on the input side, outputs, errors and
|
|
266
|
+
event params on the output side), notes an `info` diagnostic per partly
|
|
267
|
+
unrepresentable schema and throws on one it can't write, writes each route's
|
|
268
|
+
error map status by status, and surfaces RPC methods with their `RouteAuth`
|
|
269
|
+
unchanged. `create_app_surface_spec` adds the source specs.
|
|
479
270
|
|
|
480
|
-
|
|
481
|
-
- `filter_role_routes` / `filter_keeper_routes` / `filter_credential_gated_routes` (any `auth.credential_types` gate — superset of keeper)
|
|
482
|
-
- `filter_routes_with_input` / `filter_routes_with_params` / `filter_routes_with_query`
|
|
483
|
-
- `format_route_key(route)` → `'METHOD /path'`, of a surface route or a route spec — the key of the route error maps, and every `METHOD path` label
|
|
484
|
-
- `surface_auth_summary(surface)` — counts per auth bucket (`none`, `keeper`, `role`, `credential`, `authenticated`, `optional`, `other`), roles and credential channels broken out by name; multi-role / multi-channel specs count once per name. One private categorizer decides the bucket: keeper is tested before the role bucket and the general credential bucket after it — keeper is an authority _level_ and names the route, a session gate is a _channel_ restriction over the authority the route already declares (so the audit SSE stream counts under `role`)
|
|
485
|
-
|
|
486
|
-
The per-route auth predicates these filters compose over (`is_public_auth`,
|
|
487
|
-
`is_role_auth`, `is_credential_gated_auth`, `is_keeper_auth`,
|
|
488
|
-
`is_plain_authenticated_auth`, plus `needs_actor`) live
|
|
489
|
-
in `http/auth_shape.ts` next to the canonical `RouteAuth` type — import
|
|
490
|
-
them from there, not from this module. Same predicates back the
|
|
491
|
-
dispatcher's authorization phase, the route-spec auth-guard resolver,
|
|
492
|
-
`derive_route_errors`'s actor codes, and the testing harnesses.
|
|
271
|
+
### `surface_query.ts` — pure queries
|
|
493
272
|
|
|
494
|
-
|
|
495
|
-
|
|
273
|
+
Filters and groupings over `AppSurface`: `filter_protected_routes` /
|
|
274
|
+
`filter_public_routes`, `filter_role_routes` / `filter_keeper_routes` /
|
|
275
|
+
`filter_credential_gated_routes`, `filter_routes_with_input` / `_params` /
|
|
276
|
+
`_query`, `format_route_key` (the `METHOD /path` key of the error maps), and
|
|
277
|
+
`surface_auth_summary` (counts per auth bucket; keeper is an authority level
|
|
278
|
+
and names the route, a session gate is a channel restriction, so the audit
|
|
279
|
+
SSE stream counts under `role`). The predicates they compose over live in
|
|
280
|
+
`http/auth_shape.ts`. Consumer code should reach for these rather than
|
|
281
|
+
inlining `.filter` chains.
|
|
496
282
|
|
|
497
283
|
## Middleware Infrastructure
|
|
498
284
|
|
|
499
|
-
`MiddlewareSpec` (
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
path: string; // Hono pattern — '*', exact, or '/api/*'
|
|
505
|
-
handler: MiddlewareHandler;
|
|
506
|
-
errors?: ReadonlyArray<RestErrorDef>; // definitions this layer may answer with
|
|
507
|
-
}
|
|
508
|
-
```
|
|
509
|
-
|
|
510
|
-
Declared separately from `http/route_spec.ts` so middleware modules don't
|
|
511
|
-
pull in route types.
|
|
285
|
+
`MiddlewareSpec` (`http/middleware_spec.ts`, apart from `route_spec.ts` so
|
|
286
|
+
middleware modules don't pull in route types) is `{name, path, handler,
|
|
287
|
+
errors?, carve_outs?}`: `path` a Hono pattern (`'*'`, exact, `'/api/*'`),
|
|
288
|
+
`errors` the definitions the layer may answer with, `carve_outs` the
|
|
289
|
+
`MiddlewareCarveOut`s (`{path, reason}`) the layer skips.
|
|
512
290
|
|
|
513
291
|
### Trusted proxy — `http/proxy.ts`
|
|
514
292
|
|
|
515
|
-
Resolves the
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
- **Rightmost-first XFF walk, skipping trusted entries; the first entry that fails strict validation stops the walk and the request keys on the connection IP.** Stopping, not skipping, keeps a client-written entry left of a non-bare-IP hop (`ip:port`, `unknown`) from picking the bucket.
|
|
523
|
-
- **`validate_ip_strict(ip)`** is defensive against Hono's lax `distinctRemoteAddr` (which classifies anything-with-colons as IPv6 and accepts `'[::1]:8080'`, `'::1\n'` as binary-valid). Two-layer check: character-set pre-filter + round-trip through `convertIPv*ToBinary`.
|
|
524
|
-
- **`normalize_ip(ip)`** delegates to `canonicalize_ip` from `http/ip_canonical.ts` — RFC 5952 lowercase + longest-zero-run compression, IPv4-mapped IPv6 stripped to plain IPv4 so buckets collapse. Idempotent, safe on non-IP strings, strict char-set filter preserves malformed forms unchanged.
|
|
525
|
-
- **Three-branch middleware logic**: no XFF → use connection IP; XFF + connection untrusted → ignore XFF, use connection IP (spoof-proof, debug log); XFF + connection trusted → resolve from header, warn if all entries turn out trusted.
|
|
526
|
-
|
|
527
|
-
Tradeoff: legitimate non-standard proxies that include ports in XFF entries
|
|
528
|
-
(`203.0.113.1:8080`) lose per-client distinction and collapse to the
|
|
529
|
-
proxy's connection IP. nginx + cloud LBs don't include ports — bounded by
|
|
530
|
-
operator configuration in practice.
|
|
293
|
+
Resolves the client IP from `X-Forwarded-For` only when the TCP peer is a
|
|
294
|
+
configured trusted proxy, walking rightmost-first past trusted entries and
|
|
295
|
+
stopping (not skipping) at the first entry that fails strict validation.
|
|
296
|
+
Without it `get_client_ip(c)` answers `'unknown'` for every caller — one
|
|
297
|
+
shared rate-limit bucket — so it must run before auth and rate limiting (root
|
|
298
|
+
../../../CLAUDE.md §Middleware Ordering). The walk's rules and the nginx
|
|
299
|
+
recipe: ../../../docs/security.md §Trusted Proxy / Client IP.
|
|
531
300
|
|
|
532
301
|
### Origin allowlist — `http/origin.ts`
|
|
533
302
|
|
|
534
|
-
|
|
535
|
-
CSRF
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
refused wherever it points — the Rust spine's `fuz_http::compose_stack` checks
|
|
554
|
-
every route group and its fallback the same way. Probes and CLI clients send no
|
|
555
|
-
`Origin` and pass. A path leaves the check only by a named carve-out with its
|
|
556
|
-
reason (`AppServerOptions.origin_carve_outs`), for a route that refuses browser
|
|
557
|
-
callers by other means; one overlapping the auth middleware's scope
|
|
558
|
-
(`AUTH_MIDDLEWARE_PATH`, where every route that reads or mints a credential
|
|
559
|
-
sits) is refused at assembly. A carve-out skips every path it matches, routed
|
|
560
|
-
or not, so an unrouted path under it reaches the static fallback unchecked;
|
|
561
|
-
the Rust stack checks unrouted paths in its fallback group whatever a
|
|
562
|
-
carve-out names.
|
|
563
|
-
|
|
564
|
-
**Grammar** (shared with the Rust spine's `AllowedOrigins::parse`, pinned by
|
|
565
|
-
`testing/cross_backend/origin_conformance.json`): entries are trimmed of ASCII
|
|
566
|
-
whitespace and written as a browser writes an `Origin` — exact
|
|
567
|
-
`https://api.fuz.dev`; wildcard label `https://*.fuz.dev` (one label in any
|
|
568
|
-
position — matches `api.fuz.dev`, NOT `fuz.dev` or `a.b.fuz.dev`); several
|
|
569
|
-
`https://*.*.corp.fuz.dev`; port wildcard `http://localhost:*` (any port or
|
|
570
|
-
none); IPv6 `http://[::1]:3000` (exact, no wildcard inside the brackets).
|
|
571
|
-
A wildcard entry boots only with `FUZ_ALLOW_ORIGIN_WILDCARDS=true`:
|
|
572
|
-
`origin_wildcard.ts` classifies each parsed entry (`origin_wildcard_kind` —
|
|
573
|
-
port, host with some or no label fixed, or both — from the `OriginPattern`
|
|
574
|
-
`parse_allowed_origins` returns beside each matcher and brands onto it under
|
|
575
|
-
the realm-global `Symbol.for('@fuzdev/fuz_app/OriginPattern')`, so a second
|
|
576
|
-
fuz_app copy reads it — `origin_pattern_of`), renders what it admits
|
|
577
|
-
(`origin_wildcard_warning`, the Rust `fuz_http::origin_wildcard_warning` text
|
|
578
|
-
word for word), and `admit_origin_wildcards` gives `validate_server_env` and
|
|
579
|
-
`create_app_server` (the server list and each `ws_endpoints` spec's own) the
|
|
580
|
-
refusal or the warnings (`allow_origin_wildcards`). A matcher with no brand —
|
|
581
|
-
hand-built, or copied with `new RegExp` — is refused, flag or not.
|
|
582
|
-
**Nothing is normalized** — the matcher is built from the entry as written, so
|
|
583
|
-
an entry a browser would never send is refused rather than rewritten: non-ASCII
|
|
584
|
-
(punycode an IDN host), a scheme other than http/https (`null`, `file://`,
|
|
585
|
-
`chrome-extension://`), a path/query/fragment/trailing slash, userinfo, a
|
|
586
|
-
character no hostname holds (`%`, `\`, `^`, `|`, `<`, `>`, `[`, `]`), a partial
|
|
587
|
-
wildcard, an IPv4 address not written as four canonical decimal numbers, an IPv6
|
|
588
|
-
address not in the browser's form (the URL parser serves as the serializer and
|
|
589
|
-
any difference refuses), a port outside `1..=65535` or with leading zeros, the
|
|
590
|
-
scheme's default port, and an empty entry. The checks run in a fixed order so
|
|
591
|
-
both spines name the same kind for the same entry.
|
|
303
|
+
`verify_request_source(allowed_patterns, carve_outs?)` is one of the three
|
|
304
|
+
CSRF layers (../../../docs/security.md §CSRF Protection) and the one that
|
|
305
|
+
guards the never-preflighted WebSocket upgrade: one `Origin` line must match
|
|
306
|
+
the allowlist or 403 `forbidden_origin`; no `Origin` passes (CLI clients,
|
|
307
|
+
probes); an empty or repeated `Origin` is refused on every runtime. It checks
|
|
308
|
+
`Origin` only, by design, and `create_app_server` mounts it at `'*'`; a path
|
|
309
|
+
leaves it only by a named carve-out (security.md has both arguments).
|
|
310
|
+
|
|
311
|
+
- `parse_allowed_origins(raw)` — every refused entry reported (`{kind, index, entry}`); `OriginPatternErrorKind` / `AllowedOriginsErrorKind` are the wire names shared with the Rust spine, `format_allowed_origins_error` a boot-error line.
|
|
312
|
+
- `should_allow_origin(origin, patterns)` — case-insensitive; a non-visible-ASCII value matches nothing.
|
|
313
|
+
- `is_browser_context(origin_lines, referer_lines)` (`http/request_headers.ts`) — any `Origin` or `Referer` line, an empty one included; the bearer and daemon-token legs discard their credential when true.
|
|
314
|
+
|
|
315
|
+
The pattern grammar (shared with the Rust `AllowedOrigins::parse`; nothing
|
|
316
|
+
normalized, so an entry a browser would never send is refused rather than
|
|
317
|
+
rewritten) lives in `origin.ts`: `parse_allowed_origins`'s TSDoc,
|
|
318
|
+
`OriginPatternErrorKind`, and `ALLOWED_ORIGINS_ERROR_MESSAGES`, pinned by
|
|
319
|
+
`testing/cross_backend/origin_conformance.json`. The pattern checks run in a
|
|
320
|
+
fixed order, the first failure naming the kind, so both spines name the same
|
|
321
|
+
error kind for an entry.
|
|
592
322
|
|
|
593
323
|
## JSON-RPC (`http/jsonrpc.ts`, `http/jsonrpc_errors.ts`, `http/jsonrpc_helpers.ts`)
|
|
594
324
|
|
|
595
|
-
Three files
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
are object-only (no positional arrays), and the envelopes are fuz_schema
|
|
601
|
-
`loose_object`s that keep members a reader passes over; result is any value
|
|
602
|
-
(`unknown`, which needs its key) since the per-action `spec.output` is the
|
|
603
|
-
actual contract and the MCP object-only result constraint would reject any
|
|
604
|
-
spec declaring a null or primitive output on the wire. A parse returns the
|
|
605
|
-
frame itself, not a copy.
|
|
606
|
-
|
|
607
|
-
`_meta` is intentionally **not** envelope-validated — that lives in
|
|
608
|
-
per-action schemas so mismatches surface as `invalid_params` rather than
|
|
325
|
+
Three files by concern: envelope schemas, the throwable and its maps,
|
|
326
|
+
builders/guards/the classifier. JSON-RPC 2.0 with a partial **MCP superset**
|
|
327
|
+
posture: params are object-only, envelopes are `loose_object`s, `result` is
|
|
328
|
+
any value (the per-action `spec.output` is the contract). `_meta` is not
|
|
329
|
+
envelope-validated, so its mismatches surface as `invalid_params`, not
|
|
609
330
|
`invalid_request`.
|
|
610
331
|
|
|
611
|
-
###
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
`
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
once at module load beside the code (list that module in `sideEffects`). It
|
|
645
|
-
throws when the code is outside -32099..-32000, is any code
|
|
646
|
-
`JSONRPC_ERROR_CODES` defines, or is already registered with another status,
|
|
647
|
-
or when the status is outside 400–599; the same code and status again is a
|
|
648
|
-
no-op. A registered code joins neither the reverse map nor
|
|
649
|
-
`JSONRPC_ERROR_CODE_TO_NAME`. Twin of the Rust spine's `ConsumerErrorCode::new`,
|
|
650
|
-
which holds a declaration to the same rules.
|
|
651
|
-
|
|
652
|
-
### API map
|
|
653
|
-
|
|
654
|
-
- `JSONRPC_ERROR_CODES` — `Record<JsonrpcErrorName, JsonrpcErrorCode>` (frozen)
|
|
655
|
-
- `jsonrpc_error_messages` — named constructors returning `JsonrpcErrorObject`
|
|
656
|
-
- `jsonrpc_errors` — named constructors returning `ThrownJsonrpcError` (derived from `jsonrpc_error_messages` via `create_error_thrower`). Usage: `throw jsonrpc_errors.not_found('user')`, `throw jsonrpc_errors.forbidden()`
|
|
657
|
-
- `ThrownJsonrpcError` — `Error` subclass carrying `code` + optional `data`
|
|
658
|
-
- `to_thrown_jsonrpc_error(err)` — the one thrown → wire conversion: the `JsonrpcErrorObject` a `ThrownJsonrpcError` carries, recognized by a realm-global `Symbol.for` brand on its prototype (so one from a second fuz_app copy is read too), when its `code` is a JSON-RPC error code; else `null` — a foreign error class with a JSON-RPC-shaped `code` (another library's RPC error) or a `DOMException` included. Read by the REST catch layer, `perform_action`, `create_jsonrpc_error_response_from_thrown`, the frontend HTTP and WS transports, and `ActionEvent`'s handler-throw normalization, each masking everything else its own way
|
|
659
|
-
- `jsonrpc_error_code_to_http_status` / `http_status_to_jsonrpc_error_code` (fall back to 500 / `internal_error`) — the code → status table is module-private; `HTTP_STATUS_TO_JSONRPC_ERROR_CODE` (frozen) is the reverse over the base set
|
|
660
|
-
- `register_jsonrpc_error_code(code, http_status)` — declares a consumer code's status (see **Consumer codes** above)
|
|
661
|
-
- Envelope schemas in `http/jsonrpc.ts` (fuz_schema): `JsonrpcRequest`, `JsonrpcNotification`, `JsonrpcResponse`, `JsonrpcErrorResponse`, `JsonrpcResponseOrError`, `JsonrpcErrorObject`, `JsonrpcErrorCode` (`JsonrpcServerErrorCode` an integer in the server range, as `is_jsonrpc_error_code` reads it). Also `JsonrpcRequestId`, `JsonrpcMethod`, `JsonrpcResult`, and the params. `JsonrpcMessage`, `JsonrpcMessageFromClientToServer`, and `JsonrpcMessageFromServerToClient` are types only
|
|
662
|
-
- `parse_inbound_jsonrpc_error(error)` — a peer's error reply read as the Rust `parse_inbound_error` reads it: a code off the base set (a consumer's code included) is `internal_error`, a non-string message `'peer error'`, an own `data` kept as sent; what `PendingPeerRequests.resolve` hands the caller
|
|
663
|
-
- Builders in `http/jsonrpc_helpers.ts`: `create_jsonrpc_request`, `create_jsonrpc_notification`, `create_jsonrpc_response`, `create_jsonrpc_error_response`, `create_jsonrpc_error_response_from_thrown` (preserves code/message/data on a thrown JSON-RPC error, via `to_thrown_jsonrpc_error`; plain `Error` → `internal_error` with `{stack}` in DEV)
|
|
664
|
-
- Type guards: `is_jsonrpc_request_id` (rejects NaN/Infinity), `is_jsonrpc_object`, `is_jsonrpc_request` / `_notification` / `_response` / `_error_response`
|
|
665
|
-
- Converters: `to_jsonrpc_message_id`, `to_jsonrpc_params` (normalizes primitives to `{value}`)
|
|
666
|
-
- Classifier: `classify_jsonrpc_message(json)` → `ClassifiedJsonrpcMessage` (`request` / `notification` / `response` / `invalid`, the last carrying the error and the id to answer it on), twin of the Rust `fuz_http::classify` in order and answers. The WS frame handler and the HTTP POST handler switch on it, each keeping its transport's arms: WS refuses batches before it, routes `cancel` and peer responses, and checks duplicate ids and the in-flight ceiling after; POST answers a notification or a response `invalid_request` on `id: null`. Only a refused request envelope carries data — the schema's issues, DEV-only. A `request` carries the frame as parsed, validated but not rebuilt, so an own `__proto__` key in `params` reaches the dispatcher, which refuses it (`ERROR_PARAMS_PROTO_KEY`) as on GET and the Rust spine (a rebuilt copy would drop it).
|
|
667
|
-
|
|
668
|
-
Handlers can `throw jsonrpc_errors.*` — `apply_route_specs`' error-catch
|
|
669
|
-
layer converts to the flat REST body (`{error: <reason>, message?, ...rest_data}`)
|
|
670
|
-
at the correct HTTP status.
|
|
671
|
-
Generic `Error` maps to 500 `internal_error` (message in DEV only).
|
|
332
|
+
### Error taxonomy
|
|
333
|
+
|
|
334
|
+
| name | code | HTTP | meaning |
|
|
335
|
+
| --------------------- | ------ | ---- | -------------------------------------------------------------------------- |
|
|
336
|
+
| `parse_error` | -32700 | 400 | JSON parse failure |
|
|
337
|
+
| `invalid_request` | -32600 | 400 | envelope malformed |
|
|
338
|
+
| `method_not_found` | -32601 | 404 | unknown method |
|
|
339
|
+
| `invalid_params` | -32602 | 400 | params schema failure |
|
|
340
|
+
| `internal_error` | -32603 | 500 | unhandled exception |
|
|
341
|
+
| `unauthenticated` | -32001 | 401 | no credential ("unauthorized" is wrong for 401) |
|
|
342
|
+
| `forbidden` | -32002 | 403 | authenticated but denied |
|
|
343
|
+
| `not_found` | -32003 | 404 | resource not found |
|
|
344
|
+
| `conflict` | -32004 | 409 | uniqueness/state conflict |
|
|
345
|
+
| `validation_error` | -32005 | 422 | business-rule validation (schema failures are `invalid_params`) |
|
|
346
|
+
| `rate_limited` | -32006 | 429 | server policy; what a generic 429 maps back to |
|
|
347
|
+
| `service_unavailable` | -32007 | 503 | upstream down / maintenance |
|
|
348
|
+
| `timeout` | -32008 | 504 | handler exceeded its budget |
|
|
349
|
+
| `queue_overflow` | -32009 | 429 | a full buffer refused a request (WS reconnect queue, inbound dispatch cap) |
|
|
350
|
+
| `request_cancelled` | -32010 | 499 | caller-initiated cancellation |
|
|
351
|
+
|
|
352
|
+
A consumer code (cast `as JsonrpcErrorCode`) answers 500 until
|
|
353
|
+
`register_jsonrpc_error_code(code, http_status)` declares its status, once at
|
|
354
|
+
module load (list that module in `sideEffects`); its refusals are its TSDoc,
|
|
355
|
+
twin of the Rust `ConsumerErrorCode::new`.
|
|
356
|
+
|
|
357
|
+
The entry points: `jsonrpc_errors.*` throwers (`throw jsonrpc_errors.not_found('user')`);
|
|
358
|
+
`to_thrown_jsonrpc_error`, the one thrown → wire recognizer (a realm-global
|
|
359
|
+
brand, so a second fuz_app copy's error maps too, and a foreign error carrying
|
|
360
|
+
a JSON-RPC `code` doesn't); `classify_jsonrpc_message`, the one envelope
|
|
361
|
+
classifier (twin of `fuz_http::classify`), each transport keeping its own
|
|
362
|
+
arms around it; `parse_inbound_jsonrpc_error`, a peer's error reply read as
|
|
363
|
+
the Rust `parse_inbound_error` reads it. A REST handler that throws one is
|
|
364
|
+
answered by the error catch (§Validation pipeline step 8).
|
|
672
365
|
|
|
673
366
|
## Pending Effects
|
|
674
367
|
|
|
675
|
-
|
|
368
|
+
Every request — an HTTP route, an RPC call, a WS message — carries two effect
|
|
369
|
+
queues with opposite contracts. `RouteContext` and `ActionContext` both carry
|
|
370
|
+
them, which is why the module lives in `http/`. The full contract and the
|
|
371
|
+
Rust-twin note are `http/pending_effects.ts`'s TSDoc.
|
|
676
372
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
log: Logger;
|
|
680
|
-
post_commit_effects: Array<() => void | Promise<void>>;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
// `RouteContext` and `ActionContext` carry both:
|
|
684
|
-
// pending_effects: Array<Promise<void>>
|
|
685
|
-
// post_commit_effects: Array<() => void | Promise<void>>
|
|
686
|
-
```
|
|
373
|
+
- **`pending_effects: Array<Promise<void>>`** — eager. Pool writes already in flight, outside the request's transaction, so they **survive** its rollback: failure audit rows (`AppDeps.audit`) and the bearer middleware's api-token usage touch. A success audit row is not one — it is written and awaited in the transaction (`auth/CLAUDE.md` §Audit emitter).
|
|
374
|
+
- **`post_commit_effects: Array<() => void | Promise<void>>`** — deferred thunks that run **iff the transaction commits**: WS notifications (`auth/CLAUDE.md` §WS notifications), a revocation's connection closes (`queue_connection_close`, `actions/CLAUDE.md` §Connection closer), and a success audit row's listener fan-out. Push only through `emit_after_commit(ctx, fn)`.
|
|
687
375
|
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
union. The shapes encode different contracts — eager pushers say "wait for
|
|
695
|
-
this work that's already started"; thunk pushers say "run this after the
|
|
696
|
-
handler returns" — and burying both behind one field made
|
|
697
|
-
`c.var.pending_effects.push(x)` ambiguous at the call site. Splitting turns the field name into the contract.
|
|
698
|
-
|
|
699
|
-
### Why `emit_after_commit` defers — and discards on rollback
|
|
700
|
-
|
|
701
|
-
The thunk shape is **load-bearing for correctness**. Pushing
|
|
702
|
-
`Promise.resolve().then(fn)` onto an eager queue — what `emit_after_commit`
|
|
703
|
-
used to do — schedules `fn` as a microtask that drains _before_ the
|
|
704
|
-
wrapping `await db.query('COMMIT')` resumes, so a rolled-back transaction
|
|
705
|
-
would leak a notification for state that never landed. The thunk defers
|
|
706
|
-
the work to flush time; the `try/finally` in the flush middleware runs
|
|
707
|
-
after the handler (and any wrapping transaction) returns.
|
|
708
|
-
|
|
709
|
-
Deferral alone isn't enough: the flush runs whether the handler returned or
|
|
710
|
-
threw, so a thrown handler (rolling back its transaction) would still fire the
|
|
711
|
-
thunk it queued. So the contract is **two-sided**: both dispatch sites
|
|
712
|
-
(`http/route_spec.ts`, `actions/perform_action.ts`) wrap their handler in the
|
|
713
|
-
shared `dispatch_with_post_commit_rollback` helper, which discards
|
|
714
|
-
`post_commit_effects` on a handler throw — `emit_after_commit` thus reads as
|
|
715
|
-
**"run iff the wrapping transaction commits."** The eager `pending_effects`
|
|
716
|
-
queue is the deliberate opposite (survives rollback — attempt audits). The full
|
|
717
|
-
two-sided contract + Rust-twin parity note live on the helper's TSDoc in
|
|
718
|
-
`http/pending_effects.ts`.
|
|
376
|
+
The rules a caller would miss:
|
|
377
|
+
|
|
378
|
+
- **Defer, never schedule.** A thunk, not `Promise.resolve().then(fn)`: a microtask would run before the wrapping `COMMIT` resumes and announce state that may roll back.
|
|
379
|
+
- **Discard on rollback, at the dispatch site.** Both dispatch sites (`http/route_spec.ts`, `actions/perform_action.ts`) wrap the handler in `dispatch_with_post_commit_rollback`, which truncates the deferred queue on a throw. A `transaction: false` handler that opens its own transaction (`/login`, `/password`, signup, bootstrap) runs it through `transaction_with_post_commit_rollback`, which discards what that transaction queued even when the handler catches the failure and answers normally. The eager queue is never truncated.
|
|
380
|
+
- **Drain at the outer flush.** `flush_request_effects` is the one flush: the HTTP middleware in `server/app_server.ts` (awaited before the response under `await_pending_effects: true`, else left running) and the per-message WS flush (awaited after the reply is sent). It invokes the deferred thunks before awaiting the eager writes, so a connection close never waits behind a slow audit INSERT, and wraps each thunk in its own `try/catch`, so one failure can't starve its siblings. Eager rejections go to the log and `on_effect_error` (`{transport, method, path}`).
|
|
381
|
+
- **Held from acceptance.** Every HTTP request and every WS message accepted for dispatch is held on the backend's one `RequestTracker` (`AppDeps.request_tracker`; `register_action_ws`'s `request_tracker` for a hand mount) from acceptance until its handler has returned and its flush has settled (`accept()` → `AcceptedRequest.finish(flush)`). `AppServer.close` waits for every held request, then the audit emitter's writes, repeating until both are empty, within `shutdown_drain_timeout_ms` — a handler still running when the close starts is waited for, then its flush (a WS handler's `signal` is aborted by the socket close first). Once it starts draining, the server's view of the tracker (`create_request_tracker_view`, closed by `close()`) refuses what arrives: an HTTP request answers 503 `service_unavailable` (the failed-checkout shape), and a WS message — reachable only on a socket the close-all didn't end (a hand mount) — the `service_unavailable` JSON-RPC error (`WS_SHUTTING_DOWN_MESSAGE`); the backend's tracker stays open for a later server. `_testing_drain_effects` waits only for the flushes (`drain_flushes`) and the audit writes, never a running handler: its own request is one, and its flush starts only after it answers. Never await `drain_inflight` — or `AppServer.close` — from inside a request: it waits on its own caller (`AppServer.close` until its bound). **Twin difference:** the Rust spine also waits for an HTTP request already dispatched, but at shutdown drops a WS message's dispatch still in its handler with its socket loop — it rolls back — while one whose commit has started finishes, its post-commit effects included; here every accepted message runs to completion and its reply is refused.
|
|
719
382
|
|
|
720
383
|
```typescript
|
|
721
384
|
emit_after_commit(ctx, () => ctx.notification_sender.send_to_account(account_id, msg));
|
|
722
385
|
```
|
|
723
386
|
|
|
724
|
-
Used for WS sends (`ctx.notification_sender`, through
|
|
725
|
-
`queue_offer_notification` / `queue_supersede_notifications` for the
|
|
726
|
-
role-grant-offer notifications — see `auth/CLAUDE.md` §WS notifications),
|
|
727
|
-
a revocation's connection closes (`queue_connection_close` — see
|
|
728
|
-
`actions/CLAUDE.md` §Connection closer), the audit emitter's listener fan-out
|
|
729
|
-
for a success row (`auth/CLAUDE.md` §Audit emitter), and any side effect that
|
|
730
|
-
must run only after the transaction commits.
|
|
731
|
-
|
|
732
|
-
### Key properties
|
|
733
|
-
|
|
734
|
-
- **The flush owns the safety net.** `flush_post_commit_effects` wraps every thunk in `try/catch` and routes errors through `ctx.log.error`, so one failing send cannot starve sibling effects in the same batch nor corrupt the already-committed response. Per-thunk `try/catch` inside `emit_after_commit` would skip directly-pushed thunks (e.g. tests); centralizing the wrap in the flush closes that gap.
|
|
735
|
-
- **One flush, every transport.** `flush_request_effects(pending_effects, post_commit_effects, log, on_rejection?)` drains both queues; the HTTP middleware and the per-message WS flush both call it, threading `on_effect_error` (with `{transport, method, path}`) into `on_rejection`. Test mode (`await_pending_effects: true`) awaits it before the response returns; production HTTP runs it fire-and-forget; WS awaits it per frame, after the reply.
|
|
736
|
-
- **The deferred thunks never wait on the eager writes.** Every flush site (both modes here, and the per-message WS flush) invokes the `post_commit_effects` thunks before it awaits `pending_effects`, so a revocation's connection close is not held behind a slow audit INSERT. A thunk that needs a write — the audit emitter's success-row fan-out — awaits that write itself.
|
|
737
|
-
- **Drain at the outer flush; discard at the dispatch site.** The successful-path _drain_ of both queues stays at the outer flush middleware (`server/app_server.ts`) + the per-message WS flush — adjacent, one location, no per-wrapper drain timing. What the dispatch sites (route-spec wrapper / `perform_action`) own is the _rollback discard_, via the shared `dispatch_with_post_commit_rollback` helper: on a handler throw they truncate `post_commit_effects` before the outer flush ever sees it, so the flush only drains effects from a committed handler. The eager `pending_effects` queue is never truncated — it drains regardless (attempt audits survive rollback).
|
|
738
|
-
- Structurally satisfied by both `RouteContext` (HTTP) and `ActionContext` (RPC + WS) — they share the `{log, post_commit_effects}` shape, which is why this helper lives in `http/` rather than `actions/` or `auth/`.
|
|
739
|
-
|
|
740
|
-
WS sends are **not** wrapped by `create_validated_broadcaster` (that only
|
|
741
|
-
guards SSE `broadcast(channel, data)`). The input schemas of
|
|
742
|
-
`RemoteNotificationActionSpec`s are contracts for consumers, not enforced
|
|
743
|
-
at send time.
|
|
744
|
-
|
|
745
387
|
## Common Routes
|
|
746
388
|
|
|
747
|
-
`http/common_routes.ts`
|
|
748
|
-
auth-
|
|
749
|
-
|
|
750
|
-
- `create_health_route_spec()` — `GET /health` (`HEALTH_PATH`), public, returns `{status: 'ok'}` (`HealthResponse`, both from `http/health_schema.ts`). Infrastructure endpoint for uptime monitors, and what `ui/backend_probe.svelte.ts` reads
|
|
751
|
-
- `create_ready_route_spec({expected, log})` — `GET /ready`, public, the deploy gate. Introspects the live DB's columns (`db/schema_ready.ts`) and compares against the committed `expected` column map: `200 {ready: true}` on match, else `503 {error: 'schema_drift' | 'db_unreachable'}`. Detailed drift logs server-side only (minimal body — no schema leak, mirrors why `/api/surface` is admin-only). Throws at assembly on an empty `expected` (fail-loud). Opt-in like `/health`; pair with `load_expected_schema(url)` — loads + URL-caches a consumer's committed `expected_schema.json` and throws on an empty map
|
|
752
|
-
- `create_server_status_route_spec({version, get_uptime_ms})` — `GET /api/server/status`, authenticated, returns `{version, uptime_ms}` (`uptime_ms` a non-negative integer)
|
|
389
|
+
`http/common_routes.ts` has three route-spec factories with no auth-domain
|
|
390
|
+
dependency (auth-aware status routes live in `auth/`):
|
|
753
391
|
|
|
754
|
-
|
|
755
|
-
`
|
|
392
|
+
- `create_health_route_spec()` — `GET /health`, public, `{status: 'ok'}`.
|
|
393
|
+
- `create_ready_route_spec({expected, log})` — `GET /ready`, public, the deploy gate: compares the live DB's columns (`db/schema_ready.ts`) to the committed column map, `200 {ready: true}` or `503 {error: 'schema_drift' | 'db_unreachable'}`, the detail logged server-side only. Throws at assembly on an empty `expected`; pair with `load_expected_schema(url)`.
|
|
394
|
+
- `create_server_status_route_spec({version, get_uptime_ms})` — `GET /api/server/status`, authenticated, `{version, uptime_ms}`.
|
|
756
395
|
|
|
757
396
|
## DB Routes (Allowlisted Browser)
|
|
758
397
|
|
|
759
|
-
`http/db_routes.ts`
|
|
760
|
-
`
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
`
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
-
|
|
768
|
-
-
|
|
769
|
-
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
invariant 2). The routes' schemas are `@fuzdev/fuz_schema`: the queries
|
|
774
|
-
`object`s over `ActingActor`, and the counts and positions they
|
|
775
|
-
answer with (`row_count`, `total`, `offset`, `limit`) non-negative integers.
|
|
776
|
-
`GET /tables/:name`'s paging params are each a `query_int`:
|
|
777
|
-
`pipe(string, regex(/^[+-]?\d+$/), transform(Number))`, then `safe_integer`
|
|
778
|
-
and its bounds, under a default — the spellings the Rust twin's
|
|
779
|
-
`str::parse::<i64>` reads, so `""`, `" 5"`, `"1e2"`, `"5.0"` and `"0x10"` are
|
|
780
|
-
refused on both. The surface writes each as a string with that `pattern`,
|
|
781
|
-
its bounds in the `description`, and notes the steps it can't say as an
|
|
782
|
-
`info` diagnostic.
|
|
783
|
-
|
|
784
|
-
**The allowlist gates everything.** `DbRouteOptions.browsable_tables` is
|
|
785
|
-
required with no "all" escape hatch — the table list shows only listed tables,
|
|
786
|
-
and detail/`DELETE` on an unlisted table answer exactly like a table that
|
|
787
|
-
doesn't exist (404 `ERROR_TABLE_NOT_FOUND`, byte-identical masking). The
|
|
788
|
-
credential floor `NON_BROWSABLE_TABLES` (`account` — the argon2 hash corpus,
|
|
789
|
-
`auth_session` / `api_token` — credential digests, `bootstrap_lock`) is
|
|
790
|
-
subtracted from the allowlist even when a consumer names those tables. The
|
|
791
|
-
browse/delete transactions run under `SET LOCAL statement_timeout`
|
|
792
|
-
(`DB_ADMIN_STATEMENT_TIMEOUT_MS`) so no single statement outlives the bound
|
|
793
|
-
(per statement, not per request — the table listing's per-table `COUNT(*)`
|
|
794
|
-
loop can still take several in sequence).
|
|
795
|
-
|
|
796
|
-
**Single-column primary keys only.** The `DELETE` filters on one column
|
|
797
|
-
(`WHERE "<pk>" = $1`), which is correct only when the primary key _is_
|
|
798
|
-
that one column. `query_primary_key_columns` returns every PK column in
|
|
799
|
-
`ordinal_position` order, and the route proceeds only at length exactly 1 — a
|
|
800
|
-
composite key (a single-column filter would match every row sharing that
|
|
801
|
-
column's value and silently over-delete) and an absent key both refuse with 400
|
|
802
|
-
and delete nothing. `GET /tables/:name` reports `primary_key: null` in the same
|
|
803
|
-
two cases, so the UI (`ui/table_state.svelte.ts`) disables delete without firing
|
|
804
|
-
a request. Twin of the Rust spine's `fuz_db_admin` router.
|
|
805
|
-
|
|
806
|
-
**Some tables are never row-deletable.** `NON_DELETABLE_TABLES` — `audit_log`,
|
|
807
|
-
`bootstrap_lock`, `app_settings`, `schema_version` — refuses the `DELETE` with
|
|
808
|
-
400 `ERROR_TABLE_NOT_DELETABLE` before the key-shape check, because a generic
|
|
809
|
-
storage endpoint has no business deleting a row whose meaning lives in the
|
|
810
|
-
domain layer. `audit_log` is the sharpest: it is both the trail and, since
|
|
811
|
-
the revocation guard (`create_revocation_guard`) closes live connections by
|
|
812
|
-
listening to audit events, part of how revocation propagates. The three
|
|
813
|
-
singletons each fail differently on deletion — `bootstrap_lock` leaves
|
|
814
|
-
`check_bootstrap_status` advertising a window `bootstrap_account.ts` then always
|
|
815
|
-
refuses, `app_settings` makes every settings read throw, `schema_version` is the
|
|
816
|
-
migration tracker (composite-keyed, so already refused — named here so the
|
|
817
|
-
protection survives a key-shape change). Consumers add their own via
|
|
818
|
-
`DbRouteOptions.non_deletable_tables`, which is unioned with the builtin set and
|
|
819
|
-
never replaces it.
|
|
820
|
-
|
|
821
|
-
`GET /tables/:name` reports `deletable` = exactly what the `DELETE` will accept
|
|
822
|
-
(single-column PK **and** not excluded), so a client hides the affordance
|
|
823
|
-
instead of discovering the refusal — `ui/table_state.svelte.ts` gates on
|
|
824
|
-
`can_delete`. `primary_key` stays a truthful report of the key shape; a policy
|
|
825
|
-
exclusion must not masquerade as one.
|
|
826
|
-
|
|
827
|
-
**Every successful row delete is audited.** The `DELETE` handler defers a
|
|
828
|
-
`deps.audit.emit_pool` call through `emit_after_commit`, so the pool-routed
|
|
829
|
-
row lands iff the delete's transaction commits — the success-only trail can't claim a
|
|
830
|
-
delete that failed at COMMIT (the Rust twin commits before emitting for the
|
|
831
|
-
same reason). Account-grain attribution (the browser's gate is account-grain,
|
|
832
|
-
so no actor is claimed), metadata `{table, pk_column, id}`. Refusals emit
|
|
833
|
-
nothing. The completeness gate covers the event via the
|
|
834
|
-
`db_routes.db.test.ts` emission tests (excluded-with-justification in
|
|
835
|
-
`testing/audit_completeness.ts`). Twinned by `fuz_db_admin`'s emission on the
|
|
836
|
-
Rust spine.
|
|
837
|
-
|
|
838
|
-
All four routes use the keeper auth shape (`{account: 'required', actor: 'required', roles: ['keeper'], credential_types: ['daemon_token']}`).
|
|
839
|
-
Param schemas use `VALID_SQL_IDENTIFIER` regex, and every table name gets
|
|
840
|
-
`assert_valid_sql_identifier()` before string-interpolating into SQL —
|
|
841
|
-
the identifier validation is the only reason the interpolation is safe.
|
|
842
|
-
|
|
843
|
-
**Do not widen the auth on these specs.** They serve paginated rows of every
|
|
844
|
-
browsable table plus row `DELETE` — the credential tables sit behind the
|
|
845
|
-
`NON_BROWSABLE_TABLES` floor, but browsable rows can still carry secrets in
|
|
846
|
-
data columns (a consumer's `cell.data` is the live example).
|
|
847
|
-
`credential_types: ['daemon_token']` is what keeps every bearer credential
|
|
848
|
-
out, and it's why the specs need no `auth.required_scope`: a daemon token
|
|
849
|
-
resolves to `full` by construction, so no narrowed token can reach them (see
|
|
850
|
-
../../../docs/security.md §Token scoping). Re-auth them to a role a bearer
|
|
851
|
-
satisfies and both controls are gone at once — the token's scope stops
|
|
852
|
-
applying and the credential gate stops firing. A consumer that does this owns
|
|
853
|
-
the surface census for it.
|
|
854
|
-
|
|
855
|
-
Interfaces exported for consumer use: `TableInfo`, `TableWithCount`,
|
|
856
|
-
`PrimaryKeyInfo`, `ColumnInfo`, `DbRouteDeps`, `DbRouteOptions`,
|
|
857
|
-
`NON_DELETABLE_TABLES`, `NON_BROWSABLE_TABLES`, `DB_TABLE_ROWS_DEFAULT_LIMIT`,
|
|
858
|
-
`DB_TABLE_ROWS_LIMIT_MAX`, `DB_ADMIN_STATEMENT_TIMEOUT_MS`.
|
|
398
|
+
`create_db_route_specs(deps, options)` (`http/db_routes.ts`; `deps` is
|
|
399
|
+
`DbRouteDeps`, `{audit}`, which `ctx.deps` satisfies) builds a keeper-only
|
|
400
|
+
browser over the `public` schema: `GET /health`, `GET /tables`,
|
|
401
|
+
`GET /tables/:name` (paged rows, `primary_key`, `deletable`), and
|
|
402
|
+
`DELETE /tables/:name/rows/:id`. The routes, paging grammar, limits and
|
|
403
|
+
refusals are the module's TSDoc. The rules that matter:
|
|
404
|
+
|
|
405
|
+
- **The allowlist gates everything.** `browsable_tables` is required with no "all"; an unlisted table answers exactly as a missing one (404 `table_not_found`). The `NON_BROWSABLE_TABLES` credential floor is subtracted even when a consumer lists those tables.
|
|
406
|
+
- **Some rows are never deletable.** `NON_DELETABLE_TABLES` (each table's reason is its TSDoc) refuses the `DELETE` before the key-shape check; consumers add to it with `non_deletable_tables`, never replace it. Only a single-column primary key is deletable.
|
|
407
|
+
- **Every successful delete is audited** in the delete's transaction: the row lands iff the delete commits, and a refused row rolls the delete back, as on the Rust twin (`fuz_db_admin`).
|
|
408
|
+
- **Do not widen the auth.** The keeper shape's `credential_types: ['daemon_token']` keeps every bearer out, and is why the specs need no `required_scope` (a daemon token is `full` by construction). Re-auth them to a role a bearer satisfies and both controls are gone at once (../../../docs/security.md §Token scoping).
|
|
409
|
+
|
|
410
|
+
Table names pass `assert_valid_sql_identifier()` before they are
|
|
411
|
+
interpolated into SQL — the only reason the interpolation is safe.
|
|
859
412
|
|
|
860
413
|
## Cross-Module Notes
|
|
861
414
|
|
|
862
|
-
- **Middleware ordering** is
|
|
863
|
-
- **
|
|
864
|
-
- **
|
|
865
|
-
- **Error modules are complementary, not redundant.** `http/error_schemas.ts` is declaration-first (for routes and surface); `http/jsonrpc_errors.ts` is throw-first (for handlers and the catch layer). A single `ERROR_*` code can be raised either way depending on whether the handler needs to also attach diagnostic fields
|
|
415
|
+
- **Middleware ordering** is `create_app_server`'s — root ../../../CLAUDE.md §Middleware Ordering. What `http/` needs upheld: the trusted proxy runs before auth and rate limiting; origin verification before session parsing.
|
|
416
|
+
- **Input/output schemas align with SAES.** RPC via `actions/action_rpc.ts` takes the same schemas unchanged (`actions/CLAUDE.md` §Single JSON-RPC 2.0 endpoint).
|
|
417
|
+
- **The error modules are complementary.** `http/error_schemas.ts` is declaration-first (routes, surface); `http/jsonrpc_errors.ts` is throw-first (handlers, the catch layer). One `ERROR_*` code can be raised either way.
|