@fuzdev/fuz_app 0.152.0 → 0.153.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 (159) hide show
  1. package/dist/actions/CLAUDE.md +14 -11
  2. package/dist/actions/action_rpc.js +3 -3
  3. package/dist/actions/action_types.d.ts +3 -3
  4. package/dist/actions/broadcast_api.d.ts +0 -6
  5. package/dist/actions/broadcast_api.d.ts.map +1 -1
  6. package/dist/actions/connection_closer.d.ts +14 -15
  7. package/dist/actions/connection_closer.d.ts.map +1 -1
  8. package/dist/actions/connection_closer.js +13 -13
  9. package/dist/actions/perform_action.d.ts +5 -1
  10. package/dist/actions/perform_action.d.ts.map +1 -1
  11. package/dist/actions/perform_action.js +57 -19
  12. package/dist/actions/register_action_ws.d.ts +6 -5
  13. package/dist/actions/register_action_ws.d.ts.map +1 -1
  14. package/dist/actions/register_action_ws.js +5 -6
  15. package/dist/auth/CLAUDE.md +44 -14
  16. package/dist/auth/account_actions.d.ts +2 -2
  17. package/dist/auth/account_actions.js +6 -6
  18. package/dist/auth/account_routes.js +9 -9
  19. package/dist/auth/admin_actions.d.ts +2 -1
  20. package/dist/auth/admin_actions.d.ts.map +1 -1
  21. package/dist/auth/admin_actions.js +21 -20
  22. package/dist/auth/audit_emitter.d.ts +111 -64
  23. package/dist/auth/audit_emitter.d.ts.map +1 -1
  24. package/dist/auth/audit_emitter.js +130 -55
  25. package/dist/auth/audit_log_queries.d.ts +9 -10
  26. package/dist/auth/audit_log_queries.d.ts.map +1 -1
  27. package/dist/auth/audit_log_queries.js +13 -10
  28. package/dist/auth/audit_log_routes.js +2 -2
  29. package/dist/auth/audit_log_schema.d.ts +6 -1
  30. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  31. package/dist/auth/bootstrap_account.d.ts +4 -3
  32. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  33. package/dist/auth/bootstrap_account.js +4 -3
  34. package/dist/auth/bootstrap_routes.js +2 -2
  35. package/dist/auth/cell_action_helpers.d.ts +3 -2
  36. package/dist/auth/cell_action_helpers.d.ts.map +1 -1
  37. package/dist/auth/cell_action_helpers.js +9 -10
  38. package/dist/auth/cell_actions.js +6 -6
  39. package/dist/auth/cell_data_schema.d.ts +5 -0
  40. package/dist/auth/cell_data_schema.d.ts.map +1 -1
  41. package/dist/auth/cell_data_schema.js +5 -0
  42. package/dist/auth/cell_field_actions.js +2 -2
  43. package/dist/auth/cell_grant_actions.js +2 -2
  44. package/dist/auth/cell_item_actions.js +3 -3
  45. package/dist/auth/deps.d.ts +12 -10
  46. package/dist/auth/deps.d.ts.map +1 -1
  47. package/dist/auth/middleware.js +1 -1
  48. package/dist/auth/request_context.d.ts +5 -10
  49. package/dist/auth/request_context.d.ts.map +1 -1
  50. package/dist/auth/request_context.js +10 -9
  51. package/dist/auth/role_grant_offer_actions.d.ts +11 -8
  52. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  53. package/dist/auth/role_grant_offer_actions.js +57 -41
  54. package/dist/auth/self_service_role_actions.d.ts +6 -5
  55. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  56. package/dist/auth/self_service_role_actions.js +17 -6
  57. package/dist/auth/session_cookie.d.ts +4 -4
  58. package/dist/auth/session_cookie.d.ts.map +1 -1
  59. package/dist/auth/session_cookie.js +0 -1
  60. package/dist/auth/session_middleware.d.ts +8 -5
  61. package/dist/auth/session_middleware.d.ts.map +1 -1
  62. package/dist/auth/session_middleware.js +10 -7
  63. package/dist/auth/signup_routes.js +6 -6
  64. package/dist/auth/standard_rpc_actions.d.ts +3 -2
  65. package/dist/auth/standard_rpc_actions.d.ts.map +1 -1
  66. package/dist/auth/standard_rpc_actions.js +3 -2
  67. package/dist/db/CLAUDE.md +10 -1
  68. package/dist/db/create_db.d.ts +18 -1
  69. package/dist/db/create_db.d.ts.map +1 -1
  70. package/dist/db/create_db.js +15 -4
  71. package/dist/db/db.d.ts +27 -0
  72. package/dist/db/db.d.ts.map +1 -1
  73. package/dist/db/db.js +26 -0
  74. package/dist/db/db_checkout_error.d.ts +36 -0
  75. package/dist/db/db_checkout_error.d.ts.map +1 -0
  76. package/dist/db/db_checkout_error.js +48 -0
  77. package/dist/db/db_pg.d.ts +83 -5
  78. package/dist/db/db_pg.d.ts.map +1 -1
  79. package/dist/db/db_pg.js +119 -9
  80. package/dist/db/pg_error.d.ts +4 -0
  81. package/dist/db/pg_error.d.ts.map +1 -1
  82. package/dist/db/pg_error.js +13 -3
  83. package/dist/dev/setup.d.ts +4 -2
  84. package/dist/dev/setup.d.ts.map +1 -1
  85. package/dist/dev/setup.js +12 -5
  86. package/dist/hono_context.d.ts +36 -6
  87. package/dist/hono_context.d.ts.map +1 -1
  88. package/dist/hono_context.js +29 -2
  89. package/dist/http/CLAUDE.md +11 -10
  90. package/dist/http/db_routes.d.ts +7 -12
  91. package/dist/http/db_routes.d.ts.map +1 -1
  92. package/dist/http/db_routes.js +32 -17
  93. package/dist/http/error_schemas.d.ts +12 -0
  94. package/dist/http/error_schemas.d.ts.map +1 -1
  95. package/dist/http/error_schemas.js +12 -0
  96. package/dist/http/jsonrpc_errors.d.ts +10 -0
  97. package/dist/http/jsonrpc_errors.d.ts.map +1 -1
  98. package/dist/http/jsonrpc_errors.js +14 -0
  99. package/dist/http/jsonrpc_helpers.d.ts +4 -0
  100. package/dist/http/jsonrpc_helpers.d.ts.map +1 -1
  101. package/dist/http/jsonrpc_helpers.js +8 -1
  102. package/dist/http/route_spec.d.ts +4 -4
  103. package/dist/http/route_spec.d.ts.map +1 -1
  104. package/dist/http/route_spec.js +20 -3
  105. package/dist/http/schema_helpers.d.ts +21 -0
  106. package/dist/http/schema_helpers.d.ts.map +1 -1
  107. package/dist/http/schema_helpers.js +38 -0
  108. package/dist/realtime/audit_log_sse.d.ts +2 -2
  109. package/dist/realtime/audit_log_sse.js +2 -2
  110. package/dist/server/app_backend.d.ts +25 -1
  111. package/dist/server/app_backend.d.ts.map +1 -1
  112. package/dist/server/app_backend.js +16 -3
  113. package/dist/server/app_error_handler.d.ts +30 -0
  114. package/dist/server/app_error_handler.d.ts.map +1 -0
  115. package/dist/server/app_error_handler.js +41 -0
  116. package/dist/server/app_server.d.ts +1 -1
  117. package/dist/server/app_server.d.ts.map +1 -1
  118. package/dist/server/app_server.js +6 -1
  119. package/dist/server/env.d.ts +8 -3
  120. package/dist/server/env.d.ts.map +1 -1
  121. package/dist/server/env.js +26 -4
  122. package/dist/testing/CLAUDE.md +22 -16
  123. package/dist/testing/audit_drift_guard.d.ts.map +1 -1
  124. package/dist/testing/audit_drift_guard.js +2 -0
  125. package/dist/testing/auth_apps.d.ts.map +1 -1
  126. package/dist/testing/auth_apps.js +2 -2
  127. package/dist/testing/cross_backend/conformance_case.d.ts +2 -0
  128. package/dist/testing/cross_backend/conformance_case.d.ts.map +1 -1
  129. package/dist/testing/cross_backend/conformance_case.js +8 -0
  130. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  131. package/dist/testing/cross_backend/conformance_table.js +24 -7
  132. package/dist/testing/cross_backend/default_backend_configs.d.ts +4 -0
  133. package/dist/testing/cross_backend/default_backend_configs.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/default_backend_configs.js +7 -0
  135. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts +11 -0
  136. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts.map +1 -1
  137. package/dist/testing/cross_backend/testing_server_core.d.ts +1 -1
  138. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +15 -11
  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 +3 -12
  141. package/dist/testing/daemon_token_rotation.d.ts +4 -14
  142. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  143. package/dist/testing/daemon_token_rotation.js +0 -12
  144. package/dist/testing/db.d.ts.map +1 -1
  145. package/dist/testing/db.js +7 -3
  146. package/dist/testing/middleware.d.ts.map +1 -1
  147. package/dist/testing/middleware.js +2 -2
  148. package/dist/testing/rpc_helpers.d.ts +19 -0
  149. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  150. package/dist/testing/rpc_helpers.js +25 -2
  151. package/dist/testing/schema_parity.d.ts +1 -1
  152. package/dist/testing/stubs.js +2 -2
  153. package/dist/testing/surface_invariants.js +1 -1
  154. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  155. package/dist/testing/ws_round_trip.js +3 -3
  156. package/dist/zod.d.ts +9 -0
  157. package/dist/zod.d.ts.map +1 -1
  158. package/dist/zod.js +1 -1
  159. package/package.json +3 -7
@@ -1,7 +1,28 @@
1
1
  /**
2
2
  * PostgreSQL driver adapter for `Db`.
3
3
  *
4
- * Provides `create_pg_db()` to construct a `Db` backed by a `pg.Pool`.
4
+ * Provides `create_pg_pool()` to build the pool with a bounded checkout, and
5
+ * `create_pg_db()` to construct a `Db` backed by it.
6
+ *
7
+ * ## Checkout timeout
8
+ *
9
+ * Every checkout from a `create_pg_pool` pool — the wait for a free client,
10
+ * or a new client's connect — gives up after `checkout_timeout_ms`
11
+ * (`connectionTimeoutMillis`; default `DEFAULT_DB_CHECKOUT_TIMEOUT_MS`, 5 s)
12
+ * and throws a `DbCheckoutError` (`db/db_checkout_error.ts`), which every
13
+ * request surface answers with a 503. A query that fails on a client already
14
+ * checked out throws the driver's error as before (a 500). Per-statement
15
+ * `pool.query` and each transaction's `pool.connect()` both check out through
16
+ * the pool's `connect`, so both are bounded. The wait and the connect are
17
+ * bounded one by one, so a checkout that waits and is then handed a slot to
18
+ * connect in can take about twice the bound. `Db.with_checkout_timeout` gives
19
+ * a caller its own bound on the same pool — the audit emitter's pool writes
20
+ * wait `DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS` (30 s), so a pool saturated
21
+ * enough to shed requests does not also drop the failure rows recording them.
22
+ * A request that awaits its audit row — a failed login does — can therefore
23
+ * wait up to that bound, not the request's. Twin of the Rust
24
+ * `fuz_db::create_pool` / `PoolOptions`.
25
+ *
5
26
  * Statically imports only `pg` types; the `pg` runtime is dynamically
6
27
  * imported where needed — by callers (e.g., `create_db`) that construct the
7
28
  * `Pool`, and by `register_pg_type_parsers` to reach `pg.types`. pglite-only
@@ -11,6 +32,61 @@
11
32
  */
12
33
  import type { Pool } from 'pg';
13
34
  import { type DbDriverResult } from './db.js';
35
+ /** Default bound on one request's pool checkout — Rust `fuz_db::DEFAULT_CHECKOUT_TIMEOUT`. */
36
+ export declare const DEFAULT_DB_CHECKOUT_TIMEOUT_MS = 5000;
37
+ /**
38
+ * Default bound on the checkout behind one audit pool write — Rust
39
+ * `fuz_db::DEFAULT_AUDIT_CHECKOUT_TIMEOUT`.
40
+ */
41
+ export declare const DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS = 30000;
42
+ /** The largest checkout bound either env var admits (10 minutes) — Rust `DB_CHECKOUT_TIMEOUT_MAX_MS`. */
43
+ export declare const DB_CHECKOUT_TIMEOUT_MAX_MS = 600000;
44
+ /**
45
+ * A `pg.Pool` from `create_pg_pool`: a failed checkout throws `DbCheckoutError`,
46
+ * and `query_with_checkout_timeout` runs one statement under its own bound.
47
+ */
48
+ export interface DbCheckoutPool extends Pool {
49
+ /**
50
+ * `pool.query` with the checkout bounded by `timeout_ms` in place of the
51
+ * pool's own.
52
+ */
53
+ query_with_checkout_timeout: <T>(timeout_ms: number, text: string, values?: Array<unknown>) => Promise<{
54
+ rows: Array<T>;
55
+ }>;
56
+ }
57
+ /** Options for `create_pg_pool`. */
58
+ export interface CreatePgPoolOptions {
59
+ /** The `postgres://` URL. */
60
+ connection_string: string;
61
+ /** Bound on every checkout, in ms — `DEFAULT_DB_CHECKOUT_TIMEOUT_MS` in production. */
62
+ checkout_timeout_ms: number;
63
+ }
64
+ /**
65
+ * Build a `pg.Pool` whose every checkout is bounded by
66
+ * `options.checkout_timeout_ms` and throws `DbCheckoutError` when it fails
67
+ * (module doc, "Checkout timeout").
68
+ *
69
+ * The pool wraps every error of its `connect` — the wait timing out, a new
70
+ * client's connect timing out or failing, a closed pool — and nothing a query
71
+ * on a checked-out client throws. `pool.query` checks out through the same
72
+ * `connect` (pg-pool's `query` calls `this.connect`), so per-statement queries
73
+ * keep pg-pool's own error-listener handling.
74
+ *
75
+ * `query_with_checkout_timeout` lends one statement its own bound by setting
76
+ * `options.connectionTimeoutMillis` for the synchronous span of `query` →
77
+ * `connect`: pg-pool reads it there, to arm the queue wait's timer or a new
78
+ * client's connect timer, and nowhere later on that checkout's path but one —
79
+ * a waiter that a freed slot later hands a brand-new client connects under the
80
+ * pool's own bound. Pinned against the installed pg-pool by
81
+ * `src/test/db/db_pg.db.test.ts`.
82
+ *
83
+ * @param pg - the `pg` module (dynamically imported by the caller)
84
+ * @param options - the URL and the checkout bound
85
+ * @returns the pool
86
+ */
87
+ export declare const create_pg_pool: (pg: {
88
+ Pool: typeof Pool;
89
+ }, options: CreatePgPoolOptions) => DbCheckoutPool;
14
90
  /**
15
91
  * Register the shared pg type-parser overrides on the module-global `pg.types`.
16
92
  *
@@ -38,13 +114,15 @@ import { type DbDriverResult } from './db.js';
38
114
  */
39
115
  export declare const register_pg_type_parsers: () => Promise<void>;
40
116
  /**
41
- * Create a `Db` backed by a `pg.Pool`.
117
+ * Create a `Db` backed by a `create_pg_pool` pool.
42
118
  *
43
119
  * Owns the transaction implementation, acquiring a dedicated pool client
44
- * per transaction.
120
+ * per transaction. `db.with_checkout_timeout(ms)` returns a `Db` over the
121
+ * same pool whose statements check out under `ms` instead (its transactions
122
+ * keep the pool's own bound).
45
123
  *
46
- * @param pool - an already-constructed `pg.Pool`
124
+ * @param pool - a pool from `create_pg_pool`
47
125
  * @returns the `Db` instance and a `close` callback bound to `pool.end()`
48
126
  */
49
- export declare const create_pg_db: (pool: Pool) => DbDriverResult;
127
+ export declare const create_pg_db: (pool: DbCheckoutPool) => DbDriverResult;
50
128
  //# sourceMappingURL=db_pg.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"db_pg.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/db_pg.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAE/B,OAAO,EAA6B,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,wBAAwB,QAAa,OAAO,CAAC,IAAI,CAG7D,CAAC;AA2BF;;;;;;;;GAQG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,IAAI,KAAG,cAGxC,CAAC"}
1
+ {"version":3,"file":"db_pg.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/db_pg.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,IAAI,EAA0B,MAAM,IAAI,CAAC;AAEvD,OAAO,EAA6B,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzE,8FAA8F;AAC9F,eAAO,MAAM,8BAA8B,OAAQ,CAAC;AAEpD;;;GAGG;AACH,eAAO,MAAM,oCAAoC,QAAS,CAAC;AAE3D,yGAAyG;AACzG,eAAO,MAAM,0BAA0B,SAAU,CAAC;AAElD;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,IAAI;IAC3C;;;OAGG;IACH,2BAA2B,EAAE,CAAC,CAAC,EAC9B,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,KACnB,OAAO,CAAC;QAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAA;KAAE,CAAC,CAAC;CACjC;AAED,oCAAoC;AACpC,MAAM,WAAW,mBAAmB;IACnC,6BAA6B;IAC7B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uFAAuF;IACvF,mBAAmB,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,cAAc,GAC1B,IAAI;IAAE,IAAI,EAAE,OAAO,IAAI,CAAA;CAAE,EACzB,SAAS,mBAAmB,KAC1B,cAkDF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,wBAAwB,QAAa,OAAO,CAAC,IAAI,CAG7D,CAAC;AAqCF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,cAAc,KAAG,cAiBnD,CAAC"}
package/dist/db/db_pg.js CHANGED
@@ -1,7 +1,28 @@
1
1
  /**
2
2
  * PostgreSQL driver adapter for `Db`.
3
3
  *
4
- * Provides `create_pg_db()` to construct a `Db` backed by a `pg.Pool`.
4
+ * Provides `create_pg_pool()` to build the pool with a bounded checkout, and
5
+ * `create_pg_db()` to construct a `Db` backed by it.
6
+ *
7
+ * ## Checkout timeout
8
+ *
9
+ * Every checkout from a `create_pg_pool` pool — the wait for a free client,
10
+ * or a new client's connect — gives up after `checkout_timeout_ms`
11
+ * (`connectionTimeoutMillis`; default `DEFAULT_DB_CHECKOUT_TIMEOUT_MS`, 5 s)
12
+ * and throws a `DbCheckoutError` (`db/db_checkout_error.ts`), which every
13
+ * request surface answers with a 503. A query that fails on a client already
14
+ * checked out throws the driver's error as before (a 500). Per-statement
15
+ * `pool.query` and each transaction's `pool.connect()` both check out through
16
+ * the pool's `connect`, so both are bounded. The wait and the connect are
17
+ * bounded one by one, so a checkout that waits and is then handed a slot to
18
+ * connect in can take about twice the bound. `Db.with_checkout_timeout` gives
19
+ * a caller its own bound on the same pool — the audit emitter's pool writes
20
+ * wait `DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS` (30 s), so a pool saturated
21
+ * enough to shed requests does not also drop the failure rows recording them.
22
+ * A request that awaits its audit row — a failed login does — can therefore
23
+ * wait up to that bound, not the request's. Twin of the Rust
24
+ * `fuz_db::create_pool` / `PoolOptions`.
25
+ *
5
26
  * Statically imports only `pg` types; the `pg` runtime is dynamically
6
27
  * imported where needed — by callers (e.g., `create_db`) that construct the
7
28
  * `Pool`, and by `register_pg_type_parsers` to reach `pg.types`. pglite-only
@@ -10,6 +31,71 @@
10
31
  * @module
11
32
  */
12
33
  import { Db, no_nested_transaction } from './db.js';
34
+ import { DbCheckoutError } from './db_checkout_error.js';
35
+ /** Default bound on one request's pool checkout — Rust `fuz_db::DEFAULT_CHECKOUT_TIMEOUT`. */
36
+ export const DEFAULT_DB_CHECKOUT_TIMEOUT_MS = 5_000;
37
+ /**
38
+ * Default bound on the checkout behind one audit pool write — Rust
39
+ * `fuz_db::DEFAULT_AUDIT_CHECKOUT_TIMEOUT`.
40
+ */
41
+ export const DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS = 30_000;
42
+ /** The largest checkout bound either env var admits (10 minutes) — Rust `DB_CHECKOUT_TIMEOUT_MAX_MS`. */
43
+ export const DB_CHECKOUT_TIMEOUT_MAX_MS = 600_000;
44
+ /**
45
+ * Build a `pg.Pool` whose every checkout is bounded by
46
+ * `options.checkout_timeout_ms` and throws `DbCheckoutError` when it fails
47
+ * (module doc, "Checkout timeout").
48
+ *
49
+ * The pool wraps every error of its `connect` — the wait timing out, a new
50
+ * client's connect timing out or failing, a closed pool — and nothing a query
51
+ * on a checked-out client throws. `pool.query` checks out through the same
52
+ * `connect` (pg-pool's `query` calls `this.connect`), so per-statement queries
53
+ * keep pg-pool's own error-listener handling.
54
+ *
55
+ * `query_with_checkout_timeout` lends one statement its own bound by setting
56
+ * `options.connectionTimeoutMillis` for the synchronous span of `query` →
57
+ * `connect`: pg-pool reads it there, to arm the queue wait's timer or a new
58
+ * client's connect timer, and nowhere later on that checkout's path but one —
59
+ * a waiter that a freed slot later hands a brand-new client connects under the
60
+ * pool's own bound. Pinned against the installed pg-pool by
61
+ * `src/test/db/db_pg.db.test.ts`.
62
+ *
63
+ * @param pg - the `pg` module (dynamically imported by the caller)
64
+ * @param options - the URL and the checkout bound
65
+ * @returns the pool
66
+ */
67
+ export const create_pg_pool = (pg, options) => {
68
+ const config = {
69
+ connectionString: options.connection_string,
70
+ connectionTimeoutMillis: options.checkout_timeout_ms
71
+ };
72
+ const to_checkout_error = (err) => new DbCheckoutError({ cause: err });
73
+ class CheckoutPool extends pg.Pool {
74
+ connect(callback) {
75
+ if (callback) {
76
+ super.connect((err, client, done) => {
77
+ callback(err ? to_checkout_error(err) : undefined, client, done);
78
+ });
79
+ return;
80
+ }
81
+ return super.connect().catch((err) => {
82
+ throw to_checkout_error(err);
83
+ });
84
+ }
85
+ query_with_checkout_timeout = (timeout_ms, text, values) => {
86
+ const previous = this.options.connectionTimeoutMillis;
87
+ this.options.connectionTimeoutMillis = timeout_ms;
88
+ try {
89
+ const result = this.query(text, values);
90
+ return result;
91
+ }
92
+ finally {
93
+ this.options.connectionTimeoutMillis = previous;
94
+ }
95
+ };
96
+ }
97
+ return new CheckoutPool(config);
98
+ };
13
99
  /**
14
100
  * Register the shared pg type-parser overrides on the module-global `pg.types`.
15
101
  *
@@ -45,6 +131,13 @@ export const register_pg_type_parsers = async () => {
45
131
  * Acquires a dedicated client from the pool for each transaction,
46
132
  * ensuring `BEGIN` / `COMMIT` / `ROLLBACK` all hit the same connection.
47
133
  * Releases the client in `finally` regardless of outcome.
134
+ *
135
+ * Throws when PostgreSQL answers the `COMMIT` with `ROLLBACK` — a statement in
136
+ * the transaction failed and its error was swallowed (an un-awaited promise, a
137
+ * `catch` that never rethrew), so nothing committed. Without the check the
138
+ * caller would read the rolled-back transaction as a success. A handler that
139
+ * answers normally from a failed statement runs it under a savepoint and rolls
140
+ * back to it (`http/db_routes.ts`'s row delete does).
48
141
  */
49
142
  const create_pg_transaction = (pool) => async (fn) => {
50
143
  const client = await pool.connect();
@@ -52,7 +145,10 @@ const create_pg_transaction = (pool) => async (fn) => {
52
145
  await client.query('BEGIN');
53
146
  const tx_db = new Db({ client, transaction: no_nested_transaction });
54
147
  const result = await fn(tx_db);
55
- await client.query('COMMIT');
148
+ const commit = await client.query('COMMIT');
149
+ if (commit.command === 'ROLLBACK') {
150
+ throw new Error('transaction aborted before COMMIT: PostgreSQL rolled it back');
151
+ }
56
152
  return result;
57
153
  }
58
154
  catch (err) {
@@ -64,15 +160,29 @@ const create_pg_transaction = (pool) => async (fn) => {
64
160
  }
65
161
  };
66
162
  /**
67
- * Create a `Db` backed by a `pg.Pool`.
163
+ * Create a `Db` backed by a `create_pg_pool` pool.
68
164
  *
69
165
  * Owns the transaction implementation, acquiring a dedicated pool client
70
- * per transaction.
166
+ * per transaction. `db.with_checkout_timeout(ms)` returns a `Db` over the
167
+ * same pool whose statements check out under `ms` instead (its transactions
168
+ * keep the pool's own bound).
71
169
  *
72
- * @param pool - an already-constructed `pg.Pool`
170
+ * @param pool - a pool from `create_pg_pool`
73
171
  * @returns the `Db` instance and a `close` callback bound to `pool.end()`
74
172
  */
75
- export const create_pg_db = (pool) => ({
76
- db: new Db({ client: pool, transaction: create_pg_transaction(pool) }),
77
- close: () => pool.end()
78
- });
173
+ export const create_pg_db = (pool) => {
174
+ const transaction = create_pg_transaction(pool);
175
+ return {
176
+ db: new Db({
177
+ client: pool,
178
+ transaction,
179
+ with_checkout_timeout: (timeout_ms) => new Db({
180
+ client: {
181
+ query: (text, values) => pool.query_with_checkout_timeout(timeout_ms, text, values)
182
+ },
183
+ transaction
184
+ })
185
+ }),
186
+ close: () => pool.end()
187
+ };
188
+ };
@@ -9,6 +9,10 @@
9
9
  /**
10
10
  * Extract the error-code string from a caught error, for SQLSTATE checks.
11
11
  *
12
+ * A failed pool checkout (`DbCheckoutError`) is read through to its cause, so
13
+ * a connect the server refused (`3D000` for a missing database, `28P01` for a
14
+ * bad password) keeps its code.
15
+ *
12
16
  * Other error families also carry string `code`s (Node FS errors:
13
17
  * `ENOENT`, `ENOSPC`, …) — compare the result against specific SQLSTATE
14
18
  * values, never against truthiness.
@@ -1 +1 @@
1
- {"version":3,"file":"pg_error.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/pg_error.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,IAGhD,CAAC;AAET;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,OAAO,OAAO,KAAG,OAA2C,CAAC"}
1
+ {"version":3,"file":"pg_error.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/pg_error.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,IAOvD,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,OAAO,OAAO,KAAG,OAA2C,CAAC"}
@@ -6,9 +6,14 @@
6
6
  *
7
7
  * @module
8
8
  */
9
+ import { is_db_checkout_error } from './db_checkout_error.js';
9
10
  /**
10
11
  * Extract the error-code string from a caught error, for SQLSTATE checks.
11
12
  *
13
+ * A failed pool checkout (`DbCheckoutError`) is read through to its cause, so
14
+ * a connect the server refused (`3D000` for a missing database, `28P01` for a
15
+ * bad password) keeps its code.
16
+ *
12
17
  * Other error families also carry string `code`s (Node FS errors:
13
18
  * `ENOENT`, `ENOSPC`, …) — compare the result against specific SQLSTATE
14
19
  * values, never against truthiness.
@@ -17,9 +22,14 @@
17
22
  * @returns the `code` string, or `null` when the value isn't an `Error`
18
23
  * or carries no string `code`
19
24
  */
20
- export const pg_error_code = (error) => error instanceof Error && 'code' in error && typeof error.code === 'string'
21
- ? error.code
22
- : null;
25
+ export const pg_error_code = (error) => {
26
+ const err = is_db_checkout_error(error) ? error.cause : error;
27
+ return err instanceof Error &&
28
+ 'code' in err &&
29
+ typeof err.code === 'string'
30
+ ? err.code
31
+ : null;
32
+ };
23
33
  /**
24
34
  * Check if an error is a PostgreSQL unique constraint violation (error code 23505).
25
35
  *
@@ -127,8 +127,10 @@ export declare const setup_env_file: (deps: FsReadDeps & FsWriteDeps, env_path:
127
127
  /**
128
128
  * Create a bootstrap token file if it doesn't exist.
129
129
  *
130
- * The token is a one-shot secret used to create the first admin account.
131
- * Stored at `~/.{app_name}/secret_bootstrap_token` by default.
130
+ * The token is a one-shot secret used to create the first admin account:
131
+ * 32 random bytes as 64 lowercase hex characters plus one LF, the file
132
+ * `openssl rand -hex 32` writes. Stored at
133
+ * `~/.{app_name}/secret_bootstrap_token` by default.
132
134
  *
133
135
  * @param deps - file and env capabilities
134
136
  * @param app_name - application name (used for default state directory)
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/dev/setup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,KAAK,EACX,WAAW,EACX,aAAa,EACb,OAAO,EACP,UAAU,EACV,YAAY,EACZ,WAAW,EACX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAYrD;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC3B,EAAE,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC1B,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7B;AAED,2CAA2C;AAC3C,eAAO,MAAM,oBAAoB,EAAE,WAIlC,CAAC;AAEF,kCAAkC;AAClC,MAAM,WAAW,cAAc;IAC9B,6DAA6D;IAC7D,OAAO,EAAE,OAAO,CAAC;IACjB,kDAAkD;IAClD,OAAO,EAAE,OAAO,CAAC;IACjB,yBAAyB;IACzB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,yCAAyC;AACzC,MAAM,WAAW,gBAAgB;IAChC,kEAAkE;IAClE,OAAO,EAAE,OAAO,CAAC;IACjB,2BAA2B;IAC3B,UAAU,EA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/dist/dev/setup.js CHANGED
@@ -11,7 +11,6 @@
11
11
  import { to_hex } from '@fuzdev/fuz_util/hex.ts';
12
12
  import { load_env_file, parse_dotenv } from '../env/dotenv.js';
13
13
  import { update_env_content } from '../env/update_env_variable.js';
14
- import { generate_random_base64url } from '../crypto.js';
15
14
  import { write_file_atomic } from '../runtime/fs.js';
16
15
  import { query_account_by_username, query_actors_by_account, query_create_account_with_actor } from '../auth/account_queries.js';
17
16
  import { query_create_role_grant } from '../auth/role_grant_queries.js';
@@ -37,6 +36,12 @@ export const parse_db_name = (url) => {
37
36
  return null;
38
37
  }
39
38
  };
39
+ /**
40
+ * Mint an operator-facing secret: 32 random bytes as lowercase hex, the shape
41
+ * `openssl rand -hex 32` writes, so a hand-made secret and a generated one
42
+ * look the same.
43
+ */
44
+ const generate_secret_hex = () => to_hex(crypto.getRandomValues(new Uint8Array(32)));
40
45
  /**
41
46
  * Generate a cookie signing key in-process: 32 random bytes, hex-encoded.
42
47
  *
@@ -45,7 +50,7 @@ export const parse_db_name = (url) => {
45
50
  *
46
51
  * @returns a 64-character lowercase hex key
47
52
  */
48
- export const generate_cookie_key = () => to_hex(crypto.getRandomValues(new Uint8Array(32)));
53
+ export const generate_cookie_key = () => generate_secret_hex();
49
54
  // === File helpers ===
50
55
  /**
51
56
  * Read a single env var from a dotenv-style file.
@@ -133,8 +138,10 @@ export const setup_env_file = async (deps, env_path, example_path, options) => {
133
138
  /**
134
139
  * Create a bootstrap token file if it doesn't exist.
135
140
  *
136
- * The token is a one-shot secret used to create the first admin account.
137
- * Stored at `~/.{app_name}/secret_bootstrap_token` by default.
141
+ * The token is a one-shot secret used to create the first admin account:
142
+ * 32 random bytes as 64 lowercase hex characters plus one LF, the file
143
+ * `openssl rand -hex 32` writes. Stored at
144
+ * `~/.{app_name}/secret_bootstrap_token` by default.
138
145
  *
139
146
  * @param deps - file and env capabilities
140
147
  * @param app_name - application name (used for default state directory)
@@ -161,7 +168,7 @@ export const setup_bootstrap_token = async (deps, app_name, options) => {
161
168
  // existing files), so its 0600 holds unconditionally; the server-side
162
169
  // `read_secure_file` refuses anything laxer at read time.
163
170
  await deps.mkdir(state_dir, { recursive: true, mode: 0o700 });
164
- const token = generate_random_base64url();
171
+ const token = generate_secret_hex();
165
172
  await write_file_atomic(deps, token_path, token + '\n', { mode: 0o600 });
166
173
  log.ok(`Created ~/.${app_name}/secret_bootstrap_token (one-shot, deleted after first use)`);
167
174
  return { created: true, token_path };
@@ -10,6 +10,7 @@
10
10
  *
11
11
  * @module
12
12
  */
13
+ import type { Context } from 'hono';
13
14
  import type { RequestContext } from './auth/request_context.js';
14
15
  import type { ResolvedAuth } from './auth/resolved_auth.js';
15
16
  /**
@@ -22,6 +23,16 @@ import type { ResolvedAuth } from './auth/resolved_auth.js';
22
23
  * (read as `null`) for an unauthenticated request.
23
24
  */
24
25
  export declare const RESOLVED_AUTH_KEY = "resolved_auth";
26
+ /**
27
+ * Hono context variable name for the session token — set by the session
28
+ * middleware (`create_session_middleware`) to the token a verified, unexpired
29
+ * session cookie carries, `null` otherwise, and read by the session leg of the
30
+ * auth middleware (`create_request_context_middleware`), which hashes it to
31
+ * find the `auth_session` row. Fixed rather than configurable: the session
32
+ * middleware and the session leg must agree on it, and no other spine key may
33
+ * share it.
34
+ */
35
+ export declare const SESSION_TOKEN_KEY = "auth_session_id";
25
36
  /**
26
37
  * Hono context variable name for the session cookie's signed expiry, in
27
38
  * seconds since the Unix epoch — set by the session middleware on a cookie
@@ -34,19 +45,37 @@ export declare const SESSION_COOKIE_EXPIRES_AT_KEY = "auth_session_cookie_expire
34
45
  *
35
46
  * Test harnesses (`create_test_app_from_specs`, `create_fake_hono_context`,
36
47
  * the WS round-trip `connect()` helper, plus per-test middleware that
37
- * pre-populates `REQUEST_CONTEXT_KEY`) set this to `true` so
48
+ * pre-populates `REQUEST_CONTEXT_KEY`) set it to `TEST_CONTEXT_PRESET` so
38
49
  * `apply_authorization_phase` skips its DB-backed actor resolution and
39
50
  * trusts the supplied `RequestContext`. Production middleware never sets
40
51
  * this key — only test code does. The flag is the explicit escape hatch
41
52
  * that replaced the implicit "is `REQUEST_CONTEXT_KEY` already set?" probe,
42
53
  * so that future production code consulting `REQUEST_CONTEXT_KEY` cannot
43
- * silently bypass the live build.
54
+ * silently bypass the live build. Read it with `has_test_context_preset`.
44
55
  */
45
56
  export declare const TEST_CONTEXT_PRESET_KEY = "test_context_preset";
57
+ /**
58
+ * The one value that sets the test-harness preset (`TEST_CONTEXT_PRESET_KEY`).
59
+ * A symbol, so only code that imports it can set the flag: a string, a
60
+ * `true`, or any other value a misconfiguration or a request could put under
61
+ * the key reads as unset. Testing only — no module outside `testing/` writes
62
+ * it.
63
+ */
64
+ export declare const TEST_CONTEXT_PRESET: unique symbol;
65
+ /**
66
+ * Whether a test harness pre-baked this request's context — the key holds
67
+ * `TEST_CONTEXT_PRESET` itself. The skip every transport makes of the live
68
+ * authorization phase and the admission re-reads.
69
+ *
70
+ * @param c - the Hono context
71
+ * @returns `true` only when the key holds the `TEST_CONTEXT_PRESET` symbol
72
+ */
73
+ export declare const has_test_context_preset: (c: Context) => boolean;
46
74
  declare module 'hono' {
47
75
  interface ContextVariableMap {
48
76
  /** Resolved client IP, set by the trusted proxy middleware. */
49
77
  client_ip: string;
78
+ /** The session token (`SESSION_TOKEN_KEY`), set by the session middleware. */
50
79
  auth_session_id: string | null;
51
80
  request_context: RequestContext | null;
52
81
  validated_input: unknown;
@@ -84,11 +113,12 @@ declare module 'hono' {
84
113
  */
85
114
  post_commit_effects: Array<() => void | Promise<void>>;
86
115
  /**
87
- * Set to `true` by test harnesses that pre-populate `request_context`
88
- * to bypass the dispatcher's DB-backed actor resolution. Read by
89
- * `apply_authorization_phase`. Production middleware never sets this.
116
+ * Set to `TEST_CONTEXT_PRESET` by test harnesses that pre-populate
117
+ * `request_context` to bypass the dispatcher's DB-backed actor
118
+ * resolution. Read with `has_test_context_preset`. Production
119
+ * middleware never sets this.
90
120
  */
91
- test_context_preset: boolean;
121
+ test_context_preset: typeof TEST_CONTEXT_PRESET;
92
122
  }
93
123
  }
94
124
  //# sourceMappingURL=hono_context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hono_context.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/hono_context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,kBAAkB,CAAC;AAEjD;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,mCAAmC,CAAC;AAE9E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,wBAAwB,CAAC;AAE7D,OAAO,QAAQ,MAAM,CAAC;IACrB,UAAU,kBAAkB;QAC3B,+DAA+D;QAC/D,SAAS,EAAE,MAAM,CAAC;QAClB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;QAC/B,eAAe,EAAE,cAAc,GAAG,IAAI,CAAC;QACvC,eAAe,EAAE,OAAO,CAAC;QACzB,gBAAgB,EAAE,OAAO,CAAC;QAC1B,eAAe,EAAE,OAAO,CAAC;QACzB;;;;WAIG;QACH,aAAa,EAAE,YAAY,GAAG,IAAI,CAAC;QACnC,2FAA2F;QAC3F,8BAA8B,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9C;;;;;;;WAOG;QACH,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QACtC;;;;;;;;;;;;WAYG;QACH,mBAAmB,EAAE,KAAK,CAAC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QACvD;;;;WAIG;QACH,mBAAmB,EAAE,OAAO,CAAC;KAC7B;CACD"}
1
+ {"version":3,"file":"hono_context.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/hono_context.ts"],"names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AmB,EAAE,OAAO,mBAAmB,CAAC;KAChD;CACD"}
@@ -20,6 +20,16 @@
20
20
  * (read as `null`) for an unauthenticated request.
21
21
  */
22
22
  export const RESOLVED_AUTH_KEY = 'resolved_auth';
23
+ /**
24
+ * Hono context variable name for the session token — set by the session
25
+ * middleware (`create_session_middleware`) to the token a verified, unexpired
26
+ * session cookie carries, `null` otherwise, and read by the session leg of the
27
+ * auth middleware (`create_request_context_middleware`), which hashes it to
28
+ * find the `auth_session` row. Fixed rather than configurable: the session
29
+ * middleware and the session leg must agree on it, and no other spine key may
30
+ * share it.
31
+ */
32
+ export const SESSION_TOKEN_KEY = 'auth_session_id';
23
33
  /**
24
34
  * Hono context variable name for the session cookie's signed expiry, in
25
35
  * seconds since the Unix epoch — set by the session middleware on a cookie
@@ -32,12 +42,29 @@ export const SESSION_COOKIE_EXPIRES_AT_KEY = 'auth_session_cookie_expires_at';
32
42
  *
33
43
  * Test harnesses (`create_test_app_from_specs`, `create_fake_hono_context`,
34
44
  * the WS round-trip `connect()` helper, plus per-test middleware that
35
- * pre-populates `REQUEST_CONTEXT_KEY`) set this to `true` so
45
+ * pre-populates `REQUEST_CONTEXT_KEY`) set it to `TEST_CONTEXT_PRESET` so
36
46
  * `apply_authorization_phase` skips its DB-backed actor resolution and
37
47
  * trusts the supplied `RequestContext`. Production middleware never sets
38
48
  * this key — only test code does. The flag is the explicit escape hatch
39
49
  * that replaced the implicit "is `REQUEST_CONTEXT_KEY` already set?" probe,
40
50
  * so that future production code consulting `REQUEST_CONTEXT_KEY` cannot
41
- * silently bypass the live build.
51
+ * silently bypass the live build. Read it with `has_test_context_preset`.
42
52
  */
43
53
  export const TEST_CONTEXT_PRESET_KEY = 'test_context_preset';
54
+ /**
55
+ * The one value that sets the test-harness preset (`TEST_CONTEXT_PRESET_KEY`).
56
+ * A symbol, so only code that imports it can set the flag: a string, a
57
+ * `true`, or any other value a misconfiguration or a request could put under
58
+ * the key reads as unset. Testing only — no module outside `testing/` writes
59
+ * it.
60
+ */
61
+ export const TEST_CONTEXT_PRESET = Symbol('test_context_preset');
62
+ /**
63
+ * Whether a test harness pre-baked this request's context — the key holds
64
+ * `TEST_CONTEXT_PRESET` itself. The skip every transport makes of the live
65
+ * authorization phase and the admission re-reads.
66
+ *
67
+ * @param c - the Hono context
68
+ * @returns `true` only when the key holds the `TEST_CONTEXT_PRESET` symbol
69
+ */
70
+ export const has_test_context_preset = (c) => c.get(TEST_CONTEXT_PRESET_KEY) === TEST_CONTEXT_PRESET;
@@ -17,7 +17,7 @@ effects, see ../../../docs/architecture.md.
17
17
  - `http/route_spec.ts` — `RouteSpec` + `apply_route_specs`, validation pipeline, transactions.
18
18
  - `http/auth_shape.ts` — canonical `RouteAuth` Zod schema + cross-axis invariants + predicates.
19
19
  - `http/error_schemas.ts` — `ERROR_*` constants, standard error shapes, `derive_error_schemas`.
20
- - `http/schema_helpers.ts` — shared Zod introspection (null/void/strict/surface/merge/middleware-applies) + `to_void_params` / `to_input_params` / `safe_parse_dropping_unknown_keys`.
20
+ - `http/schema_helpers.ts` — shared Zod introspection (null/void/strict/surface/merge/middleware-applies) + `to_void_params` / `to_input_params` / `json_has_own_proto_key` / `safe_parse_dropping_unknown_keys`.
21
21
  - `http/middleware_spec.ts` — `MiddlewareSpec` interface.
22
22
  - `http/body_limit.ts` — `create_body_limit_middleware(max_size)`: the `413` body cap `create_app_server` mounts. Refuses on `Content-Length` without reading `c.req.raw.body` and answers `Connection: close` — `413` past the cap, `400` `ERROR_INVALID_CONTENT_LENGTH` when the value is not a plain run of ASCII digits (a length the cap cannot read, which Hono's `bodyLimit` would pass uncounted) — else falls through to Hono's `bodyLimit` (no `Content-Length`, or one beside `Transfer-Encoding`), which reads the body into memory up to the cap before the next middleware runs, so its `413` — no `Connection: close` — also precedes origin and auth. Mounted with `app.use`, not as a `MiddlewareSpec`, so neither status appears in a route's merged error schemas. After the header `413` Node and Bun close at once (the header is what makes them — Bun 1.4.3 is the tested floor, an older Bun kept the connection and served the next request) and Deno closes once the declared body has arrived (../../../docs/security.md §Body Size Limiting).
23
23
  - `http/surface.ts` — `AppSurface`, `AppSurfaceSpec`, `generate_app_surface`, diagnostics.
@@ -78,11 +78,11 @@ interface RouteContext {
78
78
  - **`route.pending_effects`** — direct push for eager fire-and-forget pool writes (audit, api-token usage tracking).
79
79
  - **`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`.
80
80
 
81
- Pool-level fire-and-forget writes (audit logs, etc.) run through the bound
82
- `AppDeps.audit` capability — see `auth/CLAUDE.md` §AppDeps split. Handlers
83
- that need rollback-resilient writes call `deps.audit.emit(route, input)`,
84
- which captures the pool inside the bound emitter so the row lands even
85
- when the handler's transaction rolls back.
81
+ Audit rows run through the bound `AppDeps.audit` capability — see
82
+ `auth/CLAUDE.md` §Audit emitter. `await deps.audit.emit(route, input)` writes
83
+ a success row in the route's transaction when one is open and a failure row
84
+ via the pool captured inside the bound emitter, so a refused attempt's row
85
+ lands even when the handler's transaction rolls back.
86
86
 
87
87
  ### Declarative transactions
88
88
 
@@ -211,7 +211,7 @@ confirmation.
211
211
 
212
212
  ### `ERROR_*` constants by category
213
213
 
214
- - **Validation**: `ERROR_INVALID_REQUEST_BODY`, `ERROR_INVALID_JSON_BODY`, `ERROR_INVALID_ROUTE_PARAMS`, `ERROR_INVALID_QUERY_PARAMS`
214
+ - **Validation**: `ERROR_INVALID_REQUEST_BODY`, `ERROR_INVALID_JSON_BODY`, `ERROR_INVALID_ROUTE_PARAMS`, `ERROR_INVALID_QUERY_PARAMS`, `ERROR_PARAMS_PROTO_KEY` (RPC params)
215
215
  - **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`
216
216
  - **Origin + bearer**: `ERROR_FORBIDDEN_ORIGIN`, `ERROR_INVALID_TOKEN`, `ERROR_ACCOUNT_NOT_FOUND`
217
217
  - **Keeper/daemon**: `ERROR_KEEPER_ACCOUNT_NOT_FOUND`
@@ -237,6 +237,7 @@ Key helpers:
237
237
  - `is_void_schema(schema)` — `instanceof z.ZodVoid`; a `z.void()` input declares a parameterless RPC method
238
238
  - `to_void_params(raw_params)` — reads absent, `null`, and `{}` params of a `z.void()` input as the no-arg call (`undefined`), passing any other shape through for `z.void()` to refuse — the twin of the Rust spine's `require_void_params`
239
239
  - `to_input_params(input, raw_params)` — the one params normalizer every receiving end runs before `input.safeParse`: `to_void_params` for a `z.void()` input, else absent/`null` → `{}`; used by both the server dispatch core (`perform_action`) and the peer receive path (`ActionDispatcher`)
240
+ - `json_has_own_proto_key(value)` — whether any object in a parsed JSON value has an own `__proto__` key, by an iterative walk (no recursion — `JSON.parse` nests deeper than the call stack); the dispatcher refuses such params with `ERROR_PARAMS_PROTO_KEY`. Twin of the Rust `fuz_http::json_has_own_proto_key`
240
241
  - `safe_parse_dropping_unknown_keys(schema, value)` — the forward-compatible read of a remote-authored payload: when every issue is an unrecognized key, strips those keys from a copy and reparses; 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
241
242
  - `is_strict_object_schema(schema)` — detects `z.strictObject()` by checking `schema.def.catchall instanceof z.ZodNever`
242
243
  - `schema_to_surface(schema)` — Zod → JSON Schema, with `$schema` and `default` keys stripped recursively (defaults may be non-deterministic; `$schema` is snapshot noise)
@@ -459,7 +460,7 @@ which holds a declaration to the same rules.
459
460
  - 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)
460
461
  - Type guards: `is_jsonrpc_request_id` (rejects NaN/Infinity), `is_jsonrpc_object`, `is_jsonrpc_request` / `_notification` / `_response` / `_error_response`
461
462
  - Converters: `to_jsonrpc_message_id`, `to_jsonrpc_params` (normalizes primitives to `{value}`)
462
- - 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.
463
+ - 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 Zod-rebuilt copy drops it).
463
464
 
464
465
  Handlers can `throw jsonrpc_errors.*` — `apply_route_specs`' error-catch
465
466
  layer converts to the flat REST body (`{error: <reason>, message?, ...rest_data}`)
@@ -608,8 +609,8 @@ instead of discovering the refusal — `ui/table_state.svelte.ts` gates on
608
609
  exclusion must not masquerade as one.
609
610
 
610
611
  **Every successful row delete is audited.** The `DELETE` handler defers a
611
- `deps.audit` emit through `emit_after_commit`, so the pool-routed row lands
612
- iff the delete's transaction commits — the success-only trail can't claim a
612
+ `deps.audit.emit_pool` call through `emit_after_commit`, so the pool-routed
613
+ row lands iff the delete's transaction commits — the success-only trail can't claim a
613
614
  delete that failed at COMMIT (the Rust twin commits before emitting for the
614
615
  same reason). Account-grain attribution (the browser's gate is account-grain,
615
616
  so no actor is claimed), metadata `{table, pk_column, id}`. Refusals emit