@fuzdev/fuz_app 0.182.0 → 0.183.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 (191) hide show
  1. package/README.md +2 -0
  2. package/dist/actions/CLAUDE.md +4 -4
  3. package/dist/auth/CLAUDE.md +58 -34
  4. package/dist/auth/account_routes.d.ts +5 -3
  5. package/dist/auth/account_routes.d.ts.map +1 -1
  6. package/dist/auth/account_routes.js +71 -66
  7. package/dist/auth/admin_actions.d.ts.map +1 -1
  8. package/dist/auth/admin_actions.js +22 -17
  9. package/dist/auth/audit_emitter.d.ts +75 -84
  10. package/dist/auth/audit_emitter.d.ts.map +1 -1
  11. package/dist/auth/audit_emitter.js +83 -71
  12. package/dist/auth/audit_log_schema.d.ts +10 -5
  13. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  14. package/dist/auth/audit_log_schema.js +22 -6
  15. package/dist/auth/bootstrap_account.d.ts +31 -13
  16. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  17. package/dist/auth/bootstrap_account.js +34 -15
  18. package/dist/auth/bootstrap_routes.d.ts +1 -1
  19. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  20. package/dist/auth/bootstrap_routes.js +7 -14
  21. package/dist/auth/deps.d.ts +8 -5
  22. package/dist/auth/deps.d.ts.map +1 -1
  23. package/dist/auth/deps.js +3 -2
  24. package/dist/auth/resolved_auth.d.ts +7 -7
  25. package/dist/auth/resolved_auth.d.ts.map +1 -1
  26. package/dist/auth/resolved_auth.js +4 -4
  27. package/dist/auth/role_grant_offer_actions.d.ts +25 -1
  28. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  29. package/dist/auth/role_grant_offer_actions.js +40 -33
  30. package/dist/auth/role_grant_offer_queries.d.ts +60 -4
  31. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  32. package/dist/auth/role_grant_offer_queries.js +79 -5
  33. package/dist/auth/role_grant_queries.d.ts +3 -52
  34. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  35. package/dist/auth/role_grant_queries.js +5 -80
  36. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  37. package/dist/auth/self_service_role_actions.js +11 -22
  38. package/dist/auth/session_queries.d.ts +6 -3
  39. package/dist/auth/session_queries.d.ts.map +1 -1
  40. package/dist/auth/session_queries.js +20 -11
  41. package/dist/auth/signup_routes.d.ts.map +1 -1
  42. package/dist/auth/signup_routes.js +90 -38
  43. package/dist/db/sql_columns.d.ts +1 -1
  44. package/dist/db/sql_columns.js +1 -1
  45. package/dist/http/CLAUDE.md +15 -10
  46. package/dist/http/db_routes.d.ts +7 -22
  47. package/dist/http/db_routes.d.ts.map +1 -1
  48. package/dist/http/db_routes.js +72 -72
  49. package/dist/http/pending_effects.d.ts +42 -4
  50. package/dist/http/pending_effects.d.ts.map +1 -1
  51. package/dist/http/pending_effects.js +34 -4
  52. package/dist/server/app_server.d.ts +43 -2
  53. package/dist/server/app_server.d.ts.map +1 -1
  54. package/dist/server/app_server.js +57 -3
  55. package/dist/testing/CLAUDE.md +255 -786
  56. package/dist/testing/adversarial_404.d.ts +6 -1
  57. package/dist/testing/adversarial_404.d.ts.map +1 -1
  58. package/dist/testing/adversarial_404.js +38 -17
  59. package/dist/testing/app_server.d.ts +20 -140
  60. package/dist/testing/app_server.d.ts.map +1 -1
  61. package/dist/testing/app_server.js +45 -124
  62. package/dist/testing/audit_drift_guard.d.ts +11 -6
  63. package/dist/testing/audit_drift_guard.d.ts.map +1 -1
  64. package/dist/testing/audit_drift_guard.js +15 -8
  65. package/dist/testing/cross_backend/audit_cross_helpers.d.ts +12 -9
  66. package/dist/testing/cross_backend/audit_cross_helpers.d.ts.map +1 -1
  67. package/dist/testing/cross_backend/audit_cross_helpers.js +13 -14
  68. package/dist/testing/cross_backend/capabilities.d.ts +9 -6
  69. package/dist/testing/cross_backend/capabilities.d.ts.map +1 -1
  70. package/dist/testing/cross_backend/capabilities.js +11 -7
  71. package/dist/testing/cross_backend/capability_mounts.d.ts +103 -0
  72. package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -0
  73. package/dist/testing/cross_backend/capability_mounts.js +423 -0
  74. package/dist/testing/cross_backend/cell_moderate.js +2 -2
  75. package/dist/testing/cross_backend/cell_relations.d.ts.map +1 -1
  76. package/dist/testing/cross_backend/cell_relations.js +12 -11
  77. package/dist/testing/cross_backend/conformance_principal.d.ts +54 -0
  78. package/dist/testing/cross_backend/conformance_principal.d.ts.map +1 -0
  79. package/dist/testing/cross_backend/conformance_principal.js +283 -0
  80. package/dist/testing/cross_backend/conformance_table.d.ts +2 -50
  81. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  82. package/dist/testing/cross_backend/conformance_table.js +2 -270
  83. package/dist/testing/cross_backend/credential_deadline.d.ts.map +1 -1
  84. package/dist/testing/cross_backend/credential_deadline.js +2 -0
  85. package/dist/testing/cross_backend/credential_wire.d.ts +1 -1
  86. package/dist/testing/cross_backend/credential_wire.d.ts.map +1 -1
  87. package/dist/testing/cross_backend/db_state_diff.d.ts +72 -0
  88. package/dist/testing/cross_backend/db_state_diff.d.ts.map +1 -0
  89. package/dist/testing/cross_backend/db_state_diff.js +444 -0
  90. package/dist/testing/cross_backend/declared_skips.d.ts +68 -0
  91. package/dist/testing/cross_backend/declared_skips.d.ts.map +1 -0
  92. package/dist/testing/cross_backend/declared_skips.js +132 -0
  93. package/dist/testing/cross_backend/differential.d.ts +11 -2
  94. package/dist/testing/cross_backend/differential.d.ts.map +1 -1
  95. package/dist/testing/cross_backend/differential.js +35 -11
  96. package/dist/testing/cross_backend/differential_normalize.d.ts +12 -0
  97. package/dist/testing/cross_backend/differential_normalize.d.ts.map +1 -1
  98. package/dist/testing/cross_backend/differential_normalize.js +16 -0
  99. package/dist/testing/cross_backend/in_process_setup.d.ts +22 -12
  100. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  101. package/dist/testing/cross_backend/in_process_setup.js +151 -134
  102. package/dist/testing/cross_backend/login_security.d.ts +12 -0
  103. package/dist/testing/cross_backend/login_security.d.ts.map +1 -1
  104. package/dist/testing/cross_backend/login_security.js +21 -4
  105. package/dist/testing/cross_backend/request_target_conformance_wire.d.ts +0 -2
  106. package/dist/testing/cross_backend/request_target_conformance_wire.d.ts.map +1 -1
  107. package/dist/testing/cross_backend/request_target_conformance_wire.js +3 -1
  108. package/dist/testing/cross_backend/revocation_drivers.d.ts +18 -5
  109. package/dist/testing/cross_backend/revocation_drivers.d.ts.map +1 -1
  110. package/dist/testing/cross_backend/revocation_drivers.js +18 -10
  111. package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts +1 -1
  112. package/dist/testing/cross_backend/role_grant_cross_helpers.d.ts.map +1 -1
  113. package/dist/testing/cross_backend/role_grant_offer_lifecycle.d.ts.map +1 -1
  114. package/dist/testing/cross_backend/role_grant_offer_lifecycle.js +33 -1
  115. package/dist/testing/cross_backend/role_grant_participation.js +4 -4
  116. package/dist/testing/cross_backend/rpc_adversarial.js +1 -1
  117. package/dist/testing/cross_backend/session_cap.d.ts +2 -2
  118. package/dist/testing/cross_backend/session_cap.d.ts.map +1 -1
  119. package/dist/testing/cross_backend/session_cap.js +22 -11
  120. package/dist/testing/cross_backend/setup.d.ts +31 -1
  121. package/dist/testing/cross_backend/setup.d.ts.map +1 -1
  122. package/dist/testing/cross_backend/setup.js +32 -1
  123. package/dist/testing/cross_backend/spine_suites.d.ts +123 -12
  124. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  125. package/dist/testing/cross_backend/spine_suites.js +454 -57
  126. package/dist/testing/cross_backend/spine_surface_constants.d.ts +1 -1
  127. package/dist/testing/cross_backend/spine_surface_constants.d.ts.map +1 -1
  128. package/dist/testing/cross_backend/spine_surface_constants.js +1 -0
  129. package/dist/testing/cross_backend/sse_round_trip.d.ts +9 -1
  130. package/dist/testing/cross_backend/sse_round_trip.d.ts.map +1 -1
  131. package/dist/testing/cross_backend/sse_round_trip.js +123 -27
  132. package/dist/testing/cross_backend/testing_backdoor.d.ts.map +1 -1
  133. package/dist/testing/cross_backend/testing_backdoor.js +4 -2
  134. package/dist/testing/cross_backend/testing_reset_actions.d.ts +59 -27
  135. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  136. package/dist/testing/cross_backend/testing_reset_actions.js +66 -42
  137. package/dist/testing/cross_backend/transport_composition.d.ts +1 -1
  138. package/dist/testing/cross_backend/transport_composition.d.ts.map +1 -1
  139. package/dist/testing/cross_backend/transport_composition.js +7 -3
  140. package/dist/testing/cross_backend/ws_round_trip.d.ts +5 -0
  141. package/dist/testing/cross_backend/ws_round_trip.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/ws_round_trip.js +54 -8
  143. package/dist/testing/data_exposure.d.ts.map +1 -1
  144. package/dist/testing/data_exposure.js +3 -0
  145. package/dist/testing/db.d.ts +0 -32
  146. package/dist/testing/db.d.ts.map +1 -1
  147. package/dist/testing/db.js +0 -86
  148. package/dist/testing/db_entities.d.ts +14 -0
  149. package/dist/testing/db_entities.d.ts.map +1 -1
  150. package/dist/testing/db_entities.js +17 -0
  151. package/dist/testing/db_invariant_queries.d.ts +259 -0
  152. package/dist/testing/db_invariant_queries.d.ts.map +1 -0
  153. package/dist/testing/db_invariant_queries.js +400 -0
  154. package/dist/testing/db_invariants.d.ts +106 -0
  155. package/dist/testing/db_invariants.d.ts.map +1 -0
  156. package/dist/testing/db_invariants.gen.sql.d.ts +11 -0
  157. package/dist/testing/db_invariants.gen.sql.d.ts.map +1 -0
  158. package/dist/testing/db_invariants.gen.sql.js +13 -0
  159. package/dist/testing/db_invariants.js +141 -0
  160. package/dist/testing/db_invariants.sql +152 -0
  161. package/dist/testing/describe_db.d.ts +36 -0
  162. package/dist/testing/describe_db.d.ts.map +1 -0
  163. package/dist/testing/describe_db.js +71 -0
  164. package/dist/testing/integration.d.ts +6 -9
  165. package/dist/testing/integration.d.ts.map +1 -1
  166. package/dist/testing/integration.js +9 -13
  167. package/dist/testing/integration_helpers.d.ts +1 -1
  168. package/dist/testing/integration_helpers.d.ts.map +1 -1
  169. package/dist/testing/rate_limiting.d.ts +1 -1
  170. package/dist/testing/rate_limiting.d.ts.map +1 -1
  171. package/dist/testing/rate_limiting.js +3 -2
  172. package/dist/testing/role_grant_helpers.d.ts +1 -1
  173. package/dist/testing/role_grant_helpers.d.ts.map +1 -1
  174. package/dist/testing/round_trip.d.ts.map +1 -1
  175. package/dist/testing/round_trip.js +3 -0
  176. package/dist/testing/rpc_attack_surface.d.ts +8 -6
  177. package/dist/testing/rpc_attack_surface.d.ts.map +1 -1
  178. package/dist/testing/rpc_attack_surface.js +69 -6
  179. package/dist/testing/rpc_round_trip.d.ts +1 -1
  180. package/dist/testing/rpc_round_trip.d.ts.map +1 -1
  181. package/dist/testing/rpc_round_trip.js +3 -0
  182. package/dist/testing/sse_round_trip.d.ts +1 -1
  183. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  184. package/dist/testing/sse_round_trip.js +13 -4
  185. package/dist/testing/stubs.d.ts +4 -2
  186. package/dist/testing/stubs.d.ts.map +1 -1
  187. package/dist/testing/stubs.js +10 -5
  188. package/dist/testing/test_app.d.ts +166 -0
  189. package/dist/testing/test_app.d.ts.map +1 -0
  190. package/dist/testing/test_app.js +124 -0
  191. package/package.json +1 -1
@@ -11,6 +11,8 @@ import { generate_random_base64url } from '../crypto.js';
11
11
  import { create_session_cookie_value } from './session_cookie.js';
12
12
  import { columns_sql, iso8601_timestamp_expr, qualify_columns } from '../db/sql_columns.js';
13
13
  import { EXPIRES_IN_MS_SQL } from './credential_deadline.js';
14
+ /** The session lifetime in whole seconds, which the insert's interval spells. */
15
+ const AUTH_SESSION_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
14
16
  /**
15
17
  * Session lifetime in milliseconds (30 days).
16
18
  *
@@ -19,7 +21,7 @@ import { EXPIRES_IN_MS_SQL } from './credential_deadline.js';
19
21
  * window renews a leaked cookie forever; see `docs/security.md` §Session
20
22
  * Security). The cookie's `SESSION_AGE_MAX` mirrors this value.
21
23
  */
22
- export const AUTH_SESSION_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
24
+ export const AUTH_SESSION_LIFETIME_MS = AUTH_SESSION_LIFETIME_SECONDS * 1000;
23
25
  /**
24
26
  * Hash a session token to its storage key using blake3.
25
27
  *
@@ -41,20 +43,28 @@ export const generate_session_token = () => {
41
43
  return generate_random_base64url();
42
44
  };
43
45
  /**
44
- * Create a new auth session.
46
+ * `AUTH_SESSION_LIFETIME_MS` as the SQL interval the session insert adds to
47
+ * `NOW()` — `INTERVAL '2592000 seconds'`, the Rust spine's literal. Elapsed
48
+ * seconds, not `'30 days'`: a day interval is calendar time in the session's
49
+ * time zone, so a session crossing a DST change would live an hour more or
50
+ * less.
51
+ */
52
+ const AUTH_SESSION_LIFETIME_SQL = `INTERVAL '${AUTH_SESSION_LIFETIME_SECONDS} seconds'`;
53
+ /**
54
+ * Create a new auth session, expiring `AUTH_SESSION_LIFETIME_MS` after the
55
+ * database's `NOW()` — the clock the validity check (`expires_at > NOW()`)
56
+ * reads, and the one `created_at` takes, so the expiry sits a whole lifetime
57
+ * past the row's creation and every session one transaction creates shares
58
+ * it. Twin of the Rust `query_create_session`, same statement.
45
59
  *
46
60
  * @param deps - query dependencies
47
61
  * @param token_hash - blake3 hash of the session token (use `hash_session_token`)
48
62
  * @param account_id - the account this session belongs to
49
- * @param expires_at - when the session expires
50
63
  * @mutates `auth_session` table - inserts a row keyed by `token_hash`
51
64
  */
52
- export const query_create_session = async (deps, token_hash, account_id, expires_at) => {
53
- await deps.db.query(`INSERT INTO auth_session (id, account_id, expires_at) VALUES ($1, $2, $3)`, [
54
- token_hash,
55
- account_id,
56
- expires_at.toISOString()
57
- ]);
65
+ export const query_create_session = async (deps, token_hash, account_id) => {
66
+ await deps.db.query(`INSERT INTO auth_session (id, account_id, expires_at)
67
+ VALUES ($1, $2, NOW() + ${AUTH_SESSION_LIFETIME_SQL})`, [token_hash, account_id]);
58
68
  };
59
69
  /**
60
70
  * The full `auth_session` column set, named explicitly so a row read fails
@@ -313,8 +323,7 @@ export const create_capped_session = async (options) => {
313
323
  const { keyring, deps, account_id, session_options, max_sessions } = options;
314
324
  const session_token = generate_session_token();
315
325
  const token_hash = hash_session_token(session_token);
316
- const expires_at = new Date(Date.now() + AUTH_SESSION_LIFETIME_MS);
317
- await query_create_session(deps, token_hash, account_id, expires_at);
326
+ await query_create_session(deps, token_hash, account_id);
318
327
  const evicted = max_sessions != null ? await query_session_enforce_limit(deps, account_id, max_sessions) : [];
319
328
  const cookie_value = await create_session_cookie_value(keyring, session_token, session_options);
320
329
  return { cookie_value, evicted };
@@ -1 +1 @@
1
- {"version":3,"file":"signup_routes.d.ts","sourceRoot":"","sources":["../../src/lib/auth/signup_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAcH,OAAO,EAAwB,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAG7E,OAAO,EAAoB,KAAK,WAAW,EAA6B,MAAM,oBAAoB,CAAC;AACnG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAOlD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAGnE;;;;;;;;;;GAUG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAEhD;;;;;;;GAOG;AACH,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,uBAAuB;IAClE;;;;;;;;;OASG;IACH,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C,6FAA6F;IAC7F,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAID;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,GACrC,MAAM,gBAAgB,EACtB,SAAS,kBAAkB,KACzB,KAAK,CAAC,SAAS,CA2NjB,CAAC"}
1
+ {"version":3,"file":"signup_routes.d.ts","sourceRoot":"","sources":["../../src/lib/auth/signup_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAcH,OAAO,EAAwB,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAI7E,OAAO,EAAoB,KAAK,WAAW,EAA6B,MAAM,oBAAoB,CAAC;AACnG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAOlD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAGnE;;;;;;;;;;GAUG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAEhD;;;;;;;GAOG;AACH,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,uBAAuB;IAClE;;;;;;;;;OASG;IACH,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C,6FAA6F;IAC7F,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAID;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,GACrC,MAAM,gBAAgB,EACtB,SAAS,kBAAkB,KACzB,KAAK,CAAC,SAAS,CA2QjB,CAAC"}
@@ -15,6 +15,7 @@ import { query_invite_find_unclaimed_match_for_update, query_invite_claim_unscop
15
15
  import { create_signup_route_shape } from './signup_route_schema.js';
16
16
  import { attach_route_handler } from '../http/route_spec.js';
17
17
  import { route_fail, route_ok } from '../http/route_result.js';
18
+ import { transaction_with_post_commit_rollback } from '../http/pending_effects.js';
18
19
  import { rate_limit_ip_key } from '../http/ip_canonical.js';
19
20
  import { reserve_optional } from '../rate_limiter.js';
20
21
  import { REST_NO_MATCHING_INVITE, REST_RATE_LIMIT_EXCEEDED, REST_SIGNUP_CONFLICT } from '../http/error_schemas.js';
@@ -93,42 +94,88 @@ export const create_signup_route_specs = (deps, options) => {
93
94
  // invite-gated success (which spends an invite), a 5xx, and a
94
95
  // request with no resolved client IP. The per-account limiter
95
96
  // bounds retries of one username only.
96
- const { open_signup } = await query_app_settings_load(route);
97
- // Start the denial-time floor concurrently with failure work.
98
- // Observed response time for 403 / 409 is `max(work, delay)`
99
- // so the cheap `no_match` path (no Argon2, find returns
100
- // nothing) and the expensive `signup_conflict` path (Argon2
101
- // + tx + rollback) converge — closes the username-enumeration
102
- // timing oracle. The same `start_fail_floor` as login. Started
103
- // after rate-limit checks so 429 stays fast.
104
- const delay = start_fail_floor(signup_fail_floor_ms, signup_fail_jitter_ms);
105
- // Hash before the transaction so the connection isn't held
106
- // across the ~100ms Argon2id. Paid on every attempt that gets
107
- // here — bounded as described above.
108
- const password_hash = await password.hash_password(pw);
97
+ //
98
+ // A failure before the transaction (the settings load, the hash,
99
+ // the `BEGIN`) leaves the `internal_error` row Rust's
100
+ // pre-transaction failures write: no `invite_id` (no find has
101
+ // run) and no `open_signup` (the load may be what failed). 5xx
102
+ // is not floored. Both failure-row helpers log an emit that
103
+ // throws rather than throwing, so the answer is always the
104
+ // original error or refusal, never the emit's.
105
+ const log_failure_audit_error = (err) => {
106
+ deps.log.error('signup: the failure audit emit threw:', err);
107
+ };
108
+ const emit_pre_tx_failure_audit = async () => {
109
+ try {
110
+ await deps.audit.emit(route, {
111
+ event_type: 'signup',
112
+ outcome: 'failure',
113
+ ip: route.client_ip,
114
+ metadata: {
115
+ username,
116
+ reason: 'internal_error',
117
+ ...(email != null && { email })
118
+ }
119
+ });
120
+ }
121
+ catch (err) {
122
+ log_failure_audit_error(err);
123
+ }
124
+ };
125
+ let open_signup;
126
+ let password_hash;
127
+ let delay;
128
+ try {
129
+ ({ open_signup } = await query_app_settings_load(route));
130
+ // Start the denial-time floor concurrently with failure work.
131
+ // Observed response time for 403 / 409 is `max(work, delay)`
132
+ // so the cheap `no_match` path (no Argon2, find returns
133
+ // nothing) and the expensive `signup_conflict` path (Argon2
134
+ // + tx + rollback) converge — closes the username-enumeration
135
+ // timing oracle. The same `start_fail_floor` as login. Started
136
+ // after rate-limit checks so 429 stays fast.
137
+ delay = start_fail_floor(signup_fail_floor_ms, signup_fail_jitter_ms);
138
+ // Hash before the transaction so the connection isn't held
139
+ // across the ~100ms Argon2id. Paid on every attempt that gets
140
+ // here — bounded as described above.
141
+ password_hash = await password.hash_password(pw);
142
+ }
143
+ catch (e) {
144
+ await emit_pre_tx_failure_audit();
145
+ throw e;
146
+ }
109
147
  // `invite` is assigned inside the tx by the FOR UPDATE find;
110
148
  // captured at the outer scope so the failure-audit catch
111
149
  // branch can still reference `invite.id` after the tx rolls
112
150
  // back on PG unique violation.
113
151
  let invite;
114
152
  const emit_failure_audit = async (reason) => {
115
- await deps.audit.emit(route, {
116
- event_type: 'signup',
117
- outcome: 'failure',
118
- ip: route.client_ip,
119
- metadata: {
120
- username,
121
- reason,
122
- ...(invite && { invite_id: invite.id }),
123
- ...(email != null && { email }),
124
- ...(open_signup && { open_signup: true })
125
- }
126
- });
153
+ try {
154
+ await deps.audit.emit(route, {
155
+ event_type: 'signup',
156
+ outcome: 'failure',
157
+ ip: route.client_ip,
158
+ metadata: {
159
+ username,
160
+ reason,
161
+ ...(invite && { invite_id: invite.id }),
162
+ ...(email != null && { email }),
163
+ ...(open_signup && { open_signup: true })
164
+ }
165
+ });
166
+ }
167
+ catch (err) {
168
+ log_failure_audit_error(err);
169
+ }
127
170
  };
128
171
  let result;
172
+ // whether the transaction began: a failure before it (the
173
+ // `BEGIN` itself, a pool checkout) is a pre-transaction failure,
174
+ // whose row carries no `open_signup`, as on the Rust spine
175
+ let tx_began = false;
129
176
  try {
130
- result = await route.db.transaction(async (tx) => {
131
- const tx_deps = { db: tx };
177
+ result = await transaction_with_post_commit_rollback(route, async (tx_ctx) => {
178
+ tx_began = true;
132
179
  // Find + claim run inside the same transaction so the
133
180
  // row lock makes them atomic. Concurrent signups for
134
181
  // the same (username, email) tuple block on the lock
@@ -137,12 +184,12 @@ export const create_signup_route_specs = (deps, options) => {
137
184
  // flipped `claimed_at`) and falls through to
138
185
  // `ERROR_NO_MATCHING_INVITE`. No race window.
139
186
  if (!open_signup) {
140
- invite = await query_invite_find_unclaimed_match_for_update(tx_deps, email ?? null, username);
187
+ invite = await query_invite_find_unclaimed_match_for_update(tx_ctx, email ?? null, username);
141
188
  if (!invite) {
142
189
  throw new NoMatchingInviteError();
143
190
  }
144
191
  }
145
- const { account, actor } = await query_create_account_with_actor(tx_deps, {
192
+ const { account, actor } = await query_create_account_with_actor(tx_ctx, {
146
193
  username,
147
194
  password_hash,
148
195
  email
@@ -154,7 +201,7 @@ export const create_signup_route_specs = (deps, options) => {
154
201
  // that invariant broke — refuse loudly (the throw
155
202
  // rolls the account back) rather than mint an
156
203
  // account no invite admitted.
157
- const claimed = await query_invite_claim_unscoped(tx_deps, invite.id, account.id);
204
+ const claimed = await query_invite_claim_unscoped(tx_ctx, invite.id, account.id);
158
205
  if (!claimed) {
159
206
  throw new Error(`invite ${invite.id} was already claimed despite the FOR UPDATE lock`);
160
207
  }
@@ -164,11 +211,22 @@ export const create_signup_route_specs = (deps, options) => {
164
211
  // once the commit has landed
165
212
  const session = await create_capped_session({
166
213
  keyring,
167
- deps: tx_deps,
214
+ deps: tx_ctx,
168
215
  account_id: account.id,
169
216
  session_options
170
217
  });
171
218
  const set_cookie = session_cookie_header(session.cookie_value, session_options);
219
+ // the success row, last: a refused row rolls the account back
220
+ // and answers through the `internal_error` catch below
221
+ await deps.audit.emit(tx_ctx, {
222
+ event_type: 'signup',
223
+ actor_id: actor.id,
224
+ account_id: account.id,
225
+ ip: route.client_ip,
226
+ metadata: invite
227
+ ? { invite_id: invite.id, username }
228
+ : { open_signup: true, username }
229
+ });
172
230
  return { account, actor, set_cookie };
173
231
  });
174
232
  }
@@ -195,7 +253,7 @@ export const create_signup_route_specs = (deps, options) => {
195
253
  // `internal_error` before rethrowing. 5xx responses are
196
254
  // not floored: they aren't response-time-controlled
197
255
  // enumeration oracles.
198
- await emit_failure_audit('internal_error');
256
+ await (tx_began ? emit_failure_audit('internal_error') : emit_pre_tx_failure_audit());
199
257
  throw e;
200
258
  }
201
259
  // Clear the account-grain bucket only — the IP aggregate stands.
@@ -216,12 +274,6 @@ export const create_signup_route_specs = (deps, options) => {
216
274
  // dry); the `finally` releases it.
217
275
  if (open_signup)
218
276
  ip_reserved.reservation.record();
219
- await deps.audit.emit(route, {
220
- event_type: 'signup',
221
- account_id: result.account.id,
222
- ip: route.client_ip,
223
- metadata: invite ? { invite_id: invite.id, username } : { open_signup: true, username }
224
- });
225
277
  return route_ok({
226
278
  ok: true,
227
279
  account: { id: result.account.id, username: result.account.username },
@@ -9,7 +9,7 @@
9
9
  * `qualify_columns` for reads that alias the table, `omit_columns` for a
10
10
  * client-safe subset — rather than spelling a second column list, so the
11
11
  * drift guard on the base const (`assert_columns_match_live` in
12
- * `testing/db.ts`) covers every derived projection too. Twin of the Rust
12
+ * `testing/describe_db.ts`) covers every derived projection too. Twin of the Rust
13
13
  * spine's `*_COLUMNS` consts + `fuz_db::qualify_columns` / `omit_columns`.
14
14
  *
15
15
  * A read that needs a column rendered as something other than the bare
@@ -9,7 +9,7 @@
9
9
  * `qualify_columns` for reads that alias the table, `omit_columns` for a
10
10
  * client-safe subset — rather than spelling a second column list, so the
11
11
  * drift guard on the base const (`assert_columns_match_live` in
12
- * `testing/db.ts`) covers every derived projection too. Twin of the Rust
12
+ * `testing/describe_db.ts`) covers every derived projection too. Twin of the Rust
13
13
  * spine's `*_COLUMNS` consts + `fuz_db::qualify_columns` / `omit_columns`.
14
14
  *
15
15
  * A read that needs a column rendered as something other than the bare
@@ -685,7 +685,7 @@ interface EmitAfterCommitContext {
685
685
  // post_commit_effects: Array<() => void | Promise<void>>
686
686
  ```
687
687
 
688
- - **`pending_effects: Array<Promise<void>>`** — eager. Producers push the in-flight `Promise<void>` for fire-and-forget pool writes already running: audit emits via `AppDeps.audit`, session-touch UPDATE, api-token usage tracking. The pool write is rollback-resilient by virtue of running outside the request transaction; pushing the in-flight handle lets test mode (`await_pending_effects: true`) await it. Drain: `flush_pending_effects(effects, log, on_rejection?)`.
688
+ - **`pending_effects: Array<Promise<void>>`** — eager. Producers push the in-flight `Promise<void>` for fire-and-forget pool writes already running: failure audit rows via `AppDeps.audit`, session-touch UPDATE, api-token usage tracking. The pool write is rollback-resilient by virtue of running outside the request transaction; pushing the in-flight handle lets test mode (`await_pending_effects: true`) await it, and `AppServer.close` awaits the flushes production leaves running, bounded (`shutdown_drain_timeout_ms`). Drain: `flush_pending_effects(effects, log, on_rejection?)`.
689
689
  - **`post_commit_effects: Array<() => void | Promise<void>>`** — deferred. Producers go through `emit_after_commit(ctx, fn)` exclusively; raw thunks should not be pushed directly. The flush middleware (in `server/app_server.ts` and the per-message WS dispatcher in `actions/ws_socket_session.ts`) is the only site that invokes each thunk, after the wrapping `db.transaction` resolves. Drain: `flush_post_commit_effects(effects, log)`.
690
690
 
691
691
  ### Why split
@@ -711,8 +711,12 @@ threw, so a thrown handler (rolling back its transaction) would still fire the
711
711
  thunk it queued. So the contract is **two-sided**: both dispatch sites
712
712
  (`http/route_spec.ts`, `actions/perform_action.ts`) wrap their handler in the
713
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`
714
+ `post_commit_effects` on a handler throw, and a `transaction: false` handler
715
+ that opens its own transaction (`/login`, `/password`, signup, bootstrap) runs
716
+ it through `transaction_with_post_commit_rollback`, the same truncation around
717
+ just that transaction — so a handler that catches its transaction's failure
718
+ and answers a refusal still discards what it queued. `emit_after_commit` thus
719
+ reads as **"run iff the wrapping transaction commits."** The eager `pending_effects`
716
720
  queue is the deliberate opposite (survives rollback — attempt audits). The full
717
721
  two-sided contract + Rust-twin parity note live on the helper's TSDoc in
718
722
  `http/pending_effects.ts`.
@@ -761,8 +765,7 @@ Auth-aware variants (account status, bootstrap status) live in `auth/` —
761
765
  table browser; the factory is domain-agnostic.
762
766
 
763
767
  `create_db_route_specs(deps, {db_type, db_name, browsable_tables, extra_stats?, log?, non_deletable_tables?})` —
764
- `deps` is `DbRouteDeps`, a structural `audit` slice of `AppDeps` declared in
765
- `http/db_routes.ts` so this directory stays auth-free (`ctx.deps` satisfies it):
768
+ `deps` is `DbRouteDeps`, `{audit: Pick<AuditEmitter, 'emit'>}` (`ctx.deps` satisfies it):
766
769
 
767
770
  - `GET /health` — connected probe + table count (schema-wide by design — a did-migrations-run diagnostic) + optional `extra_stats(db)`. Returns `{connected: false}` at 503 on failure
768
771
  - `GET /tables` — list browsable tables with row counts
@@ -824,11 +827,13 @@ instead of discovering the refusal — `ui/table_state.svelte.ts` gates on
824
827
  `can_delete`. `primary_key` stays a truthful report of the key shape; a policy
825
828
  exclusion must not masquerade as one.
826
829
 
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,
830
+ **Every successful row delete is audited.** The `DELETE` handler writes its
831
+ `db_admin_row_delete` row with `deps.audit.emit` in the route's transaction,
832
+ after the savepoint's `try` (so a refused audit write fails the request rather
833
+ than reading as a row refusal): the row lands iff the delete commits, and a
834
+ refused row rolls the delete back, as on the Rust twin. Remounted with
835
+ `transaction: false`, the handler opens a transaction around just the delete
836
+ and its row (`transaction_with_post_commit_rollback`). Account-grain attribution (the browser's gate is account-grain,
832
837
  so no actor is claimed), metadata `{table, pk_column, id}`. Refusals emit
833
838
  nothing. The completeness gate covers the event via the
834
839
  `db_routes.db.test.ts` emission tests (excluded-with-justification in
@@ -10,9 +10,9 @@
10
10
  * @module
11
11
  */
12
12
  import type { Logger } from '@fuzdev/fuz_util/log.ts';
13
- import { type Uuid } from '../primitive_schemas.js';
14
13
  import type { Db, DbType } from '../db/db.js';
15
14
  import { type RouteSpec } from './route_spec.js';
15
+ import type { AuditEmitter } from '../auth/audit_emitter.js';
16
16
  /**
17
17
  * Table metadata from `information_schema`.
18
18
  */
@@ -93,31 +93,16 @@ export declare const NON_BROWSABLE_TABLES: ReadonlyArray<string>;
93
93
  */
94
94
  export declare const NON_DELETABLE_TABLES: ReadonlyArray<string>;
95
95
  /**
96
- * Capabilities the db routes need — a narrow structural slice of `AppDeps`
97
- * (`auth/deps.ts`), declared here so `http/` stays auth-free. The bound
98
- * `auth/audit_emitter.ts` `AuditEmitter` (and therefore `AppDeps.audit` /
99
- * `RouteFactoryDeps.audit`) satisfies `audit` structurally.
96
+ * Capabilities the db routes need — a narrow slice of `AppDeps`
97
+ * (`auth/deps.ts`); `AppDeps.audit` / `RouteFactoryDeps.audit` satisfy it.
100
98
  */
101
99
  export interface DbRouteDeps {
102
100
  /**
103
- * Awaitable pool audit write. The row-`DELETE` handler calls it from an
104
- * `emit_after_commit` thunk, so the success-only trail row can never
105
- * claim a delete whose transaction failed at COMMIT, and the row is
106
- * written on the pool because the request transaction has ended by then.
107
- * The flush awaits the returned promise.
101
+ * The row-`DELETE` handler writes its `db_admin_row_delete` success row in
102
+ * the route's transaction, after the delete, so the row and the delete
103
+ * commit together or not at all.
108
104
  */
109
- audit: {
110
- emit_pool: (input: {
111
- event_type: 'db_admin_row_delete';
112
- account_id: Uuid | null;
113
- ip: string;
114
- metadata: {
115
- table: string;
116
- pk_column: string;
117
- id: string;
118
- };
119
- }) => Promise<void>;
120
- };
105
+ audit: Pick<AuditEmitter, 'emit'>;
121
106
  }
122
107
  /**
123
108
  * Per-factory configuration for db routes.
@@ -1 +1 @@
1
- {"version":3,"file":"db_routes.d.ts","sourceRoot":"","sources":["../../src/lib/http/db_routes.ts"],"names":[],"mappings":"AAAA;;;;;;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integer, literal, loose_object, max_value, min_value, n
14
14
  import { ActingActor } from '../primitive_schemas.js';
15
15
  import { define_route } from './route_spec.js';
16
16
  import { route_fail, route_ok } from './route_result.js';
17
+ import { transaction_with_post_commit_rollback } from './pending_effects.js';
17
18
  import { REST_DATABASE_CONNECTION_FAILED, REST_FOREIGN_KEY_VIOLATION, REST_ROW_NOT_FOUND, REST_TABLE_NO_PRIMARY_KEY, REST_TABLE_NOT_DELETABLE, REST_TABLE_NOT_FOUND } from './error_schemas.js';
18
19
  import { assert_valid_sql_identifier, VALID_SQL_IDENTIFIER } from '../db/sql_identifier.js';
19
20
  import { pg_error_code } from '../db/pg_error.js';
20
- import { emit_after_commit } from './pending_effects.js';
21
21
  // the spellings `query_int` reads as an integer: decimal digits with an optional sign
22
22
  const QUERY_INT_PATTERN = /^[+-]?\d+$/;
23
23
  /**
@@ -367,82 +367,82 @@ export const create_db_route_specs = (deps, options) => {
367
367
  return route_fail(REST_TABLE_NO_PRIMARY_KEY);
368
368
  }
369
369
  const pk_column = pk_columns[0];
370
- // The refusals below answer from a failed DELETE, which on PostgreSQL
371
- // aborts the route's transaction — its COMMIT would come back as a
372
- // ROLLBACK, which the pg driver throws on (`db/db_pg.ts`). A savepoint
373
- // keeps the refusal's failure out of the transaction. Guarded because
374
- // a consumer may run the route with `transaction: false`, and
375
- // `SAVEPOINT` outside a transaction block is an error.
376
- const savepoint = route.db.in_transaction;
377
- if (savepoint)
378
- await route.db.query('SAVEPOINT db_admin_row_delete');
379
- try {
380
- // Typed PK compare, twinning the Rust spine: `$1` travels as an
381
- // untyped text-format parameter, so PG infers the PK column's
382
- // type and coerces the id with that type's input function —
383
- // index-scan deletes and canonical per-type semantics (citext
384
- // case-insensitivity, char(n) padding, any valid uuid spelling).
385
- // An id that cannot be a value of the PK type errors at bind
386
- // (22P02/22003), mapped below to the same 404 as a typed miss.
387
- // `RETURNING "<pk>"::text` reads back only the PK cell — the
388
- // deleted row's other values (e.g. a bytea column) are never
389
- // materialized — so the audit trail records the row's canonical
390
- // PK rendering rather than whatever spelling the URL supplied.
391
- const pk_ident = assert_valid_sql_identifier(pk_column);
392
- const result = await route.db.query(`DELETE FROM "${assert_valid_sql_identifier(name)}" WHERE "${pk_ident}" = $1 RETURNING "${pk_ident}"::text AS pk_text`, [id]);
393
- if (result.length === 0) {
394
- return route_fail(REST_ROW_NOT_FOUND);
370
+ // The delete and its audit row are one transaction: the route's, or —
371
+ // remounted with `transaction: false` — one opened here around just
372
+ // them, so the row is written with the delete either way.
373
+ const delete_row = async (tx_ctx) => {
374
+ // The refusals below answer from a failed DELETE, which on PostgreSQL
375
+ // aborts the route's transaction — its COMMIT would come back as a
376
+ // ROLLBACK, which the pg driver throws on (`db/db_pg.ts`). A savepoint
377
+ // keeps the refusal's failure out of the transaction.
378
+ await tx_ctx.db.query('SAVEPOINT db_admin_row_delete');
379
+ let deleted_id;
380
+ try {
381
+ // Typed PK compare, twinning the Rust spine: `$1` travels as an
382
+ // untyped text-format parameter, so PG infers the PK column's
383
+ // type and coerces the id with that type's input function —
384
+ // index-scan deletes and canonical per-type semantics (citext
385
+ // case-insensitivity, char(n) padding, any valid uuid spelling).
386
+ // An id that cannot be a value of the PK type errors at bind
387
+ // (22P02/22003), mapped below to the same 404 as a typed miss.
388
+ // `RETURNING "<pk>"::text` reads back only the PK cell — the
389
+ // deleted row's other values (e.g. a bytea column) are never
390
+ // materialized — so the audit trail records the row's canonical
391
+ // PK rendering rather than whatever spelling the URL supplied.
392
+ const pk_ident = assert_valid_sql_identifier(pk_column);
393
+ const result = await tx_ctx.db.query(`DELETE FROM "${assert_valid_sql_identifier(name)}" WHERE "${pk_ident}" = $1 RETURNING "${pk_ident}"::text AS pk_text`, [id]);
394
+ if (result.length === 0) {
395
+ return route_fail(REST_ROW_NOT_FOUND);
396
+ }
397
+ deleted_id = result[0].pk_text;
398
+ }
399
+ catch (err) {
400
+ const code = pg_error_code(err);
401
+ // 22P02 invalid_text_representation / 22003 numeric_value_out_of_range
402
+ // / 22021 character_not_in_repertoire: the id cannot be coerced
403
+ // to the PK column's type — or cannot even be a text value (a
404
+ // NUL byte, rejected by the server encoding whatever the PK
405
+ // type) — so no row can match; answer with the same masked 404
406
+ // as a typed miss.
407
+ const uncoercible = code === '22P02' || code === '22003' || code === '22021';
408
+ // 23503 foreign_key_violation / 23001 restrict_violation — the
409
+ // same referencing-row refusal. Which one depends on the
410
+ // constraint: `ON DELETE RESTRICT` raises 23001 on PG 18, PGlite
411
+ // and pglet (23503 on PG ≤17), and `NO ACTION` — the default,
412
+ // when the constraint names no action — raises 23503 on all of
413
+ // them.
414
+ const referenced = code === '23503' || code === '23001';
415
+ // anything else fails the request, and the route's transaction
416
+ // rolls back whole
417
+ if (!uncoercible && !referenced)
418
+ throw err;
419
+ // the refusal answers normally, so the transaction must commit
420
+ await tx_ctx.db.query('ROLLBACK TO SAVEPOINT db_admin_row_delete');
421
+ if (uncoercible) {
422
+ return route_fail(REST_ROW_NOT_FOUND);
423
+ }
424
+ const pg_err = err;
425
+ log?.warn('Foreign key violation:', pg_err.detail, pg_err.constraint);
426
+ return route_fail(REST_FOREIGN_KEY_VIOLATION);
395
427
  }
396
- const deleted_id = result[0].pk_text;
397
428
  // The trail for the trail-adjacent surface: every successful row
398
- // delete through this endpoint is audited. Deferred via
399
- // `emit_after_commit` so the pool-routed row can never claim a
400
- // delete whose transaction failed at COMMIT — the Rust twin
401
- // commits before emitting for the same reason. The request
402
- // transaction has ended by then, so the row goes through
403
- // `emit_pool`, not the transaction-routing `emit`. Account-grain
404
- // attribution — the browser is a raw storage surface, so no actor
405
- // is claimed.
406
- const account_id = route.auth.account.id;
407
- const ip = route.client_ip;
408
- emit_after_commit(route, () => deps.audit.emit_pool({
429
+ // delete through this endpoint is audited, in the route's
430
+ // transaction, so the row commits with the delete or neither does.
431
+ // Outside the savepoint's `try`, so a refused audit write fails the
432
+ // request (and rolls the delete back) rather than reading as a row
433
+ // refusal. Account-grain attribution — the browser is a raw storage
434
+ // surface, so no actor is claimed.
435
+ await deps.audit.emit(tx_ctx, {
409
436
  event_type: 'db_admin_row_delete',
410
- account_id,
411
- ip,
437
+ account_id: route.auth.account.id,
438
+ ip: route.client_ip,
412
439
  metadata: { table: name, pk_column, id: deleted_id }
413
- }));
440
+ });
414
441
  return route_ok({ success: true });
415
- }
416
- catch (err) {
417
- const code = pg_error_code(err);
418
- // 22P02 invalid_text_representation / 22003 numeric_value_out_of_range
419
- // / 22021 character_not_in_repertoire: the id cannot be coerced
420
- // to the PK column's type — or cannot even be a text value (a
421
- // NUL byte, rejected by the server encoding whatever the PK
422
- // type) — so no row can match; answer with the same masked 404
423
- // as a typed miss.
424
- const uncoercible = code === '22P02' || code === '22003' || code === '22021';
425
- // 23503 foreign_key_violation / 23001 restrict_violation — the
426
- // same referencing-row refusal. Which one depends on the
427
- // constraint: `ON DELETE RESTRICT` raises 23001 on PG 18, PGlite
428
- // and pglet (23503 on PG ≤17), and `NO ACTION` — the default,
429
- // when the constraint names no action — raises 23503 on all of
430
- // them.
431
- const referenced = code === '23503' || code === '23001';
432
- // anything else fails the request, and the route's transaction
433
- // rolls back whole
434
- if (!uncoercible && !referenced)
435
- throw err;
436
- // the refusal answers normally, so the transaction must commit
437
- if (savepoint)
438
- await route.db.query('ROLLBACK TO SAVEPOINT db_admin_row_delete');
439
- if (uncoercible) {
440
- return route_fail(REST_ROW_NOT_FOUND);
441
- }
442
- const pg_err = err;
443
- log?.warn('Foreign key violation:', pg_err.detail, pg_err.constraint);
444
- return route_fail(REST_FOREIGN_KEY_VIOLATION);
445
- }
442
+ };
443
+ return route.db.in_transaction
444
+ ? delete_row(route)
445
+ : transaction_with_post_commit_rollback(route, delete_row);
446
446
  }
447
447
  })
448
448
  ];