@cosmicdrift/kumiko-framework 0.413.1 → 0.414.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 (463) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +63 -13
  4. package/agents/api/framework-event-store.md +14 -0
  5. package/agents/api/framework-ui-types.md +149 -21
  6. package/agents/api/renderer-web.md +93 -9
  7. package/agents/api/testing-helpers.md +3 -2
  8. package/agents/api/testing-stack.md +3 -0
  9. package/agents/api/types.md +205 -14
  10. package/agents/api.md +7 -7
  11. package/agents/boot-rules.md +63 -9
  12. package/agents/examples/api-docs.md +2 -6
  13. package/agents/examples/auth-mfa.md +57 -10
  14. package/agents/examples/chat-channels.md +2 -0
  15. package/agents/examples/currencies-global.md +1 -0
  16. package/agents/examples/env-composition.md +7 -11
  17. package/agents/examples/managed-pages.md +90 -1
  18. package/agents/examples/pwa-shell.md +210 -0
  19. package/agents/examples/rate-limiting.md +3 -3
  20. package/agents/examples/record-detail-layout.md +1537 -67
  21. package/agents/examples/workflow-engine.md +16 -12
  22. package/agents/examples.md +1 -0
  23. package/agents/features-index.md +4 -2
  24. package/agents/features.md +22 -7
  25. package/agents/widgets.md +19 -1
  26. package/dist/api/api-constants.d.ts +1 -0
  27. package/dist/api/api-constants.js +4 -0
  28. package/dist/api/auth-middleware.js +4 -3
  29. package/dist/api/auth-routes-shared.js +2 -1
  30. package/dist/api/entity-read-access.d.ts +1 -0
  31. package/dist/api/entity-read-access.js +18 -0
  32. package/dist/api/export/export-route.d.ts +6 -1
  33. package/dist/api/export/export-route.js +27 -1
  34. package/dist/api/export/export-rows.js +19 -3
  35. package/dist/api/routes.d.ts +2 -0
  36. package/dist/api/routes.js +9 -1
  37. package/dist/api/server-extra-routes.js +2 -1
  38. package/dist/api/server-feature-http-routes.d.ts +9 -0
  39. package/dist/api/server-feature-http-routes.js +109 -0
  40. package/dist/api/server-middleware.js +2 -19
  41. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  42. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  43. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  44. package/dist/api/server-rate-limit-wiring.js +37 -0
  45. package/dist/api/server-routes.d.ts +4 -12
  46. package/dist/api/server-routes.js +12 -171
  47. package/dist/api/server-schema-route.d.ts +3 -0
  48. package/dist/api/server-schema-route.js +58 -0
  49. package/dist/api/server-wiring.js +2 -37
  50. package/dist/api/server.js +3 -1
  51. package/dist/compliance/override-schema.js +5 -5
  52. package/dist/compliance/sub-processors.js +10 -1
  53. package/dist/crypto/index.d.ts +1 -1
  54. package/dist/crypto/index.js +1 -1
  55. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  56. package/dist/crypto/pii-field-encryption.js +16 -1
  57. package/dist/db/apply-entity-event.js +4 -0
  58. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  59. package/dist/db/bun-sql-connection-codes.js +7 -0
  60. package/dist/db/collect-table-metas.js +4 -1
  61. package/dist/db/config-seed.js +1 -1
  62. package/dist/db/derived-field-sql.js +15 -13
  63. package/dist/db/derived-related-sql.d.ts +2 -2
  64. package/dist/db/derived-related-sql.js +4 -2
  65. package/dist/db/dialect.d.ts +3 -0
  66. package/dist/db/dialect.js +1 -3
  67. package/dist/db/driver-row-coercion.js +2 -2
  68. package/dist/db/driver-value-preparation.js +1 -1
  69. package/dist/db/eagerload.js +15 -12
  70. package/dist/db/entity-table-meta.d.ts +2 -0
  71. package/dist/db/entity-table-meta.js +7 -0
  72. package/dist/db/event-store-executor-context.js +13 -8
  73. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  74. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  75. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  76. package/dist/db/event-store-executor-read-filter.js +28 -11
  77. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  78. package/dist/db/event-store-executor-read-search.js +6 -6
  79. package/dist/db/event-store-executor-read-sort.js +3 -3
  80. package/dist/db/event-store-executor-read-where.js +14 -5
  81. package/dist/db/event-store-executor-read.js +7 -7
  82. package/dist/db/event-store-executor-write.js +50 -95
  83. package/dist/db/executor-managed-tables.js +4 -1
  84. package/dist/db/index.d.ts +4 -2
  85. package/dist/db/index.js +4 -2
  86. package/dist/db/known-table-names.d.ts +1 -0
  87. package/dist/db/known-table-names.js +7 -5
  88. package/dist/db/list-aggregate-labels.d.ts +1 -0
  89. package/dist/db/list-aggregate-labels.js +9 -1
  90. package/dist/db/migrate-generator.js +23 -4
  91. package/dist/db/migrate-rls-diff.d.ts +1 -0
  92. package/dist/db/migrate-rls-diff.js +15 -1
  93. package/dist/db/migrate-runner.js +2 -2
  94. package/dist/db/money.d.ts +1 -1
  95. package/dist/db/money.js +1 -4
  96. package/dist/db/parent-ref-clause.d.ts +6 -2
  97. package/dist/db/parent-ref-clause.js +76 -23
  98. package/dist/db/parent-ref-global-hosts.d.ts +20 -0
  99. package/dist/db/parent-ref-global-hosts.js +47 -0
  100. package/dist/db/production-schema-command-hint.d.ts +1 -0
  101. package/dist/db/production-schema-command-hint.js +3 -0
  102. package/dist/db/queries/backfill-pii.js +55 -29
  103. package/dist/db/queries/ddl.js +13 -2
  104. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  105. package/dist/db/queries/event-store-open-streams.js +33 -0
  106. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  107. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  108. package/dist/db/queries/event-store.js +0 -1
  109. package/dist/db/queries/raw-sql.js +0 -1
  110. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  111. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  112. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  113. package/dist/db/queries/rls-boot-catalog.js +13 -8
  114. package/dist/db/queries/rls-shape.d.ts +2 -1
  115. package/dist/db/queries/rls-shape.js +10 -0
  116. package/dist/db/queries/session-advisory-lock.js +2 -1
  117. package/dist/db/queries/test-stack.js +7 -7
  118. package/dist/db/query.js +16 -11
  119. package/dist/db/rebuild-marker.js +11 -2
  120. package/dist/db/render-rls-ddl.d.ts +2 -0
  121. package/dist/db/render-rls-ddl.js +16 -11
  122. package/dist/db/replay-migration-sql.js +1 -1
  123. package/dist/db/row-level-security-boot-check.js +18 -5
  124. package/dist/db/row-level-security-connection.js +25 -12
  125. package/dist/db/row-level-security-scope.d.ts +2 -1
  126. package/dist/db/row-level-security-scope.js +9 -5
  127. package/dist/db/sql-identifier.d.ts +1 -0
  128. package/dist/db/sql-identifier.js +3 -0
  129. package/dist/db/system-tenant-read-db.d.ts +5 -0
  130. package/dist/db/system-tenant-read-db.js +28 -0
  131. package/dist/db/table-builder.d.ts +3 -1
  132. package/dist/db/table-builder.js +18 -8
  133. package/dist/db/table-info.d.ts +1 -2
  134. package/dist/db/table-introspection.d.ts +3 -0
  135. package/dist/db/table-introspection.js +6 -0
  136. package/dist/db/table-push.d.ts +1 -0
  137. package/dist/db/table-push.js +7 -1
  138. package/dist/db/tenant-db-runner.d.ts +3 -0
  139. package/dist/db/tenant-db-runner.js +19 -1
  140. package/dist/db/transaction-serialization.d.ts +1 -0
  141. package/dist/db/transaction-serialization.js +20 -3
  142. package/dist/db/where-clause.js +11 -2
  143. package/dist/db/write-ownership-failures.d.ts +25 -0
  144. package/dist/db/write-ownership-failures.js +82 -0
  145. package/dist/engine/boot-validator/boot-check.js +7 -1
  146. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  147. package/dist/engine/boot-validator/boot-phases.js +3 -2
  148. package/dist/engine/boot-validator/boot-rules.d.ts +293 -26
  149. package/dist/engine/boot-validator/boot-rules.js +4 -0
  150. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  151. package/dist/engine/boot-validator/card-meta-overflow.js +1 -0
  152. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  153. package/dist/engine/boot-validator/config-deps.js +0 -28
  154. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  155. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  156. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  157. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  158. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  159. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  160. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  161. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  162. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  163. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  164. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  165. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  166. package/dist/engine/boot-validator/entity-list-screens.js +33 -6
  167. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  168. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  169. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  170. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  171. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  172. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  173. package/dist/engine/boot-validator/list-row-guidance.js +129 -0
  174. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  175. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  176. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  177. package/dist/engine/boot-validator/list-sort-summary.js +149 -0
  178. package/dist/engine/boot-validator/list-table-options.js +15 -1
  179. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  180. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  181. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  182. package/dist/engine/boot-validator/list-toolbar-options.js +31 -0
  183. package/dist/engine/boot-validator/named-filter-rules.d.ts +32 -2
  184. package/dist/engine/boot-validator/named-filter-rules.js +32 -2
  185. package/dist/engine/boot-validator/ownership.js +10 -1
  186. package/dist/engine/boot-validator/parent-ref.js +87 -50
  187. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  188. package/dist/engine/boot-validator/projection-list-screens.js +31 -1
  189. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  190. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  191. package/dist/engine/boot-validator/query-output-guidance.js +39 -0
  192. package/dist/engine/boot-validator/query-refs.js +24 -1
  193. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  194. package/dist/engine/boot-validator/row-decoration.js +16 -0
  195. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  196. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  197. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  198. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  199. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  200. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  201. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  202. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  203. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  204. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  205. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  206. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  207. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  208. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  209. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  210. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  211. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  212. package/dist/engine/boot-validator/screens-lists.js +19 -3
  213. package/dist/engine/boot-validator/screens.js +1 -1
  214. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  215. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  216. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  217. package/dist/engine/boot-validator/zod-shape.js +19 -1
  218. package/dist/engine/build-app-schema.js +4 -0
  219. package/dist/engine/config-helpers.d.ts +1 -2
  220. package/dist/engine/config-helpers.js +6 -7
  221. package/dist/engine/define-feature.js +1 -0
  222. package/dist/engine/define-handler.d.ts +1 -0
  223. package/dist/engine/define-handler.js +4 -2
  224. package/dist/engine/definition-violations.js +2 -2
  225. package/dist/engine/entity-handlers.js +3 -8
  226. package/dist/engine/entity-list-runtime-options.js +9 -8
  227. package/dist/engine/factories.d.ts +2 -0
  228. package/dist/engine/feature-config-events-jobs.js +1 -0
  229. package/dist/engine/feature-entity-handlers.js +5 -2
  230. package/dist/engine/field-access.d.ts +1 -1
  231. package/dist/engine/field-access.js +7 -10
  232. package/dist/engine/find-entity.js +3 -3
  233. package/dist/engine/form-derivations.js +3 -3
  234. package/dist/engine/index.d.ts +3 -3
  235. package/dist/engine/index.js +2 -2
  236. package/dist/engine/named-filter-roles.d.ts +3 -0
  237. package/dist/engine/named-filter-roles.js +23 -0
  238. package/dist/engine/pipeline.js +0 -1
  239. package/dist/engine/project-app-schema-for-roles.js +17 -2
  240. package/dist/engine/qualified-name.js +0 -1
  241. package/dist/engine/registry-facade.js +1 -2
  242. package/dist/engine/registry-state.d.ts +1 -1
  243. package/dist/engine/registry-state.js +5 -2
  244. package/dist/engine/registry-validate.js +2 -1
  245. package/dist/engine/resolve-named-list-filters.js +5 -2
  246. package/dist/engine/schema-builder.js +6 -10
  247. package/dist/engine/screen-helpers.d.ts +12 -0
  248. package/dist/engine/screen-helpers.js +17 -1
  249. package/dist/engine/soft-delete-cleanup.js +1 -5
  250. package/dist/engine/state-machine.js +0 -1
  251. package/dist/engine/steps/_database-clock.d.ts +2 -0
  252. package/dist/engine/steps/_database-clock.js +6 -0
  253. package/dist/engine/steps/compute.js +1 -1
  254. package/dist/engine/steps/retry.js +5 -1
  255. package/dist/engine/steps/return.js +0 -1
  256. package/dist/engine/steps/wait-for-event.js +2 -1
  257. package/dist/engine/steps/wait.js +2 -1
  258. package/dist/engine/system-user.d.ts +2 -2
  259. package/dist/engine/system-user.js +2 -2
  260. package/dist/engine/types/handlers.d.ts +1 -1
  261. package/dist/engine/types/handlers.js +1 -1
  262. package/dist/engine/types/screen.d.ts +1 -1
  263. package/dist/engine/types/screen.js +1 -1
  264. package/dist/engine/webhook-contracts.d.ts +2 -3
  265. package/dist/engine/webhook-contracts.js +2 -25
  266. package/dist/engine/webhook-events.js +48 -29
  267. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  268. package/dist/engine/webhook-payload-strictness.js +53 -0
  269. package/dist/env/_zod-introspect.d.ts +1 -0
  270. package/dist/env/dry-run.d.ts +1 -1
  271. package/dist/env/dry-run.js +1 -1
  272. package/dist/env/field-meta.d.ts +4 -0
  273. package/dist/env/field-meta.js +67 -0
  274. package/dist/env/field-rules.d.ts +9 -0
  275. package/dist/env/field-rules.js +46 -0
  276. package/dist/env/index.d.ts +3 -3
  277. package/dist/env/index.js +16 -71
  278. package/dist/env/internals.d.ts +3 -0
  279. package/dist/env/internals.js +1 -2
  280. package/dist/env/required-env.d.ts +3 -1
  281. package/dist/env/required-env.js +5 -2
  282. package/dist/errors/serialize.js +2 -2
  283. package/dist/errors/write-error-info.js +0 -2
  284. package/dist/es-ops/operations-schema.js +18 -7
  285. package/dist/event-store/admin-api.js +3 -3
  286. package/dist/event-store/event-store.js +0 -3
  287. package/dist/event-store/index.d.ts +1 -0
  288. package/dist/event-store/index.js +1 -0
  289. package/dist/event-store/transfer.js +1 -1
  290. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  291. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  292. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  293. package/dist/files/bind-pending-file-refs.js +54 -27
  294. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  295. package/dist/files/create-file-ref.d.ts +4 -1
  296. package/dist/files/create-file-ref.js +14 -3
  297. package/dist/files/default-file-guard.js +4 -1
  298. package/dist/files/file-claim.d.ts +6 -0
  299. package/dist/files/file-claim.js +17 -0
  300. package/dist/files/file-field-slots.d.ts +2 -0
  301. package/dist/files/file-field-slots.js +28 -0
  302. package/dist/files/file-ref-entity.d.ts +3 -0
  303. package/dist/files/file-ref-entity.js +2 -0
  304. package/dist/files/file-ref-table.d.ts +3 -0
  305. package/dist/files/file-routes.d.ts +4 -1
  306. package/dist/files/file-routes.js +80 -16
  307. package/dist/files/in-memory-provider.d.ts +1 -1
  308. package/dist/files/in-memory-provider.js +2 -1
  309. package/dist/files/index.d.ts +1 -1
  310. package/dist/files/index.js +1 -1
  311. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  312. package/dist/files/invalid-file-ref-error.js +15 -0
  313. package/dist/files/local-provider.js +9 -2
  314. package/dist/files/provider-resolver.js +1 -1
  315. package/dist/files/rebind-file-ref.d.ts +3 -2
  316. package/dist/files/rebind-file-ref.js +24 -18
  317. package/dist/files/resolve-file-handles.d.ts +13 -0
  318. package/dist/files/resolve-file-handles.js +57 -0
  319. package/dist/files/storage-tracking.d.ts +1 -1
  320. package/dist/files/storage-tracking.js +5 -2
  321. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  322. package/dist/files/types.d.ts +4 -0
  323. package/dist/files/types.js +10 -0
  324. package/dist/files/upload-field-resolution.d.ts +1 -0
  325. package/dist/files/upload-field-resolution.js +16 -2
  326. package/dist/files/upload-ledger.js +1 -1
  327. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  328. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  329. package/dist/i18n/required-surface-keys.js +19 -4
  330. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  331. package/dist/internal/boot-rule-table-expectations.js +29 -0
  332. package/dist/internal/row-level-security.d.ts +1 -0
  333. package/dist/internal/row-level-security.js +1 -0
  334. package/dist/internal/testing.d.ts +1 -0
  335. package/dist/internal/testing.js +1 -0
  336. package/dist/jobs/index.d.ts +1 -0
  337. package/dist/jobs/index.js +1 -0
  338. package/dist/jobs/job-load-events.d.ts +10 -0
  339. package/dist/jobs/job-load-events.js +12 -0
  340. package/dist/jobs/job-runner-context.js +6 -158
  341. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  342. package/dist/jobs/job-runner-dispatch.js +57 -0
  343. package/dist/jobs/job-runner-event-triggers.js +18 -9
  344. package/dist/jobs/job-runner-execution.js +2 -2
  345. package/dist/jobs/job-runner-facets.d.ts +48 -0
  346. package/dist/jobs/job-runner-facets.js +156 -0
  347. package/dist/jobs/job-runner-gates.js +19 -11
  348. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  349. package/dist/jobs/job-runner-helpers.js +18 -3
  350. package/dist/jobs/job-runner-scope.d.ts +1 -0
  351. package/dist/jobs/job-runner-scope.js +2 -0
  352. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  353. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  354. package/dist/jobs/job-runner.js +31 -70
  355. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  356. package/dist/jobs/obliterate-job-queues.js +23 -0
  357. package/dist/lifecycle/lifecycle.js +1 -1
  358. package/dist/migrations/event-header-scrub.d.ts +11 -0
  359. package/dist/migrations/event-header-scrub.js +33 -0
  360. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  361. package/dist/migrations/event-payload-scrub.js +36 -4
  362. package/dist/migrations/index.d.ts +1 -0
  363. package/dist/migrations/index.js +2 -0
  364. package/dist/migrations/kumiko-drift.d.ts +5 -2
  365. package/dist/migrations/kumiko-drift.js +51 -14
  366. package/dist/migrations/pending-rebuilds.js +4 -5
  367. package/dist/observability/sensitive-filter.js +0 -12
  368. package/dist/pipeline/aggregate-type-removal.js +17 -4
  369. package/dist/pipeline/context-services.d.ts +2 -0
  370. package/dist/pipeline/context-services.js +5 -2
  371. package/dist/pipeline/dispatch-batch.js +4 -3
  372. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  373. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  374. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  375. package/dist/pipeline/dispatch-nested-write.js +119 -0
  376. package/dist/pipeline/dispatch-query.js +10 -3
  377. package/dist/pipeline/dispatch-scope.js +4 -3
  378. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  379. package/dist/pipeline/dispatch-shared.js +6 -38
  380. package/dist/pipeline/dispatch-write.d.ts +0 -1
  381. package/dist/pipeline/dispatch-write.js +3 -302
  382. package/dist/pipeline/dispatcher-utils.js +6 -0
  383. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  384. package/dist/pipeline/effective-system-scope.js +22 -0
  385. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  386. package/dist/pipeline/event-dispatcher-delivery.js +17 -9
  387. package/dist/pipeline/event-dispatcher.d.ts +4 -1
  388. package/dist/pipeline/event-dispatcher.js +6 -7
  389. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  390. package/dist/pipeline/handler-context-auth.js +3 -4
  391. package/dist/pipeline/handler-context-db.js +11 -4
  392. package/dist/pipeline/handler-context-dispatch.js +2 -2
  393. package/dist/pipeline/handler-context-events.d.ts +8 -3
  394. package/dist/pipeline/handler-context-events.js +20 -65
  395. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  396. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  397. package/dist/pipeline/handler-context-notify.js +2 -0
  398. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  399. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  400. package/dist/pipeline/handler-context-projection.js +39 -0
  401. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  402. package/dist/pipeline/handler-context-scope.js +14 -2
  403. package/dist/pipeline/index.d.ts +1 -1
  404. package/dist/pipeline/index.js +1 -1
  405. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  406. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  407. package/dist/pipeline/member-reader.js +4 -2
  408. package/dist/pipeline/msp-rebuild.js +1 -1
  409. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  410. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  411. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  412. package/dist/pipeline/projection-rebuild.js +16 -7
  413. package/dist/pipeline/projection-state.js +4 -6
  414. package/dist/pipeline/system-hooks.js +36 -6
  415. package/dist/pipeline/write-result-masking.js +31 -3
  416. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  417. package/dist/pipeline/write-transition-guard.js +95 -0
  418. package/dist/schema-cli/shared.d.ts +2 -0
  419. package/dist/schema-cli/shared.js +4 -2
  420. package/dist/schema-cli/validate-command.js +43 -28
  421. package/dist/search/meilisearch-adapter.js +14 -9
  422. package/dist/search/reindex-entity.d.ts +2 -0
  423. package/dist/search/reindex-entity.js +32 -4
  424. package/dist/search/reindex-tenants-search.js +20 -4
  425. package/dist/time/tz-context.js +1 -1
  426. package/dist/ui-types/card-column-roles.d.ts +4 -0
  427. package/dist/ui-types/card-column-roles.js +6 -3
  428. package/dist/ui-types/index.d.ts +2 -2
  429. package/dist/ui-types/index.js +1 -1
  430. package/dist/utils/ids.js +0 -1
  431. package/dist/utils/index.d.ts +1 -0
  432. package/dist/utils/index.js +1 -0
  433. package/dist/utils/return-path-limit.d.ts +1 -0
  434. package/dist/utils/return-path-limit.js +1 -0
  435. package/package.json +5 -3
  436. package/presets/biome-app.json +39 -21
  437. package/presets/biome-plugins/admin-api.grit +10 -0
  438. package/presets/biome-plugins/error-reasons.grit +53 -0
  439. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  440. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  441. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  442. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  443. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  444. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  445. package/presets/biome-plugins/no-date-api.grit +9 -0
  446. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  447. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  448. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  449. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  450. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  451. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  452. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  453. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  454. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  455. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  456. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  457. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  458. package/presets/biome-plugins/test-title.grit +20 -0
  459. package/presets/biome-plugins/unsafe-json-parse.grit +6 -0
  460. package/presets/biome-rules.json +465 -0
  461. package/src/changes.json +309 -0
  462. package/dist/engine/minor-units.d.ts +0 -2
  463. package/dist/engine/minor-units.js +0 -8
@@ -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, readRowLevelSecurityShape } 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,14 +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,
27
+ return Promise.all(rows.map(async (row) => {
28
+ const shape = row.has_isolation
29
+ ? await readRowLevelSecurityShape(db, row.relname)
30
+ : undefined;
31
+ return {
32
+ tableName: row.relname,
33
+ enabled: row.relrowsecurity,
34
+ forced: row.relforcerowsecurity,
35
+ hasIsolationPolicy: row.has_isolation,
36
+ isolationAltered: shape !== undefined && !isFrameworkIsolationIntact(shape),
37
+ hasSystemReadPolicy: row.has_system_read,
38
+ };
34
39
  }));
35
40
  }
36
41
  export async function readTablesWithRowLevelSecurityEnabled(db) {
@@ -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;
@@ -8,3 +8,4 @@ export type RowLevelSecurityShape = {
8
8
  })[];
9
9
  };
10
10
  export declare function readRowLevelSecurityShape(db: AnyDb, tableName: string): Promise<RowLevelSecurityShape | undefined>;
11
+ 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",
@@ -40,3 +41,12 @@ export async function readRowLevelSecurityShape(db, tableName) {
40
41
  });
41
42
  return { enabled: first.relrowsecurity, forced: first.relforcerowsecurity, policies };
42
43
  }
44
+ // Shared by the rebuild guard and the boot check, so both judge a hand-edited policy alike.
45
+ export function isFrameworkIsolationIntact(shape) {
46
+ const isolation = shape.policies.find((policy) => policy.name === TENANT_ISOLATION_POLICY);
47
+ return (isolation !== undefined &&
48
+ isolation.kind === "PERMISSIVE" &&
49
+ isolation.command === "ALL" &&
50
+ isolation.appliesToPublic &&
51
+ !shape.policies.some((policy) => policy.kind === "RESTRICTIVE"));
52
+ }
@@ -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
@@ -1,6 +1,6 @@
1
1
  import { InternalError } from "../errors/index.js";
2
2
  import { applyRowLevelSecurityScope, buildRowLevelSecurityScopeQuery, } from "./queries/rls-scope.js";
3
- import { activeRowLevelSecurityScope, innerOfScopedRunner, rowLevelSecurityScopeKey, runInCapturedRowLevelSecurityScope, } from "./row-level-security-scope.js";
3
+ import { activeRowLevelSecurityScope, innerOfScopedRunner, isOutsideRowLevelSecurityScope, rowLevelSecurityScopeKey, runInCapturedRowLevelSecurityScope, } from "./row-level-security-scope.js";
4
4
  import { registerRunnerProxyTarget } from "./transaction-serialization.js";
5
5
  const enforcedHandles = new WeakSet();
6
6
  // Differs from every scope key, so the next statement always re-applies its scope.
@@ -58,8 +58,16 @@ function withCapturedCallback(args, wrap) {
58
58
  function alignedStatement(target, state, run) {
59
59
  const desired = activeRowLevelSecurityScope();
60
60
  return enqueue(state, async () => {
61
- await alignScope(target, state, desired);
62
- return run();
61
+ // The scope and the statement go out back to back; a failing set_config aborts the transaction,
62
+ // so the statement fails behind it.
63
+ const scoped = startAlignScope(target, state, desired);
64
+ const statement = startQuery(run);
65
+ const [scopeResult, statementResult] = await Promise.allSettled([scoped, statement]);
66
+ if (scopeResult.status === "rejected")
67
+ throw scopeResult.reason;
68
+ if (statementResult.status === "rejected")
69
+ throw statementResult.reason;
70
+ return statementResult.value;
63
71
  });
64
72
  }
65
73
  function transactionHandleProxy(handle, state) {
@@ -104,17 +112,20 @@ function transactionHandleProxy(handle, state) {
104
112
  registerRunnerProxyTarget(proxy, handle);
105
113
  return proxy;
106
114
  }
107
- async function alignScope(handle, state, desired) {
115
+ function startAlignScope(handle, state, desired) {
108
116
  const key = rowLevelSecurityScopeKey(desired);
109
117
  // skip: scope already applied on this connection
110
118
  if (key === state.applied)
111
- return;
119
+ return Promise.resolve();
112
120
  state.applied = UNKNOWN_SCOPE_KEY;
113
- await applyRowLevelSecurityScope(handle, desired);
114
- state.applied = key;
121
+ return startQuery(() => buildRowLevelSecurityScopeQuery(handle, desired)).then(() => {
122
+ state.applied = key;
123
+ });
115
124
  }
116
125
  function newTransactionState() {
117
- return { applied: rowLevelSecurityScopeKey(undefined), tail: Promise.resolve() };
126
+ // Not "none": a pooled connection may carry a session-level scope GUC set by raw SQL, so even a
127
+ // scope-free transaction has to reset both settings itself.
128
+ return { applied: UNKNOWN_SCOPE_KEY, tail: Promise.resolve() };
118
129
  }
119
130
  const templateOf = (strings) => strings;
120
131
  // Tagged-template statements pipeline behind each other; unsafe() without parameters is sent as a
@@ -171,13 +182,15 @@ async function pipelinedScopedTransaction(pool, scope, run) {
171
182
  callMethod(conn, "release", []);
172
183
  }
173
184
  }
174
- // A pool statement under a scope runs as its own short transaction; without a scope it passes
175
- // through and the policies see no tenant (fail closed), so DDL like CONCURRENTLY keeps working.
185
+ // Every pool statement runs as its own short transaction that sets both scope settings, to '' when
186
+ // no scope is active: a pooled connection may carry a session-level scope set by raw SQL, which a
187
+ // pass-through would let every scope-free statement inherit. Only outsideRowLevelSecurityScope
188
+ // (CONCURRENTLY and other non-transactional DDL) sends a statement straight to the connection.
176
189
  export function enforceRowLevelSecurity(pool) {
177
190
  const inScopedTransaction = (run) => pipelinedScopedTransaction(pool, activeRowLevelSecurityScope(), run);
178
191
  const proxy = new Proxy(pool, {
179
192
  apply(target, _thisArg, args) {
180
- if (!isTaggedTemplateCall(args) || activeRowLevelSecurityScope() === undefined) {
193
+ if (!isTaggedTemplateCall(args) || isOutsideRowLevelSecurityScope()) {
181
194
  return applyOnTarget(target, args);
182
195
  }
183
196
  return inScopedTransaction((conn) => applyOnTarget(conn, args));
@@ -188,7 +201,7 @@ export function enforceRowLevelSecurity(pool) {
188
201
  return value;
189
202
  if (prop === "unsafe" || prop === "file") {
190
203
  return (...args) => {
191
- if (activeRowLevelSecurityScope() === undefined)
204
+ if (isOutsideRowLevelSecurityScope())
192
205
  return callMethod(target, prop, args);
193
206
  if (prop === "file") {
194
207
  // Bun sends file() only after its async file read, i.e. after the pipelined COMMIT.
@@ -7,13 +7,14 @@ export type RowLevelSecurityScope = {
7
7
  readonly kind: "system";
8
8
  readonly reason: string;
9
9
  };
10
- export declare const SYSTEM_ROW_LEVEL_SECURITY_SCOPE: RowLevelSecurityScope;
10
+ export declare function systemRowLevelSecurityScope(reason: string): RowLevelSecurityScope;
11
11
  export declare function tenantRowLevelSecurityScope(tenantId: TenantId): RowLevelSecurityScope;
12
12
  export declare function activeRowLevelSecurityScope(): RowLevelSecurityScope | undefined;
13
13
  export declare function runInRowLevelSecurityScope<T>(scope: RowLevelSecurityScope, fn: () => T): T;
14
14
  export declare function runInSystemRowLevelSecurityScope<T>(reason: string, fn: () => T): T;
15
15
  export declare function runInCapturedRowLevelSecurityScope<T>(captured: RowLevelSecurityScope | undefined, fn: () => T): T;
16
16
  export declare function outsideRowLevelSecurityScope<T>(fn: () => T): T;
17
+ export declare function isOutsideRowLevelSecurityScope(): boolean;
17
18
  export declare function rowLevelSecurityScopeKey(scope: RowLevelSecurityScope | undefined): string;
18
19
  export type TenantDbModeOptions = {
19
20
  readonly mode: "tenant";
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { InternalError } from "../errors/index.js";
3
3
  import { asEntityTableMeta } from "./table-introspection.js";
4
4
  import { registerRunnerProxyTarget } from "./transaction-serialization.js";
5
- function systemRowLevelSecurityScope(reason) {
5
+ export function systemRowLevelSecurityScope(reason) {
6
6
  if (reason.trim() === "") {
7
7
  throw new InternalError({
8
8
  message: "A system row-level-security scope requires a non-empty reason.",
@@ -10,7 +10,6 @@ function systemRowLevelSecurityScope(reason) {
10
10
  }
11
11
  return { kind: "system", reason };
12
12
  }
13
- export const SYSTEM_ROW_LEVEL_SECURITY_SCOPE = systemRowLevelSecurityScope("framework-internal cross-tenant access");
14
13
  function describeRowLevelSecurityScope(scope) {
15
14
  return scope.kind === "system"
16
15
  ? `system (reason: ${scope.reason})`
@@ -33,9 +32,14 @@ export function runInSystemRowLevelSecurityScope(reason, fn) {
33
32
  export function runInCapturedRowLevelSecurityScope(captured, fn) {
34
33
  return captured === undefined ? storage.exit(fn) : storage.run(captured, fn);
35
34
  }
36
- // DDL such as CREATE INDEX CONCURRENTLY cannot run in the per-statement transaction an enforced pool opens under a scope.
35
+ const outsideScopeStorage = new AsyncLocalStorage();
36
+ // Use for non-transactional DDL (CREATE INDEX CONCURRENTLY) and session-level statements on an RLS-enforced
37
+ // pool: it opens a per-statement transaction for every statement, and only this opt-out bypasses it.
37
38
  export function outsideRowLevelSecurityScope(fn) {
38
- return storage.exit(fn);
39
+ return storage.exit(() => outsideScopeStorage.run(true, fn));
40
+ }
41
+ export function isOutsideRowLevelSecurityScope() {
42
+ return outsideScopeStorage.getStore() === true;
39
43
  }
40
44
  export function rowLevelSecurityScopeKey(scope) {
41
45
  if (scope === undefined)
@@ -52,7 +56,7 @@ export function tenantDbRowLevelSecurityScope(options, tenantId, table) {
52
56
  if (options.mode === "system")
53
57
  return systemRowLevelSecurityScope(options.reason);
54
58
  if (asEntityTableMeta(table)?.tenancy === "global")
55
- return SYSTEM_ROW_LEVEL_SECURITY_SCOPE;
59
+ return systemRowLevelSecurityScope("global-tenancy table access");
56
60
  return tenantRowLevelSecurityScope(tenantId);
57
61
  }
58
62
  // A server or loop that inherits an ambient scope would run every later request fail-open.
@@ -1 +1,2 @@
1
1
  export declare function quoteIdent(name: string): string;
2
+ export declare function quoteLiteral(value: string): string;
@@ -1,3 +1,6 @@
1
1
  export function quoteIdent(name) {
2
2
  return `"${name.replace(/"/g, '""')}"`;
3
3
  }
4
+ export function quoteLiteral(value) {
5
+ return `'${value.replace(/'/g, "''")}'`;
6
+ }
@@ -0,0 +1,5 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-types/tenant-db-types";
2
+ import type { DbRunner } from "./connection.ts";
3
+ export declare function systemTenantReadDb(db: TenantDb | DbRunner): TenantDb;
4
+ export declare function systemTenantReadRunner(db: TenantDb | DbRunner): DbRunner;
5
+ export declare function systemTenantWriteRunner(db: TenantDb | DbRunner, reason: string): DbRunner;
@@ -0,0 +1,28 @@
1
+ import { assertReason } from "../engine/escape-hatch-reason.js";
2
+ import { SYSTEM_TENANT_ID } from "../engine/types/identifiers.js";
3
+ import { createTenantDb } from "./tenant-db.js";
4
+ import { isBoundTenantDb, tenantDbRunner } from "./tenant-db-runner.js";
5
+ // Tenant mode on the system tenant: RLS isolation passes exactly the system tenant's rows, never
6
+ // another tenant's, which a `kumiko.scope = 'system'` bypass would also expose.
7
+ export function systemTenantReadDb(db) {
8
+ return createTenantDb({
9
+ db: isBoundTenantDb(db) ? tenantDbRunner(db) : db,
10
+ tenantId: SYSTEM_TENANT_ID,
11
+ mode: "tenant",
12
+ grants: { writesDeniedReason: "on a handle that reads the system tenant's rows only" },
13
+ });
14
+ }
15
+ // Raw runner for event-store reads that take a DbRunner (event streaming, archive checks).
16
+ export function systemTenantReadRunner(db) {
17
+ return tenantDbRunner(systemTenantReadDb(db));
18
+ }
19
+ // Raw runner for event-store writes that take a DbRunner (stream archival, note erasure); RLS
20
+ // isolation limits its writes to system-tenant rows.
21
+ export function systemTenantWriteRunner(db, reason) {
22
+ assertReason("systemTenantWriteRunner", reason);
23
+ return tenantDbRunner(createTenantDb({
24
+ db: isBoundTenantDb(db) ? tenantDbRunner(db) : db,
25
+ tenantId: SYSTEM_TENANT_ID,
26
+ mode: "tenant",
27
+ }));
28
+ }
@@ -7,7 +7,7 @@ import type { MoneyRead } from "./money.ts";
7
7
  export { toSnakeCase } from "../utils/case.ts";
8
8
  import { type ColumnBuilder, type ColumnHandle, type SchemaTable, type TableColumns } from "./dialect.ts";
9
9
  export { SOFT_DELETE_LIVE_ROW_PREDICATE } from "./entity-table-indexes.ts";
10
- export declare function physicalColumnName(table: unknown, field: string): string;
10
+ export declare function physicalColumnName(table: SchemaTable, field: string): string;
11
11
  export type AnyPgColumn = ColumnHandle;
12
12
  export declare const READ_MODEL_PREFIX = "read_";
13
13
  export declare function toTableName(entityName: string): string;
@@ -227,4 +227,6 @@ export type BuildEntityTableOptions = {
227
227
  * Throws if the table has a `tenant_id` column or no EntityTableMeta to stamp.
228
228
  */
229
229
  export declare function declareGlobalTenancy<T extends SchemaTable>(table: T): T & TenancyBrand<"global">;
230
+ /** Stamps `systemRowsReadable` onto an entity table's meta in place (no-op if already set). */
231
+ export declare function declareSystemRowsReadable(table: object): void;
230
232
  export declare function buildEntityTable<E extends EntityDefinition>(entityName: string, entity: E, options?: BuildEntityTableOptions): EntityTable<E>;