@cosmicdrift/kumiko-framework 0.413.1 → 0.415.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 (479) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +69 -13
  4. package/agents/api/framework-errors.md +1 -1
  5. package/agents/api/framework-event-store.md +14 -0
  6. package/agents/api/framework-ui-types.md +158 -21
  7. package/agents/api/renderer-web.md +112 -11
  8. package/agents/api/testing-helpers.md +3 -2
  9. package/agents/api/testing-stack.md +3 -0
  10. package/agents/api/types.md +248 -24
  11. package/agents/api.md +7 -7
  12. package/agents/boot-rules.md +66 -10
  13. package/agents/examples/api-docs.md +2 -6
  14. package/agents/examples/auth-mfa.md +57 -10
  15. package/agents/examples/chat-channels.md +2 -0
  16. package/agents/examples/crypto-shredding-hr.md +63 -1
  17. package/agents/examples/currencies-global.md +1 -0
  18. package/agents/examples/env-composition.md +7 -11
  19. package/agents/examples/managed-pages.md +90 -1
  20. package/agents/examples/pwa-shell.md +210 -0
  21. package/agents/examples/rate-limiting.md +3 -3
  22. package/agents/examples/record-detail-layout.md +1643 -67
  23. package/agents/examples/workflow-engine.md +16 -12
  24. package/agents/examples.md +1 -0
  25. package/agents/features-index.md +4 -2
  26. package/agents/features.md +22 -7
  27. package/agents/widgets.md +26 -1
  28. package/dist/api/api-constants.d.ts +1 -0
  29. package/dist/api/api-constants.js +4 -0
  30. package/dist/api/auth-middleware.js +4 -3
  31. package/dist/api/auth-routes-shared.js +2 -1
  32. package/dist/api/entity-read-access.d.ts +1 -0
  33. package/dist/api/entity-read-access.js +18 -0
  34. package/dist/api/export/export-route.d.ts +6 -1
  35. package/dist/api/export/export-route.js +27 -1
  36. package/dist/api/export/export-rows.js +19 -3
  37. package/dist/api/request-context-internals.d.ts +2 -0
  38. package/dist/api/request-context-scopes.js +9 -2
  39. package/dist/api/request-context.js +1 -1
  40. package/dist/api/routes.d.ts +2 -0
  41. package/dist/api/routes.js +9 -1
  42. package/dist/api/server-event-dispatcher.js +3 -0
  43. package/dist/api/server-extra-routes.js +2 -1
  44. package/dist/api/server-feature-http-routes.d.ts +9 -0
  45. package/dist/api/server-feature-http-routes.js +109 -0
  46. package/dist/api/server-middleware.js +2 -19
  47. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  48. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  49. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  50. package/dist/api/server-rate-limit-wiring.js +37 -0
  51. package/dist/api/server-routes.d.ts +4 -12
  52. package/dist/api/server-routes.js +12 -171
  53. package/dist/api/server-schema-route.d.ts +3 -0
  54. package/dist/api/server-schema-route.js +58 -0
  55. package/dist/api/server-wiring.js +2 -37
  56. package/dist/api/server.js +3 -1
  57. package/dist/compliance/override-schema.js +5 -5
  58. package/dist/compliance/sub-processors.js +10 -1
  59. package/dist/crypto/index.d.ts +1 -1
  60. package/dist/crypto/index.js +1 -1
  61. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  62. package/dist/crypto/pii-field-encryption.js +16 -1
  63. package/dist/db/apply-entity-event.js +4 -0
  64. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  65. package/dist/db/bun-sql-connection-codes.js +7 -0
  66. package/dist/db/collect-table-metas.js +4 -1
  67. package/dist/db/config-seed.js +1 -1
  68. package/dist/db/derived-field-sql.js +15 -13
  69. package/dist/db/derived-related-sql.d.ts +2 -2
  70. package/dist/db/derived-related-sql.js +4 -2
  71. package/dist/db/dialect.d.ts +3 -0
  72. package/dist/db/dialect.js +1 -3
  73. package/dist/db/driver-row-coercion.js +2 -2
  74. package/dist/db/driver-value-preparation.js +1 -1
  75. package/dist/db/eagerload.js +15 -12
  76. package/dist/db/entity-table-meta.d.ts +2 -0
  77. package/dist/db/entity-table-meta.js +7 -0
  78. package/dist/db/event-store-executor-context.js +13 -8
  79. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  80. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  81. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  82. package/dist/db/event-store-executor-read-filter.js +28 -11
  83. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  84. package/dist/db/event-store-executor-read-search.js +6 -6
  85. package/dist/db/event-store-executor-read-sort.js +3 -3
  86. package/dist/db/event-store-executor-read-where.js +14 -5
  87. package/dist/db/event-store-executor-read.js +7 -7
  88. package/dist/db/event-store-executor-write.js +50 -95
  89. package/dist/db/executor-managed-tables.js +4 -1
  90. package/dist/db/index.d.ts +4 -2
  91. package/dist/db/index.js +4 -2
  92. package/dist/db/known-table-names.d.ts +1 -0
  93. package/dist/db/known-table-names.js +7 -5
  94. package/dist/db/list-aggregate-labels.d.ts +1 -0
  95. package/dist/db/list-aggregate-labels.js +9 -1
  96. package/dist/db/migrate-generator.js +23 -4
  97. package/dist/db/migrate-rls-diff.d.ts +1 -0
  98. package/dist/db/migrate-rls-diff.js +15 -1
  99. package/dist/db/migrate-runner.js +2 -2
  100. package/dist/db/money.d.ts +1 -1
  101. package/dist/db/money.js +1 -4
  102. package/dist/db/parent-ref-clause.d.ts +6 -2
  103. package/dist/db/parent-ref-clause.js +105 -24
  104. package/dist/db/parent-ref-global-hosts.d.ts +23 -0
  105. package/dist/db/parent-ref-global-hosts.js +85 -0
  106. package/dist/db/production-schema-command-hint.d.ts +1 -0
  107. package/dist/db/production-schema-command-hint.js +3 -0
  108. package/dist/db/queries/backfill-pii.js +55 -29
  109. package/dist/db/queries/ddl.js +13 -2
  110. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  111. package/dist/db/queries/event-store-open-streams.js +33 -0
  112. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  113. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  114. package/dist/db/queries/event-store.js +0 -1
  115. package/dist/db/queries/raw-sql.js +0 -1
  116. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  117. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  118. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  119. package/dist/db/queries/rls-boot-catalog.js +13 -9
  120. package/dist/db/queries/rls-shape.d.ts +3 -1
  121. package/dist/db/queries/rls-shape.js +31 -6
  122. package/dist/db/queries/session-advisory-lock.js +2 -1
  123. package/dist/db/queries/test-stack.js +7 -7
  124. package/dist/db/query.js +16 -11
  125. package/dist/db/rebuild-marker.js +11 -2
  126. package/dist/db/render-rls-ddl.d.ts +2 -0
  127. package/dist/db/render-rls-ddl.js +16 -11
  128. package/dist/db/replay-migration-sql.js +1 -1
  129. package/dist/db/row-level-security-boot-check.js +18 -5
  130. package/dist/db/row-level-security-connection.js +25 -12
  131. package/dist/db/row-level-security-scope.d.ts +2 -1
  132. package/dist/db/row-level-security-scope.js +9 -5
  133. package/dist/db/sql-identifier.d.ts +1 -0
  134. package/dist/db/sql-identifier.js +3 -0
  135. package/dist/db/system-tenant-read-db.d.ts +5 -0
  136. package/dist/db/system-tenant-read-db.js +28 -0
  137. package/dist/db/table-builder.d.ts +3 -1
  138. package/dist/db/table-builder.js +18 -8
  139. package/dist/db/table-info.d.ts +1 -2
  140. package/dist/db/table-introspection.d.ts +3 -0
  141. package/dist/db/table-introspection.js +6 -0
  142. package/dist/db/table-push.d.ts +1 -0
  143. package/dist/db/table-push.js +7 -1
  144. package/dist/db/tenant-db-runner.d.ts +3 -0
  145. package/dist/db/tenant-db-runner.js +19 -1
  146. package/dist/db/transaction-serialization.d.ts +1 -0
  147. package/dist/db/transaction-serialization.js +20 -3
  148. package/dist/db/where-clause.js +11 -2
  149. package/dist/db/write-ownership-failures.d.ts +25 -0
  150. package/dist/db/write-ownership-failures.js +82 -0
  151. package/dist/engine/boot-validator/boot-check.js +7 -1
  152. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  153. package/dist/engine/boot-validator/boot-phases.js +3 -2
  154. package/dist/engine/boot-validator/boot-rules.d.ts +305 -28
  155. package/dist/engine/boot-validator/boot-rules.js +4 -0
  156. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  157. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  158. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  159. package/dist/engine/boot-validator/card-meta-overflow.js +8 -5
  160. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  161. package/dist/engine/boot-validator/config-deps.js +0 -28
  162. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  163. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  164. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  165. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  166. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  167. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  168. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  169. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  170. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  171. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  172. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  173. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  174. package/dist/engine/boot-validator/entity-list-screens.js +35 -13
  175. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  176. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  177. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  178. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  179. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  180. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  181. package/dist/engine/boot-validator/list-row-guidance.js +143 -0
  182. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  183. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  184. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  185. package/dist/engine/boot-validator/list-sort-summary.js +160 -0
  186. package/dist/engine/boot-validator/list-table-options.js +15 -1
  187. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  188. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  189. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  190. package/dist/engine/boot-validator/list-toolbar-options.js +30 -0
  191. package/dist/engine/boot-validator/named-filter-rules.d.ts +42 -2
  192. package/dist/engine/boot-validator/named-filter-rules.js +42 -2
  193. package/dist/engine/boot-validator/ownership.js +10 -1
  194. package/dist/engine/boot-validator/parent-ref.js +87 -50
  195. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  196. package/dist/engine/boot-validator/projection-list-screens.js +32 -1
  197. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  198. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  199. package/dist/engine/boot-validator/query-output-guidance.js +40 -0
  200. package/dist/engine/boot-validator/query-refs.js +34 -1
  201. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  202. package/dist/engine/boot-validator/row-decoration.js +16 -0
  203. package/dist/engine/boot-validator/screens-actions.js +1 -1
  204. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  205. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  206. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  207. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  208. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  209. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  210. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  211. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  212. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  213. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  214. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  215. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  216. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  217. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  218. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  219. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  220. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  221. package/dist/engine/boot-validator/screens-lists.js +19 -3
  222. package/dist/engine/boot-validator/screens.js +1 -1
  223. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  224. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  225. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  226. package/dist/engine/boot-validator/zod-shape.js +19 -1
  227. package/dist/engine/build-app-schema.js +4 -0
  228. package/dist/engine/config-helpers.d.ts +1 -2
  229. package/dist/engine/config-helpers.js +6 -7
  230. package/dist/engine/define-feature.js +1 -0
  231. package/dist/engine/define-handler.d.ts +1 -0
  232. package/dist/engine/define-handler.js +4 -2
  233. package/dist/engine/definition-violations.js +2 -2
  234. package/dist/engine/entity-handlers.js +3 -8
  235. package/dist/engine/entity-list-runtime-options.js +9 -8
  236. package/dist/engine/factories.d.ts +2 -0
  237. package/dist/engine/feature-config-events-jobs.js +1 -0
  238. package/dist/engine/feature-entity-handlers.js +5 -2
  239. package/dist/engine/field-access.d.ts +1 -1
  240. package/dist/engine/field-access.js +7 -10
  241. package/dist/engine/find-entity.js +3 -3
  242. package/dist/engine/form-derivations.js +3 -3
  243. package/dist/engine/index.d.ts +3 -3
  244. package/dist/engine/index.js +2 -2
  245. package/dist/engine/named-filter-roles.d.ts +3 -0
  246. package/dist/engine/named-filter-roles.js +15 -0
  247. package/dist/engine/pipeline.js +0 -1
  248. package/dist/engine/project-app-schema-for-roles.js +17 -2
  249. package/dist/engine/qualified-name.js +0 -1
  250. package/dist/engine/registry-facade.js +1 -2
  251. package/dist/engine/registry-state.d.ts +1 -1
  252. package/dist/engine/registry-state.js +5 -2
  253. package/dist/engine/registry-validate.js +2 -1
  254. package/dist/engine/resolve-named-list-filters.js +5 -2
  255. package/dist/engine/schema-builder.js +9 -11
  256. package/dist/engine/screen-helpers.d.ts +12 -0
  257. package/dist/engine/screen-helpers.js +17 -1
  258. package/dist/engine/soft-delete-cleanup.js +3 -5
  259. package/dist/engine/state-machine.js +0 -1
  260. package/dist/engine/steps/_database-clock.d.ts +2 -0
  261. package/dist/engine/steps/_database-clock.js +6 -0
  262. package/dist/engine/steps/compute.js +1 -1
  263. package/dist/engine/steps/retry.js +5 -1
  264. package/dist/engine/steps/return.js +0 -1
  265. package/dist/engine/steps/wait-for-event.js +2 -1
  266. package/dist/engine/steps/wait.js +2 -1
  267. package/dist/engine/system-user.d.ts +2 -2
  268. package/dist/engine/system-user.js +2 -2
  269. package/dist/engine/types/handlers.d.ts +1 -1
  270. package/dist/engine/types/handlers.js +1 -1
  271. package/dist/engine/types/screen.d.ts +1 -1
  272. package/dist/engine/types/screen.js +1 -1
  273. package/dist/engine/webhook-contracts.d.ts +2 -3
  274. package/dist/engine/webhook-contracts.js +2 -25
  275. package/dist/engine/webhook-events.js +48 -29
  276. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  277. package/dist/engine/webhook-payload-strictness.js +53 -0
  278. package/dist/env/_zod-introspect.d.ts +1 -0
  279. package/dist/env/dry-run.d.ts +1 -1
  280. package/dist/env/dry-run.js +1 -1
  281. package/dist/env/field-meta.d.ts +4 -0
  282. package/dist/env/field-meta.js +67 -0
  283. package/dist/env/field-rules.d.ts +9 -0
  284. package/dist/env/field-rules.js +46 -0
  285. package/dist/env/index.d.ts +3 -3
  286. package/dist/env/index.js +16 -71
  287. package/dist/env/internals.d.ts +3 -0
  288. package/dist/env/internals.js +1 -2
  289. package/dist/env/required-env.d.ts +3 -1
  290. package/dist/env/required-env.js +5 -2
  291. package/dist/errors/reasons.d.ts +1 -0
  292. package/dist/errors/reasons.js +4 -0
  293. package/dist/errors/serialize.js +2 -2
  294. package/dist/errors/write-error-info.js +0 -2
  295. package/dist/es-ops/operations-schema.js +18 -7
  296. package/dist/event-store/admin-api.js +3 -3
  297. package/dist/event-store/event-store.js +0 -3
  298. package/dist/event-store/index.d.ts +1 -0
  299. package/dist/event-store/index.js +1 -0
  300. package/dist/event-store/transfer.js +1 -1
  301. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  302. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  303. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  304. package/dist/files/bind-pending-file-refs.js +54 -27
  305. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  306. package/dist/files/create-file-ref.d.ts +4 -1
  307. package/dist/files/create-file-ref.js +14 -3
  308. package/dist/files/default-file-guard.js +4 -1
  309. package/dist/files/file-claim.d.ts +6 -0
  310. package/dist/files/file-claim.js +17 -0
  311. package/dist/files/file-field-slots.d.ts +2 -0
  312. package/dist/files/file-field-slots.js +28 -0
  313. package/dist/files/file-ref-entity.d.ts +3 -0
  314. package/dist/files/file-ref-entity.js +2 -0
  315. package/dist/files/file-ref-table.d.ts +3 -0
  316. package/dist/files/file-routes.d.ts +4 -1
  317. package/dist/files/file-routes.js +80 -16
  318. package/dist/files/in-memory-provider.d.ts +1 -1
  319. package/dist/files/in-memory-provider.js +2 -1
  320. package/dist/files/index.d.ts +1 -1
  321. package/dist/files/index.js +1 -1
  322. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  323. package/dist/files/invalid-file-ref-error.js +15 -0
  324. package/dist/files/local-provider.js +9 -2
  325. package/dist/files/provider-resolver.js +1 -1
  326. package/dist/files/rebind-file-ref.d.ts +3 -2
  327. package/dist/files/rebind-file-ref.js +24 -18
  328. package/dist/files/resolve-file-handles.d.ts +13 -0
  329. package/dist/files/resolve-file-handles.js +57 -0
  330. package/dist/files/storage-tracking.d.ts +1 -1
  331. package/dist/files/storage-tracking.js +5 -2
  332. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  333. package/dist/files/types.d.ts +4 -0
  334. package/dist/files/types.js +10 -0
  335. package/dist/files/upload-field-resolution.d.ts +1 -0
  336. package/dist/files/upload-field-resolution.js +16 -2
  337. package/dist/files/upload-ledger.js +1 -1
  338. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  339. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  340. package/dist/i18n/required-surface-keys.js +21 -5
  341. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  342. package/dist/internal/boot-rule-table-expectations.js +29 -0
  343. package/dist/internal/row-level-security.d.ts +1 -0
  344. package/dist/internal/row-level-security.js +1 -0
  345. package/dist/internal/testing.d.ts +1 -0
  346. package/dist/internal/testing.js +1 -0
  347. package/dist/jobs/index.d.ts +1 -0
  348. package/dist/jobs/index.js +1 -0
  349. package/dist/jobs/job-load-events.d.ts +10 -0
  350. package/dist/jobs/job-load-events.js +12 -0
  351. package/dist/jobs/job-runner-context.js +6 -158
  352. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  353. package/dist/jobs/job-runner-dispatch.js +57 -0
  354. package/dist/jobs/job-runner-event-triggers.js +18 -9
  355. package/dist/jobs/job-runner-execution.js +5 -2
  356. package/dist/jobs/job-runner-facets.d.ts +48 -0
  357. package/dist/jobs/job-runner-facets.js +156 -0
  358. package/dist/jobs/job-runner-gates.js +19 -11
  359. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  360. package/dist/jobs/job-runner-helpers.js +18 -3
  361. package/dist/jobs/job-runner-scope.d.ts +1 -0
  362. package/dist/jobs/job-runner-scope.js +2 -0
  363. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  364. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  365. package/dist/jobs/job-runner-types.d.ts +1 -0
  366. package/dist/jobs/job-runner.js +39 -70
  367. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  368. package/dist/jobs/obliterate-job-queues.js +23 -0
  369. package/dist/lifecycle/lifecycle.js +1 -1
  370. package/dist/migrations/event-header-scrub.d.ts +11 -0
  371. package/dist/migrations/event-header-scrub.js +33 -0
  372. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  373. package/dist/migrations/event-payload-scrub.js +36 -4
  374. package/dist/migrations/index.d.ts +1 -0
  375. package/dist/migrations/index.js +2 -0
  376. package/dist/migrations/kumiko-drift.d.ts +5 -2
  377. package/dist/migrations/kumiko-drift.js +51 -14
  378. package/dist/migrations/pending-rebuilds.js +4 -5
  379. package/dist/observability/sensitive-filter.js +0 -12
  380. package/dist/pipeline/aggregate-type-removal.js +17 -4
  381. package/dist/pipeline/context-services.d.ts +2 -0
  382. package/dist/pipeline/context-services.js +5 -2
  383. package/dist/pipeline/dispatch-batch.js +4 -3
  384. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  385. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  386. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  387. package/dist/pipeline/dispatch-nested-write.js +119 -0
  388. package/dist/pipeline/dispatch-query.js +10 -3
  389. package/dist/pipeline/dispatch-scope.js +4 -3
  390. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  391. package/dist/pipeline/dispatch-shared.js +6 -38
  392. package/dist/pipeline/dispatch-write.d.ts +0 -1
  393. package/dist/pipeline/dispatch-write.js +3 -302
  394. package/dist/pipeline/dispatcher-utils.js +6 -0
  395. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  396. package/dist/pipeline/effective-system-scope.js +22 -0
  397. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  398. package/dist/pipeline/event-dispatcher-delivery.js +20 -9
  399. package/dist/pipeline/event-dispatcher.d.ts +6 -1
  400. package/dist/pipeline/event-dispatcher.js +6 -7
  401. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  402. package/dist/pipeline/handler-context-auth.js +3 -4
  403. package/dist/pipeline/handler-context-db.js +11 -4
  404. package/dist/pipeline/handler-context-dispatch.js +2 -2
  405. package/dist/pipeline/handler-context-events.d.ts +8 -3
  406. package/dist/pipeline/handler-context-events.js +20 -65
  407. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  408. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  409. package/dist/pipeline/handler-context-notify.js +2 -0
  410. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  411. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  412. package/dist/pipeline/handler-context-projection.js +39 -0
  413. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  414. package/dist/pipeline/handler-context-scope.js +14 -2
  415. package/dist/pipeline/index.d.ts +1 -1
  416. package/dist/pipeline/index.js +1 -1
  417. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  418. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  419. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  420. package/dist/pipeline/member-reader.js +4 -2
  421. package/dist/pipeline/msp-rebuild.js +1 -1
  422. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  423. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  424. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  425. package/dist/pipeline/projection-rebuild.js +16 -7
  426. package/dist/pipeline/projection-state.js +4 -6
  427. package/dist/pipeline/system-hooks.js +36 -6
  428. package/dist/pipeline/write-result-masking.js +31 -3
  429. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  430. package/dist/pipeline/write-transition-guard.js +95 -0
  431. package/dist/schema-cli/shared.d.ts +2 -0
  432. package/dist/schema-cli/shared.js +4 -2
  433. package/dist/schema-cli/validate-command.js +43 -28
  434. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  435. package/dist/search/meilisearch-adapter-internals.js +5 -0
  436. package/dist/search/meilisearch-adapter.d.ts +1 -0
  437. package/dist/search/meilisearch-adapter.js +17 -11
  438. package/dist/search/reindex-entity.d.ts +2 -0
  439. package/dist/search/reindex-entity.js +32 -4
  440. package/dist/search/reindex-tenants-search.js +20 -4
  441. package/dist/time/tz-context.js +1 -1
  442. package/dist/ui-types/card-column-roles.d.ts +6 -0
  443. package/dist/ui-types/card-column-roles.js +21 -3
  444. package/dist/ui-types/index.d.ts +3 -3
  445. package/dist/ui-types/index.js +2 -2
  446. package/dist/utils/ids.js +0 -1
  447. package/dist/utils/index.d.ts +1 -0
  448. package/dist/utils/index.js +1 -0
  449. package/dist/utils/return-path-limit.d.ts +1 -0
  450. package/dist/utils/return-path-limit.js +1 -0
  451. package/package.json +5 -3
  452. package/presets/biome-app.json +39 -21
  453. package/presets/biome-plugins/admin-api.grit +10 -0
  454. package/presets/biome-plugins/error-reasons.grit +53 -0
  455. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  456. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  457. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  458. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  459. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  460. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  461. package/presets/biome-plugins/no-date-api.grit +11 -0
  462. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  463. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  464. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  465. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  466. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  467. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  468. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  469. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  470. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  471. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  472. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  473. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  474. package/presets/biome-plugins/test-title.grit +20 -0
  475. package/presets/biome-plugins/unsafe-json-parse.grit +12 -0
  476. package/presets/biome-rules.json +467 -0
  477. package/src/changes.json +366 -0
  478. package/dist/engine/minor-units.d.ts +0 -2
  479. package/dist/engine/minor-units.js +0 -8
@@ -0,0 +1,33 @@
1
+ import { asRawClient } from "../query.js";
2
+ import { toPostgresArrayLiteral } from "./postgres-array-literal.js";
3
+ // Cross-tenant on a raw runner: system sweepers find streams that never got their closing event.
4
+ // Archived streams are skipped, since nothing can be appended to them anymore.
5
+ export async function selectOpenStreamsStartedBefore(db, args) {
6
+ const rows = await asRawClient(db).unsafe(`SELECT s."id"::text AS "id", s."tenant_id", s."aggregate_id"
7
+ FROM "kumiko_events" s
8
+ WHERE s."aggregate_type" = $1 AND s."type" = $2 AND s."created_at" < $3::timestamptz
9
+ AND ($6::bigint IS NULL OR s."id" > $6::bigint)
10
+ AND NOT EXISTS (
11
+ SELECT 1 FROM "kumiko_events" c
12
+ WHERE c."tenant_id" = s."tenant_id" AND c."aggregate_id" = s."aggregate_id"
13
+ AND c."type" = ANY($4::text[])
14
+ )
15
+ AND NOT EXISTS (
16
+ SELECT 1 FROM "kumiko_archived_streams" a
17
+ WHERE a."tenant_id" = s."tenant_id" AND a."aggregate_id" = s."aggregate_id"
18
+ )
19
+ ORDER BY s."id" ASC
20
+ LIMIT $5`, [
21
+ args.aggregateType,
22
+ args.startedType,
23
+ args.startedBeforeIso,
24
+ toPostgresArrayLiteral([...args.closingTypes]),
25
+ args.limit,
26
+ args.afterId ?? null,
27
+ ]);
28
+ return rows.map((row) => ({
29
+ id: row.id,
30
+ tenantId: row.tenant_id,
31
+ aggregateId: row.aggregate_id,
32
+ }));
33
+ }
@@ -10,3 +10,8 @@ export type ScrubEventRow = {
10
10
  export declare function selectEventsOfTypeAfter(db: DbRunner, eventType: string, afterEventId: string, limit: number): Promise<readonly ScrubEventRow[]>;
11
11
  export declare function replaceEventPayload(db: DbRunner, eventId: bigint | string, payload: Record<string, unknown>): Promise<void>;
12
12
  export declare function deleteSnapshotsOfAggregates(db: DbRunner, aggregateIds: readonly string[]): Promise<number>;
13
+ export declare function removeEventHeaderKey(db: DbRunner, args: {
14
+ readonly eventTypes: readonly string[];
15
+ readonly key: string;
16
+ readonly dryRun: boolean;
17
+ }): Promise<number>;
@@ -18,3 +18,14 @@ export async function deleteSnapshotsOfAggregates(db, aggregateIds) {
18
18
  const deleted = await asRawClient(db).unsafe(`DELETE FROM "kumiko_snapshots" WHERE "aggregate_id" = ANY($1::uuid[]) RETURNING "aggregate_id"`, [toPostgresArrayLiteral([...aggregateIds])]);
19
19
  return deleted.length;
20
20
  }
21
+ // Returns the number of events whose header carried the key; with dryRun nothing is written.
22
+ export async function removeEventHeaderKey(db, args) {
23
+ const types = toPostgresArrayLiteral([...args.eventTypes]);
24
+ const rows = args.dryRun
25
+ ? await asRawClient(db).unsafe(`SELECT "id" FROM "kumiko_events"
26
+ WHERE "type" = ANY($1::text[]) AND "metadata"->'headers' ? $2`, [types, args.key])
27
+ : await asRawClient(db).unsafe(`UPDATE "kumiko_events" SET "metadata" = "metadata" #- ARRAY['headers', $2]::text[]
28
+ WHERE "type" = ANY($1::text[]) AND "metadata"->'headers' ? $2
29
+ RETURNING "id"`, [types, args.key]);
30
+ return rows.length;
31
+ }
@@ -232,7 +232,6 @@ export async function selectEventsHighWaterMark(db) {
232
232
  return BigInt(raw);
233
233
  }
234
234
  /** Head event id for lag metrics — alias for selectEventsHighWaterMark. */
235
- // @wrapper-known semantic-alias
236
235
  export async function selectEventsHeadId(db) {
237
236
  return selectEventsHighWaterMark(db);
238
237
  }
@@ -7,7 +7,6 @@ export async function executeRawQuery(db, sqlText, params = []) {
7
7
  }
8
8
  /** SELECT-only escape hatch with the closed-connection retry. Do not pass
9
9
  * INSERT/UPDATE/DELETE — retry re-executes the statement. */
10
- // @wrapper-known semantic-alias
11
10
  export async function executeRawQueryRead(db, sqlText, params = []) {
12
11
  return unsafeReadRetrying(db, sqlText, params);
13
12
  }
@@ -1,2 +1,3 @@
1
+ import type { EntityTableMeta } from "../entity-table-meta.ts";
1
2
  import { type AnyDb } from "../query.ts";
2
- export declare function assertRebuildableRowLevelSecurity(tx: AnyDb, tableName: string): Promise<void>;
3
+ export declare function assertRebuildableRowLevelSecurity(tx: AnyDb, meta: EntityTableMeta): Promise<void>;
@@ -2,28 +2,41 @@
2
2
  // policy admits for every row; a table whose policies differ from the framework's shape could hide
3
3
  // rows from the guards and let the swap drop them, so it is refused before anything is read.
4
4
  import { asRawClient } from "../query.js";
5
- import { TENANT_ISOLATION_POLICY } from "../render-rls-ddl.js";
6
- import { readRowLevelSecurityShape } from "./rls-shape.js";
5
+ import { renderCreatePolicy, TENANT_ISOLATION_POLICY, tenantRowLevelSecurityFor, } from "../render-rls-ddl.js";
6
+ import { isFrameworkIsolationIntact, readRowLevelSecurityShape } from "./rls-shape.js";
7
7
  import { quoteTableIdent } from "./table-ops.js";
8
- export async function assertRebuildableRowLevelSecurity(tx, tableName) {
8
+ // Postgres deparses a policy expression only against a relation, so the framework expression is
9
+ // created on a throwaway copy of the live table's columns and deparsed the same way as the live one.
10
+ async function isolationExpressionsMatchFramework(tx, meta) {
11
+ const expected = tenantRowLevelSecurityFor(meta)?.policies.find((policy) => policy.name === TENANT_ISOLATION_POLICY);
12
+ if (expected === undefined)
13
+ return true;
14
+ const raw = asRawClient(tx);
15
+ const referenceTable = "kumiko_rls_reference";
16
+ await raw.unsafe(`CREATE TEMP TABLE ${referenceTable} ON COMMIT DROP AS SELECT * FROM public.${quoteTableIdent(meta.tableName)} WITH NO DATA`);
17
+ await raw.unsafe(renderCreatePolicy(`pg_temp.${referenceTable}`, expected));
18
+ const read = async (relation) => (await raw.unsafe(`SELECT pg_get_expr(polqual, polrelid) AS "using", pg_get_expr(polwithcheck, polrelid) AS "withCheck" FROM pg_policy WHERE polrelid = $1::regclass AND polname = $2`, [relation, TENANT_ISOLATION_POLICY]))[0];
19
+ const live = await read(`public.${quoteTableIdent(meta.tableName)}`);
20
+ const referenceExpressions = await read(`pg_temp.${referenceTable}`);
21
+ return (live !== undefined &&
22
+ live.using === referenceExpressions?.using &&
23
+ live.withCheck === referenceExpressions?.withCheck);
24
+ }
25
+ export async function assertRebuildableRowLevelSecurity(tx, meta) {
26
+ const tableName = meta.tableName;
9
27
  // SHARE UPDATE EXCLUSIVE conflicts with CREATE/ALTER/DROP POLICY and ENABLE/FORCE (ACCESS EXCLUSIVE) but not with readers, and with itself: a second rebuild waits instead of both holding a shared lock and deadlocking on the swap's ACCESS EXCLUSIVE.
10
28
  await asRawClient(tx).unsafe(`LOCK TABLE public.${quoteTableIdent(tableName)} IN SHARE UPDATE EXCLUSIVE MODE`);
11
29
  const state = await readRowLevelSecurityShape(tx, tableName);
12
30
  // skip: table has no row-level security, nothing to verify
13
31
  if (state === undefined || !state.enabled)
14
32
  return;
15
- const isolation = state.policies.find((policy) => policy.name === TENANT_ISOLATION_POLICY);
16
- const hasRestrictive = state.policies.some((policy) => policy.kind === "RESTRICTIVE");
17
- const isolationIntact = isolation !== undefined &&
18
- isolation.kind === "PERMISSIVE" &&
19
- isolation.command === "ALL" &&
20
- isolation.appliesToPublic;
21
33
  // skip: framework policy intact, rebuild reads are safe
22
- if (isolationIntact && !hasRestrictive)
34
+ if (isFrameworkIsolationIntact(state) && (await isolationExpressionsMatchFramework(tx, meta))) {
23
35
  return;
36
+ }
24
37
  const listed = state.policies
25
38
  .map((policy) => `${policy.name} (${policy.kind} ${policy.command})`)
26
39
  .join(", ");
27
40
  throw new Error(`rebuild: public.${tableName} has row level security that a system scope rebuild cannot rely on ` +
28
- `(needs a PERMISSIVE ALL ${TENANT_ISOLATION_POLICY} policy for PUBLIC and no RESTRICTIVE policy); policies: ${listed || "(none)"}`);
41
+ `(needs the framework's PERMISSIVE ALL ${TENANT_ISOLATION_POLICY} policy for PUBLIC and no RESTRICTIVE policy); policies: ${listed || "(none)"}`);
29
42
  }
@@ -9,6 +9,7 @@ export type TenantTableRowLevelSecurity = {
9
9
  readonly enabled: boolean;
10
10
  readonly forced: boolean;
11
11
  readonly hasIsolationPolicy: boolean;
12
+ readonly isolationAltered: boolean;
12
13
  readonly hasSystemReadPolicy: boolean;
13
14
  };
14
15
  export declare function readConnectedRoleAttributes(db: AnyDb): Promise<ConnectedRoleAttributes | undefined>;
@@ -1,5 +1,6 @@
1
1
  import { asRawClient } from "../query.js";
2
2
  import { SYSTEM_TENANT_READ_POLICY, TENANT_ISOLATION_POLICY } from "../render-rls-ddl.js";
3
+ import { isFrameworkIsolationIntact, readRowLevelSecurityShapes } from "./rls-shape.js";
3
4
  export async function readConnectedRoleAttributes(db) {
4
5
  const rows = await asRawClient(db).unsafe(`SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`);
5
6
  const row = rows[0];
@@ -23,15 +24,18 @@ export async function readTenantTablesRowLevelSecurity(db) {
23
24
  AND EXISTS (SELECT 1 FROM pg_attribute a
24
25
  WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND a.attnum > 0 AND NOT a.attisdropped)
25
26
  ORDER BY c.relname COLLATE "C"`, [TENANT_ISOLATION_POLICY, SYSTEM_TENANT_READ_POLICY]);
26
- return rows.map(
27
- // guard:dup-ok catalog row to snapshot field mapping; only the object-literal shape matches other mappers
28
- (row) => ({
29
- tableName: row.relname,
30
- enabled: row.relrowsecurity,
31
- forced: row.relforcerowsecurity,
32
- hasIsolationPolicy: row.has_isolation,
33
- hasSystemReadPolicy: row.has_system_read,
34
- }));
27
+ const shapes = await readRowLevelSecurityShapes(db, rows.filter((row) => row.has_isolation).map((row) => row.relname));
28
+ return rows.map((row) => {
29
+ const shape = shapes.get(row.relname);
30
+ return {
31
+ tableName: row.relname,
32
+ enabled: row.relrowsecurity,
33
+ forced: row.relforcerowsecurity,
34
+ hasIsolationPolicy: row.has_isolation,
35
+ isolationAltered: shape !== undefined && !isFrameworkIsolationIntact(shape),
36
+ hasSystemReadPolicy: row.has_system_read,
37
+ };
38
+ });
35
39
  }
36
40
  export async function readTablesWithRowLevelSecurityEnabled(db) {
37
41
  const rows = await asRawClient(db).unsafe(`SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -1,5 +1,5 @@
1
1
  import { type AnyDb } from "../query.ts";
2
- import type { RowLevelSecurityPolicy } from "../render-rls-ddl.ts";
2
+ import { type RowLevelSecurityPolicy } from "../render-rls-ddl.ts";
3
3
  export type RowLevelSecurityShape = {
4
4
  readonly enabled: boolean;
5
5
  readonly forced: boolean;
@@ -7,4 +7,6 @@ export type RowLevelSecurityShape = {
7
7
  readonly appliesToPublic: boolean;
8
8
  })[];
9
9
  };
10
+ export declare function readRowLevelSecurityShapes(db: AnyDb, tableNames: readonly string[]): Promise<ReadonlyMap<string, RowLevelSecurityShape>>;
10
11
  export declare function readRowLevelSecurityShape(db: AnyDb, tableName: string): Promise<RowLevelSecurityShape | undefined>;
12
+ export declare function isFrameworkIsolationIntact(shape: RowLevelSecurityShape): boolean;
@@ -2,6 +2,7 @@
2
2
  // policy expressions. pg_get_expr (behind the pg_policies view) opens the table with ACCESS SHARE,
3
3
  // which queues behind a pending ACCESS EXCLUSIVE; this read never touches the table itself.
4
4
  import { asRawClient } from "../query.js";
5
+ import { TENANT_ISOLATION_POLICY } from "../render-rls-ddl.js";
5
6
  const COMMAND_BY_CODE = {
6
7
  "*": "ALL",
7
8
  r: "SELECT",
@@ -16,12 +17,7 @@ function commandOf(code) {
16
17
  throw new Error(`unknown pg_policy.polcmd code "${code}"`);
17
18
  return command;
18
19
  }
19
- export async function readRowLevelSecurityShape(db, tableName) {
20
- const rows = await asRawClient(db).unsafe(`SELECT c.relrowsecurity, c.relforcerowsecurity, p.polname, p.polpermissive, p.polcmd::text AS polcmd, (p.polroles = '{0}'::oid[]) AS polpublic
21
- FROM pg_class c
22
- JOIN pg_namespace n ON n.oid = c.relnamespace
23
- LEFT JOIN pg_policy p ON p.polrelid = c.oid
24
- WHERE n.nspname = 'public' AND c.relname = $1`, [tableName]);
20
+ function shapeOfRows(rows) {
25
21
  const first = rows[0];
26
22
  if (first === undefined)
27
23
  return undefined;
@@ -40,3 +36,32 @@ export async function readRowLevelSecurityShape(db, tableName) {
40
36
  });
41
37
  return { enabled: first.relrowsecurity, forced: first.relforcerowsecurity, policies };
42
38
  }
39
+ export async function readRowLevelSecurityShapes(db, tableNames) {
40
+ const shapes = new Map();
41
+ if (tableNames.length === 0)
42
+ return shapes;
43
+ const rows = await asRawClient(db).unsafe(`SELECT c.relname, c.relrowsecurity, c.relforcerowsecurity, p.polname, p.polpermissive, p.polcmd::text AS polcmd, (p.polroles = '{0}'::oid[]) AS polpublic
44
+ FROM pg_class c
45
+ JOIN pg_namespace n ON n.oid = c.relnamespace
46
+ LEFT JOIN pg_policy p ON p.polrelid = c.oid
47
+ WHERE n.nspname = 'public' AND c.relname = ANY($1::text[])`, [tableNames]);
48
+ const rowsByTable = Map.groupBy(rows, (row) => row.relname);
49
+ for (const [tableName, tableRows] of rowsByTable) {
50
+ const shape = shapeOfRows(tableRows);
51
+ if (shape !== undefined)
52
+ shapes.set(tableName, shape);
53
+ }
54
+ return shapes;
55
+ }
56
+ export async function readRowLevelSecurityShape(db, tableName) {
57
+ return (await readRowLevelSecurityShapes(db, [tableName])).get(tableName);
58
+ }
59
+ // Shared by the rebuild guard and the boot check, so both judge a hand-edited policy alike.
60
+ export function isFrameworkIsolationIntact(shape) {
61
+ const isolation = shape.policies.find((policy) => policy.name === TENANT_ISOLATION_POLICY);
62
+ return (isolation !== undefined &&
63
+ isolation.kind === "PERMISSIVE" &&
64
+ isolation.command === "ALL" &&
65
+ isolation.appliesToPublic &&
66
+ !shape.policies.some((policy) => policy.kind === "RESTRICTIVE"));
67
+ }
@@ -17,10 +17,11 @@ export async function withSessionAdvisoryLock(db, key, fn) {
17
17
  finally {
18
18
  // A dropped session already released its lock; failing here would mask fn's outcome.
19
19
  await conn.unsafe(`SELECT pg_advisory_unlock($1)`, [key]).catch(() => undefined);
20
- await conn.unsafe("RESET statement_timeout").catch(() => undefined);
21
20
  }
22
21
  }
23
22
  finally {
23
+ // Outside the inner try: a failing lock call must not hand the connection back without the pool's cap.
24
+ await conn.unsafe("RESET statement_timeout").catch(() => undefined);
24
25
  await conn.release();
25
26
  }
26
27
  }
@@ -1,5 +1,7 @@
1
1
  import { extractPgError } from "../pg-error.js";
2
2
  import { asRawClient } from "../query.js";
3
+ import { outsideRowLevelSecurityScope } from "../row-level-security-scope.js";
4
+ import { quoteLiteral } from "../sql-identifier.js";
3
5
  import { toPostgresArrayLiteral } from "./postgres-array-literal.js";
4
6
  import { PROJECTION_REBUILD_SCHEMA } from "./shadow-swap.js";
5
7
  import { quoteTableIdent } from "./table-ops.js";
@@ -18,7 +20,8 @@ export async function databaseExists(db, dbName) {
18
20
  export async function createDatabase(db, dbName, templateDbName, owner) {
19
21
  const template = templateDbName === undefined ? "" : ` TEMPLATE ${quoteTableIdent(templateDbName)}`;
20
22
  const ownerClause = owner === undefined ? "" : ` OWNER ${quoteTableIdent(owner)}`;
21
- await asRawClient(db).unsafe(`CREATE DATABASE ${quoteTableIdent(dbName)}${template}${ownerClause}`);
23
+ // CREATE/ALTER DATABASE cannot run inside the transaction an enforced pool wraps statements in.
24
+ await outsideRowLevelSecurityScope(() => asRawClient(db).unsafe(`CREATE DATABASE ${quoteTableIdent(dbName)}${template}${ownerClause}`));
22
25
  }
23
26
  const DUPLICATE_OBJECT = "42710";
24
27
  const UNIQUE_VIOLATION = "23505";
@@ -59,11 +62,8 @@ export async function createApplicationRole(admin, role, password) {
59
62
  throw error;
60
63
  }
61
64
  }
62
- function quoteLiteral(value) {
63
- return `'${value.replace(/'/g, "''")}'`;
64
- }
65
65
  export async function transferDatabaseOwnership(admin, dbName, owner) {
66
- await asRawClient(admin).unsafe(`ALTER DATABASE ${quoteTableIdent(dbName)} OWNER TO ${quoteTableIdent(owner)}`);
66
+ await outsideRowLevelSecurityScope(() => asRawClient(admin).unsafe(`ALTER DATABASE ${quoteTableIdent(dbName)} OWNER TO ${quoteTableIdent(owner)}`));
67
67
  }
68
68
  const OWNED_SCHEMA_PUBLIC = "public";
69
69
  const OWNED_RELATION_KINDS = {
@@ -99,7 +99,7 @@ export async function transferPublicSchemaOwnership(db, owner) {
99
99
  }
100
100
  }
101
101
  export async function renameDatabase(db, fromName, toName) {
102
- await asRawClient(db).unsafe(`ALTER DATABASE ${quoteTableIdent(fromName)} RENAME TO ${quoteTableIdent(toName)}`);
102
+ await outsideRowLevelSecurityScope(() => asRawClient(db).unsafe(`ALTER DATABASE ${quoteTableIdent(fromName)} RENAME TO ${quoteTableIdent(toName)}`));
103
103
  }
104
104
  export async function listDatabaseNamesWithPrefix(db, prefix) {
105
105
  const rows = await asRawClient(db).unsafe(`SELECT datname FROM pg_database WHERE starts_with(datname, $1) ORDER BY datname`, [prefix]);
@@ -111,5 +111,5 @@ export async function acquireSessionAdvisoryLock(db, key) {
111
111
  await asRawClient(db).unsafe(`SELECT pg_advisory_lock(hashtext($1))`, [key]);
112
112
  }
113
113
  export async function dropDatabaseIfExists(db, dbName) {
114
- await asRawClient(db).unsafe(`DROP DATABASE IF EXISTS ${quoteTableIdent(dbName)}`);
114
+ await outsideRowLevelSecurityScope(() => asRawClient(db).unsafe(`DROP DATABASE IF EXISTS ${quoteTableIdent(dbName)}`));
115
115
  }
package/dist/db/query.js CHANGED
@@ -24,7 +24,7 @@ import { executorManagedWriteDenied } from "./executor-managed-tables.js";
24
24
  import { extractPgError } from "./pg-error.js";
25
25
  import { extractTableInfo } from "./table-info.js";
26
26
  import { asEntityTableMeta, requireEntityTableMeta } from "./table-introspection.js";
27
- import { openSerializedSavepoint } from "./transaction-serialization.js";
27
+ import { openSerializedSavepoint, runStatementBehindPendingUnits, } from "./transaction-serialization.js";
28
28
  import { buildWhereClause } from "./where-clause.js";
29
29
  // table() (dialect) stores the canonical, shadow-proof EntityTableMeta under
30
30
  // `Symbol.for("kumiko:schema:Meta")`. The column handles on the table object are
@@ -151,7 +151,6 @@ function tenantDbDelegate(db) {
151
151
  }
152
152
  // Fails loudly for helpers that don't delegate to TenantDb (upsert/increment/insertMany) —
153
153
  // passing one here would otherwise reach asRawClient and throw with a less specific message.
154
- // @wrapper-known semantic-alias
155
154
  function assertNotTenantScoped(db, fnName) {
156
155
  if (tenantDbDelegate(db) !== undefined) {
157
156
  throw new Error(`${fnName}: received a tenant-scoped db but this helper does not apply the tenant filter. ` +
@@ -169,10 +168,14 @@ function coerceRows(rows, info) {
169
168
  }
170
169
  // Write and other non-retried paths: log when a closed-connection error leaves
171
170
  // the db layer, rethrow unchanged.
171
+ // A plain statement on a transaction waits for savepoints opened before it, see transaction-serialization.
172
+ function unsafeBehindPendingUnits(raw, sqlText, params) {
173
+ return Promise.resolve(runStatementBehindPendingUnits(raw, () => raw.unsafe(sqlText, params)));
174
+ }
172
175
  export async function unsafeLoggingClosedConnection(db, sqlText, params, context) {
173
176
  const raw = asRawClient(db);
174
177
  try {
175
- return await raw.unsafe(sqlText, params);
178
+ return await unsafeBehindPendingUnits(raw, sqlText, params);
176
179
  }
177
180
  catch (err) {
178
181
  logClosedConnection(raw, err, 1, context);
@@ -186,7 +189,7 @@ export async function unsafeLoggingClosedConnection(db, sqlText, params, context
186
189
  export async function unsafeReadRetrying(db, sqlText, params) {
187
190
  const raw = asRawClient(db);
188
191
  try {
189
- return await raw.unsafe(sqlText, params);
192
+ return await unsafeBehindPendingUnits(raw, sqlText, params);
190
193
  }
191
194
  catch (err) {
192
195
  if (!isPooledClient(raw) || !isClosedConnectionError(err)) {
@@ -198,7 +201,7 @@ export async function unsafeReadRetrying(db, sqlText, params) {
198
201
  let lastErr = err;
199
202
  for (let attempt = 0; attempt < maxRetries; attempt++) {
200
203
  try {
201
- return await raw.unsafe(sqlText, params);
204
+ return await unsafeBehindPendingUnits(raw, sqlText, params);
202
205
  }
203
206
  catch (retryErr) {
204
207
  lastErr = retryErr;
@@ -348,12 +351,10 @@ export async function insertMany(db, table, rows) {
348
351
  if (managedDenied)
349
352
  throw managedDenied;
350
353
  const info = extractTableInfo(table);
351
- // Use the column-set from the first row; assume all rows share keys.
352
- const firstRow = rows[0];
353
- if (firstRow === undefined)
354
- return [];
355
- // Filter out fields that don't exist as columns in the table (like drizzle did implicitly)
356
- const fields = Object.keys(firstRow).filter((k) => info.hasColumn(k));
354
+ // Union of all rows' keys, so a field only a later row sets is not dropped; rows that omit it
355
+ // get DEFAULT, like a single insertOne without that key. Keys that aren't table columns are
356
+ // filtered out (like drizzle did implicitly).
357
+ const fields = [...new Set(rows.flatMap((row) => Object.keys(row)))].filter((k) => info.hasColumn(k));
357
358
  if (fields.length === 0)
358
359
  throw new Error("insertMany: empty row object");
359
360
  const cols = fields.map((k) => quoteIdent(info.columnOf(k))).join(", ");
@@ -362,6 +363,10 @@ export async function insertMany(db, table, rows) {
362
363
  for (const row of rows) {
363
364
  const placeholders = [];
364
365
  for (const f of fields) {
366
+ if (!Object.hasOwn(row, f)) {
367
+ placeholders.push("DEFAULT");
368
+ continue;
369
+ }
365
370
  const col = info.columnOf(f);
366
371
  const pgType = info.pgTypeOf(col);
367
372
  const p = prepareValue(row[f], pgType);
@@ -15,7 +15,7 @@
15
15
  // than being re-derived during apply from the possibly hand-edited SQL.
16
16
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
17
17
  import { join } from "node:path";
18
- import { managedChangeRequiresRecreate } from "./migrate-generator.js";
18
+ import { managedChangeRequiresRecreate, } from "./migrate-generator.js";
19
19
  const MARKER_VERSION = 1;
20
20
  function markerPathFor(migrationsDir, migrationId) {
21
21
  return join(migrationsDir, `${migrationId}.rebuild.json`);
@@ -43,12 +43,21 @@ function markerPathFor(migrationsDir, migrationId) {
43
43
  // convention `${snake}_bidx` from entity-table-meta.ts:111) is always
44
44
  // additive SQL-wise but still needs a rebuild — the index is an HMAC over
45
45
  // the decrypted value, which SQL cannot backfill.
46
+ //
47
+ // Second exception: a jsonb default change (`{}` → `[]` via emptyValue). SET DEFAULT only
48
+ // affects future inserts; existing rows keep the old shape until the projection is re-derived.
49
+ function hasJsonbDefaultChange(diff) {
50
+ return diff.changedColumns.some((change) => change.defaultChanged !== undefined &&
51
+ diff.nextMeta.columns.some((col) => col.name === change.name && col.pgType === "jsonb"));
52
+ }
46
53
  export function rebuildTablesFromDiff(diff) {
47
54
  const names = new Set();
48
55
  for (const t of diff.changedTables) {
49
56
  if (t.nextMeta.source !== "managed")
50
57
  continue;
51
- if (managedChangeRequiresRecreate(t) || t.newColumns.some((c) => c.name.endsWith("_bidx"))) {
58
+ if (managedChangeRequiresRecreate(t) ||
59
+ t.newColumns.some((c) => c.name.endsWith("_bidx")) ||
60
+ hasJsonbDefaultChange(t)) {
52
61
  names.add(t.tableName);
53
62
  }
54
63
  }
@@ -7,6 +7,7 @@ export declare const SYSTEM_TENANT_READ_POLICY = "kumiko_system_tenant_read";
7
7
  export declare const TENANT_ID_SETTING = "kumiko.tenant_id";
8
8
  export declare const SCOPE_SETTING = "kumiko.scope";
9
9
  export declare const SYSTEM_SCOPE = "system";
10
+ export declare const TENANT_COLUMN = "tenant_id";
10
11
  export declare const POLICY_COMMANDS: readonly ["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"];
11
12
  export declare const POLICY_KINDS: readonly ["PERMISSIVE", "RESTRICTIVE"];
12
13
  export type RowLevelSecurityPolicy = {
@@ -27,6 +28,7 @@ export type RowLevelSecurityFlags = {
27
28
  export declare function tenantRowLevelSecurityFor(meta: EntityTableMeta): TableRowLevelSecurity | undefined;
28
29
  export declare function rowLevelSecurityByTable(metas: readonly EntityTableMeta[]): Record<string, TableRowLevelSecurity>;
29
30
  export declare function renderCreatePolicy(tableSql: string, policy: RowLevelSecurityPolicy): string;
31
+ export declare function renderDropPolicy(tableSql: string, policyName: string): string;
30
32
  export declare function renderRowLevelSecurityFlags(tableSql: string, flags: RowLevelSecurityFlags): string[];
31
33
  export declare function renderEnableRowLevelSecurity(tableSql: string, next: TableRowLevelSecurity, previous?: TableRowLevelSecurity): string[];
32
34
  export declare function renderDisableRowLevelSecurity(tableSql: string, previous: TableRowLevelSecurity): string[];
@@ -1,5 +1,6 @@
1
1
  // Pure renderer for Postgres row level security: EntityTableMeta → policy DDL.
2
- // Every table with a `tenant_id` column gets two policies; tables without one are untouched.
2
+ // Every table with a `tenant_id` column gets the isolation policy; only tables marked `systemRowsReadable`
3
+ // also get the system-tenant read policy. Tables without `tenant_id` are untouched.
3
4
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-types/identifiers";
4
5
  import { isOneOf, isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
5
6
  import { pgTypeToSqlType } from "./dialect.js";
@@ -11,7 +12,7 @@ export const SYSTEM_TENANT_READ_POLICY = "kumiko_system_tenant_read";
11
12
  export const TENANT_ID_SETTING = "kumiko.tenant_id";
12
13
  export const SCOPE_SETTING = "kumiko.scope";
13
14
  export const SYSTEM_SCOPE = "system";
14
- const TENANT_COLUMN = "tenant_id";
15
+ export const TENANT_COLUMN = "tenant_id";
15
16
  export const POLICY_COMMANDS = ["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"];
16
17
  export const POLICY_KINDS = ["PERMISSIVE", "RESTRICTIVE"];
17
18
  export function tenantRowLevelSecurityFor(meta) {
@@ -23,16 +24,20 @@ export function tenantRowLevelSecurityFor(meta) {
23
24
  // NULLIF: after a transaction-local set_config, current_setting returns '' instead of NULL.
24
25
  const sessionTenant = `NULLIF(current_setting('${TENANT_ID_SETTING}', true), '')`;
25
26
  const isolation = `${column} = ${sessionTenant}::${sqlType} OR current_setting('${SCOPE_SETTING}', true) = '${SYSTEM_SCOPE}'`;
27
+ const isolationPolicy = {
28
+ name: TENANT_ISOLATION_POLICY,
29
+ command: "ALL",
30
+ kind: "PERMISSIVE",
31
+ rolesSql: "PUBLIC",
32
+ using: isolation,
33
+ withCheck: isolation,
34
+ };
35
+ // Positive classification: a table without the marker never lets a tenant session read system rows.
36
+ if (meta.systemRowsReadable !== true)
37
+ return { policies: [isolationPolicy] };
26
38
  return {
27
39
  policies: [
28
- {
29
- name: TENANT_ISOLATION_POLICY,
30
- command: "ALL",
31
- kind: "PERMISSIVE",
32
- rolesSql: "PUBLIC",
33
- using: isolation,
34
- withCheck: isolation,
35
- },
40
+ isolationPolicy,
36
41
  {
37
42
  name: SYSTEM_TENANT_READ_POLICY,
38
43
  command: "SELECT",
@@ -57,7 +62,7 @@ export function renderCreatePolicy(tableSql, policy) {
57
62
  const withCheck = policy.withCheck !== undefined ? ` WITH CHECK (${policy.withCheck})` : "";
58
63
  return `CREATE POLICY ${quoteIdent(policy.name)} ON ${tableSql} AS ${policy.kind} FOR ${policy.command} TO ${policy.rolesSql}${using}${withCheck};`;
59
64
  }
60
- function renderDropPolicy(tableSql, policyName) {
65
+ export function renderDropPolicy(tableSql, policyName) {
61
66
  return `DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${tableSql};`;
62
67
  }
63
68
  export function renderRowLevelSecurityFlags(tableSql, flags) {
@@ -151,7 +151,7 @@ function applyStatement(schema, statement, context) {
151
151
  // skip: DO block fully handled above
152
152
  return;
153
153
  }
154
- const createAs = statement.match(new RegExp(`^CREATE\\s+(?:UNLOGGED\\s+)?TABLE\\s+(IF NOT EXISTS\\s+)?${IDENT}(?:\\s*\\(([^)]*)\\)\\s*|\\s+)AS\\b([\\s\\S]*)$`, "i"));
154
+ const createAs = statement.match(new RegExp(`^CREATE\\s+(?:UNLOGGED\\s+)?TABLE\\s+(IF NOT EXISTS\\s+)?${IDENT}(?:\\s*\\(([^)]*)\\)\\s*|(?<=")\\s*|\\s+)AS\\b([\\s\\S]*)$`, "i"));
155
155
  if (createAs?.[2] !== undefined && createAs[4] !== undefined) {
156
156
  if (!(createAs[1] !== undefined && schema.has(createAs[2]))) {
157
157
  const explicitColumns = createAs[3] === undefined ? undefined : parseColumnNames(createAs[3]);
@@ -1,12 +1,25 @@
1
1
  import { InternalError } from "../errors/index.js";
2
2
  import { isLiveFrameworkTable } from "./known-table-names.js";
3
+ import { PRODUCTION_SCHEMA_COMMAND_HINT } from "./production-schema-command-hint.js";
3
4
  import { readConnectedRoleAttributes, readTablesWithRowLevelSecurityEnabled, readTenantTablesRowLevelSecurity, } from "./queries/rls-boot-catalog.js";
4
- function missingPartsOf(table) {
5
+ function missingPartsOf(table, knownTables) {
6
+ const expectsSystemRead = knownTables.readsSystemRows(table.tableName);
5
7
  return [
6
8
  ...(table.enabled ? [] : ["ENABLE ROW LEVEL SECURITY"]),
7
9
  ...(table.forced ? [] : ["FORCE ROW LEVEL SECURITY"]),
8
10
  ...(table.hasIsolationPolicy ? [] : ["policy kumiko_tenant_isolation"]),
9
- ...(table.hasSystemReadPolicy ? [] : ["policy kumiko_system_tenant_read"]),
11
+ ...(table.isolationAltered
12
+ ? [
13
+ "policy kumiko_tenant_isolation altered (must be PERMISSIVE ALL for PUBLIC, no RESTRICTIVE policy)",
14
+ ]
15
+ : []),
16
+ ...(table.hasSystemReadPolicy === expectsSystemRead
17
+ ? []
18
+ : [
19
+ expectsSystemRead
20
+ ? "policy kumiko_system_tenant_read"
21
+ : "policy kumiko_system_tenant_read on a table not marked systemRowsReadable (must be dropped)",
22
+ ]),
10
23
  ];
11
24
  }
12
25
  async function assertEnforcingRole(db) {
@@ -31,7 +44,7 @@ function listingOf(entries) {
31
44
  async function assertAllTenantTablesProtected(db, knownTables, scope) {
32
45
  const incomplete = (await readTenantTablesRowLevelSecurity(db))
33
46
  .filter((table) => scope === "database" || knownTables.has(table.tableName))
34
- .map((table) => ({ table: table.tableName, missing: missingPartsOf(table) }))
47
+ .map((table) => ({ table: table.tableName, missing: missingPartsOf(table, knownTables) }))
35
48
  .filter((entry) => entry.missing.length > 0);
36
49
  // skip: every tenant table is protected
37
50
  if (incomplete.length === 0)
@@ -57,7 +70,7 @@ async function assertAllTenantTablesProtected(db, knownTables, scope) {
57
70
  : []),
58
71
  ];
59
72
  throw new InternalError({
60
- message: `rowLevelSecurity is "on" but tenant tables lack row-level security. ${sections.join(" ")}`,
73
+ message: `rowLevelSecurity is "on" but tenant tables lack row-level security. ${sections.join(" ")} ${PRODUCTION_SCHEMA_COMMAND_HINT}`,
61
74
  });
62
75
  }
63
76
  async function assertNoLiveRowLevelSecurity(db, knownTables, scope) {
@@ -66,7 +79,7 @@ async function assertNoLiveRowLevelSecurity(db, knownTables, scope) {
66
79
  if (tables.length === 0)
67
80
  return;
68
81
  throw new InternalError({
69
- message: `rowLevelSecurity is "off" but row-level security is still enabled on: ${tables.join(", ")}. Without a tenant scope every statement would see zero rows. Run \`bun kumiko-schema generate\` with rowLevelSecurity off to produce the DISABLE ROW LEVEL SECURITY migration and apply it.`,
82
+ message: `rowLevelSecurity is "off" but row-level security is still enabled on: ${tables.join(", ")}. Without a tenant scope every statement would see zero rows. Run \`bun kumiko-schema generate\` with rowLevelSecurity off to produce the DISABLE ROW LEVEL SECURITY migration and apply it. ${PRODUCTION_SCHEMA_COMMAND_HINT}`,
70
83
  });
71
84
  }
72
85
  // Table state only, no role check: the role is a runtime property of the boot connection, so tools