@fuzdev/fuz_app 0.184.0 → 0.186.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/dist/actions/CLAUDE.md +18 -3
  2. package/dist/actions/perform_action.d.ts.map +1 -1
  3. package/dist/actions/perform_action.js +36 -5
  4. package/dist/actions/register_action_ws.d.ts +14 -7
  5. package/dist/actions/register_action_ws.d.ts.map +1 -1
  6. package/dist/actions/ws_socket_session.d.ts +17 -4
  7. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  8. package/dist/actions/ws_socket_session.js +41 -7
  9. package/dist/auth/CLAUDE.md +18 -9
  10. package/dist/auth/account_queries.d.ts +53 -40
  11. package/dist/auth/account_queries.d.ts.map +1 -1
  12. package/dist/auth/account_queries.js +57 -50
  13. package/dist/auth/account_routes.d.ts.map +1 -1
  14. package/dist/auth/account_routes.js +59 -25
  15. package/dist/auth/admin_actions.d.ts.map +1 -1
  16. package/dist/auth/admin_actions.js +26 -9
  17. package/dist/auth/audit_emitter.js +2 -2
  18. package/dist/auth/audit_log_queries.d.ts +11 -3
  19. package/dist/auth/audit_log_queries.d.ts.map +1 -1
  20. package/dist/auth/audit_log_queries.js +4 -4
  21. package/dist/auth/audit_log_routes.d.ts +1 -1
  22. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  23. package/dist/auth/audit_log_routes.js +3 -2
  24. package/dist/auth/audit_log_schema.js +1 -1
  25. package/dist/auth/auth_ddl.d.ts.map +1 -1
  26. package/dist/auth/auth_ddl.js +4 -0
  27. package/dist/auth/cleanup.d.ts +34 -3
  28. package/dist/auth/cleanup.d.ts.map +1 -1
  29. package/dist/auth/cleanup.js +12 -4
  30. package/dist/auth/migrations.d.ts.map +1 -1
  31. package/dist/auth/migrations.js +35 -0
  32. package/dist/auth/role_grant_offer_queries.d.ts +13 -13
  33. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  34. package/dist/auth/role_grant_offer_queries.js +12 -13
  35. package/dist/auth/role_grant_queries.d.ts +16 -9
  36. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  37. package/dist/auth/role_grant_queries.js +16 -9
  38. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  39. package/dist/auth/self_service_role_actions.js +15 -0
  40. package/dist/auth/session_queries.d.ts +24 -0
  41. package/dist/auth/session_queries.d.ts.map +1 -1
  42. package/dist/auth/session_queries.js +28 -0
  43. package/dist/db/CLAUDE.md +3 -3
  44. package/dist/db/cell_ddl.d.ts +8 -3
  45. package/dist/db/cell_ddl.d.ts.map +1 -1
  46. package/dist/db/cell_ddl.js +10 -5
  47. package/dist/http/CLAUDE.md +1 -1
  48. package/dist/http/body_limit.d.ts +4 -4
  49. package/dist/http/body_limit.js +4 -4
  50. package/dist/http/pending_effects.d.ts +8 -4
  51. package/dist/http/pending_effects.d.ts.map +1 -1
  52. package/dist/http/route_spec.d.ts +3 -3
  53. package/dist/http/route_spec.d.ts.map +1 -1
  54. package/dist/realtime/audit_log_sse.d.ts +1 -1
  55. package/dist/realtime/sse.d.ts +2 -2
  56. package/dist/realtime/sse.d.ts.map +1 -1
  57. package/dist/realtime/sse_constants.d.ts +1 -1
  58. package/dist/realtime/sse_constants.js +1 -1
  59. package/dist/server/app_server.d.ts +59 -71
  60. package/dist/server/app_server.d.ts.map +1 -1
  61. package/dist/server/app_server.js +52 -60
  62. package/dist/server/shutdown_drain.d.ts +69 -0
  63. package/dist/server/shutdown_drain.d.ts.map +1 -0
  64. package/dist/server/shutdown_drain.js +77 -0
  65. package/dist/testing/CLAUDE.md +197 -66
  66. package/dist/testing/admin_integration.d.ts +2 -2
  67. package/dist/testing/admin_integration.d.ts.map +1 -1
  68. package/dist/testing/admin_integration.js +36 -20
  69. package/dist/testing/app_server.d.ts +5 -7
  70. package/dist/testing/app_server.d.ts.map +1 -1
  71. package/dist/testing/app_server.js +5 -7
  72. package/dist/testing/auth_apps.d.ts +3 -1
  73. package/dist/testing/auth_apps.d.ts.map +1 -1
  74. package/dist/testing/auth_apps.js +22 -5
  75. package/dist/testing/cross_backend/backend_config.d.ts +8 -0
  76. package/dist/testing/cross_backend/backend_config.d.ts.map +1 -1
  77. package/dist/testing/cross_backend/backend_log.d.ts +71 -0
  78. package/dist/testing/cross_backend/backend_log.d.ts.map +1 -0
  79. package/dist/testing/cross_backend/backend_log.js +134 -0
  80. package/dist/testing/cross_backend/backend_swap.d.ts +41 -0
  81. package/dist/testing/cross_backend/backend_swap.d.ts.map +1 -0
  82. package/dist/testing/cross_backend/backend_swap.js +431 -0
  83. package/dist/testing/cross_backend/body_size_smuggling.js +3 -3
  84. package/dist/testing/cross_backend/bootstrap_backend.d.ts +3 -1
  85. package/dist/testing/cross_backend/bootstrap_backend.d.ts.map +1 -1
  86. package/dist/testing/cross_backend/bootstrap_backend.js +9 -5
  87. package/dist/testing/cross_backend/conformance_case.d.ts +11 -6
  88. package/dist/testing/cross_backend/conformance_case.d.ts.map +1 -1
  89. package/dist/testing/cross_backend/conformance_case.js +4 -0
  90. package/dist/testing/cross_backend/conformance_principal.d.ts +2 -2
  91. package/dist/testing/cross_backend/conformance_principal.d.ts.map +1 -1
  92. package/dist/testing/cross_backend/conformance_principal.js +27 -10
  93. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts +10 -1
  94. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts.map +1 -1
  95. package/dist/testing/cross_backend/create_dual_spawn_global_setup.js +33 -7
  96. package/dist/testing/cross_backend/default_backend_configs.d.ts +38 -5
  97. package/dist/testing/cross_backend/default_backend_configs.d.ts.map +1 -1
  98. package/dist/testing/cross_backend/default_backend_configs.js +50 -15
  99. package/dist/testing/cross_backend/in_process_setup.d.ts +1 -1
  100. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  101. package/dist/testing/cross_backend/in_process_setup.js +53 -31
  102. package/dist/testing/cross_backend/revocation_drivers.d.ts +14 -2
  103. package/dist/testing/cross_backend/revocation_drivers.d.ts.map +1 -1
  104. package/dist/testing/cross_backend/revocation_drivers.js +36 -8
  105. package/dist/testing/cross_backend/rpc_success_fixtures.d.ts.map +1 -1
  106. package/dist/testing/cross_backend/rpc_success_fixtures.js +2 -1
  107. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts +7 -0
  108. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts.map +1 -1
  109. package/dist/testing/cross_backend/rust_spine_stub_backend_config.js +4 -2
  110. package/dist/testing/cross_backend/setup.d.ts +44 -43
  111. package/dist/testing/cross_backend/setup.d.ts.map +1 -1
  112. package/dist/testing/cross_backend/setup.js +64 -62
  113. package/dist/testing/cross_backend/spawn_backend.d.ts +19 -1
  114. package/dist/testing/cross_backend/spawn_backend.d.ts.map +1 -1
  115. package/dist/testing/cross_backend/spawn_backend.js +138 -11
  116. package/dist/testing/cross_backend/spine_suites.d.ts +17 -14
  117. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  118. package/dist/testing/cross_backend/spine_suites.js +37 -15
  119. package/dist/testing/cross_backend/sse_round_trip.d.ts.map +1 -1
  120. package/dist/testing/cross_backend/sse_round_trip.js +4 -2
  121. package/dist/testing/cross_backend/standard.d.ts +18 -82
  122. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  123. package/dist/testing/cross_backend/standard.js +6 -21
  124. package/dist/testing/cross_backend/standard_auth.d.ts +74 -0
  125. package/dist/testing/cross_backend/standard_auth.d.ts.map +1 -0
  126. package/dist/testing/cross_backend/standard_auth.js +28 -0
  127. package/dist/testing/cross_backend/standard_bundle.d.ts +48 -0
  128. package/dist/testing/cross_backend/standard_bundle.d.ts.map +1 -0
  129. package/dist/testing/cross_backend/standard_bundle.js +43 -0
  130. package/dist/testing/cross_backend/testing_reset_actions.d.ts +18 -6
  131. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  132. package/dist/testing/cross_backend/testing_reset_actions.js +23 -8
  133. package/dist/testing/cross_backend/testing_server_bun.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/testing_server_bun.js +7 -30
  135. package/dist/testing/cross_backend/testing_server_core.d.ts +16 -3
  136. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  137. package/dist/testing/cross_backend/testing_server_core.js +20 -4
  138. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +6 -2
  139. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  140. package/dist/testing/cross_backend/ts_spine_backend_config.js +7 -3
  141. package/dist/testing/cross_backend/ws_round_trip.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/ws_round_trip.js +4 -3
  143. package/dist/testing/data_exposure.d.ts +4 -1
  144. package/dist/testing/data_exposure.d.ts.map +1 -1
  145. package/dist/testing/data_exposure.js +93 -25
  146. package/dist/testing/db_invariants.d.ts +5 -5
  147. package/dist/testing/db_invariants.js +5 -5
  148. package/dist/testing/error_coverage.d.ts +5 -0
  149. package/dist/testing/error_coverage.d.ts.map +1 -1
  150. package/dist/testing/error_coverage.js +2 -1
  151. package/dist/testing/integration.d.ts +4 -20
  152. package/dist/testing/integration.d.ts.map +1 -1
  153. package/dist/testing/integration.js +49 -79
  154. package/dist/testing/integration_helpers.d.ts +16 -0
  155. package/dist/testing/integration_helpers.d.ts.map +1 -1
  156. package/dist/testing/integration_helpers.js +29 -1
  157. package/dist/testing/logged_errors.d.ts +61 -0
  158. package/dist/testing/logged_errors.d.ts.map +1 -0
  159. package/dist/testing/logged_errors.js +285 -0
  160. package/dist/testing/middleware_gate_probes.d.ts +55 -1
  161. package/dist/testing/middleware_gate_probes.d.ts.map +1 -1
  162. package/dist/testing/middleware_gate_probes.js +76 -3
  163. package/dist/testing/rpc_attack_surface.d.ts.map +1 -1
  164. package/dist/testing/rpc_attack_surface.js +41 -16
  165. package/dist/testing/stubs.d.ts +5 -1
  166. package/dist/testing/stubs.d.ts.map +1 -1
  167. package/dist/testing/stubs.js +6 -3
  168. package/dist/testing/test_app.d.ts +39 -9
  169. package/dist/testing/test_app.d.ts.map +1 -1
  170. package/dist/testing/test_app.js +70 -12
  171. package/dist/testing/transports/fetch_transport.d.ts +10 -0
  172. package/dist/testing/transports/fetch_transport.d.ts.map +1 -1
  173. package/dist/testing/transports/fetch_transport.js +13 -0
  174. package/package.json +4 -3
@@ -18,7 +18,7 @@ import './assert_dev_env.js';
18
18
  */
19
19
  import { describe, test, assert, afterAll } from 'vitest';
20
20
  import { parse_or_throw } from '@fuzdev/fuz_schema/schema.ts';
21
- import { find_auth_route, assert_response_matches_spec, assert_no_error_info_leakage } from './integration_helpers.js';
21
+ import { find_auth_route, assert_response_matches_spec, assert_no_error_info_leakage, is_standard_integration_route, MIDDLEWARE_GATE_ERROR_CODES } from './integration_helpers.js';
22
22
  import { find_rpc_action, rpc_call_for_spec, require_rpc_endpoint_path, resolve_rpc_endpoints_for_setup } from './rpc_helpers.js';
23
23
  import { ErrorCoverageCollector, assert_error_coverage, DEFAULT_INTEGRATION_ERROR_COVERAGE } from './error_coverage.js';
24
24
  import { is_public_auth } from '../http/auth_shape.js';
@@ -30,7 +30,6 @@ import { assert_iso8601_seconds, assert_iso8601_seconds_nullable } from './cross
30
30
  import { DEFAULT_TEST_PASSWORD } from './test_credentials.js';
31
31
  import { create_test_request_headers, TEST_ORIGIN } from './test_origin.js';
32
32
  import { create_test_raw_api_token } from './entities.js';
33
- import { assert_middleware_gate_refusal, format_middleware_gate_probe, plan_middleware_gate_probes, send_middleware_gate_probe } from './middleware_gate_probes.js';
34
33
  /**
35
34
  * Standard integration test suite for fuz_app auth routes.
36
35
  *
@@ -38,8 +37,10 @@ import { assert_middleware_gate_refusal, format_middleware_gate_probe, plan_midd
38
37
  * revocation, password change (incl. API token revocation), origin
39
38
  * verification, bearer auth (incl. browser context discard on mutations),
40
39
  * token revocation, cross-account isolation, expired credential rejection,
41
- * signup invite edge cases, response body validation, and the middleware
42
- * gates each counted route's error map declares (`middleware_gate_probes.ts`).
40
+ * signup invite edge cases, and response body validation. The middleware
41
+ * gates each counted route's error map declares are
42
+ * `describe_middleware_gate_tests`' (`middleware_gate_probes.ts`), a suite of
43
+ * their own since over a socket they write raw request heads.
43
44
  *
44
45
  * Each test group asserts that required routes exist, failing with a descriptive
45
46
  * message if the consumer's route specs are misconfigured.
@@ -74,17 +75,9 @@ export const describe_standard_integration_tests = (options) => {
74
75
  const cookie_name = options.session_cookie_name;
75
76
  // Error coverage tracking across test groups
76
77
  const error_collector = new ErrorCoverageCollector(options.surface_source.route_error_maps);
77
- // the auth routes this suite drives: login / logout / password, signup
78
- // (when wired), and the shared RPC endpoint — admin-role routes belong to
79
- // the admin suite
80
- const is_suite_auth_route = (s) => {
81
- if (s.auth.roles?.includes('admin') ?? false)
82
- return false;
83
- const rest_suffixes = ['/login', '/logout', '/password', '/signup'];
84
- if (rest_suffixes.some((suffix) => s.path.endsWith(suffix)))
85
- return true;
86
- return s.path === rpc_path;
87
- };
78
+ // the auth routes this suite drives — admin-role routes belong to the
79
+ // admin suite
80
+ const is_suite_auth_route = (s) => is_standard_integration_route(s, rpc_path);
88
81
  afterAll(() => {
89
82
  // Scope coverage to auth routes this suite actually exercises:
90
83
  // login / logout / password drivers + signup invite edge cases
@@ -97,8 +90,11 @@ export const describe_standard_integration_tests = (options) => {
97
90
  // the admin suite instead.
98
91
  const auth_routes = route_specs.filter(is_suite_auth_route);
99
92
  const scoped_routes = auth_routes.length > 0 ? auth_routes : route_specs;
100
- options.check_uncovered_errors?.(error_collector.uncovered(scoped_routes));
93
+ // the middleware gates' refusals are `describe_middleware_gate_tests`'
94
+ const filter = { ignore_codes: MIDDLEWARE_GATE_ERROR_CODES };
95
+ options.check_uncovered_errors?.(error_collector.uncovered(scoped_routes, filter));
101
96
  assert_error_coverage(error_collector, scoped_routes, {
97
+ ...filter,
102
98
  min_coverage: options.error_coverage_min ?? DEFAULT_INTEGRATION_ERROR_COVERAGE
103
99
  });
104
100
  });
@@ -680,40 +676,43 @@ export const describe_standard_integration_tests = (options) => {
680
676
  });
681
677
  // --- 8. Cross-account isolation ---
682
678
  describe('cross-account isolation', () => {
683
- test('non-admin cannot access admin routes', async () => {
684
- const fixture = await options.setup_test();
685
- // admin routes are optional in the base suite — admin-specific coverage
686
- // lives in describe_standard_admin_integration_tests.
687
- //
688
- // Pick an admin REST route where a clean role-denial 403 is
689
- // reachable: account-grain (`actor: 'none'`, so the authorization
690
- // phase doesn't first demand an acting actor → `actor_required`)
691
- // and input/param/query-free (params and query still validate ahead
692
- // of the auth phase — only body validation moved behind the gates,
693
- // per the 401 → authz → 403 → 429 → 400 order). Admin surfaces are
694
- // RPC-first now; a consumer may expose no such REST route (fuz_app
695
- // itself, zzz) — then this REST-era check is a no-op and RPC denial
696
- // is covered by `describe_rpc_attack_surface_tests`.
697
- const admin_route = route_specs.find((s) => (s.auth.roles?.includes('admin') ?? false) &&
698
- s.auth.actor === 'none' &&
699
- !s.input &&
700
- !s.params &&
701
- !s.query);
702
- if (!admin_route)
703
- return;
704
- // Probe with a freshly-created account — it holds no admin role
705
- // (the keeper fixture behind `create_session_headers` does, so it
706
- // would pass the gate).
707
- const non_admin = await fixture.create_account({ username: 'non_admin_admin_probe' });
708
- const res = await fixture.transport(admin_route.path, {
709
- method: admin_route.method,
710
- headers: { cookie: `${cookie_name}=${non_admin.session_cookie}` }
711
- });
712
- assert.strictEqual(res.status, 403);
713
- await error_collector.assert_and_record(route_specs, admin_route.method, admin_route.path, res);
714
- const body = await res.json();
715
- assert.strictEqual(body.error, 'insufficient_permissions');
716
- });
679
+ // admin routes are optional in the base suite — admin-specific coverage
680
+ // lives in describe_standard_admin_integration_tests.
681
+ //
682
+ // Pick an admin REST route where a clean role-denial 403 is
683
+ // reachable: account-grain (`actor: 'none'`, so the authorization
684
+ // phase doesn't first demand an acting actor → `actor_required`)
685
+ // and input/param/query-free (params and query still validate ahead
686
+ // of the auth phase — only body validation moved behind the gates,
687
+ // per the 401 → authz → 403 → 429 → 400 order). Admin surfaces are
688
+ // RPC-first now; a consumer may expose no such REST route (fuz_app
689
+ // itself, zzz) — then this REST-era check isn't registered and RPC denial
690
+ // is covered by `describe_rpc_attack_surface_tests`.
691
+ const admin_route = route_specs.find((s) => (s.auth.roles?.includes('admin') ?? false) &&
692
+ s.auth.actor === 'none' &&
693
+ !s.input &&
694
+ !s.params &&
695
+ !s.query);
696
+ // registered only where such a route exists: a plain skip would leave the
697
+ // transcript differential's run partial (its stale-ledger check unjudged),
698
+ // and a gated one would owe every consumer an `expected_skips` entry
699
+ if (admin_route) {
700
+ test('non-admin cannot access admin routes', async () => {
701
+ const fixture = await options.setup_test();
702
+ // Probe with a freshly-created account — it holds no admin role
703
+ // (the keeper fixture behind `create_session_headers` does, so it
704
+ // would pass the gate).
705
+ const non_admin = await fixture.create_account({ username: 'non_admin_admin_probe' });
706
+ const res = await fixture.transport(admin_route.path, {
707
+ method: admin_route.method,
708
+ headers: { cookie: `${cookie_name}=${non_admin.session_cookie}` }
709
+ });
710
+ assert.strictEqual(res.status, 403);
711
+ await error_collector.assert_and_record(route_specs, admin_route.method, admin_route.path, res);
712
+ const body = await res.json();
713
+ assert.strictEqual(body.error, 'insufficient_permissions');
714
+ });
715
+ }
717
716
  test("user A cannot revoke user B's sessions", async () => {
718
717
  const fixture = await options.setup_test();
719
718
  // Create a second account
@@ -1052,35 +1051,6 @@ export const describe_standard_integration_tests = (options) => {
1052
1051
  }
1053
1052
  });
1054
1053
  });
1055
- // --- 12c. Middleware gates: each counted route's declared gates refuse ---
1056
- describe('middleware gates', () => {
1057
- // One probe per gate each counted route's error map declares — the
1058
- // origin check, the Rust spine's host gate, the body limit — each a
1059
- // bodiless head with no credential that the gate refuses before auth,
1060
- // rate limiting or body parsing. A gate the map doesn't declare on a
1061
- // route (a carve-out, a backend without the layer) gets no probe.
1062
- const probes = plan_middleware_gate_probes({
1063
- route_specs: route_specs.filter(is_suite_auth_route),
1064
- route_error_maps: options.surface_source.route_error_maps,
1065
- base_url: options.base_url,
1066
- max_body_bytes: options.max_body_bytes,
1067
- rpc_path,
1068
- rpc_max_body_bytes: options.rpc_max_body_bytes
1069
- });
1070
- // in-process the probes share one fixture's transport, made by the first
1071
- // to run; over a socket they need none, as they read and write no state
1072
- let in_process_transport = null;
1073
- const get_transport = () => (in_process_transport ??= options
1074
- .setup_test()
1075
- .then((fixture) => fixture.fresh_transport({ origin: null })));
1076
- for (const probe of probes) {
1077
- test(format_middleware_gate_probe(probe), async () => {
1078
- const transport = options.base_url === null ? await get_transport() : null;
1079
- const res = await send_middleware_gate_probe(probe, options.base_url, transport);
1080
- await assert_middleware_gate_refusal(probe, res, error_collector, route_specs);
1081
- });
1082
- }
1083
- });
1084
1054
  // --- 13. Password change revokes API tokens ---
1085
1055
  describe('password change revokes API tokens', () => {
1086
1056
  test('API tokens are invalidated after password change', async () => {
@@ -40,6 +40,22 @@ export type RestAuthRouteSuffix = (typeof rest_auth_route_suffixes)[number];
40
40
  * @throws Error if `suffix` is not in `rest_auth_route_suffixes`.
41
41
  */
42
42
  export declare const find_auth_route: (specs: Array<RouteSpec>, suffix: RestAuthRouteSuffix, method: RouteMethod) => RouteSpec | undefined;
43
+ /**
44
+ * The middleware gates' refusals: the origin check's, the host gate's and the
45
+ * body limit's. `describe_middleware_gate_tests` probes each on every counted
46
+ * route that declares it, so the integration suite's coverage leaves them out.
47
+ */
48
+ export declare const MIDDLEWARE_GATE_ERROR_CODES: ReadonlyArray<string>;
49
+ /**
50
+ * Whether the standard integration suite counts a route: login, logout,
51
+ * password and signup (when wired), and the shared RPC endpoint — the routes
52
+ * its error coverage is scoped to and `describe_middleware_gate_tests` probes.
53
+ * An admin-role route belongs to the admin suite.
54
+ *
55
+ * @param spec - the route
56
+ * @param rpc_path - the RPC endpoint's path
57
+ */
58
+ export declare const is_standard_integration_route: (spec: RouteSpec, rpc_path: string) => boolean;
43
59
  /**
44
60
  * Validate a response body against the route spec's declared schemas.
45
61
  *
@@ -1 +1 @@
1
- {"version":3,"file":"integration_helpers.d.ts","sourceRoot":"","sources":["../../src/lib/testing/integration_helpers.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,eAAe,EAAE,CAAC,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,KAAK,gBAAgB,CAAC;CAC9F;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,sBAAsB,GAClC,WAAW,aAAa,EACxB,SAAS,mBAAmB,KAC1B,gBAWF,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,GAC7B,MAAM,SAAS,EACf,QAAQ,oBAAoB,EAC5B,gBAAgB,WAAW,EAC3B,eAAe,WAAW,KACxB,MAAM,CAAC,MAAM,EAAE,MAAM,CACoE,CAAC;AAE7F;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,6BAA6B,GACzC,WAAW,aAAa,EACxB,cAAc,OAAO,KACnB,OAAiD,CAAC;AAErD;;;;;;;;;GASG;AACH,eAAO,MAAM,0BAA0B,GAAI,QAAQ,MAAM,EAAE,QAAQ,OAAO,KAAG,OACQ,CAAC;AAEtF;;;;;;;;;GASG;AACH,eAAO,MAAM,0BAA0B,GAAI,QAAQ,MAAM,EAAE,QAAQ,OAAO,KAAG,OACjB,CAAC"}
@@ -9,7 +9,7 @@ import { parse } from '@fuzdev/fuz_schema/schema.ts';
9
9
  import { is_null_schema } from '../http/schema_helpers.js';
10
10
  import { get_route_error_map } from '../http/route_errors.js';
11
11
  import { is_public_auth } from '../http/auth_shape.js';
12
- import { ERROR_AUTHENTICATION_REQUIRED, ERROR_CREDENTIAL_TYPE_REQUIRED, ERROR_METHOD_NOT_ALLOWED, ERROR_ROUTE_NOT_FOUND, NOT_FOUND_TEXT } from '../http/error_schemas.js';
12
+ import { ERROR_AUTHENTICATION_REQUIRED, ERROR_CREDENTIAL_TYPE_REQUIRED, ERROR_METHOD_NOT_ALLOWED, ERROR_ROUTE_NOT_FOUND, NOT_FOUND_TEXT, REST_FORBIDDEN_HOST, REST_FORBIDDEN_ORIGIN, REST_INVALID_CONTENT_LENGTH, REST_PAYLOAD_TOO_LARGE } from '../http/error_schemas.js';
13
13
  import { ROLE_ADMIN } from '../auth/role_schema.js';
14
14
  import { create_test_request_headers } from './test_origin.js';
15
15
  import { find_mounted_route, is_json_response, to_mounted_routes } from '../http/route_error_check.js';
@@ -83,6 +83,34 @@ export const find_auth_route = (specs, suffix, method) => {
83
83
  }
84
84
  return specs.find((s) => s.method === method && s.path.endsWith(suffix));
85
85
  };
86
+ /**
87
+ * The middleware gates' refusals: the origin check's, the host gate's and the
88
+ * body limit's. `describe_middleware_gate_tests` probes each on every counted
89
+ * route that declares it, so the integration suite's coverage leaves them out.
90
+ */
91
+ export const MIDDLEWARE_GATE_ERROR_CODES = [
92
+ REST_FORBIDDEN_ORIGIN.code,
93
+ REST_FORBIDDEN_HOST.code,
94
+ REST_PAYLOAD_TOO_LARGE.code,
95
+ REST_INVALID_CONTENT_LENGTH.code
96
+ ];
97
+ /**
98
+ * Whether the standard integration suite counts a route: login, logout,
99
+ * password and signup (when wired), and the shared RPC endpoint — the routes
100
+ * its error coverage is scoped to and `describe_middleware_gate_tests` probes.
101
+ * An admin-role route belongs to the admin suite.
102
+ *
103
+ * @param spec - the route
104
+ * @param rpc_path - the RPC endpoint's path
105
+ */
106
+ export const is_standard_integration_route = (spec, rpc_path) => {
107
+ if (spec.auth.roles?.includes('admin') ?? false)
108
+ return false;
109
+ const rest_suffixes = ['/login', '/logout', '/password', '/signup'];
110
+ if (rest_suffixes.some((suffix) => spec.path.endsWith(suffix)))
111
+ return true;
112
+ return spec.path === rpc_path;
113
+ };
86
114
  /**
87
115
  * Validate a response body against the route spec's declared schemas.
88
116
  *
@@ -0,0 +1,61 @@
1
+ import './assert_dev_env.js';
2
+ /** What a logged error is matched against: a substring, or a `RegExp` searched for. */
3
+ export type LoggedErrorPattern = string | RegExp;
4
+ /** A logged error the gate lets pass, and why. */
5
+ export interface LoggedErrorAllowance {
6
+ readonly pattern: LoggedErrorPattern;
7
+ /** Why the error is expected — required, and shown nowhere but the source. */
8
+ readonly reason: string;
9
+ }
10
+ /**
11
+ * The designed test-mode banners, allowed in every test: each is printed with
12
+ * `console.error`, once per module instance, when a test-only mode is on, so a
13
+ * production log that shows one is the alarm. In a test run they are the
14
+ * mode working.
15
+ */
16
+ export declare const LOGGED_ERROR_BANNERS: ReadonlyArray<LoggedErrorAllowance>;
17
+ /** Options for `install_logged_error_gate`. */
18
+ export interface InstallLoggedErrorGateOptions {
19
+ /**
20
+ * Errors allowed in every test of every file, beside `LOGGED_ERROR_BANNERS`
21
+ * — a consumer's own designed banners. Each needs its reason.
22
+ */
23
+ readonly allow?: ReadonlyArray<LoggedErrorAllowance>;
24
+ }
25
+ /**
26
+ * Install the gate for the current test file — call at the top level of a
27
+ * vitest `setupFiles` module, which vitest runs ahead of each test file. Wraps
28
+ * `Logger.prototype.error` and `console.error` once per process (each wrapper
29
+ * calls the original), resets the file's state, and registers the file's
30
+ * hooks: a `beforeEach` that starts the test's buffer and checks it in an
31
+ * `onTestFinished` hook, and an `afterAll` that checks what was logged outside
32
+ * any test.
33
+ *
34
+ * @param options - errors allowed in every test beside `LOGGED_ERROR_BANNERS`
35
+ * @throws Error on an allowance without its reason
36
+ */
37
+ export declare const install_logged_error_gate: (options?: InstallLoggedErrorGateOptions) => void;
38
+ /**
39
+ * Declare that the running test logs an error matching `pattern`, and fail
40
+ * the test when it ends unless one was logged: the error the test provokes is
41
+ * asserted, not just tolerated. Every error the pattern matches is allowed.
42
+ *
43
+ * @param pattern - a substring of the error's text, or a `RegExp` searched for
44
+ * @throws Error outside a test, in a concurrent test, or when no setup file installed the gate
45
+ */
46
+ export declare const expect_logged_error: (pattern: LoggedErrorPattern) => void;
47
+ /**
48
+ * Allow logged errors matching `pattern`, with the reason they are expected:
49
+ * inside a test, for that test; at collection, for every test of the
50
+ * enclosing `describe` (the whole file at its top level) and for what the
51
+ * file logs outside its tests or in its concurrent tests. It throws in a
52
+ * concurrent test, whose errors share the file's bucket with its siblings',
53
+ * so an allowance made there would hide theirs. Unlike `expect_logged_error`
54
+ * it asserts nothing. A no-op when no setup file installed the gate.
55
+ *
56
+ * @param pattern - a substring of the error's text, or a `RegExp` searched for
57
+ * @param reason - why the error is expected; required
58
+ * @throws Error on an empty reason or pattern, or in a concurrent test
59
+ */
60
+ export declare const allow_logged_error: (pattern: LoggedErrorPattern, reason: string) => void;
61
+ //# sourceMappingURL=logged_errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logged_errors.d.ts","sourceRoot":"","sources":["../../src/lib/testing/logged_errors.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,CAAC;AAsD7B,uFAAuF;AACvF,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,MAAM,CAAC;AAEjD,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,OAAO,EAAE,kBAAkB,CAAC;IACrC,8EAA8E;IAC9E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB;AAED;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAAa,CAAC,oBAAoB,CAapE,CAAC;AAEF,+CAA+C;AAC/C,MAAM,WAAW,6BAA6B;IAC7C;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,CAAC,oBAAoB,CAAC,CAAC;CACrD;AAoLD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,yBAAyB,GAAI,UAAS,6BAAkC,KAAG,IAsCvF,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,GAAI,SAAS,kBAAkB,KAAG,IAkBjE,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,kBAAkB,EAAE,QAAQ,MAAM,KAAG,IAqBhF,CAAC"}
@@ -0,0 +1,285 @@
1
+ import './assert_dev_env.js';
2
+ /**
3
+ * The per-test logged-error gate: every error a test logs — a
4
+ * `Logger.prototype.error` call or a `console.error` — fails the test once it
5
+ * ends, unless the test declared it. A test that provokes an error on purpose
6
+ * says so with `expect_logged_error(pattern)`, which also asserts the error
7
+ * appeared, so the noise becomes coverage; an error that is a side effect of
8
+ * what a test or describe sets up, and not what it checks, is
9
+ * `allow_logged_error(pattern, reason)`. The designed test-mode banners
10
+ * (`LOGGED_ERROR_BANNERS`) are allowed everywhere.
11
+ *
12
+ * Wire it as a vitest `setupFiles` entry whose top level calls
13
+ * `install_logged_error_gate()`:
14
+ *
15
+ * ```ts
16
+ * // src/test/logged_error_gate.ts
17
+ * import { install_logged_error_gate } from '@fuzdev/fuz_app/testing/logged_errors.ts';
18
+ *
19
+ * install_logged_error_gate();
20
+ * ```
21
+ *
22
+ * A call counts whatever the logger's level: a `Logger` at `'off'` prints
23
+ * nothing and is still a logged error, so a test's silent logger hides nothing
24
+ * from the gate. A test that replaces `console.error` with a spy has claimed
25
+ * the calls it swallows; a `Logger` call still reaches the gate first.
26
+ *
27
+ * Errors only — warnings are not gated. An error logged outside any test (a
28
+ * `beforeAll` or `afterAll`, the file's top level) fails the file in its last
29
+ * `afterAll`, allowed by any `allow_logged_error` the file declared at
30
+ * collection. The check runs in the last of the test's `onTestFinished` hooks,
31
+ * after its `afterEach` hooks and after a `create_test_app` app's close, so
32
+ * what a shutdown logs counts. A test that already failed is left as it
33
+ * failed. An error a test's work logs after the test has finished — a
34
+ * background timer, an effect nothing awaited — lands on the next test or the
35
+ * file. A concurrent test runs beside its siblings, so no buffer can say whose
36
+ * error a log is: what it logs goes to the file's, checked in its last
37
+ * `afterAll` against the file's allowances, and both `expect_logged_error` and
38
+ * `allow_logged_error` throw in one — allow its errors on its `describe`, at
39
+ * collection.
40
+ *
41
+ * @module
42
+ */
43
+ import { inspect } from 'node:util';
44
+ import { afterAll, beforeEach, TestRunner } from 'vitest';
45
+ import { Logger } from '@fuzdev/fuz_util/log.ts';
46
+ import { RATE_LIMITERS_DISABLED_BANNER } from '../rate_limiter.js';
47
+ import { LOGIN_FAIL_FLOOR_DISABLED_BANNER, SIGNUP_FAIL_FLOOR_DISABLED_BANNER } from '../auth/fail_floor.js';
48
+ /**
49
+ * The designed test-mode banners, allowed in every test: each is printed with
50
+ * `console.error`, once per module instance, when a test-only mode is on, so a
51
+ * production log that shows one is the alarm. In a test run they are the
52
+ * mode working.
53
+ */
54
+ export const LOGGED_ERROR_BANNERS = [
55
+ {
56
+ pattern: RATE_LIMITERS_DISABLED_BANNER,
57
+ reason: "the banner of `rate_limiters: 'disabled_for_testing'`, the test default"
58
+ },
59
+ {
60
+ pattern: LOGIN_FAIL_FLOOR_DISABLED_BANNER,
61
+ reason: 'the banner of a login failure timing floor of 0, the test default'
62
+ },
63
+ {
64
+ pattern: SIGNUP_FAIL_FLOOR_DISABLED_BANNER,
65
+ reason: 'the banner of a signup failure timing floor of 0, the test default'
66
+ }
67
+ ];
68
+ const GATE_STATE_KEY = Symbol.for('@fuzdev/fuz_app/testing/logged_errors');
69
+ /** Marks a function as the gate's wrapper, so it is installed once per object. */
70
+ const WRAPPED_KEY = Symbol.for('@fuzdev/fuz_app/testing/logged_errors/wrapped');
71
+ /** How much of an error's text a failure message shows. */
72
+ const REPORTED_TEXT_MAX_LENGTH = 600;
73
+ const format_logged_value = (value) => {
74
+ if (typeof value === 'string')
75
+ return value;
76
+ if (value instanceof Error) {
77
+ const cause = value.cause === undefined ? '' : ` [cause: ${format_logged_value(value.cause)}]`;
78
+ return `${value.name}: ${value.message}${cause}`;
79
+ }
80
+ return inspect(value, { depth: 4, breakLength: Infinity });
81
+ };
82
+ const format_logged_args = (args) => args.map(format_logged_value).join(' ');
83
+ const pattern_matches = (pattern, text) => typeof pattern === 'string' ? text.includes(pattern) : text.search(pattern) !== -1;
84
+ const record_logged_error = (state, error) => {
85
+ if (state.file === null)
86
+ return;
87
+ (state.test?.errors ?? state.file.outside).push(error);
88
+ };
89
+ const wrap_error_method = (target, state, source, format) => {
90
+ const original = target.error;
91
+ if (original[WRAPPED_KEY])
92
+ return;
93
+ const wrapped = function (...args) {
94
+ if (source === 'logger') {
95
+ record_logged_error(state, { source, text: format(this, args) });
96
+ const outer = state.in_logger;
97
+ state.in_logger = true;
98
+ try {
99
+ return original.apply(this, args);
100
+ }
101
+ finally {
102
+ state.in_logger = outer;
103
+ }
104
+ }
105
+ if (!state.in_logger)
106
+ record_logged_error(state, { source, text: format(this, args) });
107
+ return original.apply(this, args);
108
+ };
109
+ wrapped[WRAPPED_KEY] = true;
110
+ target.error = wrapped;
111
+ };
112
+ /** The gate state, creating it and wrapping `Logger.prototype.error` and `console.error` once. */
113
+ const get_gate_state = () => {
114
+ const globals = globalThis;
115
+ let state = globals[GATE_STATE_KEY];
116
+ if (!state) {
117
+ state = { file: null, test: null, in_logger: false };
118
+ globals[GATE_STATE_KEY] = state;
119
+ }
120
+ // each its own check: under `isolate` a file may load a fresh `Logger`
121
+ wrap_error_method(Logger.prototype, state, 'logger', (self, args) => {
122
+ const label = self.label;
123
+ const text = format_logged_args(args);
124
+ return label ? `[${label}] ${text}` : text;
125
+ });
126
+ wrap_error_method(console, state, 'console', (_self, args) => format_logged_args(args));
127
+ return state;
128
+ };
129
+ /** The gate state if a setup file installed it, else `null`. */
130
+ const read_gate_state = () => {
131
+ const state = globalThis[GATE_STATE_KEY];
132
+ return state?.file ? state : null;
133
+ };
134
+ const validate_allowance = (allowance, label) => {
135
+ if (typeof allowance.reason !== 'string' || allowance.reason.trim() === '') {
136
+ throw new Error(`${label}: an allowed logged error needs its reason (${String(allowance.pattern)})`);
137
+ }
138
+ if (allowance.pattern === '') {
139
+ throw new Error(`${label}: an empty pattern would allow every logged error`);
140
+ }
141
+ };
142
+ /** Whether `suite` is `task` or one of its ancestors. */
143
+ const task_is_within = (task, suite) => {
144
+ for (let t = task; t; t = t.suite) {
145
+ if (t === suite)
146
+ return true;
147
+ }
148
+ return false;
149
+ };
150
+ const format_unexpected = (errors, where) => {
151
+ const lines = errors.map((e) => {
152
+ const text = e.text.length > REPORTED_TEXT_MAX_LENGTH
153
+ ? `${e.text.slice(0, REPORTED_TEXT_MAX_LENGTH)}…`
154
+ : e.text;
155
+ return ` - (${e.source}) ${text}`;
156
+ });
157
+ return (`${where} logged ${errors.length === 1 ? 'an error' : 'errors'} it did not declare:\n` +
158
+ `${lines.join('\n')}\n` +
159
+ 'Declare one the test provokes with `expect_logged_error(pattern)`, or one it ' +
160
+ 'tolerates with `allow_logged_error(pattern, reason)` (`testing/logged_errors.ts`).');
161
+ };
162
+ const check_test = (file, test) => {
163
+ const allowed = (text) => file.global.some((a) => pattern_matches(a.pattern, text)) ||
164
+ test.allowances.some((a) => pattern_matches(a.pattern, text)) ||
165
+ file.allowances.some((a) => (a.suite === null || task_is_within(test.task, a.suite)) && pattern_matches(a.pattern, text)) ||
166
+ test.expected.some((x) => pattern_matches(x.pattern, text));
167
+ const missing = test.expected.filter((x) => !test.errors.some((e) => pattern_matches(x.pattern, e.text)));
168
+ const unexpected = test.errors.filter((e) => !allowed(e.text));
169
+ const problems = [];
170
+ if (missing.length > 0) {
171
+ problems.push(`expected a logged error matching ${missing.map((x) => String(x.pattern)).join(', ')}, ` +
172
+ `but ${test.errors.length === 0 ? 'none was logged' : `the test logged only:\n${test.errors.map((e) => ` - ${e.text.slice(0, REPORTED_TEXT_MAX_LENGTH)}`).join('\n')}`}`);
173
+ }
174
+ if (unexpected.length > 0)
175
+ problems.push(format_unexpected(unexpected, 'the test'));
176
+ if (problems.length > 0)
177
+ throw new Error(problems.join('\n\n'));
178
+ };
179
+ /**
180
+ * Install the gate for the current test file — call at the top level of a
181
+ * vitest `setupFiles` module, which vitest runs ahead of each test file. Wraps
182
+ * `Logger.prototype.error` and `console.error` once per process (each wrapper
183
+ * calls the original), resets the file's state, and registers the file's
184
+ * hooks: a `beforeEach` that starts the test's buffer and checks it in an
185
+ * `onTestFinished` hook, and an `afterAll` that checks what was logged outside
186
+ * any test.
187
+ *
188
+ * @param options - errors allowed in every test beside `LOGGED_ERROR_BANNERS`
189
+ * @throws Error on an allowance without its reason
190
+ */
191
+ export const install_logged_error_gate = (options = {}) => {
192
+ const global = [...LOGGED_ERROR_BANNERS, ...(options.allow ?? [])];
193
+ for (const allowance of global)
194
+ validate_allowance(allowance, 'install_logged_error_gate');
195
+ const state = get_gate_state();
196
+ const file = { global, allowances: [], outside: [] };
197
+ state.file = file;
198
+ state.test = null;
199
+ beforeEach((ctx) => {
200
+ // a concurrent test runs beside its siblings, so no buffer can tell whose
201
+ // error a log is: what it logs goes to the file's, checked in `afterAll`
202
+ if (ctx.task.concurrent) {
203
+ state.test = null;
204
+ return;
205
+ }
206
+ const test = { task: ctx.task, errors: [], allowances: [], expected: [] };
207
+ state.test = test;
208
+ // the first `onTestFinished` hook registered runs last: after the test's
209
+ // own, so what a `create_test_app` close logs is the test's
210
+ ctx.onTestFinished(({ task }) => {
211
+ if (state.test === test)
212
+ state.test = null;
213
+ if (task.result?.state === 'fail')
214
+ return;
215
+ check_test(file, test);
216
+ });
217
+ });
218
+ afterAll(() => {
219
+ state.test = null;
220
+ const unexpected = file.outside.filter((e) => !file.global.some((a) => pattern_matches(a.pattern, e.text)) &&
221
+ !file.allowances.some((a) => pattern_matches(a.pattern, e.text)));
222
+ file.outside.length = 0;
223
+ if (unexpected.length > 0) {
224
+ throw new Error(format_unexpected(unexpected, 'the file, outside any test or in a concurrent test,'));
225
+ }
226
+ });
227
+ };
228
+ /**
229
+ * Declare that the running test logs an error matching `pattern`, and fail
230
+ * the test when it ends unless one was logged: the error the test provokes is
231
+ * asserted, not just tolerated. Every error the pattern matches is allowed.
232
+ *
233
+ * @param pattern - a substring of the error's text, or a `RegExp` searched for
234
+ * @throws Error outside a test, in a concurrent test, or when no setup file installed the gate
235
+ */
236
+ export const expect_logged_error = (pattern) => {
237
+ const state = read_gate_state();
238
+ if (!state) {
239
+ throw new Error('expect_logged_error needs the logged-error gate — install it in a setup file (`install_logged_error_gate`)');
240
+ }
241
+ const current = TestRunner.getCurrentTest();
242
+ if (current?.concurrent) {
243
+ throw new Error("expect_logged_error: a concurrent test's errors can't be attributed to it — allow them with `allow_logged_error` on its `describe`");
244
+ }
245
+ if (!state.test || !current) {
246
+ throw new Error('expect_logged_error must be called inside a test');
247
+ }
248
+ if (pattern === '')
249
+ throw new Error('expect_logged_error: an empty pattern matches every error');
250
+ state.test.expected.push({ pattern });
251
+ };
252
+ /**
253
+ * Allow logged errors matching `pattern`, with the reason they are expected:
254
+ * inside a test, for that test; at collection, for every test of the
255
+ * enclosing `describe` (the whole file at its top level) and for what the
256
+ * file logs outside its tests or in its concurrent tests. It throws in a
257
+ * concurrent test, whose errors share the file's bucket with its siblings',
258
+ * so an allowance made there would hide theirs. Unlike `expect_logged_error`
259
+ * it asserts nothing. A no-op when no setup file installed the gate.
260
+ *
261
+ * @param pattern - a substring of the error's text, or a `RegExp` searched for
262
+ * @param reason - why the error is expected; required
263
+ * @throws Error on an empty reason or pattern, or in a concurrent test
264
+ */
265
+ export const allow_logged_error = (pattern, reason) => {
266
+ validate_allowance({ pattern, reason }, 'allow_logged_error');
267
+ const state = read_gate_state();
268
+ if (!state)
269
+ return;
270
+ const current = TestRunner.getCurrentTest();
271
+ if (current?.concurrent) {
272
+ // an allowance it added would reach the file's bucket, every sibling's
273
+ // errors in it, so its errors are allowed where the scope is visible
274
+ throw new Error("allow_logged_error: a concurrent test's errors can't be attributed to it — allow them on its `describe`, at collection");
275
+ }
276
+ if (state.test && current) {
277
+ state.test.allowances.push({ pattern, reason });
278
+ return;
279
+ }
280
+ state.file.allowances.push({
281
+ pattern,
282
+ reason,
283
+ suite: TestRunner.getCurrentSuite().suite ?? null
284
+ });
285
+ };