@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
@@ -0,0 +1,259 @@
1
+ import './assert_dev_env.js';
2
+ /**
3
+ * Database invariants of the auth schema — states no sequence of spine
4
+ * operations may leave behind, checked over the rows themselves.
5
+ *
6
+ * A wire-level test asserts what one request answers; these hold the
7
+ * database a whole test leaves, so a cascade that misses a row (a session
8
+ * outliving its account's tombstone, an offer still pending from a deleted
9
+ * grantor) fails even when no request ever reads the row. One SQL set serves
10
+ * both spines: schema parity keeps their DDL identical.
11
+ *
12
+ * Two kinds:
13
+ *
14
+ * - **State** — over the live rows: no credential of a tombstoned account, no
15
+ * pending offer or unclaimed invite with a dead party, a bootstrapped
16
+ * database keeps a live keeper and a live admin and an unbootstrapped one
17
+ * has no account, an actor's tombstone agrees with its account's, and the
18
+ * structural pairings the writes keep.
19
+ * - **History** — over `audit_log`, so an undelete can't hide a cascade that
20
+ * missed: no pending offer, unclaimed invite or live credential that a
21
+ * successful removal of its account should have ended.
22
+ *
23
+ * An invite's issuer is its `created_by` actor's account, or — once a purge's
24
+ * cascade has nulled `created_by` — the `account_id` of the invite's
25
+ * successful `invite_create` audit row (`metadata.invite_id`; both spines
26
+ * write it). `account_purge` counts as a removal only for invites: a purge's
27
+ * cascade deletes the account's offers, sessions and tokens with it, so for
28
+ * those a purge leaves nothing to check.
29
+ *
30
+ * **Order against a removal.** Where both spines audit the row's creation
31
+ * (`role_grant_offer_create` with `metadata.offer_id`, `invite_create` with
32
+ * `metadata.invite_id`, `token_create` with `metadata.token_id`), the
33
+ * removal's audit `seq` is compared with the creation row's — exact, whatever
34
+ * the clocks: the creation row is written under the account lock the removal
35
+ * takes, in the creating transaction. Otherwise (sessions, and rows written
36
+ * without the action, as the in-process fixture writes them) the timestamps
37
+ * are compared, and a removal in the same clock tick as the creation counts as
38
+ * after it: the database clock may tick in milliseconds (pglet), and a
39
+ * creation tied with the removal that should have ended it is the leak the
40
+ * check exists for, while the opposite order — a removal, an undelete, and a
41
+ * fresh creation in one tick — is not a sequence the tests drive.
42
+ *
43
+ * **The long-transaction walk.** A timestamp is its transaction's start
44
+ * (`created_at` defaults to `NOW()`), not when the row was written, so a
45
+ * timestamp comparison misflags one legal sequence: a login's transaction
46
+ * begins, a delete and then an undelete of its account commit, and only then
47
+ * does the login take the account lock, find the account live, and insert —
48
+ * a session minted after the undelete, its `created_at` before the delete.
49
+ * Nothing drives it: the login must stall between its transaction's start and
50
+ * the account lock while two admin actions commit, which only a test stalling
51
+ * the login's connection between its `BEGIN` and its lock statement could
52
+ * arrange, on Postgres, and none does. Sessions keep this false positive:
53
+ * their creation is audited by `login` (or `signup`, `bootstrap`), whose rows
54
+ * carry no `session_id` to order by, and adding one would change an audit
55
+ * shape on both spines — not taken. An API token minted by
56
+ * `account_token_create` is ordered by its `token_create` row, so the walk
57
+ * can't misflag one — nor could it reach one: that mint re-reads its
58
+ * authorizing session under the account lock, and a delete revokes every
59
+ * session. A token minted without that row (a fixture, a consumer's own mint)
60
+ * falls back to `created_at`.
61
+ *
62
+ * Not invariants, by design: the role grants of a tombstoned actor (kept
63
+ * through delete and undelete, inert while no credential authenticates) and
64
+ * expired credentials no sweep has removed.
65
+ *
66
+ * The whole set is one statement, `DB_INVARIANTS_SQL`, binding the role names
67
+ * as `$1` (keeper) and `$2` (admin). `db_invariants.gen.sql.ts` writes it to
68
+ * `db_invariants.sql`, which the Rust spine's `fuz_testing` embeds byte for
69
+ * byte: the `_testing_db_invariants` backdoor runs it on either spine, so a
70
+ * cross-process harness checks a database it can't reach. Each violation
71
+ * comes back as its invariant's name and the row as JSON text
72
+ * (`jsonb_build_object(...)::text`), parsed on the reading side; exclusions
73
+ * filter the parsed rows (`to_db_invariant_violations`).
74
+ *
75
+ * Vitest-free, so a test binary can mount the backdoor; the per-test hooks
76
+ * live in `db_invariants.ts`.
77
+ *
78
+ * @module
79
+ */
80
+ import { type Infer } from '@fuzdev/fuz_schema/schema.ts';
81
+ import type { QueryDeps } from '../db/query_deps.js';
82
+ /** One invariant: its name, what it holds, and the query naming the rows that break it. */
83
+ export interface DbInvariant {
84
+ readonly name: string;
85
+ /** The columns `sql` selects, reported for each violating row. */
86
+ readonly columns: ReadonlyArray<string>;
87
+ /** What holds — the message a violation is reported under. */
88
+ readonly description: string;
89
+ /**
90
+ * Selects one row per violation, with the identity needed to debug it. May
91
+ * read the shared CTEs (`role_param`, `removal`, `offer_party`,
92
+ * `invite_issuer`, `token_issued`); the role parameters are read through
93
+ * `role_param`.
94
+ */
95
+ readonly sql: string;
96
+ }
97
+ /**
98
+ * Every invariant, in report order. State invariants first, then the history
99
+ * ones over `audit_log`.
100
+ */
101
+ export declare const DB_INVARIANTS: readonly [{
102
+ readonly name: "credential_of_tombstoned_account";
103
+ readonly columns: readonly ["kind", "id", "account_id"];
104
+ readonly description: "no session or API token belongs to a tombstoned account";
105
+ readonly sql: "SELECT 'auth_session' AS kind, LEFT(s.id, 12) AS id, s.account_id\n\t\t\tFROM auth_session s JOIN account ac ON ac.id = s.account_id\n\t\t\tWHERE ac.deleted_at IS NOT NULL\n\t\t\tUNION ALL\n\t\t\tSELECT 'api_token' AS kind, t.id, t.account_id\n\t\t\tFROM api_token t JOIN account ac ON ac.id = t.account_id\n\t\t\tWHERE ac.deleted_at IS NOT NULL";
106
+ }, {
107
+ readonly name: "pending_offer_with_dead_party";
108
+ readonly columns: readonly ["id", "from_actor_id", "from_account_id", "to_account_id", "to_actor_id", "from_actor_dead", "from_account_dead", "to_account_dead", "to_actor_dead"];
109
+ readonly description: "no pending role grant offer has a tombstoned grantor actor, grantor account, recipient account, or recipient actor";
110
+ readonly sql: "SELECT op.id, op.from_actor_id, op.from_account_id, op.to_account_id, op.to_actor_id,\n\t\t\t\tfa.deleted_at IS NOT NULL AS from_actor_dead,\n\t\t\t\tfac.deleted_at IS NOT NULL AS from_account_dead,\n\t\t\t\tta.deleted_at IS NOT NULL AS to_account_dead,\n\t\t\t\tCOALESCE(tac.deleted_at IS NOT NULL, false) AS to_actor_dead\n\t\t\tFROM offer_party op\n\t\t\tJOIN actor fa ON fa.id = op.from_actor_id\n\t\t\tJOIN account fac ON fac.id = op.from_account_id\n\t\t\tJOIN account ta ON ta.id = op.to_account_id\n\t\t\tLEFT JOIN actor tac ON tac.id = op.to_actor_id\n\t\t\tWHERE fa.deleted_at IS NOT NULL OR fac.deleted_at IS NOT NULL\n\t\t\t OR ta.deleted_at IS NOT NULL OR tac.deleted_at IS NOT NULL";
111
+ }, {
112
+ readonly name: "unclaimed_invite_of_dead_issuer";
113
+ readonly columns: readonly ["id", "created_by", "issuer_account_id", "actor_dead", "issuer_purged"];
114
+ readonly description: "no unclaimed invite was issued by a tombstoned actor, or by an account tombstoned or purged";
115
+ readonly sql: "SELECT ii.id, ii.created_by, ii.issuer_account_id,\n\t\t\t\tii.actor_dead, ac.id IS NULL AS issuer_purged\n\t\t\tFROM invite_issuer ii\n\t\t\tLEFT JOIN account ac ON ac.id = ii.issuer_account_id\n\t\t\tWHERE ii.issuer_account_id IS NOT NULL\n\t\t\t AND (ii.actor_dead OR ac.id IS NULL OR ac.deleted_at IS NOT NULL)";
116
+ }, {
117
+ readonly name: "bootstrapped_without_live_keeper";
118
+ readonly columns: readonly ["bootstrapped"];
119
+ readonly description: "a bootstrapped database keeps a live actor of a live account holding an active global keeper grant — the keeper is never removable";
120
+ readonly sql: `SELECT true AS bootstrapped FROM bootstrap_lock
121
+ \t\t\tWHERE bootstrapped AND NOT ${string}`;
122
+ }, {
123
+ readonly name: "bootstrapped_without_live_admin";
124
+ readonly columns: readonly ["bootstrapped"];
125
+ readonly description: "a bootstrapped database keeps a live actor of a live account holding an active global admin grant — bootstrap grants one and the last-admin guard keeps one";
126
+ readonly sql: `SELECT true AS bootstrapped FROM bootstrap_lock
127
+ \t\t\tWHERE bootstrapped AND NOT ${string}`;
128
+ }, {
129
+ readonly name: "account_without_bootstrap";
130
+ readonly columns: readonly ["account_id"];
131
+ readonly description: "an unbootstrapped database has no account — the bootstrap that writes the first one flips the lock in its transaction";
132
+ readonly sql: "SELECT ac.id AS account_id FROM account ac\n\t\t\tWHERE NOT EXISTS (SELECT 1 FROM bootstrap_lock WHERE bootstrapped)";
133
+ }, {
134
+ readonly name: "actor_tombstone_disagrees_with_account";
135
+ readonly columns: readonly ["actor_id", "account_id", "actor_dead", "account_dead"];
136
+ readonly description: "an actor is tombstoned exactly when its account is — no wire path deletes one actor";
137
+ readonly sql: "SELECT a.id AS actor_id, a.account_id,\n\t\t\t\ta.deleted_at IS NOT NULL AS actor_dead, ac.deleted_at IS NOT NULL AS account_dead\n\t\t\tFROM actor a JOIN account ac ON ac.id = a.account_id\n\t\t\tWHERE (a.deleted_at IS NULL) <> (ac.deleted_at IS NULL)";
138
+ }, {
139
+ readonly name: "offer_to_actor_outside_to_account";
140
+ readonly columns: readonly ["id", "to_account_id", "to_actor_id", "to_actor_account_id"];
141
+ readonly description: "an offer's recipient actor belongs to its recipient account";
142
+ readonly sql: "SELECT o.id, o.to_account_id, o.to_actor_id, a.account_id AS to_actor_account_id\n\t\t\tFROM role_grant_offer o JOIN actor a ON a.id = o.to_actor_id\n\t\t\tWHERE a.account_id <> o.to_account_id";
143
+ }, {
144
+ readonly name: "invite_claimed_by_without_claimed_at";
145
+ readonly columns: readonly ["id", "claimed_by"];
146
+ readonly description: "an invite naming its claimant records when it was claimed";
147
+ readonly sql: "SELECT i.id, i.claimed_by FROM invite i\n\t\t\tWHERE i.claimed_by IS NOT NULL AND i.claimed_at IS NULL";
148
+ }, {
149
+ readonly name: "pending_offer_outlived_party_removal";
150
+ readonly columns: readonly ["id", "from_actor_id", "from_account_id", "to_account_id"];
151
+ readonly description: "no pending offer is older than a successful delete of its grantor or recipient account";
152
+ readonly sql: `SELECT op.id, op.from_actor_id, op.from_account_id, op.to_account_id
153
+ \t\t\tFROM offer_party op
154
+ \t\t\tWHERE ${string}
155
+ \t\t\t OR ${string}`;
156
+ }, {
157
+ readonly name: "unclaimed_invite_outlived_issuer_removal";
158
+ readonly columns: readonly ["id", "created_by", "issuer_account_id"];
159
+ readonly description: "no unclaimed invite is older than a successful delete or purge of its issuer account";
160
+ readonly sql: `SELECT ii.id, ii.created_by, ii.issuer_account_id
161
+ \t\t\tFROM invite_issuer ii
162
+ \t\t\tWHERE ${string}`;
163
+ }, {
164
+ readonly name: "credential_outlived_account_removal";
165
+ readonly columns: readonly ["kind", "id", "account_id"];
166
+ readonly description: "no session or API token was created before a successful delete of its account";
167
+ readonly sql: `SELECT 'auth_session' AS kind, LEFT(s.id, 12) AS id, s.account_id
168
+ \t\t\tFROM auth_session s
169
+ \t\t\tWHERE ${string}
170
+ \t\t\tUNION ALL
171
+ \t\t\tSELECT 'api_token' AS kind, ti.id, ti.account_id
172
+ \t\t\tFROM token_issued ti
173
+ \t\t\tWHERE ${string}`;
174
+ }];
175
+ /** The name of one of `DB_INVARIANTS`. */
176
+ export type DbInvariantName = (typeof DB_INVARIANTS)[number]['name'];
177
+ /** The rows breaking one invariant. */
178
+ export interface DbInvariantViolation {
179
+ readonly name: DbInvariantName;
180
+ readonly description: string;
181
+ readonly rows: ReadonlyArray<Record<string, unknown>>;
182
+ }
183
+ /** The `DbInvariantExclusions` key that excludes every invariant. */
184
+ export declare const DB_INVARIANTS_EXCLUDE_ALL = "all";
185
+ /**
186
+ * Invariants left unchecked, each by name with the non-empty reason it can't
187
+ * hold for the tests at hand — rows a test writes directly, without the
188
+ * cascade the spine would run. A test an `xfail_until` marker tracks breaks
189
+ * the invariant its gap breaks while the gap is open, and the per-test check
190
+ * fails it whatever the marker expects: exclude that invariant on the setup
191
+ * the marked test uses, with the marker's tracking id in the reason.
192
+ *
193
+ * `all` turns the whole check off, with its reason, and stands alone: a cross-process backend
194
+ * that doesn't serve `_testing_db_invariants` must say so this way, and a
195
+ * setup refuses it otherwise.
196
+ */
197
+ export type DbInvariantExclusions = Readonly<Partial<Record<DbInvariantName | typeof DB_INVARIANTS_EXCLUDE_ALL, string>>>;
198
+ /**
199
+ * Refuse an exclusion naming no invariant or carrying no reason.
200
+ *
201
+ * @param exclude - the exclusions to check
202
+ * @param label - names the caller in the error
203
+ * @throws Error naming the first unknown invariant or empty reason, or a
204
+ * named invariant beside `all`, which already excludes it
205
+ */
206
+ export declare const validate_db_invariant_exclusions: (exclude: DbInvariantExclusions | undefined, label: string) => void;
207
+ /**
208
+ * Every invariant in one statement, `$1` the keeper role and `$2` the admin
209
+ * role: one `{invariant, row}` per violating row, `row` its columns as JSON
210
+ * text. What `db_invariants.sql` holds, and what `_testing_db_invariants` runs
211
+ * on both spines.
212
+ */
213
+ export declare const DB_INVARIANTS_SQL: string;
214
+ /** One violating row: its invariant's name and its columns. */
215
+ export declare const DbInvariantRow: import("@fuzdev/fuz_schema/schema.ts").ObjectSchema<{
216
+ invariant: import("@fuzdev/fuz_schema/schema.ts").StringSchema;
217
+ row: import("@fuzdev/fuz_schema/schema.ts").RecordSchema<import("@fuzdev/fuz_schema/schema.ts").UnknownSchema>;
218
+ }>;
219
+ export type DbInvariantRow = Infer<typeof DbInvariantRow>;
220
+ /** What `_testing_db_invariants` answers — every violating row, unfiltered. */
221
+ export declare const DbInvariantRows: import("@fuzdev/fuz_schema/schema.ts").ObjectSchema<{
222
+ rows: import("@fuzdev/fuz_schema/schema.ts").ArraySchema<import("@fuzdev/fuz_schema/schema.ts").ObjectSchema<{
223
+ invariant: import("@fuzdev/fuz_schema/schema.ts").StringSchema;
224
+ row: import("@fuzdev/fuz_schema/schema.ts").RecordSchema<import("@fuzdev/fuz_schema/schema.ts").UnknownSchema>;
225
+ }>>;
226
+ }>;
227
+ export type DbInvariantRows = Infer<typeof DbInvariantRows>;
228
+ /**
229
+ * Run `DB_INVARIANTS_SQL`, parsing each row's JSON text.
230
+ *
231
+ * @param deps - the database to read
232
+ * @returns every violating row, in no promised order
233
+ */
234
+ export declare const query_db_invariant_rows: (deps: QueryDeps) => Promise<Array<DbInvariantRow>>;
235
+ /**
236
+ * Group violating rows by invariant, dropping the excluded ones.
237
+ *
238
+ * @param rows - what `query_db_invariant_rows` or `_testing_db_invariants` returned
239
+ * @param exclude - invariants to skip, each with its reason
240
+ * @returns one entry per broken invariant, in `DB_INVARIANTS` order; empty when all hold
241
+ * @throws Error on a row naming no invariant (a reader out of step with the statement)
242
+ */
243
+ export declare const to_db_invariant_violations: (rows: ReadonlyArray<DbInvariantRow>, exclude?: DbInvariantExclusions) => Array<DbInvariantViolation>;
244
+ /**
245
+ * Query every invariant not excluded, returning those with violating rows.
246
+ *
247
+ * @param deps - the database to read
248
+ * @param exclude - invariants to skip, each with its reason
249
+ * @returns one entry per broken invariant, in `DB_INVARIANTS` order; empty when all hold
250
+ */
251
+ export declare const query_db_invariant_violations: (deps: QueryDeps, exclude?: DbInvariantExclusions) => Promise<Array<DbInvariantViolation>>;
252
+ /**
253
+ * Render violations as one message, an invariant per paragraph with its rows.
254
+ *
255
+ * @param violations - what `query_db_invariant_violations` returned
256
+ * @param label - names the database (the backend, or the in-process leg)
257
+ */
258
+ export declare const format_db_invariant_violations: (violations: ReadonlyArray<DbInvariantViolation>, label: string) => string;
259
+ //# sourceMappingURL=db_invariant_queries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db_invariant_queries.d.ts","sourceRoot":"","sources":["../../src/lib/testing/db_invariant_queries.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,CAAC;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6EG;AAEH,OAAO,EAA0C,KAAK,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAElG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAqFrD,2FAA2F;AAC3F,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACxC,8DAA8D;IAC9D,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4IqB,CAAC;AAEhD,0CAA0C;AAC1C,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;AAErE,uCAAuC;AACvC,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACtD;AAED,qEAAqE;AACrE,eAAO,MAAM,yBAAyB,QAAQ,CAAC;AAE/C;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAC3C,OAAO,CAAC,MAAM,CAAC,eAAe,GAAG,OAAO,yBAAyB,EAAE,MAAM,CAAC,CAAC,CAC3E,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,gCAAgC,GAC5C,SAAS,qBAAqB,GAAG,SAAS,EAC1C,OAAO,MAAM,KACX,IAiBF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,QAML,CAAC;AAE1B,+DAA+D;AAC/D,eAAO,MAAM,cAAc;;;EAGzB,CAAC;AACH,MAAM,MAAM,cAAc,GAAG,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAE1D,+EAA+E;AAC/E,eAAO,MAAM,eAAe;;;;;EAE1B,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAE5D;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,GAAU,MAAM,SAAS,KAAG,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAS5F,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,0BAA0B,GACtC,MAAM,aAAa,CAAC,cAAc,CAAC,EACnC,UAAU,qBAAqB,KAC7B,KAAK,CAAC,oBAAoB,CAiB5B,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,GACzC,MAAM,SAAS,EACf,UAAU,qBAAqB,KAC7B,OAAO,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAGrC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,8BAA8B,GAC1C,YAAY,aAAa,CAAC,oBAAoB,CAAC,EAC/C,OAAO,MAAM,KACX,MAOU,CAAC"}
@@ -0,0 +1,400 @@
1
+ import './assert_dev_env.js';
2
+ /**
3
+ * Database invariants of the auth schema — states no sequence of spine
4
+ * operations may leave behind, checked over the rows themselves.
5
+ *
6
+ * A wire-level test asserts what one request answers; these hold the
7
+ * database a whole test leaves, so a cascade that misses a row (a session
8
+ * outliving its account's tombstone, an offer still pending from a deleted
9
+ * grantor) fails even when no request ever reads the row. One SQL set serves
10
+ * both spines: schema parity keeps their DDL identical.
11
+ *
12
+ * Two kinds:
13
+ *
14
+ * - **State** — over the live rows: no credential of a tombstoned account, no
15
+ * pending offer or unclaimed invite with a dead party, a bootstrapped
16
+ * database keeps a live keeper and a live admin and an unbootstrapped one
17
+ * has no account, an actor's tombstone agrees with its account's, and the
18
+ * structural pairings the writes keep.
19
+ * - **History** — over `audit_log`, so an undelete can't hide a cascade that
20
+ * missed: no pending offer, unclaimed invite or live credential that a
21
+ * successful removal of its account should have ended.
22
+ *
23
+ * An invite's issuer is its `created_by` actor's account, or — once a purge's
24
+ * cascade has nulled `created_by` — the `account_id` of the invite's
25
+ * successful `invite_create` audit row (`metadata.invite_id`; both spines
26
+ * write it). `account_purge` counts as a removal only for invites: a purge's
27
+ * cascade deletes the account's offers, sessions and tokens with it, so for
28
+ * those a purge leaves nothing to check.
29
+ *
30
+ * **Order against a removal.** Where both spines audit the row's creation
31
+ * (`role_grant_offer_create` with `metadata.offer_id`, `invite_create` with
32
+ * `metadata.invite_id`, `token_create` with `metadata.token_id`), the
33
+ * removal's audit `seq` is compared with the creation row's — exact, whatever
34
+ * the clocks: the creation row is written under the account lock the removal
35
+ * takes, in the creating transaction. Otherwise (sessions, and rows written
36
+ * without the action, as the in-process fixture writes them) the timestamps
37
+ * are compared, and a removal in the same clock tick as the creation counts as
38
+ * after it: the database clock may tick in milliseconds (pglet), and a
39
+ * creation tied with the removal that should have ended it is the leak the
40
+ * check exists for, while the opposite order — a removal, an undelete, and a
41
+ * fresh creation in one tick — is not a sequence the tests drive.
42
+ *
43
+ * **The long-transaction walk.** A timestamp is its transaction's start
44
+ * (`created_at` defaults to `NOW()`), not when the row was written, so a
45
+ * timestamp comparison misflags one legal sequence: a login's transaction
46
+ * begins, a delete and then an undelete of its account commit, and only then
47
+ * does the login take the account lock, find the account live, and insert —
48
+ * a session minted after the undelete, its `created_at` before the delete.
49
+ * Nothing drives it: the login must stall between its transaction's start and
50
+ * the account lock while two admin actions commit, which only a test stalling
51
+ * the login's connection between its `BEGIN` and its lock statement could
52
+ * arrange, on Postgres, and none does. Sessions keep this false positive:
53
+ * their creation is audited by `login` (or `signup`, `bootstrap`), whose rows
54
+ * carry no `session_id` to order by, and adding one would change an audit
55
+ * shape on both spines — not taken. An API token minted by
56
+ * `account_token_create` is ordered by its `token_create` row, so the walk
57
+ * can't misflag one — nor could it reach one: that mint re-reads its
58
+ * authorizing session under the account lock, and a delete revokes every
59
+ * session. A token minted without that row (a fixture, a consumer's own mint)
60
+ * falls back to `created_at`.
61
+ *
62
+ * Not invariants, by design: the role grants of a tombstoned actor (kept
63
+ * through delete and undelete, inert while no credential authenticates) and
64
+ * expired credentials no sweep has removed.
65
+ *
66
+ * The whole set is one statement, `DB_INVARIANTS_SQL`, binding the role names
67
+ * as `$1` (keeper) and `$2` (admin). `db_invariants.gen.sql.ts` writes it to
68
+ * `db_invariants.sql`, which the Rust spine's `fuz_testing` embeds byte for
69
+ * byte: the `_testing_db_invariants` backdoor runs it on either spine, so a
70
+ * cross-process harness checks a database it can't reach. Each violation
71
+ * comes back as its invariant's name and the row as JSON text
72
+ * (`jsonb_build_object(...)::text`), parsed on the reading side; exclusions
73
+ * filter the parsed rows (`to_db_invariant_violations`).
74
+ *
75
+ * Vitest-free, so a test binary can mount the backdoor; the per-test hooks
76
+ * live in `db_invariants.ts`.
77
+ *
78
+ * @module
79
+ */
80
+ import { array, object, record, string, unknown } from '@fuzdev/fuz_schema/schema.ts';
81
+ import { offer_pending_predicate, role_grant_active_sql } from '../auth/role_grant_sql.js';
82
+ import { ROLE_ADMIN, ROLE_KEEPER } from '../auth/role_schema.js';
83
+ /**
84
+ * The CTEs every invariant may read, heading `DB_INVARIANTS_SQL`.
85
+ * `role_param` binds and types the role parameters (`$1` keeper, `$2` admin)
86
+ * in one place — an invariant reads them from it, never as `$n`.
87
+ */
88
+ const SHARED_CTES_SQL = `
89
+ role_param AS (SELECT $1::text AS keeper, $2::text AS admin),
90
+ removal AS (
91
+ SELECT target_account_id AS account_id, event_type, seq, created_at
92
+ FROM audit_log
93
+ WHERE outcome = 'success'
94
+ AND event_type IN ('account_delete', 'account_purge')
95
+ AND target_account_id IS NOT NULL
96
+ ),
97
+ offer_party AS (
98
+ SELECT o.id, o.from_actor_id, fa.account_id AS from_account_id, o.to_account_id,
99
+ o.to_actor_id, o.created_at,
100
+ (SELECT MIN(al.seq) FROM audit_log al
101
+ WHERE al.event_type = 'role_grant_offer_create' AND al.outcome = 'success'
102
+ AND al.metadata->>'offer_id' = o.id::text) AS create_seq
103
+ FROM role_grant_offer o
104
+ JOIN actor fa ON fa.id = o.from_actor_id
105
+ WHERE ${offer_pending_predicate('o')}
106
+ ),
107
+ invite_issuer AS (
108
+ SELECT i.id, i.created_by, i.created_at, a.deleted_at IS NOT NULL AS actor_dead,
109
+ COALESCE(a.account_id, (SELECT al.account_id FROM audit_log al
110
+ WHERE al.event_type = 'invite_create' AND al.outcome = 'success'
111
+ AND al.metadata->>'invite_id' = i.id::text
112
+ ORDER BY al.seq LIMIT 1)) AS issuer_account_id,
113
+ (SELECT MIN(al.seq) FROM audit_log al
114
+ WHERE al.event_type = 'invite_create' AND al.outcome = 'success'
115
+ AND al.metadata->>'invite_id' = i.id::text) AS create_seq
116
+ FROM invite i
117
+ LEFT JOIN actor a ON a.id = i.created_by
118
+ WHERE i.claimed_at IS NULL
119
+ ),
120
+ token_issued AS (
121
+ SELECT t.id, t.account_id, t.created_at,
122
+ (SELECT MIN(al.seq) FROM audit_log al
123
+ WHERE al.event_type = 'token_create' AND al.outcome = 'success'
124
+ AND al.metadata->>'token_id' = t.id) AS create_seq
125
+ FROM api_token t
126
+ )`;
127
+ /**
128
+ * A `removal` row of `account_sql`, of one of `events`, after the row created
129
+ * at `created_at_sql` (with audit creation `seq` `create_seq_sql`, or null) —
130
+ * see the module doc for the order.
131
+ */
132
+ const removed_after_sql = (account_sql, created_at_sql, create_seq_sql, events) => `EXISTS (
133
+ SELECT 1 FROM removal r
134
+ WHERE r.account_id = ${account_sql}
135
+ AND r.event_type IN (${events.map((e) => `'${e}'`).join(', ')})
136
+ AND ${create_seq_sql === null
137
+ ? `r.created_at >= ${created_at_sql}`
138
+ : `CASE WHEN ${create_seq_sql} IS NULL THEN r.created_at >= ${created_at_sql}
139
+ ELSE r.seq > ${create_seq_sql} END`}
140
+ )`;
141
+ /** A live actor of a live account holding an active global grant of `role_param`'s `column`. */
142
+ const live_global_holder_sql = (column) => `EXISTS (
143
+ SELECT 1 FROM role_grant rg
144
+ JOIN actor a ON a.id = rg.actor_id
145
+ JOIN account ac ON ac.id = a.account_id
146
+ WHERE rg.role = (SELECT ${column} FROM role_param)
147
+ AND rg.scope_id IS NULL
148
+ AND ${role_grant_active_sql('rg')}
149
+ AND a.deleted_at IS NULL
150
+ AND ac.deleted_at IS NULL
151
+ )`;
152
+ /**
153
+ * Every invariant, in report order. State invariants first, then the history
154
+ * ones over `audit_log`.
155
+ */
156
+ export const DB_INVARIANTS = [
157
+ {
158
+ name: 'credential_of_tombstoned_account',
159
+ columns: ['kind', 'id', 'account_id'],
160
+ description: 'no session or API token belongs to a tombstoned account',
161
+ sql: `SELECT 'auth_session' AS kind, LEFT(s.id, 12) AS id, s.account_id
162
+ FROM auth_session s JOIN account ac ON ac.id = s.account_id
163
+ WHERE ac.deleted_at IS NOT NULL
164
+ UNION ALL
165
+ SELECT 'api_token' AS kind, t.id, t.account_id
166
+ FROM api_token t JOIN account ac ON ac.id = t.account_id
167
+ WHERE ac.deleted_at IS NOT NULL`
168
+ },
169
+ {
170
+ name: 'pending_offer_with_dead_party',
171
+ columns: [
172
+ 'id',
173
+ 'from_actor_id',
174
+ 'from_account_id',
175
+ 'to_account_id',
176
+ 'to_actor_id',
177
+ 'from_actor_dead',
178
+ 'from_account_dead',
179
+ 'to_account_dead',
180
+ 'to_actor_dead'
181
+ ],
182
+ description: 'no pending role grant offer has a tombstoned grantor actor, grantor account, recipient account, or recipient actor',
183
+ sql: `SELECT op.id, op.from_actor_id, op.from_account_id, op.to_account_id, op.to_actor_id,
184
+ fa.deleted_at IS NOT NULL AS from_actor_dead,
185
+ fac.deleted_at IS NOT NULL AS from_account_dead,
186
+ ta.deleted_at IS NOT NULL AS to_account_dead,
187
+ COALESCE(tac.deleted_at IS NOT NULL, false) AS to_actor_dead
188
+ FROM offer_party op
189
+ JOIN actor fa ON fa.id = op.from_actor_id
190
+ JOIN account fac ON fac.id = op.from_account_id
191
+ JOIN account ta ON ta.id = op.to_account_id
192
+ LEFT JOIN actor tac ON tac.id = op.to_actor_id
193
+ WHERE fa.deleted_at IS NOT NULL OR fac.deleted_at IS NOT NULL
194
+ OR ta.deleted_at IS NOT NULL OR tac.deleted_at IS NOT NULL`
195
+ },
196
+ {
197
+ name: 'unclaimed_invite_of_dead_issuer',
198
+ columns: ['id', 'created_by', 'issuer_account_id', 'actor_dead', 'issuer_purged'],
199
+ description: 'no unclaimed invite was issued by a tombstoned actor, or by an account tombstoned or purged',
200
+ sql: `SELECT ii.id, ii.created_by, ii.issuer_account_id,
201
+ ii.actor_dead, ac.id IS NULL AS issuer_purged
202
+ FROM invite_issuer ii
203
+ LEFT JOIN account ac ON ac.id = ii.issuer_account_id
204
+ WHERE ii.issuer_account_id IS NOT NULL
205
+ AND (ii.actor_dead OR ac.id IS NULL OR ac.deleted_at IS NOT NULL)`
206
+ },
207
+ {
208
+ name: 'bootstrapped_without_live_keeper',
209
+ columns: ['bootstrapped'],
210
+ description: 'a bootstrapped database keeps a live actor of a live account holding an active global keeper grant — the keeper is never removable',
211
+ sql: `SELECT true AS bootstrapped FROM bootstrap_lock
212
+ WHERE bootstrapped AND NOT ${live_global_holder_sql('keeper')}`
213
+ },
214
+ {
215
+ name: 'bootstrapped_without_live_admin',
216
+ columns: ['bootstrapped'],
217
+ description: 'a bootstrapped database keeps a live actor of a live account holding an active global admin grant — bootstrap grants one and the last-admin guard keeps one',
218
+ sql: `SELECT true AS bootstrapped FROM bootstrap_lock
219
+ WHERE bootstrapped AND NOT ${live_global_holder_sql('admin')}`
220
+ },
221
+ {
222
+ name: 'account_without_bootstrap',
223
+ columns: ['account_id'],
224
+ description: 'an unbootstrapped database has no account — the bootstrap that writes the first one flips the lock in its transaction',
225
+ sql: `SELECT ac.id AS account_id FROM account ac
226
+ WHERE NOT EXISTS (SELECT 1 FROM bootstrap_lock WHERE bootstrapped)`
227
+ },
228
+ {
229
+ name: 'actor_tombstone_disagrees_with_account',
230
+ columns: ['actor_id', 'account_id', 'actor_dead', 'account_dead'],
231
+ description: 'an actor is tombstoned exactly when its account is — no wire path deletes one actor',
232
+ sql: `SELECT a.id AS actor_id, a.account_id,
233
+ a.deleted_at IS NOT NULL AS actor_dead, ac.deleted_at IS NOT NULL AS account_dead
234
+ FROM actor a JOIN account ac ON ac.id = a.account_id
235
+ WHERE (a.deleted_at IS NULL) <> (ac.deleted_at IS NULL)`
236
+ },
237
+ {
238
+ name: 'offer_to_actor_outside_to_account',
239
+ columns: ['id', 'to_account_id', 'to_actor_id', 'to_actor_account_id'],
240
+ description: "an offer's recipient actor belongs to its recipient account",
241
+ sql: `SELECT o.id, o.to_account_id, o.to_actor_id, a.account_id AS to_actor_account_id
242
+ FROM role_grant_offer o JOIN actor a ON a.id = o.to_actor_id
243
+ WHERE a.account_id <> o.to_account_id`
244
+ },
245
+ {
246
+ name: 'invite_claimed_by_without_claimed_at',
247
+ columns: ['id', 'claimed_by'],
248
+ description: 'an invite naming its claimant records when it was claimed',
249
+ sql: `SELECT i.id, i.claimed_by FROM invite i
250
+ WHERE i.claimed_by IS NOT NULL AND i.claimed_at IS NULL`
251
+ },
252
+ {
253
+ name: 'pending_offer_outlived_party_removal',
254
+ columns: ['id', 'from_actor_id', 'from_account_id', 'to_account_id'],
255
+ description: 'no pending offer is older than a successful delete of its grantor or recipient account',
256
+ sql: `SELECT op.id, op.from_actor_id, op.from_account_id, op.to_account_id
257
+ FROM offer_party op
258
+ WHERE ${removed_after_sql('op.from_account_id', 'op.created_at', 'op.create_seq', ['account_delete'])}
259
+ OR ${removed_after_sql('op.to_account_id', 'op.created_at', 'op.create_seq', ['account_delete'])}`
260
+ },
261
+ {
262
+ name: 'unclaimed_invite_outlived_issuer_removal',
263
+ columns: ['id', 'created_by', 'issuer_account_id'],
264
+ description: 'no unclaimed invite is older than a successful delete or purge of its issuer account',
265
+ sql: `SELECT ii.id, ii.created_by, ii.issuer_account_id
266
+ FROM invite_issuer ii
267
+ WHERE ${removed_after_sql('ii.issuer_account_id', 'ii.created_at', 'ii.create_seq', [
268
+ 'account_delete',
269
+ 'account_purge'
270
+ ])}`
271
+ },
272
+ // A token is ordered by its `token_create` row's `seq`, a session by its
273
+ // `created_at` — which misflags a login whose transaction began before a
274
+ // delete and an undelete it then waited out; the module doc's
275
+ // long-transaction walk says why that is legal, undriven, and kept.
276
+ {
277
+ name: 'credential_outlived_account_removal',
278
+ columns: ['kind', 'id', 'account_id'],
279
+ description: 'no session or API token was created before a successful delete of its account',
280
+ sql: `SELECT 'auth_session' AS kind, LEFT(s.id, 12) AS id, s.account_id
281
+ FROM auth_session s
282
+ WHERE ${removed_after_sql('s.account_id', 's.created_at', null, ['account_delete'])}
283
+ UNION ALL
284
+ SELECT 'api_token' AS kind, ti.id, ti.account_id
285
+ FROM token_issued ti
286
+ WHERE ${removed_after_sql('ti.account_id', 'ti.created_at', 'ti.create_seq', ['account_delete'])}`
287
+ }
288
+ ];
289
+ /** The `DbInvariantExclusions` key that excludes every invariant. */
290
+ export const DB_INVARIANTS_EXCLUDE_ALL = 'all';
291
+ /**
292
+ * Refuse an exclusion naming no invariant or carrying no reason.
293
+ *
294
+ * @param exclude - the exclusions to check
295
+ * @param label - names the caller in the error
296
+ * @throws Error naming the first unknown invariant or empty reason, or a
297
+ * named invariant beside `all`, which already excludes it
298
+ */
299
+ export const validate_db_invariant_exclusions = (exclude, label) => {
300
+ if (!exclude)
301
+ return;
302
+ const names = new Set([DB_INVARIANTS_EXCLUDE_ALL, ...DB_INVARIANTS.map((i) => i.name)]);
303
+ if (exclude[DB_INVARIANTS_EXCLUDE_ALL] !== undefined && Object.keys(exclude).length > 1) {
304
+ const named = Object.keys(exclude).filter((name) => name !== DB_INVARIANTS_EXCLUDE_ALL);
305
+ throw new Error(`${label}: exclude_db_invariants '${named[0]}' is redundant — '${DB_INVARIANTS_EXCLUDE_ALL}' excludes every invariant`);
306
+ }
307
+ for (const [name, reason] of Object.entries(exclude)) {
308
+ if (!names.has(name)) {
309
+ throw new Error(`${label}: exclude_db_invariants names unknown invariant '${name}'`);
310
+ }
311
+ if (typeof reason !== 'string' || reason.trim() === '') {
312
+ throw new Error(`${label}: exclude_db_invariants '${name}' needs a reason`);
313
+ }
314
+ }
315
+ };
316
+ /**
317
+ * Every invariant in one statement, `$1` the keeper role and `$2` the admin
318
+ * role: one `{invariant, row}` per violating row, `row` its columns as JSON
319
+ * text. What `db_invariants.sql` holds, and what `_testing_db_invariants` runs
320
+ * on both spines.
321
+ */
322
+ export const DB_INVARIANTS_SQL = `WITH${SHARED_CTES_SQL}
323
+ ${DB_INVARIANTS.map((invariant) => `SELECT '${invariant.name}' AS invariant, jsonb_build_object(${invariant.columns
324
+ .map((c) => `'${c}', v.${c}`)
325
+ .join(', ')})::text AS row FROM (${invariant.sql}) v`).join('\nUNION ALL\n')}`;
326
+ /** One violating row: its invariant's name and its columns. */
327
+ export const DbInvariantRow = object({
328
+ invariant: string,
329
+ row: record(unknown)
330
+ });
331
+ /** What `_testing_db_invariants` answers — every violating row, unfiltered. */
332
+ export const DbInvariantRows = object({
333
+ rows: array(DbInvariantRow)
334
+ });
335
+ /**
336
+ * Run `DB_INVARIANTS_SQL`, parsing each row's JSON text.
337
+ *
338
+ * @param deps - the database to read
339
+ * @returns every violating row, in no promised order
340
+ */
341
+ export const query_db_invariant_rows = async (deps) => {
342
+ const rows = await deps.db.query(DB_INVARIANTS_SQL, [
343
+ ROLE_KEEPER,
344
+ ROLE_ADMIN
345
+ ]);
346
+ return rows.map((r) => ({
347
+ invariant: r.invariant,
348
+ row: JSON.parse(r.row)
349
+ }));
350
+ };
351
+ /**
352
+ * Group violating rows by invariant, dropping the excluded ones.
353
+ *
354
+ * @param rows - what `query_db_invariant_rows` or `_testing_db_invariants` returned
355
+ * @param exclude - invariants to skip, each with its reason
356
+ * @returns one entry per broken invariant, in `DB_INVARIANTS` order; empty when all hold
357
+ * @throws Error on a row naming no invariant (a reader out of step with the statement)
358
+ */
359
+ export const to_db_invariant_violations = (rows, exclude) => {
360
+ const names = new Set(DB_INVARIANTS.map((i) => i.name));
361
+ for (const r of rows) {
362
+ if (!names.has(r.invariant)) {
363
+ throw new Error(`database invariant row names unknown invariant '${r.invariant}'`);
364
+ }
365
+ }
366
+ if (exclude?.[DB_INVARIANTS_EXCLUDE_ALL] !== undefined)
367
+ return [];
368
+ const violations = [];
369
+ for (const invariant of DB_INVARIANTS) {
370
+ if (exclude?.[invariant.name] !== undefined)
371
+ continue;
372
+ const broken = rows.filter((r) => r.invariant === invariant.name).map((r) => r.row);
373
+ if (broken.length > 0) {
374
+ violations.push({ name: invariant.name, description: invariant.description, rows: broken });
375
+ }
376
+ }
377
+ return violations;
378
+ };
379
+ /**
380
+ * Query every invariant not excluded, returning those with violating rows.
381
+ *
382
+ * @param deps - the database to read
383
+ * @param exclude - invariants to skip, each with its reason
384
+ * @returns one entry per broken invariant, in `DB_INVARIANTS` order; empty when all hold
385
+ */
386
+ export const query_db_invariant_violations = async (deps, exclude) => {
387
+ if (exclude?.[DB_INVARIANTS_EXCLUDE_ALL] !== undefined)
388
+ return [];
389
+ return to_db_invariant_violations(await query_db_invariant_rows(deps), exclude);
390
+ };
391
+ /**
392
+ * Render violations as one message, an invariant per paragraph with its rows.
393
+ *
394
+ * @param violations - what `query_db_invariant_violations` returned
395
+ * @param label - names the database (the backend, or the in-process leg)
396
+ */
397
+ export const format_db_invariant_violations = (violations, label) => `database invariants broken (${label}):\n` +
398
+ violations
399
+ .map((v) => `- ${v.name}: ${v.description}\n` + v.rows.map((r) => ` ${JSON.stringify(r)}`).join('\n'))
400
+ .join('\n');