@cosmicdrift/kumiko-framework 0.413.0 → 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 (467) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +64 -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/helpdesk.md +15 -8
  18. package/agents/examples/managed-pages.md +90 -1
  19. package/agents/examples/pwa-shell.md +210 -0
  20. package/agents/examples/rate-limiting.md +3 -3
  21. package/agents/examples/record-detail-layout.md +1537 -67
  22. package/agents/examples/workflow-engine.md +16 -12
  23. package/agents/examples.md +1 -0
  24. package/agents/features-index.md +4 -2
  25. package/agents/features.md +22 -7
  26. package/agents/widgets.md +19 -1
  27. package/dist/api/api-constants.d.ts +1 -0
  28. package/dist/api/api-constants.js +4 -0
  29. package/dist/api/auth-middleware.js +4 -3
  30. package/dist/api/auth-routes-shared.js +2 -1
  31. package/dist/api/entity-read-access.d.ts +1 -0
  32. package/dist/api/entity-read-access.js +18 -0
  33. package/dist/api/export/export-route.d.ts +6 -1
  34. package/dist/api/export/export-route.js +27 -1
  35. package/dist/api/export/export-rows.js +19 -3
  36. package/dist/api/routes.d.ts +2 -0
  37. package/dist/api/routes.js +9 -1
  38. package/dist/api/server-extra-routes.js +2 -1
  39. package/dist/api/server-feature-http-routes.d.ts +9 -0
  40. package/dist/api/server-feature-http-routes.js +109 -0
  41. package/dist/api/server-middleware.js +2 -19
  42. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  43. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  44. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  45. package/dist/api/server-rate-limit-wiring.js +37 -0
  46. package/dist/api/server-routes.d.ts +4 -12
  47. package/dist/api/server-routes.js +12 -171
  48. package/dist/api/server-schema-route.d.ts +3 -0
  49. package/dist/api/server-schema-route.js +58 -0
  50. package/dist/api/server-wiring.js +2 -37
  51. package/dist/api/server.js +3 -1
  52. package/dist/compliance/override-schema.js +5 -5
  53. package/dist/compliance/sub-processors.js +10 -1
  54. package/dist/crypto/index.d.ts +1 -1
  55. package/dist/crypto/index.js +1 -1
  56. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  57. package/dist/crypto/pii-field-encryption.js +16 -1
  58. package/dist/db/apply-entity-event.js +4 -0
  59. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  60. package/dist/db/bun-sql-connection-codes.js +7 -0
  61. package/dist/db/collect-table-metas.js +4 -1
  62. package/dist/db/config-seed.js +1 -1
  63. package/dist/db/derived-field-sql.js +15 -13
  64. package/dist/db/derived-related-sql.d.ts +2 -2
  65. package/dist/db/derived-related-sql.js +4 -2
  66. package/dist/db/dialect.d.ts +3 -0
  67. package/dist/db/dialect.js +1 -3
  68. package/dist/db/driver-row-coercion.js +2 -2
  69. package/dist/db/driver-value-preparation.js +1 -1
  70. package/dist/db/eagerload.js +15 -12
  71. package/dist/db/entity-table-meta.d.ts +2 -0
  72. package/dist/db/entity-table-meta.js +7 -0
  73. package/dist/db/event-store-executor-context.js +13 -8
  74. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  75. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  76. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  77. package/dist/db/event-store-executor-read-filter.js +28 -11
  78. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  79. package/dist/db/event-store-executor-read-search.js +6 -6
  80. package/dist/db/event-store-executor-read-sort.js +3 -3
  81. package/dist/db/event-store-executor-read-where.js +14 -5
  82. package/dist/db/event-store-executor-read.js +7 -7
  83. package/dist/db/event-store-executor-write.js +50 -95
  84. package/dist/db/executor-managed-tables.js +4 -1
  85. package/dist/db/index.d.ts +4 -2
  86. package/dist/db/index.js +4 -2
  87. package/dist/db/known-table-names.d.ts +1 -0
  88. package/dist/db/known-table-names.js +7 -5
  89. package/dist/db/list-aggregate-labels.d.ts +1 -0
  90. package/dist/db/list-aggregate-labels.js +9 -1
  91. package/dist/db/migrate-generator.js +23 -4
  92. package/dist/db/migrate-rls-diff.d.ts +1 -0
  93. package/dist/db/migrate-rls-diff.js +15 -1
  94. package/dist/db/migrate-runner.js +2 -2
  95. package/dist/db/money.d.ts +1 -1
  96. package/dist/db/money.js +1 -4
  97. package/dist/db/parent-ref-clause.d.ts +6 -2
  98. package/dist/db/parent-ref-clause.js +76 -23
  99. package/dist/db/parent-ref-global-hosts.d.ts +20 -0
  100. package/dist/db/parent-ref-global-hosts.js +47 -0
  101. package/dist/db/production-schema-command-hint.d.ts +1 -0
  102. package/dist/db/production-schema-command-hint.js +3 -0
  103. package/dist/db/queries/backfill-pii.js +55 -29
  104. package/dist/db/queries/ddl.js +13 -2
  105. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  106. package/dist/db/queries/event-store-open-streams.js +33 -0
  107. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  108. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  109. package/dist/db/queries/event-store.js +0 -1
  110. package/dist/db/queries/raw-sql.js +0 -1
  111. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  112. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  113. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  114. package/dist/db/queries/rls-boot-catalog.js +13 -8
  115. package/dist/db/queries/rls-shape.d.ts +2 -1
  116. package/dist/db/queries/rls-shape.js +10 -0
  117. package/dist/db/queries/session-advisory-lock.js +2 -1
  118. package/dist/db/queries/test-stack.js +7 -7
  119. package/dist/db/query.js +16 -11
  120. package/dist/db/rebuild-marker.js +11 -2
  121. package/dist/db/render-rls-ddl.d.ts +2 -0
  122. package/dist/db/render-rls-ddl.js +16 -11
  123. package/dist/db/replay-migration-sql.js +1 -1
  124. package/dist/db/row-level-security-boot-check.js +18 -5
  125. package/dist/db/row-level-security-connection.js +25 -12
  126. package/dist/db/row-level-security-scope.d.ts +2 -1
  127. package/dist/db/row-level-security-scope.js +9 -5
  128. package/dist/db/sql-identifier.d.ts +1 -0
  129. package/dist/db/sql-identifier.js +3 -0
  130. package/dist/db/system-tenant-read-db.d.ts +5 -0
  131. package/dist/db/system-tenant-read-db.js +28 -0
  132. package/dist/db/table-builder.d.ts +3 -1
  133. package/dist/db/table-builder.js +18 -8
  134. package/dist/db/table-info.d.ts +1 -2
  135. package/dist/db/table-introspection.d.ts +3 -0
  136. package/dist/db/table-introspection.js +6 -0
  137. package/dist/db/table-push.d.ts +1 -0
  138. package/dist/db/table-push.js +7 -1
  139. package/dist/db/tenant-db-runner.d.ts +3 -0
  140. package/dist/db/tenant-db-runner.js +19 -1
  141. package/dist/db/transaction-serialization.d.ts +1 -0
  142. package/dist/db/transaction-serialization.js +20 -3
  143. package/dist/db/where-clause.js +11 -2
  144. package/dist/db/write-ownership-failures.d.ts +25 -0
  145. package/dist/db/write-ownership-failures.js +82 -0
  146. package/dist/engine/boot-validator/boot-check.js +7 -1
  147. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  148. package/dist/engine/boot-validator/boot-phases.js +3 -2
  149. package/dist/engine/boot-validator/boot-rules.d.ts +293 -26
  150. package/dist/engine/boot-validator/boot-rules.js +4 -0
  151. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  152. package/dist/engine/boot-validator/card-meta-overflow.js +1 -0
  153. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  154. package/dist/engine/boot-validator/config-deps.js +0 -28
  155. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  156. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  157. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  158. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  159. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  160. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  161. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  162. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  163. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  164. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  165. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  166. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  167. package/dist/engine/boot-validator/entity-list-screens.js +33 -6
  168. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  169. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  170. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  171. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  172. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  173. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  174. package/dist/engine/boot-validator/list-row-guidance.js +129 -0
  175. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  176. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  177. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  178. package/dist/engine/boot-validator/list-sort-summary.js +149 -0
  179. package/dist/engine/boot-validator/list-table-options.js +15 -1
  180. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  181. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  182. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  183. package/dist/engine/boot-validator/list-toolbar-options.js +31 -0
  184. package/dist/engine/boot-validator/named-filter-rules.d.ts +32 -2
  185. package/dist/engine/boot-validator/named-filter-rules.js +32 -2
  186. package/dist/engine/boot-validator/ownership.js +10 -1
  187. package/dist/engine/boot-validator/parent-ref.js +87 -50
  188. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  189. package/dist/engine/boot-validator/projection-list-screens.js +31 -1
  190. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  191. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  192. package/dist/engine/boot-validator/query-output-guidance.js +39 -0
  193. package/dist/engine/boot-validator/query-refs.js +24 -1
  194. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  195. package/dist/engine/boot-validator/row-decoration.js +16 -0
  196. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  197. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  198. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  199. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  200. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  201. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  202. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  203. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  204. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  205. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  206. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  207. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  208. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  209. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  210. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  211. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  212. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  213. package/dist/engine/boot-validator/screens-lists.js +19 -3
  214. package/dist/engine/boot-validator/screens.js +1 -1
  215. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  216. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  217. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  218. package/dist/engine/boot-validator/zod-shape.js +19 -1
  219. package/dist/engine/build-app-schema.js +4 -0
  220. package/dist/engine/config-helpers.d.ts +1 -2
  221. package/dist/engine/config-helpers.js +6 -7
  222. package/dist/engine/define-feature.js +1 -0
  223. package/dist/engine/define-handler.d.ts +1 -0
  224. package/dist/engine/define-handler.js +4 -2
  225. package/dist/engine/definition-violations.js +2 -2
  226. package/dist/engine/entity-handlers.js +3 -8
  227. package/dist/engine/entity-list-runtime-options.js +9 -8
  228. package/dist/engine/factories.d.ts +2 -0
  229. package/dist/engine/feature-config-events-jobs.js +1 -0
  230. package/dist/engine/feature-entity-handlers.js +5 -2
  231. package/dist/engine/field-access.d.ts +1 -1
  232. package/dist/engine/field-access.js +7 -10
  233. package/dist/engine/find-entity.js +3 -3
  234. package/dist/engine/form-derivations.js +3 -3
  235. package/dist/engine/index.d.ts +3 -3
  236. package/dist/engine/index.js +2 -2
  237. package/dist/engine/named-filter-roles.d.ts +3 -0
  238. package/dist/engine/named-filter-roles.js +23 -0
  239. package/dist/engine/pipeline.js +0 -1
  240. package/dist/engine/project-app-schema-for-roles.js +17 -2
  241. package/dist/engine/qualified-name.js +0 -1
  242. package/dist/engine/registry-facade.js +1 -2
  243. package/dist/engine/registry-state.d.ts +1 -1
  244. package/dist/engine/registry-state.js +5 -2
  245. package/dist/engine/registry-validate.d.ts +1 -0
  246. package/dist/engine/registry-validate.js +9 -1
  247. package/dist/engine/registry.js +2 -1
  248. package/dist/engine/resolve-named-list-filters.js +5 -2
  249. package/dist/engine/schema-builder.js +6 -10
  250. package/dist/engine/screen-helpers.d.ts +12 -0
  251. package/dist/engine/screen-helpers.js +17 -1
  252. package/dist/engine/soft-delete-cleanup.js +5 -8
  253. package/dist/engine/state-machine.js +0 -1
  254. package/dist/engine/steps/_database-clock.d.ts +2 -0
  255. package/dist/engine/steps/_database-clock.js +6 -0
  256. package/dist/engine/steps/compute.js +1 -1
  257. package/dist/engine/steps/retry.js +5 -1
  258. package/dist/engine/steps/return.js +0 -1
  259. package/dist/engine/steps/wait-for-event.js +2 -1
  260. package/dist/engine/steps/wait.js +2 -1
  261. package/dist/engine/system-user.d.ts +2 -2
  262. package/dist/engine/system-user.js +2 -2
  263. package/dist/engine/types/handlers.d.ts +1 -1
  264. package/dist/engine/types/handlers.js +1 -1
  265. package/dist/engine/types/screen.d.ts +1 -1
  266. package/dist/engine/types/screen.js +1 -1
  267. package/dist/engine/webhook-contracts.d.ts +2 -3
  268. package/dist/engine/webhook-contracts.js +2 -25
  269. package/dist/engine/webhook-events.js +48 -29
  270. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  271. package/dist/engine/webhook-payload-strictness.js +53 -0
  272. package/dist/env/_zod-introspect.d.ts +1 -0
  273. package/dist/env/dry-run.d.ts +1 -1
  274. package/dist/env/dry-run.js +1 -1
  275. package/dist/env/field-meta.d.ts +4 -0
  276. package/dist/env/field-meta.js +67 -0
  277. package/dist/env/field-rules.d.ts +9 -0
  278. package/dist/env/field-rules.js +46 -0
  279. package/dist/env/index.d.ts +3 -3
  280. package/dist/env/index.js +16 -71
  281. package/dist/env/internals.d.ts +3 -0
  282. package/dist/env/internals.js +1 -2
  283. package/dist/env/required-env.d.ts +3 -1
  284. package/dist/env/required-env.js +5 -2
  285. package/dist/errors/serialize.js +2 -2
  286. package/dist/errors/write-error-info.js +0 -2
  287. package/dist/es-ops/operations-schema.js +18 -7
  288. package/dist/event-store/admin-api.js +3 -3
  289. package/dist/event-store/event-store.js +0 -3
  290. package/dist/event-store/index.d.ts +1 -0
  291. package/dist/event-store/index.js +1 -0
  292. package/dist/event-store/transfer.js +1 -1
  293. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  294. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  295. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  296. package/dist/files/bind-pending-file-refs.js +54 -27
  297. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  298. package/dist/files/create-file-ref.d.ts +4 -1
  299. package/dist/files/create-file-ref.js +14 -3
  300. package/dist/files/default-file-guard.js +4 -1
  301. package/dist/files/feature.js +1 -0
  302. package/dist/files/file-claim.d.ts +6 -0
  303. package/dist/files/file-claim.js +17 -0
  304. package/dist/files/file-field-slots.d.ts +2 -0
  305. package/dist/files/file-field-slots.js +28 -0
  306. package/dist/files/file-ref-entity.d.ts +3 -0
  307. package/dist/files/file-ref-entity.js +2 -0
  308. package/dist/files/file-ref-table.d.ts +3 -0
  309. package/dist/files/file-routes.d.ts +4 -1
  310. package/dist/files/file-routes.js +80 -16
  311. package/dist/files/in-memory-provider.d.ts +1 -1
  312. package/dist/files/in-memory-provider.js +2 -1
  313. package/dist/files/index.d.ts +1 -1
  314. package/dist/files/index.js +1 -1
  315. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  316. package/dist/files/invalid-file-ref-error.js +15 -0
  317. package/dist/files/local-provider.js +9 -2
  318. package/dist/files/provider-resolver.js +1 -1
  319. package/dist/files/rebind-file-ref.d.ts +3 -2
  320. package/dist/files/rebind-file-ref.js +24 -18
  321. package/dist/files/resolve-file-handles.d.ts +13 -0
  322. package/dist/files/resolve-file-handles.js +57 -0
  323. package/dist/files/storage-tracking.d.ts +1 -1
  324. package/dist/files/storage-tracking.js +5 -2
  325. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  326. package/dist/files/types.d.ts +4 -0
  327. package/dist/files/types.js +10 -0
  328. package/dist/files/upload-field-resolution.d.ts +1 -0
  329. package/dist/files/upload-field-resolution.js +16 -2
  330. package/dist/files/upload-ledger.js +1 -1
  331. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  332. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  333. package/dist/i18n/required-surface-keys.js +19 -4
  334. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  335. package/dist/internal/boot-rule-table-expectations.js +29 -0
  336. package/dist/internal/row-level-security.d.ts +1 -0
  337. package/dist/internal/row-level-security.js +1 -0
  338. package/dist/internal/testing.d.ts +1 -0
  339. package/dist/internal/testing.js +1 -0
  340. package/dist/jobs/index.d.ts +1 -0
  341. package/dist/jobs/index.js +1 -0
  342. package/dist/jobs/job-load-events.d.ts +10 -0
  343. package/dist/jobs/job-load-events.js +12 -0
  344. package/dist/jobs/job-runner-context.js +6 -158
  345. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  346. package/dist/jobs/job-runner-dispatch.js +57 -0
  347. package/dist/jobs/job-runner-event-triggers.js +18 -9
  348. package/dist/jobs/job-runner-execution.js +2 -2
  349. package/dist/jobs/job-runner-facets.d.ts +48 -0
  350. package/dist/jobs/job-runner-facets.js +156 -0
  351. package/dist/jobs/job-runner-gates.js +24 -12
  352. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  353. package/dist/jobs/job-runner-helpers.js +18 -3
  354. package/dist/jobs/job-runner-scope.d.ts +1 -0
  355. package/dist/jobs/job-runner-scope.js +2 -0
  356. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  357. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  358. package/dist/jobs/job-runner.js +31 -70
  359. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  360. package/dist/jobs/obliterate-job-queues.js +23 -0
  361. package/dist/lifecycle/lifecycle.js +1 -1
  362. package/dist/migrations/event-header-scrub.d.ts +11 -0
  363. package/dist/migrations/event-header-scrub.js +33 -0
  364. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  365. package/dist/migrations/event-payload-scrub.js +36 -4
  366. package/dist/migrations/index.d.ts +1 -0
  367. package/dist/migrations/index.js +2 -0
  368. package/dist/migrations/kumiko-drift.d.ts +5 -2
  369. package/dist/migrations/kumiko-drift.js +51 -14
  370. package/dist/migrations/pending-rebuilds.js +4 -5
  371. package/dist/observability/sensitive-filter.js +0 -12
  372. package/dist/pipeline/aggregate-type-removal.js +17 -4
  373. package/dist/pipeline/context-services.d.ts +2 -0
  374. package/dist/pipeline/context-services.js +5 -2
  375. package/dist/pipeline/dispatch-batch.js +4 -3
  376. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  377. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  378. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  379. package/dist/pipeline/dispatch-nested-write.js +119 -0
  380. package/dist/pipeline/dispatch-query.js +10 -3
  381. package/dist/pipeline/dispatch-scope.js +4 -3
  382. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  383. package/dist/pipeline/dispatch-shared.js +6 -38
  384. package/dist/pipeline/dispatch-write.d.ts +0 -1
  385. package/dist/pipeline/dispatch-write.js +3 -302
  386. package/dist/pipeline/dispatcher-utils.js +6 -0
  387. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  388. package/dist/pipeline/effective-system-scope.js +22 -0
  389. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  390. package/dist/pipeline/event-dispatcher-delivery.js +17 -9
  391. package/dist/pipeline/event-dispatcher.d.ts +4 -1
  392. package/dist/pipeline/event-dispatcher.js +6 -7
  393. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  394. package/dist/pipeline/handler-context-auth.js +3 -4
  395. package/dist/pipeline/handler-context-db.js +11 -4
  396. package/dist/pipeline/handler-context-dispatch.js +2 -2
  397. package/dist/pipeline/handler-context-events.d.ts +8 -3
  398. package/dist/pipeline/handler-context-events.js +20 -65
  399. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  400. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  401. package/dist/pipeline/handler-context-notify.js +2 -0
  402. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  403. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  404. package/dist/pipeline/handler-context-projection.js +39 -0
  405. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  406. package/dist/pipeline/handler-context-scope.js +14 -2
  407. package/dist/pipeline/index.d.ts +1 -1
  408. package/dist/pipeline/index.js +1 -1
  409. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  410. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  411. package/dist/pipeline/member-reader.js +4 -2
  412. package/dist/pipeline/msp-rebuild.js +1 -1
  413. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  414. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  415. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  416. package/dist/pipeline/projection-rebuild.js +16 -7
  417. package/dist/pipeline/projection-state.js +4 -6
  418. package/dist/pipeline/system-hooks.js +36 -6
  419. package/dist/pipeline/write-result-masking.js +31 -3
  420. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  421. package/dist/pipeline/write-transition-guard.js +95 -0
  422. package/dist/schema-cli/shared.d.ts +2 -0
  423. package/dist/schema-cli/shared.js +4 -2
  424. package/dist/schema-cli/validate-command.js +43 -28
  425. package/dist/search/meilisearch-adapter.js +14 -9
  426. package/dist/search/reindex-entity.d.ts +2 -0
  427. package/dist/search/reindex-entity.js +32 -4
  428. package/dist/search/reindex-tenants-search.js +20 -4
  429. package/dist/time/tz-context.js +1 -1
  430. package/dist/ui-types/card-column-roles.d.ts +4 -0
  431. package/dist/ui-types/card-column-roles.js +6 -3
  432. package/dist/ui-types/index.d.ts +2 -2
  433. package/dist/ui-types/index.js +1 -1
  434. package/dist/utils/ids.js +0 -1
  435. package/dist/utils/index.d.ts +1 -0
  436. package/dist/utils/index.js +1 -0
  437. package/dist/utils/return-path-limit.d.ts +1 -0
  438. package/dist/utils/return-path-limit.js +1 -0
  439. package/package.json +5 -3
  440. package/presets/biome-app.json +39 -21
  441. package/presets/biome-plugins/admin-api.grit +10 -0
  442. package/presets/biome-plugins/error-reasons.grit +53 -0
  443. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  444. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  445. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  446. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  447. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  448. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  449. package/presets/biome-plugins/no-date-api.grit +9 -0
  450. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  451. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  452. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  453. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  454. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  455. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  456. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  457. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  458. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  459. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  460. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  461. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  462. package/presets/biome-plugins/test-title.grit +20 -0
  463. package/presets/biome-plugins/unsafe-json-parse.grit +6 -0
  464. package/presets/biome-rules.json +465 -0
  465. package/src/changes.json +309 -0
  466. package/dist/engine/minor-units.d.ts +0 -2
  467. package/dist/engine/minor-units.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Row level security part of the migration generator: diffs the per-table policy
2
2
  // specs between two snapshots and renders the resulting DDL section.
3
- import { isSameTableRowLevelSecurity, renderDisableRowLevelSecurity, renderEnableRowLevelSecurity, } from "./render-rls-ddl.js";
3
+ import { isSameTableRowLevelSecurity, renderDisableRowLevelSecurity, renderDropPolicy, renderEnableRowLevelSecurity, } from "./render-rls-ddl.js";
4
4
  import { quoteIdent } from "./sql-identifier.js";
5
5
  function specOf(view, tableName) {
6
6
  const byTable = view?.rowLevelSecurity;
@@ -59,3 +59,17 @@ export function renderRowLevelSecurityChanges(changes = []) {
59
59
  "",
60
60
  ];
61
61
  }
62
+ // Postgres refuses ALTER COLUMN TYPE / DROP COLUMN on a column a policy still references, so the
63
+ // previous policies must go before the in-place table changes; the section after them recreates them.
64
+ export function renderPolicyDropsBeforeTenantColumnChange(changes = [], tablesChangingTenantColumn) {
65
+ const statements = changes.flatMap((change) => {
66
+ if (!tablesChangingTenantColumn.has(change.tableName) || change.previous === undefined) {
67
+ return [];
68
+ }
69
+ const tableSql = quoteIdent(change.tableName);
70
+ return change.previous.policies.map((policy) => renderDropPolicy(tableSql, policy.name));
71
+ });
72
+ if (statements.length === 0)
73
+ return [];
74
+ return ["-- === Row level security (pre) ===", ...statements, ""];
75
+ }
@@ -19,7 +19,7 @@ import { join } from "node:path";
19
19
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
20
20
  import { applyRowLevelSecurityScope } from "./queries/rls-scope.js";
21
21
  import { asRawClient, hasBegin, } from "./query.js";
22
- import { SYSTEM_ROW_LEVEL_SECURITY_SCOPE } from "./row-level-security-scope.js";
22
+ import { systemRowLevelSecurityScope } from "./row-level-security-scope.js";
23
23
  // Advisory-lock key (random 32-bit integer, stable). Prevents two Pods
24
24
  // booting at the same time from both running migrate apply (the second
25
25
  // blocks until the first finishes).
@@ -264,7 +264,7 @@ export async function runMigrations(db, migrations) {
264
264
  await conn.unsafe("BEGIN");
265
265
  try {
266
266
  // Transaction-local, so the next migration's BEGIN starts clean; migrations rewrite every tenant's rows.
267
- await applyRowLevelSecurityScope(conn, SYSTEM_ROW_LEVEL_SECURITY_SCOPE);
267
+ await applyRowLevelSecurityScope(conn, systemRowLevelSecurityScope("migration run"));
268
268
  for (const stmt of m.statements) {
269
269
  await conn.unsafe(stmt);
270
270
  }
@@ -1,5 +1,5 @@
1
1
  import type { EntityDefinition } from "@cosmicdrift/kumiko-types/fields";
2
- import { toMinorUnits } from "../engine/minor-units.ts";
2
+ import { toMinorUnits } from "@cosmicdrift/kumiko-types/minor-units";
3
3
  export declare const FRAMEWORK_DEFAULT_CURRENCY: "EUR";
4
4
  export { toMinorUnits };
5
5
  export declare function moneyPayloadToMinorUnits(raw: unknown): number | undefined;
package/dist/db/money.js CHANGED
@@ -31,12 +31,9 @@ import { DEFAULT_CURRENCIES } from "../engine/field-helpers.js";
31
31
  // Unlike locatedTimestamp, we retain the field name `<name>` as the
32
32
  // amount column (legacy DB convention for money — `SUM(buying_price)` remains
33
33
  // idiomatic). `<name>Currency` is the additional column.
34
- import { MINOR_UNIT_SCALE, toMinorUnits } from "../engine/minor-units.js";
34
+ import { toMajorUnits, toMinorUnits } from "@cosmicdrift/kumiko-types/minor-units";
35
35
  export const FRAMEWORK_DEFAULT_CURRENCY = DEFAULT_CURRENCIES[0]; // "EUR"
36
36
  export { toMinorUnits };
37
- function toMajorUnits(amountScaled) {
38
- return amountScaled / MINOR_UNIT_SCALE;
39
- }
40
37
  // One money field's write payload — `{ amount, currency }` or a bare number
41
38
  // (both MAJOR units, see file header) — reduced to minor units. This is the
42
39
  // counterpart a write-handler needs when comparing a top-level money field
@@ -5,8 +5,12 @@ import type { SessionUser } from "../engine/types/index.ts";
5
5
  import type { Table } from "./event-store-executor-context.ts";
6
6
  import type { TenantDb } from "./tenant-db.ts";
7
7
  export type { ParentVisibilityOption } from "@cosmicdrift/kumiko-types/event-store-executor-types";
8
- export declare function buildParentRefClause(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: {
8
+ type ParentRefGateOptions = {
9
9
  readonly includeDeleted?: boolean;
10
10
  readonly narrowTypes?: ReadonlySet<string>;
11
11
  readonly requireReadHandler?: boolean;
12
- }): OwnershipClause;
12
+ };
13
+ export type ParentRefGateMode = "statement" | "globalHostsOnly";
14
+ export declare function buildParentRefClause(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: ParentRefGateOptions): OwnershipClause;
15
+ export declare function readsGlobalHostsUnderTenantScope(db: TenantDb, joinTable: Table): boolean;
16
+ export declare function buildParentRefGate(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: ParentRefGateOptions, mode: ParentRefGateMode): OwnershipClause;
@@ -2,6 +2,7 @@ import { buildOwnershipClause } from "../engine/ownership.js";
2
2
  import { SYSTEM_TENANT_ID, UUID_SHAPE_PATTERN } from "../engine/types/identifiers.js";
3
3
  import { buildEntityTable, physicalColumnName } from "./table-builder.js";
4
4
  import { schemaTableName } from "./table-introspection.js";
5
+ import { isGlobalTenancyTable } from "./tenant-db-runner.js";
5
6
  const candidateStaticsCache = new WeakMap();
6
7
  function candidateStaticsFor(candidateName, candidate, resolveTable) {
7
8
  if (resolveTable !== undefined)
@@ -49,6 +50,14 @@ function selectCandidates(parentRef, option, narrowTypes, requireReadHandler) {
49
50
  return candidates;
50
51
  }
51
52
  export function buildParentRefClause(entity, table, tableName, user, db, option, opts) {
53
+ return buildParentRefGate(entity, table, tableName, user, db, option, opts, "statement");
54
+ }
55
+ // A tenant-scoped statement reads a global host table under row level security, which hides the
56
+ // system tenant rows a global host lives on; a join table that is global itself runs in the system scope.
57
+ export function readsGlobalHostsUnderTenantScope(db, joinTable) {
58
+ return db.mode === "tenant" && !isGlobalTenancyTable(joinTable);
59
+ }
60
+ export function buildParentRefGate(entity, table, tableName, user, db, option, opts, mode) {
52
61
  const parentRef = entity.parentRef;
53
62
  if (parentRef === undefined)
54
63
  return { kind: "pass" };
@@ -70,40 +79,84 @@ export function buildParentRefClause(entity, table, tableName, user, db, option,
70
79
  const candidates = selectCandidates(parentRef, option, opts.narrowTypes, opts.requireReadHandler === true);
71
80
  if (candidates.length === 0)
72
81
  return { kind: "empty" };
73
- // The uuid shape and the tenant ids are bound once and shared by every
74
- // branch. The shape is a parameter rather than a literal because shiftParams
75
- // rewrites `$<digits>` anywhere in the text, including inside a string.
76
- const params = [UUID_SHAPE_PATTERN];
77
- const uuidIdx = params.length;
78
- let tenantIdx;
79
- if (db.mode === "tenant") {
80
- params.push(db.tenantId, SYSTEM_TENANT_ID);
81
- tenantIdx = [params.length - 1, params.length];
82
- }
82
+ const { branches, params } = collectGateBranches(candidates, mode, {
83
+ db,
84
+ user,
85
+ option,
86
+ joinTableName: tableName,
87
+ typeCol,
88
+ idCol,
89
+ includeDeleted: opts.includeDeleted === true,
90
+ globalHostsHidden: readsGlobalHostsUnderTenantScope(db, table),
91
+ });
92
+ if (branches.length === 0)
93
+ return { kind: "empty" };
94
+ return { kind: "sql", sqlText: `(${branches.join(" OR ")})`, params };
95
+ }
96
+ function collectGateBranches(candidates, mode, gate) {
97
+ // The uuid shape and the tenant ids are bound once, together with the first kept
98
+ // EXISTS branch, and shared by every later one: Postgres rejects a statement with
99
+ // a parameter it cannot type, which an unused one is. The shape is a parameter
100
+ // rather than a literal because shiftParams rewrites `$<digits>` anywhere in the
101
+ // text, including inside a string.
102
+ const params = [];
103
+ let shared;
83
104
  const branches = [];
84
105
  for (const [candidateName, candidate] of candidates) {
85
- const branch = buildCandidateBranch(candidateName, candidate, user, {
86
- joinTableName: tableName,
87
- typeCol,
88
- idCol,
89
- uuidIdx,
90
- tenantIdx,
91
- includeDeleted: opts.includeDeleted === true,
106
+ const isHiddenGlobalHost = gate.globalHostsHidden && candidate.tenancy === "global";
107
+ if (mode === "globalHostsOnly" && !isHiddenGlobalHost)
108
+ continue;
109
+ const resolvesHostIds = mode === "statement" && isHiddenGlobalHost;
110
+ const pendingShared = resolvesHostIds || shared !== undefined
111
+ ? undefined
112
+ : planSharedBinding(gate.db, params.length);
113
+ const binding = pendingShared ?? shared;
114
+ const branchContext = {
115
+ joinTableName: gate.joinTableName,
116
+ typeCol: gate.typeCol,
117
+ idCol: gate.idCol,
118
+ uuidIdx: binding?.uuidIdx ?? 0,
119
+ tenantIdx: binding?.tenantIdx,
120
+ includeDeleted: gate.includeDeleted,
92
121
  // Ownership params are laid out right after the branch's own host-type
93
122
  // placeholder. Nothing reaches the shared `params` until the branch is
94
123
  // kept, so a dropped branch reserves no index and can't shift the
95
124
  // positional binding of the branches after it.
96
- typeParamIdx: params.length + 1,
97
- resolveTable: option.resolveTable,
98
- });
125
+ typeParamIdx: params.length + (pendingShared?.values.length ?? 0) + 1,
126
+ resolveTable: gate.option.resolveTable,
127
+ };
128
+ const branch = resolvesHostIds
129
+ ? buildResolvedHostBranch(gate.option.globalHostIds?.get(candidateName), branchContext)
130
+ : buildCandidateBranch(candidateName, candidate, gate.user, branchContext);
99
131
  if (branch === undefined)
100
132
  continue;
133
+ if (pendingShared !== undefined) {
134
+ params.push(...pendingShared.values);
135
+ shared = pendingShared;
136
+ }
101
137
  params.push(candidateName, ...branch.params);
102
138
  branches.push(branch.sqlText);
103
139
  }
104
- if (branches.length === 0)
105
- return { kind: "empty" };
106
- return { kind: "sql", sqlText: `(${branches.join(" OR ")})`, params };
140
+ return { branches, params };
141
+ }
142
+ function planSharedBinding(db, boundSoFar) {
143
+ if (db.mode !== "tenant") {
144
+ return { values: [UUID_SHAPE_PATTERN], uuidIdx: boundSoFar + 1, tenantIdx: undefined };
145
+ }
146
+ return {
147
+ values: [UUID_SHAPE_PATTERN, db.tenantId, SYSTEM_TENANT_ID],
148
+ uuidIdx: boundSoFar + 1,
149
+ tenantIdx: [boundSoFar + 2, boundSoFar + 3],
150
+ };
151
+ }
152
+ // Unresolved ids leave the arm out: a host the statement cannot check is never treated as readable.
153
+ function buildResolvedHostBranch(hostIds, ctx) {
154
+ if (hostIds === undefined || hostIds.length === 0)
155
+ return undefined;
156
+ return {
157
+ sqlText: `("${ctx.joinTableName}"."${ctx.typeCol}" = $${ctx.typeParamIdx} AND "${ctx.joinTableName}"."${ctx.idCol}"::text = ANY($${ctx.typeParamIdx + 1}::text[]))`,
158
+ params: [hostIds],
159
+ };
107
160
  }
108
161
  // One `entity_type = $n AND EXISTS (...)` arm, or undefined when the host's own
109
162
  // read ownership can never match — an unsatisfiable arm is dropped rather than
@@ -0,0 +1,20 @@
1
+ import type { ParentVisibilityOption } from "@cosmicdrift/kumiko-types/event-store-executor-types";
2
+ import type { EntityDefinition } from "@cosmicdrift/kumiko-types/fields";
3
+ import type { EntityId } from "@cosmicdrift/kumiko-types/identifiers";
4
+ import type { SessionUser } from "../engine/types/index.ts";
5
+ import type { Table } from "./event-store-executor-context.ts";
6
+ import type { TenantDb } from "./tenant-db.ts";
7
+ export type GlobalHostRowScope = {
8
+ readonly kind: "row";
9
+ readonly rowId: EntityId;
10
+ } | {
11
+ readonly kind: "list";
12
+ readonly pinnedHostIds: ReadonlySet<string> | undefined;
13
+ };
14
+ export declare function withGlobalParentHosts(ctx: {
15
+ readonly entity: EntityDefinition;
16
+ readonly table: Table;
17
+ }, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, gate: {
18
+ readonly includeDeleted: boolean;
19
+ readonly narrowTypes: ReadonlySet<string> | undefined;
20
+ }, rowScope: GlobalHostRowScope): Promise<ParentVisibilityOption | undefined>;
@@ -0,0 +1,47 @@
1
+ import { buildParentRefGate, readsGlobalHostsUnderTenantScope } from "./parent-ref-clause.js";
2
+ import { executeRawQueryRead } from "./queries/raw-sql.js";
3
+ import { systemScopedRunner } from "./row-level-security-scope.js";
4
+ import { physicalColumnName } from "./table-builder.js";
5
+ import { schemaTableName } from "./table-introspection.js";
6
+ import { tenantDbRunner } from "./tenant-db-runner.js";
7
+ // The gated statement runs under the tenant scope, where a global host's EXISTS sees no row. The
8
+ // same host check runs here in the system scope, limited to the caller's join rows by an explicit
9
+ // tenant filter, and only host ids leave it; the gated statement keeps its own row level security.
10
+ export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScope) {
11
+ const { entity, table } = ctx;
12
+ const parentRef = entity.parentRef;
13
+ if (option === undefined || parentRef === undefined || db.mode !== "tenant")
14
+ return option;
15
+ if (!readsGlobalHostsUnderTenantScope(db, table) || table["tenantId"] === undefined) {
16
+ return option;
17
+ }
18
+ const joinTableName = String(schemaTableName(table));
19
+ const hostCheck = buildParentRefGate(entity, table, joinTableName, user, db, option, gate, "globalHostsOnly");
20
+ if (hostCheck.kind !== "sql")
21
+ return option;
22
+ if (rowScope.kind === "list" && rowScope.pinnedHostIds?.size === 0) {
23
+ return { ...option, globalHostIds: new Map() };
24
+ }
25
+ const params = [...hostCheck.params, db.tenantId];
26
+ const column = (field) => `"${joinTableName}"."${physicalColumnName(table, field)}"`;
27
+ const whereParts = [`${column("tenantId")} = $${params.length}`, hostCheck.sqlText];
28
+ if (rowScope.kind === "row") {
29
+ params.push(rowScope.rowId);
30
+ whereParts.push(`${column("id")} = $${params.length}`);
31
+ }
32
+ else if (rowScope.pinnedHostIds !== undefined) {
33
+ params.push([...rowScope.pinnedHostIds]);
34
+ whereParts.push(`${column(parentRef.entityIdField)}::text = ANY($${params.length}::text[])`);
35
+ }
36
+ const rows = await executeRawQueryRead(systemScopedRunner(tenantDbRunner(db), "parent-ref gate checks global hosts, whose rows carry the system tenant, for the caller's own join rows"), `SELECT DISTINCT ${column(parentRef.entityTypeField)}::text AS "entityType", ${column(parentRef.entityIdField)}::text AS "entityId" ` +
37
+ `FROM "${joinTableName}" WHERE ${whereParts.join(" AND ")}`, params);
38
+ const globalHostIds = new Map();
39
+ for (const row of rows) {
40
+ const ids = globalHostIds.get(row.entityType);
41
+ if (ids === undefined)
42
+ globalHostIds.set(row.entityType, [row.entityId]);
43
+ else
44
+ ids.push(row.entityId);
45
+ }
46
+ return { ...option, globalHostIds };
47
+ }
@@ -0,0 +1 @@
1
+ export declare const PRODUCTION_SCHEMA_COMMAND_HINT = "In the production image run `bun /app/kumiko.js schema <subcommand>` instead of `bun kumiko-schema <subcommand>`.";
@@ -0,0 +1,3 @@
1
+ // The `kumiko-schema` bin ships with dev-server and is absent from the production image, whose
2
+ // standalone bundle only understands `kumiko schema …`; boot errors fire in both places.
3
+ export const PRODUCTION_SCHEMA_COMMAND_HINT = "In the production image run `bun /app/kumiko.js schema <subcommand>` instead of `bun kumiko-schema <subcommand>`.";
@@ -45,7 +45,10 @@
45
45
  // tenant-keyed ciphertext of a userOwned field moves under the user the
46
46
  // strict chain (stages 1+2, never whenAbsent) names; user-keyed ciphertext
47
47
  // moves under the projection's current owner when that is another user (an
48
- // owner change made before owner transitions re-keyed the value). An owner
48
+ // owner change made before owner transitions re-keyed the value). Only the latest
49
+ // event that carries the field moves: older events were written for the previous
50
+ // owner, and a newer event means the live path already re-keyed the value, so a
51
+ // forget of the previous owner must keep erasing the older ones. An owner
49
52
  // cleared again (owner → none) is not recoverable from the projection: such
50
53
  // values stay tenant-keyed, unlike the live path that keeps the last owner.
51
54
  // For whenAbsent: "self" fields the same stage moves tenant-keyed ciphertext
@@ -130,6 +133,36 @@ async function backfillAllEventBatches(db, registry, options) {
130
133
  }
131
134
  return { ...total, failures };
132
135
  }
136
+ function failureReason(e) {
137
+ const reason = e instanceof Error ? e.message : String(e);
138
+ if (!(e instanceof SubjectResolutionError))
139
+ return reason;
140
+ return (`${reason} (retry with { resolveOwnerFromProjection: true } to resolve the owner ` +
141
+ "from the entity's projection table, and/or { eraseUnresolvableSubjects: true } to " +
142
+ "erase fields whose subject stays unresolvable)");
143
+ }
144
+ function selectEventBatch(raw, aggregateTypes, catalogTypes, options, batchSize) {
145
+ if (options.eventIds) {
146
+ return raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
147
+ FROM "kumiko_events"
148
+ WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" = ANY($3::bigint[])
149
+ ORDER BY "id" ASC`, [
150
+ toPostgresArrayLiteral(aggregateTypes),
151
+ toPostgresArrayLiteral(catalogTypes),
152
+ toPostgresArrayLiteral([...options.eventIds]),
153
+ ]);
154
+ }
155
+ return raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
156
+ FROM "kumiko_events"
157
+ WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" > $3::bigint
158
+ ORDER BY "id" ASC
159
+ LIMIT $4`, [
160
+ toPostgresArrayLiteral(aggregateTypes),
161
+ toPostgresArrayLiteral(catalogTypes),
162
+ String(options.afterEventId ?? 0),
163
+ batchSize,
164
+ ]);
165
+ }
133
166
  // Processes exactly one batch. Snapshots of the batch's touched aggregates are
134
167
  // dropped inside the same call so an abort between batches never leaves a
135
168
  // snapshot that caches plaintext for an already-encrypted stream.
@@ -164,25 +197,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
164
197
  });
165
198
  if (aggregateTypes.length === 0 && catalogTypes.length === 0)
166
199
  return emptyBatch();
167
- const rows = await (options.eventIds
168
- ? raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
169
- FROM "kumiko_events"
170
- WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" = ANY($3::bigint[])
171
- ORDER BY "id" ASC`, [
172
- toPostgresArrayLiteral(aggregateTypes),
173
- toPostgresArrayLiteral(catalogTypes),
174
- toPostgresArrayLiteral([...options.eventIds]),
175
- ])
176
- : raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
177
- FROM "kumiko_events"
178
- WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" > $3::bigint
179
- ORDER BY "id" ASC
180
- LIMIT $4`, [
181
- toPostgresArrayLiteral(aggregateTypes),
182
- toPostgresArrayLiteral(catalogTypes),
183
- String(options.afterEventId ?? 0),
184
- batchSize,
185
- ]));
200
+ const rows = await selectEventBatch(raw, aggregateTypes, catalogTypes, options, batchSize);
186
201
  const last = rows[rows.length - 1];
187
202
  if (last === undefined)
188
203
  return emptyBatch();
@@ -214,16 +229,8 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
214
229
  touchedEventTypes.add(row.type);
215
230
  }
216
231
  catch (e) {
217
- const reason = e instanceof Error ? e.message : String(e);
218
232
  firstFailedEventId ??= String(row.id);
219
- result.failures.push({
220
- eventId: String(row.id),
221
- reason: e instanceof SubjectResolutionError
222
- ? `${reason} (retry with { resolveOwnerFromProjection: true } to resolve the owner ` +
223
- "from the entity's projection table, and/or { eraseUnresolvableSubjects: true } to " +
224
- "erase fields whose subject stays unresolvable)"
225
- : reason,
226
- });
233
+ result.failures.push({ eventId: String(row.id), reason: failureReason(e) });
227
234
  }
228
235
  }
229
236
  // Snapshots may cache the plaintext state of touched aggregates.
@@ -389,6 +396,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
389
396
  kmsCtx,
390
397
  dryRun: options.dryRun === true,
391
398
  isForgottenSubject: (subject) => isForgottenSubject(subject, row.aggregate_id),
399
+ hasNewerValueOfField: (fieldName) => aggregateHasNewerValueOfField(row, fieldName),
392
400
  predictOutcome: predictEncryptOutcome,
393
401
  }, {
394
402
  entity,
@@ -399,6 +407,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
399
407
  subjectSource,
400
408
  ownerFallback,
401
409
  projectionOwnerRow,
410
+ isSupersededHistory: section === payload["previous"] && isRecord(payload["changes"]),
402
411
  });
403
412
  if (rekey.kind === "rekeyed") {
404
413
  section[field] = rekey.value;
@@ -460,6 +469,19 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
460
469
  }
461
470
  return subject.kind === "user" && forgottenAggregates.has(subject.userId);
462
471
  }
472
+ // A later event that sets the field (`changes`, or the flat payload of a created event). An
473
+ // explicit null counts: it replaced the value this event carries, so that value is stale.
474
+ async function aggregateHasNewerValueOfField(event, fieldName) {
475
+ const rows = await raw.unsafe(`SELECT 1 AS found FROM "kumiko_events"
476
+ WHERE "aggregate_id" = $1 AND "tenant_id" = $2 AND "id" > $3::bigint
477
+ AND (
478
+ jsonb_exists("payload" -> 'changes', $4::text)
479
+ OR ("payload" -> 'changes' IS NULL AND "payload" -> 'previous' IS NULL
480
+ AND jsonb_exists("payload", $4::text))
481
+ )
482
+ LIMIT 1`, [event.aggregate_id, event.tenant_id, event.id, fieldName]);
483
+ return rows.length > 0;
484
+ }
463
485
  // A tenant destroyed before its name was record-owned never had a record key
464
486
  // to erase, and destroy tombstones the row instead of emitting *.forgotten —
465
487
  // read_tenants.destroyed_at is the only durable marker.
@@ -503,6 +525,10 @@ async function rekeyTenantKeyedValue(deps, target) {
503
525
  : null;
504
526
  if (userSubject === null)
505
527
  return { kind: "unchanged" };
528
+ if (keyedUnder?.kind === "user" &&
529
+ (target.isSupersededHistory || (await deps.hasNewerValueOfField(field)))) {
530
+ return { kind: "unchanged" };
531
+ }
506
532
  if (await deps.isForgottenSubject(userSubject))
507
533
  return { kind: "erased" };
508
534
  if (deps.dryRun) {
@@ -1,5 +1,5 @@
1
1
  import { asRawClient, transaction } from "../query.js";
2
- import { renderTableRowLevelSecurityDdl, tenantRowLevelSecurityFor } from "../render-rls-ddl.js";
2
+ import { renderDropPolicy, renderTableRowLevelSecurityDdl, SYSTEM_TENANT_READ_POLICY, tenantRowLevelSecurityFor, } from "../render-rls-ddl.js";
3
3
  import { quoteIdent } from "../sql-identifier.js";
4
4
  import { readRowLevelSecurityShape } from "./rls-shape.js";
5
5
  import { quoteTableIdent } from "./table-ops.js";
@@ -23,12 +23,19 @@ export async function createIndexIfNotExists(db, indexKind, indexName, tableName
23
23
  const where = whereSql !== undefined ? ` WHERE ${whereSql}` : "";
24
24
  await asRawClient(db).unsafe(`CREATE ${indexKind} IF NOT EXISTS ${quoteTableIdent(indexName)} ON ${quoteTableIdent(tableName)} (${columnList})${where}`);
25
25
  }
26
+ function expectsSystemReadPolicy(meta) {
27
+ return (tenantRowLevelSecurityFor(meta)?.policies.some((policy) => policy.name === SYSTEM_TENANT_READ_POLICY) === true);
28
+ }
26
29
  // Policy texts are not compared: a hand-edited kumiko policy is the operator's to keep, and the
27
30
  // catalog check of the boot path reports it. Foreign policies are ignored.
28
31
  function hasKumikoRowLevelSecurity(state, meta) {
29
32
  const spec = tenantRowLevelSecurityFor(meta);
30
33
  if (state === undefined || spec === undefined || !state.enabled || !state.forced)
31
34
  return false;
35
+ if (!expectsSystemReadPolicy(meta) &&
36
+ state.policies.some((actual) => actual.name === SYSTEM_TENANT_READ_POLICY)) {
37
+ return false;
38
+ }
32
39
  return spec.policies.every((expected) => state.policies.some((actual) => actual.name === expected.name &&
33
40
  actual.kind === expected.kind &&
34
41
  actual.command === expected.command));
@@ -49,7 +56,11 @@ export async function applyTableRowLevelSecurity(db, meta) {
49
56
  if (hasKumikoRowLevelSecurity(await readRowLevelSecurityShape(tx, meta.tableName), meta)) {
50
57
  return;
51
58
  }
52
- for (const statement of statements)
59
+ // A policy the table no longer qualifies for (marker removed) would survive the re-create below.
60
+ const staleSystemRead = expectsSystemReadPolicy(meta)
61
+ ? []
62
+ : [renderDropPolicy(quoteIdent(meta.tableName), SYSTEM_TENANT_READ_POLICY)];
63
+ for (const statement of [...staleSystemRead, ...statements])
53
64
  await tx.unsafe(statement);
54
65
  });
55
66
  }
@@ -0,0 +1,15 @@
1
+ import type { DbRunner } from "../connection.ts";
2
+ export type OpenStreamsArgs = {
3
+ readonly aggregateType: string;
4
+ readonly startedType: string;
5
+ readonly closingTypes: readonly string[];
6
+ readonly startedBeforeIso: string;
7
+ readonly limit: number;
8
+ readonly afterId?: string;
9
+ };
10
+ export type OpenStream = {
11
+ readonly id: string;
12
+ readonly tenantId: string;
13
+ readonly aggregateId: string;
14
+ };
15
+ export declare function selectOpenStreamsStartedBefore(db: DbRunner, args: OpenStreamsArgs): Promise<readonly OpenStream[]>;
@@ -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>;