@cosmicdrift/kumiko-framework 0.413.1 → 0.415.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (479) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +69 -13
  4. package/agents/api/framework-errors.md +1 -1
  5. package/agents/api/framework-event-store.md +14 -0
  6. package/agents/api/framework-ui-types.md +158 -21
  7. package/agents/api/renderer-web.md +112 -11
  8. package/agents/api/testing-helpers.md +3 -2
  9. package/agents/api/testing-stack.md +3 -0
  10. package/agents/api/types.md +248 -24
  11. package/agents/api.md +7 -7
  12. package/agents/boot-rules.md +66 -10
  13. package/agents/examples/api-docs.md +2 -6
  14. package/agents/examples/auth-mfa.md +57 -10
  15. package/agents/examples/chat-channels.md +2 -0
  16. package/agents/examples/crypto-shredding-hr.md +63 -1
  17. package/agents/examples/currencies-global.md +1 -0
  18. package/agents/examples/env-composition.md +7 -11
  19. package/agents/examples/managed-pages.md +90 -1
  20. package/agents/examples/pwa-shell.md +210 -0
  21. package/agents/examples/rate-limiting.md +3 -3
  22. package/agents/examples/record-detail-layout.md +1643 -67
  23. package/agents/examples/workflow-engine.md +16 -12
  24. package/agents/examples.md +1 -0
  25. package/agents/features-index.md +4 -2
  26. package/agents/features.md +22 -7
  27. package/agents/widgets.md +26 -1
  28. package/dist/api/api-constants.d.ts +1 -0
  29. package/dist/api/api-constants.js +4 -0
  30. package/dist/api/auth-middleware.js +4 -3
  31. package/dist/api/auth-routes-shared.js +2 -1
  32. package/dist/api/entity-read-access.d.ts +1 -0
  33. package/dist/api/entity-read-access.js +18 -0
  34. package/dist/api/export/export-route.d.ts +6 -1
  35. package/dist/api/export/export-route.js +27 -1
  36. package/dist/api/export/export-rows.js +19 -3
  37. package/dist/api/request-context-internals.d.ts +2 -0
  38. package/dist/api/request-context-scopes.js +9 -2
  39. package/dist/api/request-context.js +1 -1
  40. package/dist/api/routes.d.ts +2 -0
  41. package/dist/api/routes.js +9 -1
  42. package/dist/api/server-event-dispatcher.js +3 -0
  43. package/dist/api/server-extra-routes.js +2 -1
  44. package/dist/api/server-feature-http-routes.d.ts +9 -0
  45. package/dist/api/server-feature-http-routes.js +109 -0
  46. package/dist/api/server-middleware.js +2 -19
  47. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  48. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  49. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  50. package/dist/api/server-rate-limit-wiring.js +37 -0
  51. package/dist/api/server-routes.d.ts +4 -12
  52. package/dist/api/server-routes.js +12 -171
  53. package/dist/api/server-schema-route.d.ts +3 -0
  54. package/dist/api/server-schema-route.js +58 -0
  55. package/dist/api/server-wiring.js +2 -37
  56. package/dist/api/server.js +3 -1
  57. package/dist/compliance/override-schema.js +5 -5
  58. package/dist/compliance/sub-processors.js +10 -1
  59. package/dist/crypto/index.d.ts +1 -1
  60. package/dist/crypto/index.js +1 -1
  61. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  62. package/dist/crypto/pii-field-encryption.js +16 -1
  63. package/dist/db/apply-entity-event.js +4 -0
  64. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  65. package/dist/db/bun-sql-connection-codes.js +7 -0
  66. package/dist/db/collect-table-metas.js +4 -1
  67. package/dist/db/config-seed.js +1 -1
  68. package/dist/db/derived-field-sql.js +15 -13
  69. package/dist/db/derived-related-sql.d.ts +2 -2
  70. package/dist/db/derived-related-sql.js +4 -2
  71. package/dist/db/dialect.d.ts +3 -0
  72. package/dist/db/dialect.js +1 -3
  73. package/dist/db/driver-row-coercion.js +2 -2
  74. package/dist/db/driver-value-preparation.js +1 -1
  75. package/dist/db/eagerload.js +15 -12
  76. package/dist/db/entity-table-meta.d.ts +2 -0
  77. package/dist/db/entity-table-meta.js +7 -0
  78. package/dist/db/event-store-executor-context.js +13 -8
  79. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  80. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  81. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  82. package/dist/db/event-store-executor-read-filter.js +28 -11
  83. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  84. package/dist/db/event-store-executor-read-search.js +6 -6
  85. package/dist/db/event-store-executor-read-sort.js +3 -3
  86. package/dist/db/event-store-executor-read-where.js +14 -5
  87. package/dist/db/event-store-executor-read.js +7 -7
  88. package/dist/db/event-store-executor-write.js +50 -95
  89. package/dist/db/executor-managed-tables.js +4 -1
  90. package/dist/db/index.d.ts +4 -2
  91. package/dist/db/index.js +4 -2
  92. package/dist/db/known-table-names.d.ts +1 -0
  93. package/dist/db/known-table-names.js +7 -5
  94. package/dist/db/list-aggregate-labels.d.ts +1 -0
  95. package/dist/db/list-aggregate-labels.js +9 -1
  96. package/dist/db/migrate-generator.js +23 -4
  97. package/dist/db/migrate-rls-diff.d.ts +1 -0
  98. package/dist/db/migrate-rls-diff.js +15 -1
  99. package/dist/db/migrate-runner.js +2 -2
  100. package/dist/db/money.d.ts +1 -1
  101. package/dist/db/money.js +1 -4
  102. package/dist/db/parent-ref-clause.d.ts +6 -2
  103. package/dist/db/parent-ref-clause.js +105 -24
  104. package/dist/db/parent-ref-global-hosts.d.ts +23 -0
  105. package/dist/db/parent-ref-global-hosts.js +85 -0
  106. package/dist/db/production-schema-command-hint.d.ts +1 -0
  107. package/dist/db/production-schema-command-hint.js +3 -0
  108. package/dist/db/queries/backfill-pii.js +55 -29
  109. package/dist/db/queries/ddl.js +13 -2
  110. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  111. package/dist/db/queries/event-store-open-streams.js +33 -0
  112. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  113. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  114. package/dist/db/queries/event-store.js +0 -1
  115. package/dist/db/queries/raw-sql.js +0 -1
  116. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  117. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  118. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  119. package/dist/db/queries/rls-boot-catalog.js +13 -9
  120. package/dist/db/queries/rls-shape.d.ts +3 -1
  121. package/dist/db/queries/rls-shape.js +31 -6
  122. package/dist/db/queries/session-advisory-lock.js +2 -1
  123. package/dist/db/queries/test-stack.js +7 -7
  124. package/dist/db/query.js +16 -11
  125. package/dist/db/rebuild-marker.js +11 -2
  126. package/dist/db/render-rls-ddl.d.ts +2 -0
  127. package/dist/db/render-rls-ddl.js +16 -11
  128. package/dist/db/replay-migration-sql.js +1 -1
  129. package/dist/db/row-level-security-boot-check.js +18 -5
  130. package/dist/db/row-level-security-connection.js +25 -12
  131. package/dist/db/row-level-security-scope.d.ts +2 -1
  132. package/dist/db/row-level-security-scope.js +9 -5
  133. package/dist/db/sql-identifier.d.ts +1 -0
  134. package/dist/db/sql-identifier.js +3 -0
  135. package/dist/db/system-tenant-read-db.d.ts +5 -0
  136. package/dist/db/system-tenant-read-db.js +28 -0
  137. package/dist/db/table-builder.d.ts +3 -1
  138. package/dist/db/table-builder.js +18 -8
  139. package/dist/db/table-info.d.ts +1 -2
  140. package/dist/db/table-introspection.d.ts +3 -0
  141. package/dist/db/table-introspection.js +6 -0
  142. package/dist/db/table-push.d.ts +1 -0
  143. package/dist/db/table-push.js +7 -1
  144. package/dist/db/tenant-db-runner.d.ts +3 -0
  145. package/dist/db/tenant-db-runner.js +19 -1
  146. package/dist/db/transaction-serialization.d.ts +1 -0
  147. package/dist/db/transaction-serialization.js +20 -3
  148. package/dist/db/where-clause.js +11 -2
  149. package/dist/db/write-ownership-failures.d.ts +25 -0
  150. package/dist/db/write-ownership-failures.js +82 -0
  151. package/dist/engine/boot-validator/boot-check.js +7 -1
  152. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  153. package/dist/engine/boot-validator/boot-phases.js +3 -2
  154. package/dist/engine/boot-validator/boot-rules.d.ts +305 -28
  155. package/dist/engine/boot-validator/boot-rules.js +4 -0
  156. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  157. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  158. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  159. package/dist/engine/boot-validator/card-meta-overflow.js +8 -5
  160. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  161. package/dist/engine/boot-validator/config-deps.js +0 -28
  162. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  163. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  164. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  165. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  166. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  167. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  168. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  169. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  170. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  171. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  172. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  173. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  174. package/dist/engine/boot-validator/entity-list-screens.js +35 -13
  175. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  176. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  177. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  178. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  179. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  180. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  181. package/dist/engine/boot-validator/list-row-guidance.js +143 -0
  182. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  183. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  184. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  185. package/dist/engine/boot-validator/list-sort-summary.js +160 -0
  186. package/dist/engine/boot-validator/list-table-options.js +15 -1
  187. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  188. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  189. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  190. package/dist/engine/boot-validator/list-toolbar-options.js +30 -0
  191. package/dist/engine/boot-validator/named-filter-rules.d.ts +42 -2
  192. package/dist/engine/boot-validator/named-filter-rules.js +42 -2
  193. package/dist/engine/boot-validator/ownership.js +10 -1
  194. package/dist/engine/boot-validator/parent-ref.js +87 -50
  195. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  196. package/dist/engine/boot-validator/projection-list-screens.js +32 -1
  197. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  198. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  199. package/dist/engine/boot-validator/query-output-guidance.js +40 -0
  200. package/dist/engine/boot-validator/query-refs.js +34 -1
  201. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  202. package/dist/engine/boot-validator/row-decoration.js +16 -0
  203. package/dist/engine/boot-validator/screens-actions.js +1 -1
  204. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  205. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  206. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  207. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  208. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  209. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  210. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  211. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  212. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  213. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  214. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  215. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  216. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  217. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  218. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  219. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  220. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  221. package/dist/engine/boot-validator/screens-lists.js +19 -3
  222. package/dist/engine/boot-validator/screens.js +1 -1
  223. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  224. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  225. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  226. package/dist/engine/boot-validator/zod-shape.js +19 -1
  227. package/dist/engine/build-app-schema.js +4 -0
  228. package/dist/engine/config-helpers.d.ts +1 -2
  229. package/dist/engine/config-helpers.js +6 -7
  230. package/dist/engine/define-feature.js +1 -0
  231. package/dist/engine/define-handler.d.ts +1 -0
  232. package/dist/engine/define-handler.js +4 -2
  233. package/dist/engine/definition-violations.js +2 -2
  234. package/dist/engine/entity-handlers.js +3 -8
  235. package/dist/engine/entity-list-runtime-options.js +9 -8
  236. package/dist/engine/factories.d.ts +2 -0
  237. package/dist/engine/feature-config-events-jobs.js +1 -0
  238. package/dist/engine/feature-entity-handlers.js +5 -2
  239. package/dist/engine/field-access.d.ts +1 -1
  240. package/dist/engine/field-access.js +7 -10
  241. package/dist/engine/find-entity.js +3 -3
  242. package/dist/engine/form-derivations.js +3 -3
  243. package/dist/engine/index.d.ts +3 -3
  244. package/dist/engine/index.js +2 -2
  245. package/dist/engine/named-filter-roles.d.ts +3 -0
  246. package/dist/engine/named-filter-roles.js +15 -0
  247. package/dist/engine/pipeline.js +0 -1
  248. package/dist/engine/project-app-schema-for-roles.js +17 -2
  249. package/dist/engine/qualified-name.js +0 -1
  250. package/dist/engine/registry-facade.js +1 -2
  251. package/dist/engine/registry-state.d.ts +1 -1
  252. package/dist/engine/registry-state.js +5 -2
  253. package/dist/engine/registry-validate.js +2 -1
  254. package/dist/engine/resolve-named-list-filters.js +5 -2
  255. package/dist/engine/schema-builder.js +9 -11
  256. package/dist/engine/screen-helpers.d.ts +12 -0
  257. package/dist/engine/screen-helpers.js +17 -1
  258. package/dist/engine/soft-delete-cleanup.js +3 -5
  259. package/dist/engine/state-machine.js +0 -1
  260. package/dist/engine/steps/_database-clock.d.ts +2 -0
  261. package/dist/engine/steps/_database-clock.js +6 -0
  262. package/dist/engine/steps/compute.js +1 -1
  263. package/dist/engine/steps/retry.js +5 -1
  264. package/dist/engine/steps/return.js +0 -1
  265. package/dist/engine/steps/wait-for-event.js +2 -1
  266. package/dist/engine/steps/wait.js +2 -1
  267. package/dist/engine/system-user.d.ts +2 -2
  268. package/dist/engine/system-user.js +2 -2
  269. package/dist/engine/types/handlers.d.ts +1 -1
  270. package/dist/engine/types/handlers.js +1 -1
  271. package/dist/engine/types/screen.d.ts +1 -1
  272. package/dist/engine/types/screen.js +1 -1
  273. package/dist/engine/webhook-contracts.d.ts +2 -3
  274. package/dist/engine/webhook-contracts.js +2 -25
  275. package/dist/engine/webhook-events.js +48 -29
  276. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  277. package/dist/engine/webhook-payload-strictness.js +53 -0
  278. package/dist/env/_zod-introspect.d.ts +1 -0
  279. package/dist/env/dry-run.d.ts +1 -1
  280. package/dist/env/dry-run.js +1 -1
  281. package/dist/env/field-meta.d.ts +4 -0
  282. package/dist/env/field-meta.js +67 -0
  283. package/dist/env/field-rules.d.ts +9 -0
  284. package/dist/env/field-rules.js +46 -0
  285. package/dist/env/index.d.ts +3 -3
  286. package/dist/env/index.js +16 -71
  287. package/dist/env/internals.d.ts +3 -0
  288. package/dist/env/internals.js +1 -2
  289. package/dist/env/required-env.d.ts +3 -1
  290. package/dist/env/required-env.js +5 -2
  291. package/dist/errors/reasons.d.ts +1 -0
  292. package/dist/errors/reasons.js +4 -0
  293. package/dist/errors/serialize.js +2 -2
  294. package/dist/errors/write-error-info.js +0 -2
  295. package/dist/es-ops/operations-schema.js +18 -7
  296. package/dist/event-store/admin-api.js +3 -3
  297. package/dist/event-store/event-store.js +0 -3
  298. package/dist/event-store/index.d.ts +1 -0
  299. package/dist/event-store/index.js +1 -0
  300. package/dist/event-store/transfer.js +1 -1
  301. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  302. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  303. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  304. package/dist/files/bind-pending-file-refs.js +54 -27
  305. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  306. package/dist/files/create-file-ref.d.ts +4 -1
  307. package/dist/files/create-file-ref.js +14 -3
  308. package/dist/files/default-file-guard.js +4 -1
  309. package/dist/files/file-claim.d.ts +6 -0
  310. package/dist/files/file-claim.js +17 -0
  311. package/dist/files/file-field-slots.d.ts +2 -0
  312. package/dist/files/file-field-slots.js +28 -0
  313. package/dist/files/file-ref-entity.d.ts +3 -0
  314. package/dist/files/file-ref-entity.js +2 -0
  315. package/dist/files/file-ref-table.d.ts +3 -0
  316. package/dist/files/file-routes.d.ts +4 -1
  317. package/dist/files/file-routes.js +80 -16
  318. package/dist/files/in-memory-provider.d.ts +1 -1
  319. package/dist/files/in-memory-provider.js +2 -1
  320. package/dist/files/index.d.ts +1 -1
  321. package/dist/files/index.js +1 -1
  322. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  323. package/dist/files/invalid-file-ref-error.js +15 -0
  324. package/dist/files/local-provider.js +9 -2
  325. package/dist/files/provider-resolver.js +1 -1
  326. package/dist/files/rebind-file-ref.d.ts +3 -2
  327. package/dist/files/rebind-file-ref.js +24 -18
  328. package/dist/files/resolve-file-handles.d.ts +13 -0
  329. package/dist/files/resolve-file-handles.js +57 -0
  330. package/dist/files/storage-tracking.d.ts +1 -1
  331. package/dist/files/storage-tracking.js +5 -2
  332. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  333. package/dist/files/types.d.ts +4 -0
  334. package/dist/files/types.js +10 -0
  335. package/dist/files/upload-field-resolution.d.ts +1 -0
  336. package/dist/files/upload-field-resolution.js +16 -2
  337. package/dist/files/upload-ledger.js +1 -1
  338. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  339. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  340. package/dist/i18n/required-surface-keys.js +21 -5
  341. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  342. package/dist/internal/boot-rule-table-expectations.js +29 -0
  343. package/dist/internal/row-level-security.d.ts +1 -0
  344. package/dist/internal/row-level-security.js +1 -0
  345. package/dist/internal/testing.d.ts +1 -0
  346. package/dist/internal/testing.js +1 -0
  347. package/dist/jobs/index.d.ts +1 -0
  348. package/dist/jobs/index.js +1 -0
  349. package/dist/jobs/job-load-events.d.ts +10 -0
  350. package/dist/jobs/job-load-events.js +12 -0
  351. package/dist/jobs/job-runner-context.js +6 -158
  352. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  353. package/dist/jobs/job-runner-dispatch.js +57 -0
  354. package/dist/jobs/job-runner-event-triggers.js +18 -9
  355. package/dist/jobs/job-runner-execution.js +5 -2
  356. package/dist/jobs/job-runner-facets.d.ts +48 -0
  357. package/dist/jobs/job-runner-facets.js +156 -0
  358. package/dist/jobs/job-runner-gates.js +19 -11
  359. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  360. package/dist/jobs/job-runner-helpers.js +18 -3
  361. package/dist/jobs/job-runner-scope.d.ts +1 -0
  362. package/dist/jobs/job-runner-scope.js +2 -0
  363. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  364. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  365. package/dist/jobs/job-runner-types.d.ts +1 -0
  366. package/dist/jobs/job-runner.js +39 -70
  367. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  368. package/dist/jobs/obliterate-job-queues.js +23 -0
  369. package/dist/lifecycle/lifecycle.js +1 -1
  370. package/dist/migrations/event-header-scrub.d.ts +11 -0
  371. package/dist/migrations/event-header-scrub.js +33 -0
  372. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  373. package/dist/migrations/event-payload-scrub.js +36 -4
  374. package/dist/migrations/index.d.ts +1 -0
  375. package/dist/migrations/index.js +2 -0
  376. package/dist/migrations/kumiko-drift.d.ts +5 -2
  377. package/dist/migrations/kumiko-drift.js +51 -14
  378. package/dist/migrations/pending-rebuilds.js +4 -5
  379. package/dist/observability/sensitive-filter.js +0 -12
  380. package/dist/pipeline/aggregate-type-removal.js +17 -4
  381. package/dist/pipeline/context-services.d.ts +2 -0
  382. package/dist/pipeline/context-services.js +5 -2
  383. package/dist/pipeline/dispatch-batch.js +4 -3
  384. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  385. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  386. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  387. package/dist/pipeline/dispatch-nested-write.js +119 -0
  388. package/dist/pipeline/dispatch-query.js +10 -3
  389. package/dist/pipeline/dispatch-scope.js +4 -3
  390. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  391. package/dist/pipeline/dispatch-shared.js +6 -38
  392. package/dist/pipeline/dispatch-write.d.ts +0 -1
  393. package/dist/pipeline/dispatch-write.js +3 -302
  394. package/dist/pipeline/dispatcher-utils.js +6 -0
  395. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  396. package/dist/pipeline/effective-system-scope.js +22 -0
  397. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  398. package/dist/pipeline/event-dispatcher-delivery.js +20 -9
  399. package/dist/pipeline/event-dispatcher.d.ts +6 -1
  400. package/dist/pipeline/event-dispatcher.js +6 -7
  401. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  402. package/dist/pipeline/handler-context-auth.js +3 -4
  403. package/dist/pipeline/handler-context-db.js +11 -4
  404. package/dist/pipeline/handler-context-dispatch.js +2 -2
  405. package/dist/pipeline/handler-context-events.d.ts +8 -3
  406. package/dist/pipeline/handler-context-events.js +20 -65
  407. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  408. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  409. package/dist/pipeline/handler-context-notify.js +2 -0
  410. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  411. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  412. package/dist/pipeline/handler-context-projection.js +39 -0
  413. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  414. package/dist/pipeline/handler-context-scope.js +14 -2
  415. package/dist/pipeline/index.d.ts +1 -1
  416. package/dist/pipeline/index.js +1 -1
  417. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  418. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  419. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  420. package/dist/pipeline/member-reader.js +4 -2
  421. package/dist/pipeline/msp-rebuild.js +1 -1
  422. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  423. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  424. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  425. package/dist/pipeline/projection-rebuild.js +16 -7
  426. package/dist/pipeline/projection-state.js +4 -6
  427. package/dist/pipeline/system-hooks.js +36 -6
  428. package/dist/pipeline/write-result-masking.js +31 -3
  429. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  430. package/dist/pipeline/write-transition-guard.js +95 -0
  431. package/dist/schema-cli/shared.d.ts +2 -0
  432. package/dist/schema-cli/shared.js +4 -2
  433. package/dist/schema-cli/validate-command.js +43 -28
  434. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  435. package/dist/search/meilisearch-adapter-internals.js +5 -0
  436. package/dist/search/meilisearch-adapter.d.ts +1 -0
  437. package/dist/search/meilisearch-adapter.js +17 -11
  438. package/dist/search/reindex-entity.d.ts +2 -0
  439. package/dist/search/reindex-entity.js +32 -4
  440. package/dist/search/reindex-tenants-search.js +20 -4
  441. package/dist/time/tz-context.js +1 -1
  442. package/dist/ui-types/card-column-roles.d.ts +6 -0
  443. package/dist/ui-types/card-column-roles.js +21 -3
  444. package/dist/ui-types/index.d.ts +3 -3
  445. package/dist/ui-types/index.js +2 -2
  446. package/dist/utils/ids.js +0 -1
  447. package/dist/utils/index.d.ts +1 -0
  448. package/dist/utils/index.js +1 -0
  449. package/dist/utils/return-path-limit.d.ts +1 -0
  450. package/dist/utils/return-path-limit.js +1 -0
  451. package/package.json +5 -3
  452. package/presets/biome-app.json +39 -21
  453. package/presets/biome-plugins/admin-api.grit +10 -0
  454. package/presets/biome-plugins/error-reasons.grit +53 -0
  455. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  456. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  457. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  458. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  459. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  460. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  461. package/presets/biome-plugins/no-date-api.grit +11 -0
  462. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  463. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  464. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  465. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  466. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  467. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  468. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  469. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  470. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  471. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  472. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  473. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  474. package/presets/biome-plugins/test-title.grit +20 -0
  475. package/presets/biome-plugins/unsafe-json-parse.grit +12 -0
  476. package/presets/biome-rules.json +467 -0
  477. package/src/changes.json +366 -0
  478. package/dist/engine/minor-units.d.ts +0 -2
  479. package/dist/engine/minor-units.js +0 -8
@@ -287,6 +287,14 @@ import { createInMemorySuspendedRunFetcher } from "../postgres-resume-loop";
287
287
  import { runResumeLoop, type SuspendableRun } from "../resume-loop";
288
288
  import { startAndRunWorkflow } from "../workflow-runner";
289
289
 
290
+ // No Postgres in-memory: wait steps read their wake time from this stand-in for the database clock.
291
+ function makeAppendOnlyCtx() {
292
+ return {
293
+ events: { unsafeAppend: mock().mockResolvedValue(undefined) },
294
+ db: { databaseNow: async () => new Date("2031-03-04T05:06:07.000Z") },
295
+ };
296
+ }
297
+
290
298
  function makeWaitWorkflow(name: string) {
291
299
  return defineWorkflow({
292
300
  name,
@@ -325,7 +333,7 @@ describe("workflow-engine", () => {
325
333
  });
326
334
 
327
335
  it("webhook-delivery completes with exactly one dispatch request", async () => {
328
- const ctx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
336
+ const ctx = makeAppendOnlyCtx();
329
337
 
330
338
  const result = await startAndRunWorkflow({
331
339
  runId: "wf-webhook-delivery-1",
@@ -366,10 +374,6 @@ describe("workflow-engine", () => {
366
374
  });
367
375
 
368
376
  describe("workflow-runner", () => {
369
- function makeAppendOnlyCtx() {
370
- return { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
371
- }
372
-
373
377
  it("startAndRunWorkflow writes run.started with Q7 snapshot fingerprint, then runs the pipeline to completion when no suspension", async () => {
374
378
  const workflow = defineWorkflow({
375
379
  name: "demo-sync",
@@ -453,7 +457,7 @@ describe("workflow-runner", () => {
453
457
 
454
458
  describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
455
459
  it("suspends on the first wait, then resume-loop runs it through to completion", async () => {
456
- const ctx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
460
+ const ctx = makeAppendOnlyCtx();
457
461
  const trigger = {
458
462
  aggregateId: "agg_user_42",
459
463
  type: "user.signed-up",
@@ -516,7 +520,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
516
520
  definitionFingerprint: waitingCall.payload["definitionFingerprint"] as string,
517
521
  };
518
522
 
519
- const resumeCtx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
523
+ const resumeCtx = makeAppendOnlyCtx();
520
524
  const count = await runResumeLoop(
521
525
  createInMemorySuspendedRunFetcher([suspendedRun]),
522
526
  resumeCtx as never,
@@ -542,7 +546,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
542
546
  });
543
547
 
544
548
  it("not-engaged path picks the reminder branch", async () => {
545
- const ctx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
549
+ const ctx = makeAppendOnlyCtx();
546
550
  const trigger = {
547
551
  aggregateId: "agg_user_cold",
548
552
  type: "user.signed-up",
@@ -568,7 +572,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
568
572
  triggerEvent: trigger as never,
569
573
  definitionFingerprint: waiting.payload["definitionFingerprint"] as string,
570
574
  };
571
- const resumeCtx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
575
+ const resumeCtx = makeAppendOnlyCtx();
572
576
  await runResumeLoop(createInMemorySuspendedRunFetcher([suspendedRun]), resumeCtx as never);
573
577
 
574
578
  const reminderMail = resumeCtx.events.unsafeAppend.mock.calls[1]![0] as {
@@ -722,7 +726,7 @@ describe("cron-scheduler", () => {
722
726
  steps: stepsPipeline(({ r }) => [r.step.return({ isSuccess: true, data: undefined })]),
723
727
  });
724
728
 
725
- const handlerCtx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
729
+ const handlerCtx = makeAppendOnlyCtx();
726
730
  const lastRuns = new Map<string, Temporal.Instant>();
727
731
  const lastRun = Temporal.Instant.from("2025-05-31T08:00:00Z");
728
732
  lastRuns.set("test-daily", lastRun);
@@ -770,7 +774,7 @@ describe("resume-loop", () => {
770
774
  };
771
775
 
772
776
  const fetchRuns = createInMemorySuspendedRunFetcher([suspendedRun]);
773
- const handlerCtx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
777
+ const handlerCtx = makeAppendOnlyCtx();
774
778
 
775
779
  const count = await runResumeLoop(fetchRuns, handlerCtx as never);
776
780
 
@@ -804,7 +808,7 @@ describe("resume-loop", () => {
804
808
  };
805
809
 
806
810
  const fetchRuns = createInMemorySuspendedRunFetcher([suspendedRun]);
807
- const handlerCtx = { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
811
+ const handlerCtx = makeAppendOnlyCtx();
808
812
 
809
813
  const count = await runResumeLoop(fetchRuns, handlerCtx as never);
810
814
 
@@ -62,6 +62,7 @@
62
62
  | `pipeline-basics` | M.1 Tier-1 step-vocabulary showcase: every step in one inventory-management feature (aggregate.{create,update,appendEvent}, read.{findOne,findMany}, branch, forEach, compute, return, unsafeProjection{Upsert,Delete}). | `examples/pipeline-basics.md` |
63
63
  | `prod-boot-options` | runProdApp boot options: mail, kmsMode, fileStorage, demoMode and signal handling declared as options instead of hand-wired in bin/main.ts. | `examples/prod-boot-options.md` |
64
64
  | `public-share-token` | Generic share-token entity: mint hash-stored token, anonymous read-by-token with IP rate-limit. | `examples/public-share-token.md` |
65
+ | `pwa-shell` | pwa option on runProdApp and the dev server: web manifest, generated service worker with an offline app shell and a one-time install hint. | `examples/pwa-shell.md` |
65
66
  | `rate-limiting` | End-to-end rate limiting: L1 global-IP + L2 auth-endpoints + L3 handler opt-in. | `examples/rate-limiting.md` |
66
67
  | `realtime-sse` | Server-sent events demo. Goodbye F5. | `examples/realtime-sse.md` |
67
68
  | `record-detail-layout` | projectionDetail record header, metrics band, and layout.mode: "tabs" — an order screen with two relatedList tabs and a fields tab. | `examples/record-detail-layout.md` |
@@ -42,6 +42,8 @@ One entry per feature a package ships: purpose, import of its factory, required
42
42
  `import { createChannelTeamsFeature } from "@cosmicdrift/kumiko-bundled-features/channel-teams"`; requires `delivery`, `secrets`
43
43
  - `channel-telegram`: Sends delivery notifications through the Telegram Bot API (`sendMessage`, plain text), registered as the `telegram` channel in the delivery system.
44
44
  `import { createChannelTelegramFeature } from "@cosmicdrift/kumiko-bundled-features/channel-telegram"`; requires `delivery`, `secrets`; secrets `channel-telegram:secret:bot-token`
45
+ - `channel-whatsapp`: WhatsApp Business (Meta Cloud API) as a two-way channel, not a delivery channel.
46
+ `import { createChannelWhatsappFeature } from "@cosmicdrift/kumiko-bundled-features/channel-whatsapp"`; requires `secrets`; secrets `channel-whatsapp:secret:access-token`, `channel-whatsapp:secret:app-secret`, `channel-whatsapp:secret:verify-token`
45
47
  - `compliance-profiles`: Lets each tenant select a compliance regime (e.g. `eu-dsgvo`, `swiss-dsg`, `de-hr-dsgvo-hgb`) that bundles user-rights grace periods, breach-disclosure deadlines, sub-processor requirements, and audit-retention rules into a single named profile.
46
48
  `import { createComplianceProfilesFeature } from "@cosmicdrift/kumiko-bundled-features/compliance-profiles"`
47
49
  - `compliance-profiles-ops`: Platform-wide SystemAdmin counterpart to `compliance-profiles`' `needs-profile` query (#2089): `tenants-missing-profile` lists every enabled tenant with no row in `tenantComplianceProfile` at all, tenant-wide instead of scoped to the caller's own tenant.
@@ -95,7 +97,7 @@ One entry per feature a package ships: purpose, import of its factory, required
95
97
  - `inbound-mail-foundation`: Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send.
96
98
  `import { createInboundMailFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-mail-foundation"`; requires `tenant-lifecycle`
97
99
  - `inbound-provider-imap`: Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot).
98
- `import { createInboundProviderImapFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-imap"`; requires `inbound-mail-foundation`, `secrets`
100
+ `import { createInboundProviderImapFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-imap"`; requires `inbound-mail-foundation`, `secrets`, `user`
99
101
  - `inbound-provider-inmemory`: Registers a scriptable in-process `"inmemory"` provider for `inbound-mail-foundation`.
100
102
  `import { createInboundProviderInMemoryFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-inmemory"`; requires `inbound-mail-foundation`
101
103
  - `jobs`: Persistence and operator tooling for background jobs registered via `r.job(...)`.
@@ -147,7 +149,7 @@ One entry per feature a package ships: purpose, import of its factory, required
147
149
  - `subscription-mollie`: Mollie payment provider plugin for `billing-foundation`, covering the DACH/EU mid-market use case.
148
150
  `import { createSubscriptionMollieFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-mollie"`; requires `billing-foundation`
149
151
  - `subscription-paddle`: Paddle Billing provider plugin for `billing-foundation`.
150
- `import { createSubscriptionPaddleFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-paddle"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `client-token`, `tenant-binding-key`, `webhook-secret`
152
+ `import { createSubscriptionPaddleFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-paddle"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `client-token`, `webhook-secret`
151
153
  - `subscription-stripe`: Stripe payment provider plugin for `billing-foundation`.
152
154
  `import { createSubscriptionStripeFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-stripe"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `webhook-secret`
153
155
  - `tags`: Generic, host-agnostic tagging for any entity.
@@ -168,6 +168,22 @@ Secrets:
168
168
  | --- | --- | --- |
169
169
  | `channel-telegram:secret:bot-token` | tenant | Telegram bot token |
170
170
 
171
+ ## channel-whatsapp
172
+
173
+ WhatsApp Business (Meta Cloud API) as a two-way channel, not a delivery channel. Inbound: mount `createWhatsappWebhookRoutes()` via `extraRoutes` (default path `/api/channel-whatsapp/webhook/:tenantId`, the tenant id is part of the URL because the secrets are tenant-scoped); GET answers Meta's `hub.challenge` handshake, POST checks `X-Hub-Signature-256` over the raw body and normalizes each message and status. Events: `channel-whatsapp:event:message-received` (sender, wamid, type text|audio|image|interactive_button|other, text, button payload, `contextWamid`, media id and mime type, `phoneNumberId`), `status-updated` (sent|delivered|read|failed|other) and `throttled` (sender over the per-number limit). Sender number, text, button payload and status recipient are PII, stored as tenant-key ciphertext; read them with `readWhatsappMessagePii`. A redelivered wamid is stored once and answered 200; a failed dispatch answers 500 so Meta redelivers. Outbound: `createWhatsappClient(opts)` gives `sendText`, `sendTemplate`, `sendButtons`, `sendMedia` (each takes the sending `phoneNumberId` and answers `{ ok: true, wamid }` or a typed failure) and `fetchMedia` (media id to bytes and mime type; the URL from the Graph answer is checked against `allowedHosts` before the token is sent). Tenant secrets `channel-whatsapp:secret:access-token`, `app-secret` and `verify-token`. App options of `createChannelWhatsappFeature(opts)`: `apiBaseUrl`, `apiVersion` (default v21.0), `allowedHosts` (default graph.facebook.com and lookaside.fbsbx.com), `requireHttps` (default true; boot fails on a mismatch), `timeoutMs`, `mediaMaxBytes`, `transport` (in-memory Meta for tests), `senderRateLimits` (default 30 per hour and 200 per day per sender and tenant) and `rateLimit` (flood guard of the inbound handlers; cannot be disabled while a sender limit is set). Requires `secrets`. A worker-run job triggered by `message-received` attaches the business process.
174
+
175
+ Category: notifications
176
+
177
+ Requires: `secrets`
178
+
179
+ Secrets:
180
+
181
+ | Secret | Scope | Label |
182
+ | --- | --- | --- |
183
+ | `channel-whatsapp:secret:access-token` | tenant | WhatsApp access token |
184
+ | `channel-whatsapp:secret:app-secret` | tenant | WhatsApp app secret |
185
+ | `channel-whatsapp:secret:verify-token` | tenant | WhatsApp verify token |
186
+
171
187
  ## collection-labels
172
188
 
173
189
  Nav labels for the content collections mounted by this sample app.
@@ -216,7 +232,7 @@ Exposes APIs: `retention.policyFor`
216
232
 
217
233
  ## delivery
218
234
 
219
- The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: "deferred" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: "dispatched", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting — add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app's `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message's `data.unsubscribeUrl` points at the unsubscribe route. A notification declared with `unsubscribe: true` gets that link from delivery itself when the service has `unsubscribeLinks` (the `runProdApp` and `runDevApp` option `unsubscribe: { secret }` mounts the routes and wires it; base URL from `auth.publicOrigin`, `auth.mail.baseUrl` or `APP_BASE_URL`): user recipients get a user token, `route` recipients an address token (needs a blind-index key, otherwise no link); a `data.unsubscribeUrl` from the caller wins. `unsubscribe.tenantOrigin: (ctx) => origin | null` points the link at the tenant's own host (subdomain or custom domain, must serve this app's `/api`); null, a throw or a non-https value fall back to the app origin. The token carries the mail's locale, so the confirmation and result pages render in the mail's language. An app serving its own (e.g. legacy) unsubscribe links renders the same result page with `renderUnsubscribeResultPage({ kind, locale })`. To react to a no-account opt-out (e.g. remove the app's own subscriber row), declare `r.job(name, { trigger: { on: DeliveryHandlers.unsubscribeAddress } }, handler)` on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with `unsubscribeAddressPayloadSchema` (`addressHash`, `notificationType`, `channel`) as payload and the tenant in `ctx.triggeredBy.tenantId`; match the subscriber via `hashUnsubscribeAddress(email)`. Declare `unsubscribeUrl` as an optional template variable if the mail body shows it.
235
+ The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: "deferred" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: "dispatched", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting — add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app's `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message's `data.unsubscribeUrl` points at the unsubscribe route. A notification declared with `unsubscribe: true` gets that link from delivery itself when the service has `unsubscribeLinks` (the `runProdApp` and `runDevApp` option `unsubscribe: { secret }` mounts the routes and wires it; base URL from `auth.publicOrigin`, `auth.mail.baseUrl` or `APP_BASE_URL`): user recipients get a user token, `route` recipients an address token (needs a blind-index key, otherwise no link); a `data.unsubscribeUrl` from the caller wins. `unsubscribe.tenantOrigin: (ctx) => origin | null` points the link at the tenant's own host (subdomain or custom domain, must serve this app's `/api`); null, a throw or a non-https value fall back to the app origin. The token carries the mail's locale, so the confirmation and result pages render in the mail's language. An app serving its own (e.g. legacy) unsubscribe links renders the same result page with `renderUnsubscribeResultPage({ kind, locale })`. To react to a no-account opt-out (e.g. remove the app's own subscriber row), declare `r.job(name, { trigger: { on: DeliveryHandlers.unsubscribeAddress } }, handler)` on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with `unsubscribeAddressPayloadSchema` (`addressHash`, `notificationType`, `channel`) as payload and the tenant in `ctx.triggeredBy.tenantId`; match the subscriber via `hashUnsubscribeAddress(email)`. Declare `unsubscribeUrl` as an optional template variable if the mail body shows it. A job that sends an opt-in notification (e.g. a daily digest) reads the members who switched it on from the job-only query `delivery:query:opted-in-user-ids` (`{ notificationType, channel }` answers `{ userIds }`).
220
236
 
221
237
  Category: notifications
222
238
 
@@ -405,7 +421,7 @@ Requires: `auth-foundation`, `tenant`
405
421
 
406
422
  ## inbound-mail-foundation
407
423
 
408
- Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send. `sendMailFromAccount(ctx, { accountId, message })` sends from a connected mailbox through its provider (From = the mailbox address, no fallback to the app sender) and answers typed failures (not configured, login rejected, server unreachable, rejected, invalid message); app write handlers call it, it is no endpoint of its own. The foundation owns three event-sourced streams (mail-account lifecycle, inbound-message with exactly-once ingest via deterministic aggregate ids, mail-thread rollup) and their projections `read_mail_accounts`/`read_inbound_messages`/`read_mail_threads`; PII fields are envelope-encrypted per tenant subject key before every append (crypto-shredding on tenant destroy). Wire `createInboundMailConnectRoutes` (OAuth connect + anonymous callback outside /api) and `createInboundMailSupervisor` (IDLE watch with backoff + reconciliation poll) in bin/server.ts. Consume `inbound-mail-foundation:event:inbound-message-received` from app features to attach business processes.
424
+ Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send. `sendMailFromAccount(ctx, { accountId, message })` sends from a connected mailbox through its provider (From = the mailbox address, no fallback to the app sender) and answers typed failures (not configured, login rejected, server unreachable, rejected, invalid message); app write handlers call it from `beforeTransaction` (it sends at once and a rollback cannot recall the mail), it is no endpoint of its own. The foundation owns three event-sourced streams (mail-account lifecycle, inbound-message with exactly-once ingest via deterministic aggregate ids, mail-thread rollup) and their projections `read_mail_accounts`/`read_inbound_messages`/`read_mail_threads`; PII fields are envelope-encrypted per tenant subject key before every append (crypto-shredding on tenant destroy). Wire `createInboundMailConnectRoutes` (OAuth connect + anonymous callback outside /api) and `createInboundMailSupervisor` (IDLE watch with backoff + reconciliation poll) in bin/server.ts. Consume `inbound-mail-foundation:event:inbound-message-received` from app features to attach business processes.
409
425
 
410
426
  Category: notifications
411
427
 
@@ -413,11 +429,11 @@ Requires: `tenant-lifecycle`
413
429
 
414
430
  ## inbound-provider-imap
415
431
 
416
- Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot). Incremental sync via a UIDVALIDITY:lastUid cursor (UIDVALIDITY change triggers a cursor-invalid full resync), initial backfill bounded by the foundation backfill window, and live push via IMAP IDLE for the watch supervisor. Tenant admins connect a shared mailbox through the "Connect mailbox" form on the mail accounts list and members a personal one through the same form on "My mail accounts" (`connect-mailbox` and `connect-my-mailbox` check the IMAP login and the SMTP login of the outgoing server first, then creates the account and its credential secret in one transaction; `reconnect-mailbox` does the same check for an existing mailbox with a sign-in error and overwrites its credential secret); programmatic setups store the per-account connection JSON (host/port/secure/user/password, plus smtpHost/smtpPort for sending) in the account credential secret slot before the first sync. Implements the provider `send`: `sendMailFromAccount` sends over the SMTP server of the mailbox itself (implicit TLS, same login) with the mailbox address as From and stores a copy in its sent folder.
432
+ Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot). Incremental sync via a UIDVALIDITY:lastUid cursor (UIDVALIDITY change triggers a cursor-invalid full resync), initial backfill bounded by the foundation backfill window, and live push via IMAP IDLE for the watch supervisor. Tenant admins connect a shared mailbox through the "Connect mailbox" form on the mail accounts list and members a personal one through the same form on "My mail accounts" (`connect-mailbox` and `connect-my-mailbox` check the IMAP login and the SMTP login of the outgoing server first, then creates the account and its credential secret in one transaction; `reconnect-mailbox` does the same check for an existing mailbox with a sign-in error and overwrites its credential secret); programmatic setups store the per-account connection JSON (host/port/secure/user/password, plus smtpHost/smtpPort for sending) in the account credential secret slot before the first sync. Implements the provider `send`: `sendMailFromAccount` sends over the SMTP server of the mailbox itself (TLS enforced: implicit on port 465, STARTTLS with requireTLS on every other port, port from the credential document, connect form default 587; same login) with the mailbox address as From and stores a copy in its sent folder.
417
433
 
418
434
  Category: notifications
419
435
 
420
- Requires: `inbound-mail-foundation`, `secrets`
436
+ Requires: `inbound-mail-foundation`, `secrets`, `user`
421
437
 
422
438
  ## inbound-provider-inmemory
423
439
 
@@ -646,7 +662,7 @@ Exposes APIs: `sessions.revokeAllForUser`
646
662
 
647
663
  ## step-dispatcher
648
664
 
649
- Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits. An `r.multiStreamProjection` on the `kumiko:system:step.dispatch-requested` system event enqueues one `step-dispatcher:job:deliver` BullMQ job per dispatch (Redis carries only the stream id and tenant, never the request payload). The job performs the actual HTTP or mail delivery and appends `kumiko:system:step.dispatched` or `kumiko:system:step.dispatch-failed` back onto the same stream, so the outcome is recorded in the event log without a separate status table. Transient failures (network error, timeout, 5xx, 408, 429, any mail adapter failure) are retried 3 times with exponential backoff; the outcome is recorded after the final attempt and the payload key is erased only then. Permanent failures (invalid url, blocked host, other 4xx, unavailable auth secret) are recorded immediately. At most 2 deliveries per tenant run at once (`maxPerTenant` with `onLimit: "defer"`), so a slow receiver of one tenant does not delay other tenants. Requires a job runner (Redis) and a worker consuming the job's default `worker` lane; without a job runner the projection fails loudly. Mount this feature explicitly via `createStepDispatcherFeature()` in your app's feature list alongside any features that use `r.step.webhook.send` or `r.step.mail.send`. Requires the `secrets` feature (`createSecretsFeature()`) to be mounted — `webhook.send` auth resolves per-tenant through it, under `step-dispatcher:webhook-auth.<name>`. Every `webhook.send` request carries `Idempotency-Key: <dispatch stream id>`, stable across retries and redeliveries of the same dispatch request; an explicit `Idempotency-Key` in `headers` takes precedence.
665
+ Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits. An `r.multiStreamProjection` on the `kumiko:system:step.dispatch-requested` system event enqueues one `step-dispatcher:job:deliver` BullMQ job per dispatch (Redis carries only the stream id and tenant, never the request payload). The job performs the actual HTTP or mail delivery and appends `kumiko:system:step.dispatched` or `kumiko:system:step.dispatch-failed` back onto the same stream, so the outcome is recorded in the event log without a separate status table. Transient failures (network error, timeout, 5xx, 408, 429, any mail adapter failure) are retried 3 times with exponential backoff; the outcome is recorded after the final attempt and the payload key is erased only then. A request that still has no outcome after 24 hours (job stalled or lost, or its final attempt could not record one) is closed by the daily `step-dispatcher:job:sweep-abandoned` cron (it pages through all such requests; requests that already have an outcome are not swept) with a generic `dispatch-failed` event and its payload key is erased. Permanent failures (invalid url, blocked host, other 4xx, unavailable auth secret) are recorded immediately. At most 2 deliveries per tenant run at once (`maxPerTenant` with `onLimit: "defer"`), so a slow receiver of one tenant does not delay other tenants. Requires a job runner (Redis) and a worker consuming the job's default `worker` lane; without a job runner the projection fails loudly. Mount this feature explicitly via `createStepDispatcherFeature()` in your app's feature list alongside any features that use `r.step.webhook.send` or `r.step.mail.send`. Requires the `secrets` feature (`createSecretsFeature()`) to be mounted — `webhook.send` auth resolves per-tenant through it, under `step-dispatcher:webhook-auth.<name>`. Every `webhook.send` request carries `Idempotency-Key: <dispatch stream id>`, stable across retries and redeliveries of the same dispatch request; an explicit `Idempotency-Key` in `headers` takes precedence.
650
666
 
651
667
  Category: infrastructure
652
668
 
@@ -662,7 +678,7 @@ Requires: `billing-foundation`
662
678
 
663
679
  ## subscription-paddle
664
680
 
665
- Paddle Billing provider plugin for `billing-foundation`. Paddle acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key, webhook secret and tenant binding key from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant), the public Paddle.js `client-token`, a `billingLive` master switch and an `environment` key (sandbox | live). `environment` is its own key because Paddle serves sandbox and live from different API hosts and a live key must never hit the sandbox host or the other way round; `billingLive` only decides whether checkouts are offered at all. All of them are runtime config, so keys rotate and prod goes live without a redeploy, and the `mask` on each derives the sysadmin settings screen and nav. Mount via `createSubscriptionPaddleFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret`/`tenantBindingKey`/`clientToken` options are env to config bridge fallbacks (`PADDLE_API_KEY`, `PADDLE_WEBHOOK_SECRET`, `PADDLE_TENANT_BINDING_KEY`, `PADDLE_CLIENT_TOKEN`). The plugin always mounts; `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true, and billing counts as enabled only with API key and binding key present. Webhooks arrive at `/webhooks/subscription/paddle` when mounted through the server-runtime `billing.paddle` boot option, or at `/api/subscription/webhook/paddle` when `createSubscriptionWebhookRoute` is mounted by hand and are verified with the `Paddle-Signature` header (HMAC-SHA256 over `ts:rawBody` keyed with the raw secret, any `h1` may match, 5 minute tolerance). Paddle.js can open checkouts with arbitrary `customData` from the browser, so `custom_data.tenantId` is only trusted together with `tenantBinding`, an HMAC of the tenant id under the binding key; events without a valid binding, for prices outside `priceToTier` or without a tenant are dropped. Rotating the binding key makes the webhooks of existing subscriptions fail that check until they are re-bound. Paddle has no hosted checkout page, so the feature serves the Default Payment Link itself at `/billing/paddle-checkout` (the Default Payment Link in the Paddle dashboard must point to `<APP_BASE_URL>/billing/paddle-checkout`; it is the only source, because checkouts are created without a `checkout.url`). Create subscription prices in the Paddle catalog with quantity minimum and maximum 1; for one-off packs set the quantity limits on purpose, because the payment event carries `quantity` and the app has to multiply its credits by it: an anonymous page with its own CSP that loads Paddle.js from cdn.paddle.com, the one external script this framework allows, and opens the overlay for the transaction. Implements checkout, customer portal, cancel and resume, `retrievePrices` (batched, 10-minute TTL cache), `retrieveSubscription` for the sync job, and an in-app plan switch: `previewPlanSwitch` shows the proration before the customer confirms, `applyPlanSwitch` changes the plan without a hosted page and waits for the `subscription.updated` webhook to move the tier.
681
+ Paddle Billing provider plugin for `billing-foundation`. Paddle acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key and webhook secret from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant), the public Paddle.js `client-token`, a `billingLive` master switch and an `environment` key (sandbox | live). `environment` is its own key because Paddle serves sandbox and live from different API hosts and a live key must never hit the sandbox host or the other way round; `billingLive` only decides whether checkouts are offered at all. All of them are runtime config, so keys rotate and prod goes live without a redeploy, and the `mask` on each derives the sysadmin settings screen and nav. Mount via `createSubscriptionPaddleFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret`/`clientToken` options are env to config bridge fallbacks (`PADDLE_API_KEY`, `PADDLE_WEBHOOK_SECRET`, `PADDLE_CLIENT_TOKEN`). The plugin always mounts; `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true, and billing counts as enabled only with the API key present. Webhooks arrive at `/webhooks/subscription/paddle` when mounted through the server-runtime `billing.paddle` boot option, or at `/api/subscription/webhook/paddle` when `createSubscriptionWebhookRoute` is mounted by hand and are verified with the `Paddle-Signature` header (HMAC-SHA256 over `ts:rawBody` keyed with the raw secret, any `h1` may match, 5 minute tolerance). Paddle.js can open checkouts with arbitrary `customData` from the browser, so `custom_data.tenantId` only locates the tenant stream: billing-foundation keeps a checkout ledger and accepts a webhook only for a transaction the server opened itself (a `subscription.created` must name it in `transaction_id`), so events for prices outside `priceToTier`, without a tenant or for foreign transactions are dropped. The `backfill-checkout-ledger` job ledgers Paddle checkouts that were open when the ledger was introduced, then goes quiet. Paddle has no hosted checkout page, so the feature serves the Default Payment Link itself at `/billing/paddle-checkout` (the Default Payment Link in the Paddle dashboard must point to `<APP_BASE_URL>/billing/paddle-checkout`; it is the only source, because checkouts are created without a `checkout.url`). Create subscription prices in the Paddle catalog with quantity minimum and maximum 1; for one-off packs set the quantity limits on purpose, because the payment event carries `quantity` and the app has to multiply its credits by it: an anonymous page with its own CSP that loads Paddle.js from cdn.paddle.com, the one external script this framework allows, and opens the overlay for the transaction. Implements checkout, customer portal, cancel and resume, `retrievePrices` (batched, 10-minute TTL cache), `retrieveSubscription` for the sync job, and an in-app plan switch: `previewPlanSwitch` shows the proration before the customer confirms, `applyPlanSwitch` changes the plan without a hosted page and waits for the `subscription.updated` webhook to move the tier.
666
682
 
667
683
  Category: billing
668
684
 
@@ -676,7 +692,6 @@ Config keys:
676
692
  | `billing-live` | boolean | system | `false` |
677
693
  | `client-token` | text | system | |
678
694
  | `environment` | select | system | `sandbox` |
679
- | `tenant-binding-key` | text | system | |
680
695
  | `webhook-secret` | text | system | |
681
696
 
682
697
  ## subscription-stripe
package/agents/widgets.md CHANGED
@@ -29,6 +29,12 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
29
29
  | `DetailList` | Read-only key-value list for detail views (dimmed label on the left, value on the right). |
30
30
  | `DispatcherProvider` | |
31
31
  | `Drawer` | Slide-in panel beside a list (e.g. mail reader next to the inbox) — thin wrapper over the Sheet primitive with header/body/footer slots so screens skip per-route Radix boilerplate. |
32
+ | `DrawnFilter` | |
33
+ | `DrawnPanel` | |
34
+ | `DrawnPencil` | |
35
+ | `DrawnSearch` | |
36
+ | `DrawnSparkles` | |
37
+ | `DrawnWand` | |
32
38
  | `DropdownMenu` | |
33
39
  | `DropdownMenuCheckboxItem` | |
34
40
  | `DropdownMenuContent` | |
@@ -37,14 +43,25 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
37
43
  | `DropdownMenuPortal` | |
38
44
  | `DropdownMenuSeparator` | |
39
45
  | `DropdownMenuTrigger` | |
46
+ | `EditorBody` | |
47
+ | `EditorFooter` | |
48
+ | `EditorFrame` | |
49
+ | `EditorHeader` | |
50
+ | `EditorInfoBar` | |
51
+ | `EditorLocaleSwitch` | |
52
+ | `EditorModeSwitch` | |
40
53
  | `EditorPanel` | |
54
+ | `EditorWorkbench` | |
41
55
  | `EmptyState` | Empty state with an optional icon and CTA, using the dashed-box style of entityList empty states as a standalone widget for custom screens. |
42
56
  | `ErrorState` | Error state based on the Banner primitive, with a retry button. |
43
57
  | `FeedList` | Non-tabular compact list (e.g. "upcoming appointments") — primary text plus an optional right-aligned trailing value for each row. |
44
58
  | `FileField` | File upload = Field + Input(kind:"file"\|"image"), based on FileRef. |
59
+ | `FileViewAction` | "View" action for a stored file: renders only for PDFs and opens the viewer in a drawer. |
45
60
  | `FloatingPanel` | Non-modal panel floating above the page: draggable by its header, resizable from all edges and corners, clamped to the viewport, geometry optionally remembered. |
46
61
  | `FormScreenShell` | |
47
62
  | `HeaderActionGroup` | |
63
+ | `HeaderActionPinned` | Marks an app header action (e.g. the assistant trigger) that stays in the bar on a phone, next to the bell; the rest of `headerActions` folds into the "…" menu. |
64
+ | `HtmlMailFrame` | Renders server-sanitized mail HTML in a script-free sandboxed iframe that grows to its content. |
48
65
  | `Icon` | |
49
66
  | `InfinityList` | Cursor-paginated scroll list (mail inbox, activity feeds) — loads the next page when the end sentinel becomes visible (IntersectionObserver), instead of a pager bar like QueryTable/entityList. |
50
67
  | `KumikoLink` | |
@@ -72,12 +89,17 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
72
89
  | `PlanGrid` | |
73
90
  | `PresenceAvatars` | Small round avatars of the people on a row, with "+n" for the rest; for list rows. |
74
91
  | `PresenceNotice` | One quiet line above a record: who else is on it and for how long. |
92
+ | `PreviewWidthFrame` | |
75
93
  | `PrimitivesProvider` | |
76
94
  | `ProfileMenu` | |
77
95
  | `ProgressBar` | Progress bar, `value` 0..1 (clamped). |
78
96
  | `ProgressList` | Label/value header and progress bar for each entry (for example, loan repayment progress). |
79
97
  | `PublicShell` | One header and footer for anonymous pages; `focus` narrows to a task column, `card` centers a single card (sign-in). |
80
98
  | `QueryTable` | |
99
+ | `RailField` | |
100
+ | `RailHint` | |
101
+ | `RailRow` | |
102
+ | `RailSection` | |
81
103
  | `RangeField` | Slider = Field + Input(kind:"range"). |
82
104
  | `RenderEdit` | |
83
105
  | `RenderField` | |
@@ -132,6 +154,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
132
154
  | `useDispatcher` | |
133
155
  | `useDispatcherStatus` | |
134
156
  | `useDraft` | Form state for calculator screens: a draft object plus `patch` for partial updates, and `field(name)` that provides `{ id, name, value, onChange }` props ready for field widgets (NumberField/MoneyField/PercentField). |
157
+ | `useFileMeta` | |
135
158
  | `useForm` | |
136
159
  | `useIsNarrowViewport` | |
137
160
  | `useIsViewportBelow` | |
@@ -160,6 +183,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
160
183
  | `buildFileUploadFormData` | |
161
184
  | `buildNavRegistrySlice` | |
162
185
  | `buildNavRegistrySliceForApp` | |
186
+ | `clearNavCollapseState` | Forgets the collapsed containers and the revealed screen; logout calls it so the next user starts expanded. |
163
187
  | `clearRememberedListState` | Forgets all remembered list state and the identity marker. |
164
188
  | `cn` | Standard shadcn helper: `clsx` combines conditional classes, while `tailwind-merge` resolves conflicts (for example, `px-2 px-4` → `px-4`). |
165
189
  | `createBrowserDraftStorage` | Default DraftStorage when createKumikoApp boots without one. |
@@ -175,6 +199,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
175
199
  | `filterByAccess` | |
176
200
  | `formatMoney` | |
177
201
  | `formatPath` | |
202
+ | `formatRelativeWhen` | |
178
203
  | `parsePath` | |
179
204
  | `parseTargetFromSearchParams` | Parses the current search parameters back into a TargetRef. |
180
205
  | `postWithDownload` | |
@@ -186,7 +211,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
186
211
  | `smoothPath` | Quadratic midpoint technique: smooths the zigzag line without overshoot (~5 lines instead of a Catmull-Rom/Bezier fit). |
187
212
  | `synthesizeActionFormEntity` | Builds a minimal EntityDefinition from the inline fields of an ActionForm or SecretMint screen. |
188
213
  | `synthesizeActionFormScreen` | Converts an ActionFormScreenDefinition or SecretMintScreenDefinition to the EntityEditScreen shape expected by RenderEdit. |
189
- | `uploadFileRef` | Posts one file to the stack's file endpoint (double-submit CSRF) and returns the new FileRef id. |
214
+ | `uploadFileRef` | Posts one file to the stack's file endpoint (double-submit CSRF) and returns the new FileRef id, or the claim handle when the server issued one (anonymous uploads), which a save must submit. |
190
215
 
191
216
  ## Constants
192
217
 
@@ -46,4 +46,5 @@ export declare const STATE_CHANGING_METHODS: ReadonlySet<string>;
46
46
  export declare const TENANT_HEADER_NAME = "X-Tenant";
47
47
  export declare const LOCALE_HEADER_NAME = "X-Locale";
48
48
  export declare const NO_ROUTE_MATCH_HEADER_NAME = "X-Kumiko-No-Route-Match";
49
+ export declare const APP_NOW_HEADER_NAME = "X-Kumiko-Now";
49
50
  export type Route = (typeof Routes)[keyof typeof Routes];
@@ -146,3 +146,7 @@ export const LOCALE_HEADER_NAME = "X-Locale";
146
146
  // "unregistered path" from "registered path, access denied" — a leak the
147
147
  // denying routes deliberately collapse into one status code.
148
148
  export const NO_ROUTE_MATCH_HEADER_NAME = "X-Kumiko-No-Route-Match";
149
+ // Every query answer carries the app clock (`ctx.clock`, a fixed clock in tests and screenshot
150
+ // runs) as an ISO instant, so the UI's "As of" and relative times follow the app, not the device.
151
+ // The renderer reads it by the same name (renderer/src/server-clock.ts).
152
+ export const APP_NOW_HEADER_NAME = "X-Kumiko-Now";
@@ -20,7 +20,6 @@ export const PAT_TOKEN_PREFIX = "kpat_";
20
20
  export function sessionCheckStatus(result) {
21
21
  return typeof result === "string" ? result : result.status;
22
22
  }
23
- // @wrapper-known error-helper
24
23
  function middlewareReject(c, opts) {
25
24
  return c.json({
26
25
  error: {
@@ -455,12 +454,14 @@ function resolveAgainstDefault(defaultTenantId, clientTenant) {
455
454
  async function resolveWithAuthoritativeResolver(c, tenantResolver, clientTenant) {
456
455
  const resolved = await tenantResolver(c);
457
456
  if (resolved !== null && resolved !== undefined) {
458
- if (clientTenant && clientTenant.id !== resolved) {
457
+ // A cookie is ambient state (possibly apex-scoped, left over from another
458
+ // tenant's subdomain); only an explicit header counts as a conflicting claim.
459
+ if (clientTenant && clientTenant.source === "header" && clientTenant.id !== resolved) {
459
460
  return {
460
461
  error: {
461
462
  code: "tenant_mismatch",
462
463
  status: 400,
463
- message: `${clientTenant.source} tenant disagrees with resolved tenant`,
464
+ message: "header tenant disagrees with resolved tenant",
464
465
  i18nKey: "auth.errors.tenantMismatch",
465
466
  details: { clientTenantId: clientTenant.id, resolvedTenantId: resolved },
466
467
  },
@@ -3,10 +3,11 @@ import { createAnonymousUser } from "../engine/system-user.js";
3
3
  import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
4
4
  import { NotFoundError } from "../errors/index.js";
5
5
  import { createFallbackLogger } from "../logging/utils.js";
6
+ import { MAX_RETURN_PATH_LENGTH } from "../utils/return-path-limit.js";
6
7
  const log = createFallbackLogger("kumiko");
7
8
  // Content is checked where the mail link is built (bundled-features knows the path rules); a bad
8
9
  // value must never void the whole body, or the request would silently send no mail.
9
- const returnToField = z.string().max(2048).optional().catch(undefined);
10
+ const returnToField = z.string().max(MAX_RETURN_PATH_LENGTH).optional().catch(undefined);
10
11
  // Cross-device try-first handover: an optional tenant-handover grant the signup-request
11
12
  // route forwards to the handler for server-side verification and binding —
12
13
  // the grant itself never appears anywhere else (URL, mail, log, response).
@@ -5,4 +5,5 @@ export declare function assertNoAggregateTypeKeyCollisions(registry: Registry):
5
5
  export declare function collectEntityDetailQueries(registry: Registry): ReadonlyMap<string, string>;
6
6
  export declare function collectEntityDetailAccess(registry: Registry): ReadonlyMap<string, AccessRule>;
7
7
  export declare function collectEntityReadAccess(registry: Registry): ReadonlyMap<string, readonly AccessRule[]>;
8
+ export declare function collectEntityQueryAccess(registry: Registry): ReadonlyMap<string, readonly AccessRule[]>;
8
9
  export declare function collectEntityRowReadMaps(registry: Registry): ReadonlyMap<string, OwnershipMap>;
@@ -80,6 +80,24 @@ export function collectEntityReadAccess(registry) {
80
80
  }
81
81
  return rulesByEntity;
82
82
  }
83
+ // Access rules of the query handlers that belong to an entity. Unlike collectEntityReadAccess,
84
+ // a handler that merely names the entity in liveEntities does not count: it returns signals,
85
+ // not the entity's rows, so it must not open derived values over the entity.
86
+ export function collectEntityQueryAccess(registry) {
87
+ assertNoAggregateTypeKeyCollisions(registry);
88
+ const rulesByEntity = new Map();
89
+ for (const [handlerName, handler] of registry.getAllQueryHandlers()) {
90
+ const entityName = registry.getHandlerEntity(handlerName);
91
+ if (entityName === undefined)
92
+ continue;
93
+ for (const key of new Set([entityName, toKebab(entityName)])) {
94
+ const rules = rulesByEntity.get(key) ?? [];
95
+ rules.push(handler.access);
96
+ rulesByEntity.set(key, rules);
97
+ }
98
+ }
99
+ return rulesByEntity;
100
+ }
83
101
  // Entities whose own access.read narrows rows per role (e.g. Driver sees only assigned rows).
84
102
  // A signal for such an entity must not name ids to a role that does not read every row.
85
103
  export function collectEntityRowReadMaps(registry) {
@@ -1,4 +1,9 @@
1
+ import type { RateLimitResolver } from "@cosmicdrift/kumiko-types/rate-limit-types";
1
2
  import { Hono } from "hono";
2
3
  import type { Registry } from "../../engine/types/index.ts";
3
4
  import type { Dispatcher } from "../../pipeline/dispatcher.ts";
4
- export declare function createExportRoutes(dispatcher: Dispatcher, registry: Registry): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
5
+ export declare const EXPORT_RATE_LIMIT: {
6
+ readonly limit: 60;
7
+ readonly windowSeconds: 60;
8
+ };
9
+ export declare function createExportRoutes(dispatcher: Dispatcher, registry: Registry, rateLimitResolver?: RateLimitResolver): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -1,5 +1,6 @@
1
1
  import { Hono } from "hono";
2
2
  import * as z from "zod";
3
+ import { RateLimitError } from "../../errors/classes.js";
3
4
  import { toKumikoError } from "../../errors/to-kumiko-error.js";
4
5
  import { createI18n } from "../../i18n/index.js";
5
6
  import { DEFAULT_LOCALE } from "../../i18n/request-locale.js";
@@ -14,6 +15,10 @@ import { resolveExportPlan } from "./export-screen.js";
14
15
  import { writeExportWorkbook } from "./export-xlsx-writer.js";
15
16
  const XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
16
17
  const MAX_ID_LENGTH = 200;
18
+ // One export fans out into up to maxRows / MAX_LIST_LIMIT queries and buffers the whole
19
+ // workbook; the per-request IP limiter counts it as a single request.
20
+ const EXPORT_BUCKET = "export-xlsx-in-flight";
21
+ const EXPORT_RETRY_AFTER_SECONDS = 5;
17
22
  const exportBodySchema = z.object({
18
23
  screen: z.string().max(MAX_ID_LENGTH),
19
24
  payload: z.record(z.string(), z.unknown()).default({}),
@@ -32,12 +37,30 @@ function downloadFileName(screenShortId, now) {
32
37
  const safeId = screenShortId.replace(/[^A-Za-z0-9_-]/g, "_");
33
38
  return `${safeId}-${now.toISOString().slice(0, 10)}.xlsx`;
34
39
  }
35
- export function createExportRoutes(dispatcher, registry) {
40
+ function exportAlreadyRunning() {
41
+ return new RateLimitError({
42
+ bucket: EXPORT_BUCKET,
43
+ limit: 1,
44
+ windowSeconds: EXPORT_RETRY_AFTER_SECONDS,
45
+ remaining: 0,
46
+ retryAfterSeconds: EXPORT_RETRY_AFTER_SECONDS,
47
+ resetAt: new Date(Date.now() + EXPORT_RETRY_AFTER_SECONDS * 1000).toISOString(),
48
+ });
49
+ }
50
+ export const EXPORT_RATE_LIMIT = { limit: 60, windowSeconds: 60 };
51
+ export function createExportRoutes(dispatcher, registry, rateLimitResolver) {
36
52
  const api = new Hono();
37
53
  const i18n = createI18n(registry, { defaultLocale: DEFAULT_LOCALE });
54
+ const exportsInFlight = new Set();
38
55
  api.post(Routes.exportXlsx, async (c) => {
39
56
  const user = getUser(c);
57
+ const inFlightKey = `${user.tenantId}:${user.id}`;
58
+ if (exportsInFlight.has(inFlightKey)) {
59
+ return queryErrorResponse(c, exportAlreadyRunning(), Routes.exportXlsx);
60
+ }
61
+ exportsInFlight.add(inFlightKey);
40
62
  try {
63
+ await rateLimitResolver?.enforce(`export-xlsx:${inFlightKey}`, EXPORT_RATE_LIMIT);
41
64
  const parsed = exportBodySchema.safeParse(await c.req.json().catch(() => undefined));
42
65
  if (!parsed.success)
43
66
  throw exportRejection("export_invalid_request", "body");
@@ -70,6 +93,9 @@ export function createExportRoutes(dispatcher, registry) {
70
93
  catch (e) {
71
94
  return queryErrorResponse(c, toKumikoError(e), Routes.exportXlsx);
72
95
  }
96
+ finally {
97
+ exportsInFlight.delete(inFlightKey);
98
+ }
73
99
  });
74
100
  return api;
75
101
  }
@@ -33,11 +33,22 @@ function parsePage(result, queryType) {
33
33
  nextCursor: typeof nextCursor === "string" && nextCursor !== "" ? nextCursor : undefined,
34
34
  };
35
35
  }
36
+ // Rows without a string id cannot be told apart, so they always count as unseen.
37
+ function claimRowId(row, seenRowIds) {
38
+ const id = row["id"];
39
+ if (typeof id !== "string")
40
+ return true;
41
+ if (seenRowIds.has(id))
42
+ return false;
43
+ seenRowIds.add(id);
44
+ return true;
45
+ }
36
46
  /** Reads the whole filtered list page by page; gives up as soon as more than `maxRows` exist. */
37
47
  export async function readExportRows(dispatcher, plan, clientPayload, user) {
38
48
  const base = sanitizeExportPayload(clientPayload, plan);
39
49
  const rows = [];
40
50
  const seenCursors = new Set();
51
+ const seenRowIds = new Set();
41
52
  let cursor;
42
53
  for (;;) {
43
54
  const limit = Math.min(MAX_LIST_LIMIT, plan.maxRows + 1 - rows.length);
@@ -47,11 +58,16 @@ export async function readExportRows(dispatcher, plan, clientPayload, user) {
47
58
  ? { ...base, limit, offset: rows.length }
48
59
  : { ...base, limit };
49
60
  const page = parsePage(await dispatcher.query(plan.queryType, pagingPayload, user), plan.queryType);
50
- rows.push(...page.rows);
61
+ const freshRows = page.rows.filter((row) => claimRowId(row, seenRowIds));
62
+ rows.push(...freshRows);
51
63
  if (rows.length > plan.maxRows)
52
64
  return { tooMany: true };
53
- // A short or empty page is the end of the list; a repeated cursor would loop forever.
54
- if (page.rows.length < limit || page.rows.length === 0)
65
+ // A short page proves nothing (a query may cap `limit` itself), so only an empty page ends the
66
+ // list. A page without any unseen row means the query ignores offset/cursor and would repeat
67
+ // itself until maxRows. A repeated cursor would loop forever.
68
+ if (page.rows.length === 0 || freshRows.length === 0)
69
+ return { tooMany: false, rows };
70
+ if (cursor !== undefined && page.nextCursor === undefined)
55
71
  return { tooMany: false, rows };
56
72
  if (page.nextCursor !== undefined) {
57
73
  if (seenCursors.has(page.nextCursor))
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { IrreversibleWithoutEntryHandler } from "@cosmicdrift/kumiko-types/config";
2
3
  import type { WriteOrigin } from "@cosmicdrift/kumiko-types/event-store-types";
3
4
  import type { AgentRisk } from "@cosmicdrift/kumiko-types/handlers";
4
5
  import type { ErrorDocsConfig } from "../errors/docs-url.ts";
@@ -23,6 +24,7 @@ export type RequestContextData = {
23
24
  };
24
25
  readonly chargedRateLimitBuckets?: Set<string>;
25
26
  readonly agentToolCall?: true;
27
+ readonly irreversibleWithoutEntryHandler?: IrreversibleWithoutEntryHandler;
26
28
  };
27
29
  export declare const storage: AsyncLocalStorage<RequestContextData>;
28
30
  export declare function setRequestIdentity(identity: {
@@ -50,11 +50,18 @@ export function runWithOrigin(origin, fn) {
50
50
  export function isAgentToolCallScope() {
51
51
  return requestContext.get()?.agentToolCall === true;
52
52
  }
53
+ function withoutIrreversibleExemption(data) {
54
+ const { irreversibleWithoutEntryHandler: _irreversibleWithoutEntryHandler, ...rest } = data;
55
+ return rest;
56
+ }
53
57
  // An ungated origin never mints a scope: seeds and boot writes keep their missing context.
58
+ // Hooks and nested dispatches run through here too, so a job's or consumer's irreversible-operation
59
+ // exception ends at this boundary and is never inherited by them.
54
60
  export function runWithWriteOrigin(origin, fn) {
55
- const current = requestContext.get();
61
+ const scope = requestContext.get();
62
+ const current = scope && withoutIrreversibleExemption(scope);
56
63
  if (!isPersonalDataGated(origin)) {
57
- if (!current?.writeOrigin)
64
+ if (!current || (!scope?.writeOrigin && !scope?.irreversibleWithoutEntryHandler))
58
65
  return fn();
59
66
  const { writeOrigin: _writeOrigin, ...rest } = current;
60
67
  return requestContext.run(rest, fn);
@@ -46,7 +46,7 @@ export const requestContext = {
46
46
  export function runAsAgentToolCallEntry(fn) {
47
47
  const current = requestContext.get();
48
48
  const requestId = current?.requestId ?? requestContext.generateId();
49
- const { entryHandler: _entryHandler, ...rest } = current ?? {};
49
+ const { entryHandler: _entryHandler, irreversibleWithoutEntryHandler: _irreversibleWithoutEntryHandler, ...rest } = current ?? {};
50
50
  return requestContext.run({
51
51
  ...rest,
52
52
  requestId,
@@ -1,3 +1,4 @@
1
+ import type { Clock } from "@cosmicdrift/kumiko-types/tz-context";
1
2
  import { type Context, Hono } from "hono";
2
3
  import { type KumikoError } from "../errors/index.ts";
3
4
  import type { Dispatcher } from "../pipeline/dispatcher.ts";
@@ -9,6 +10,7 @@ export declare const StreamFrame: {
9
10
  };
10
11
  export type ApiRoutesOptions = {
11
12
  readonly sseHeartbeatMs?: number;
13
+ readonly clock?: Clock;
12
14
  };
13
15
  export declare function createApiRoutes(dispatcher: Dispatcher, options?: ApiRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
14
16
  export type SseWriter = {