@cosmicdrift/kumiko-samples 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 (459) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +16 -1
  3. package/packages/bundled-features/src/admin-shell/changes.json +6 -0
  4. package/packages/bundled-features/src/admin-shell/feature.ts +8 -7
  5. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +5 -1
  6. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +36 -27
  7. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +8 -1
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +3 -2
  9. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +6 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +1 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +38 -1
  12. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +1 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/resolve-config.ts +17 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/scope-slug-collisions.ts +17 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/translation-gaps.ts +42 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/webhook-example-problems.ts +30 -0
  17. package/packages/bundled-features/src/agent-tools/changes.json +12 -0
  18. package/packages/bundled-features/src/agent-tools/index.ts +1 -0
  19. package/packages/bundled-features/src/agent-tools/labels.ts +19 -6
  20. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +18 -7
  21. package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +14 -1
  22. package/packages/bundled-features/src/agent-tools/types.ts +4 -0
  23. package/packages/bundled-features/src/audit/event-classification.ts +6 -0
  24. package/packages/bundled-features/src/audit/web/i18n.ts +1 -0
  25. package/packages/bundled-features/src/auth-email-password/changes.json +18 -0
  26. package/packages/bundled-features/src/auth-email-password/errors.ts +0 -13
  27. package/packages/bundled-features/src/auth-email-password/handlers/invite-signup-complete.write.ts +147 -121
  28. package/packages/bundled-features/src/auth-email-password/handlers/login-options.query.ts +1 -1
  29. package/packages/bundled-features/src/auth-email-password/handlers/request-account-unlock.write.ts +1 -1
  30. package/packages/bundled-features/src/auth-email-password/handlers/request-email-verification.write.ts +0 -1
  31. package/packages/bundled-features/src/auth-email-password/handlers/request-password-reset.write.ts +0 -1
  32. package/packages/bundled-features/src/auth-email-password/handlers/self-registration-status.query.ts +1 -1
  33. package/packages/bundled-features/src/auth-email-password/reset-token.ts +0 -2
  34. package/packages/bundled-features/src/auth-email-password/seeding.ts +39 -7
  35. package/packages/bundled-features/src/auth-email-password/unlock-token.ts +0 -2
  36. package/packages/bundled-features/src/auth-email-password/verification-token.ts +0 -2
  37. package/packages/bundled-features/src/auth-email-password/web/auth-form-primitives.tsx +2 -2
  38. package/packages/bundled-features/src/auth-email-password/web/auth-gate.tsx +2 -2
  39. package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +5 -0
  40. package/packages/bundled-features/src/auth-email-password/web/forgot-password-screen.tsx +1 -6
  41. package/packages/bundled-features/src/auth-email-password/web/invite-accept-screen.tsx +1 -1
  42. package/packages/bundled-features/src/auth-email-password/web/return-path.ts +2 -1
  43. package/packages/bundled-features/src/auth-email-password/web/session.tsx +10 -12
  44. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +1 -6
  45. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +6 -1
  46. package/packages/bundled-features/src/auth-email-password/web/tenant-switcher.tsx +1 -1
  47. package/packages/bundled-features/src/auth-email-password/web/token-confirm-screen.tsx +4 -5
  48. package/packages/bundled-features/src/auth-email-password/web/user-menu.tsx +1 -1
  49. package/packages/bundled-features/src/auth-mfa/web/mfa-code-or-recovery-field.tsx +17 -1
  50. package/packages/bundled-features/src/auth-mfa/web/mfa-disable-dialog.tsx +1 -1
  51. package/packages/bundled-features/src/auth-mfa/web/mfa-regenerate-recovery-dialog.tsx +1 -1
  52. package/packages/bundled-features/src/auth-mfa/web/mfa-setup-preauth-screen.tsx +1 -1
  53. package/packages/bundled-features/src/auth-mfa/web/mfa-verify-screen.tsx +16 -47
  54. package/packages/bundled-features/src/auth-mfa-user-data/index.ts +5 -6
  55. package/packages/bundled-features/src/billing-foundation/aggregate-id.ts +0 -4
  56. package/packages/bundled-features/src/billing-foundation/changes.json +37 -0
  57. package/packages/bundled-features/src/billing-foundation/checkout-core.ts +8 -1
  58. package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +59 -0
  59. package/packages/bundled-features/src/billing-foundation/consumer-protection/consent-gate.ts +2 -1
  60. package/packages/bundled-features/src/billing-foundation/consumer-protection/consent-text.ts +49 -2
  61. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-open-cancels.ts +5 -0
  62. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-provider-timeout.ts +23 -0
  63. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-record.ts +12 -7
  64. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-revoke.ts +1 -1
  65. package/packages/bundled-features/src/billing-foundation/events.ts +49 -10
  66. package/packages/bundled-features/src/billing-foundation/feature.ts +15 -1
  67. package/packages/bundled-features/src/billing-foundation/handlers/billing-plans.query.ts +47 -14
  68. package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +7 -1
  69. package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +124 -10
  70. package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +33 -9
  71. package/packages/bundled-features/src/billing-foundation/handlers/record-checkout-opened.write.ts +25 -0
  72. package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +7 -1
  73. package/packages/bundled-features/src/billing-foundation/handlers/switch-plan.write.ts +16 -4
  74. package/packages/bundled-features/src/billing-foundation/i18n.ts +3 -0
  75. package/packages/bundled-features/src/billing-foundation/pending-plan-switch.ts +80 -0
  76. package/packages/bundled-features/src/billing-foundation/scrub-raw-payload-headers.ts +50 -0
  77. package/packages/bundled-features/src/billing-foundation/types.ts +47 -30
  78. package/packages/bundled-features/src/billing-foundation/validate-options.ts +18 -0
  79. package/packages/bundled-features/src/billing-foundation/web/billing-plans-panel.tsx +10 -5
  80. package/packages/bundled-features/src/billing-foundation/web/cancel-contract-dialog.tsx +1 -1
  81. package/packages/bundled-features/src/billing-foundation/web/checkout-consent-dialog.tsx +1 -1
  82. package/packages/bundled-features/src/billing-foundation/web/constants.ts +5 -2
  83. package/packages/bundled-features/src/billing-foundation/web/plan-switch-confirm-dialog.tsx +1 -1
  84. package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +65 -17
  85. package/packages/bundled-features/src/cap-counter/aggregate-id.ts +0 -2
  86. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  87. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +19 -4
  88. package/packages/bundled-features/src/cap-overview/changes.json +6 -0
  89. package/packages/bundled-features/src/cap-overview/handlers/tenant-caps-list.query.ts +22 -6
  90. package/packages/bundled-features/src/cap-overview/i18n.ts +1 -0
  91. package/packages/bundled-features/src/cap-overview/index.ts +1 -0
  92. package/packages/bundled-features/src/cap-overview/types.ts +11 -1
  93. package/packages/bundled-features/src/cap-overview/web/cap-cards-panel.tsx +6 -2
  94. package/packages/bundled-features/src/cap-overview/web/cap-usage-bar.tsx +10 -1
  95. package/packages/bundled-features/src/cap-overview/web/usage-math.ts +5 -0
  96. package/packages/bundled-features/src/channel-in-app/changes.json +6 -0
  97. package/packages/bundled-features/src/channel-in-app/handlers/read-state-by-keys.query.ts +2 -2
  98. package/packages/bundled-features/src/channel-whatsapp/aggregate-id.ts +29 -0
  99. package/packages/bundled-features/src/channel-whatsapp/changes.json +8 -0
  100. package/packages/bundled-features/src/channel-whatsapp/constants.ts +46 -0
  101. package/packages/bundled-features/src/channel-whatsapp/events.ts +93 -0
  102. package/packages/bundled-features/src/channel-whatsapp/feature.ts +72 -0
  103. package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +398 -0
  104. package/packages/bundled-features/src/channel-whatsapp/in-memory-meta.ts +300 -0
  105. package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +189 -0
  106. package/packages/bundled-features/src/channel-whatsapp/index.ts +66 -0
  107. package/packages/bundled-features/src/channel-whatsapp/meta-signature.ts +26 -0
  108. package/packages/bundled-features/src/channel-whatsapp/options.ts +149 -0
  109. package/packages/bundled-features/src/channel-whatsapp/pii.ts +109 -0
  110. package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +226 -0
  111. package/packages/bundled-features/src/channel-whatsapp/webhook-routes.ts +185 -0
  112. package/packages/bundled-features/src/compliance-profiles/handlers/sub-processors.query.ts +1 -1
  113. package/packages/bundled-features/src/config/changes.json +12 -0
  114. package/packages/bundled-features/src/config/handlers/set.write.ts +7 -0
  115. package/packages/bundled-features/src/config/handlers/values.query.ts +8 -1
  116. package/packages/bundled-features/src/config/index.ts +1 -0
  117. package/packages/bundled-features/src/config/read-redaction.ts +6 -3
  118. package/packages/bundled-features/src/config/table.ts +1 -0
  119. package/packages/bundled-features/src/config/write-helpers.ts +3 -2
  120. package/packages/bundled-features/src/crypto-shredding/changes.json +18 -0
  121. package/packages/bundled-features/src/crypto-shredding/constants.ts +2 -0
  122. package/packages/bundled-features/src/crypto-shredding/handlers/forget-subject.write.ts +38 -18
  123. package/packages/bundled-features/src/crypto-shredding/index.ts +4 -0
  124. package/packages/bundled-features/src/crypto-shredding/subject-forget-after-delete-hook.ts +49 -0
  125. package/packages/bundled-features/src/custom-fields/aggregate-id.ts +0 -1
  126. package/packages/bundled-features/src/custom-fields/entity.ts +1 -0
  127. package/packages/bundled-features/src/custom-fields/wire-for-entity.ts +0 -1
  128. package/packages/bundled-features/src/data-retention/changes.json +18 -0
  129. package/packages/bundled-features/src/data-retention/erase-notes-of-deleted-row.ts +23 -0
  130. package/packages/bundled-features/src/data-retention/feature.ts +4 -7
  131. package/packages/bundled-features/src/data-retention/run-retention-cleanup.ts +38 -18
  132. package/packages/bundled-features/src/data-retention/tenant-destruction-hold.ts +9 -0
  133. package/packages/bundled-features/src/delivery/attempt-log-factory.ts +11 -0
  134. package/packages/bundled-features/src/delivery/attempt-log.ts +3 -3
  135. package/packages/bundled-features/src/delivery/changes.json +6 -0
  136. package/packages/bundled-features/src/delivery/channel-context.ts +6 -3
  137. package/packages/bundled-features/src/delivery/db/queries/preferences.ts +0 -1
  138. package/packages/bundled-features/src/delivery/delivery-service.ts +3 -0
  139. package/packages/bundled-features/src/delivery/feature.ts +4 -13
  140. package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +45 -0
  141. package/packages/bundled-features/src/delivery/handlers/preferences.query.ts +2 -20
  142. package/packages/bundled-features/src/delivery/handlers/resubscribe-user.write.ts +2 -25
  143. package/packages/bundled-features/src/delivery/handlers/unsubscribe-page-chrome.query.ts +2 -0
  144. package/packages/bundled-features/src/delivery/handlers/unsubscribe-user.write.ts +2 -27
  145. package/packages/bundled-features/src/delivery/index.ts +3 -1
  146. package/packages/bundled-features/src/delivery/options.ts +11 -0
  147. package/packages/bundled-features/src/delivery/preference-rows.ts +33 -0
  148. package/packages/bundled-features/src/delivery/set-preference-enabled.ts +40 -0
  149. package/packages/bundled-features/src/delivery/testing.ts +3 -1
  150. package/packages/bundled-features/src/delivery/types.ts +1 -0
  151. package/packages/bundled-features/src/delivery/unsubscribe-page.ts +7 -1
  152. package/packages/bundled-features/src/delivery/upsert-preference.ts +0 -1
  153. package/packages/bundled-features/src/delivery/web/public-names.ts +1 -0
  154. package/packages/bundled-features/src/derivatives-sharp/render.ts +9 -9
  155. package/packages/bundled-features/src/document-ingest-foundation/aggregate-id.ts +0 -1
  156. package/packages/bundled-features/src/document-ingest-foundation/append-missing-extract-event.ts +37 -25
  157. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +32 -14
  158. package/packages/bundled-features/src/documents/aggregate-id.ts +0 -2
  159. package/packages/bundled-features/src/documents/changes.json +18 -0
  160. package/packages/bundled-features/src/documents/constants.ts +10 -2
  161. package/packages/bundled-features/src/documents/ensure-link.ts +3 -4
  162. package/packages/bundled-features/src/documents/feature.ts +28 -6
  163. package/packages/bundled-features/src/documents/handlers/import.write.ts +2 -2
  164. package/packages/bundled-features/src/documents/queries/expiry-overview.query.ts +2 -1
  165. package/packages/bundled-features/src/documents/queries/for-record.query.ts +3 -4
  166. package/packages/bundled-features/src/documents/queries/list-page.ts +11 -3
  167. package/packages/bundled-features/src/documents/queries/overview.query.ts +2 -2
  168. package/packages/bundled-features/src/documents/screens.ts +8 -3
  169. package/packages/bundled-features/src/documents/tab.ts +1 -1
  170. package/packages/bundled-features/src/feature-toggles/toggle-sync-signal.ts +6 -3
  171. package/packages/bundled-features/src/file-derivatives/handlers/public-variant-by-file-ref.query.ts +1 -1
  172. package/packages/bundled-features/src/file-derivatives/handlers/public-variant.query.ts +1 -1
  173. package/packages/bundled-features/src/file-foundation/probe.ts +9 -3
  174. package/packages/bundled-features/src/file-foundation/read-file-ref-content.ts +24 -11
  175. package/packages/bundled-features/src/file-provider-inmemory/feature.ts +1 -1
  176. package/packages/bundled-features/src/file-provider-s3/changes.json +14 -0
  177. package/packages/bundled-features/src/file-provider-s3/env-feature.ts +1 -1
  178. package/packages/bundled-features/src/file-provider-s3/env-named-feature.ts +1 -1
  179. package/packages/bundled-features/src/file-provider-s3/env-schema.ts +24 -7
  180. package/packages/bundled-features/src/file-provider-s3/feature.ts +1 -1
  181. package/packages/bundled-features/src/file-provider-s3/index.ts +7 -1
  182. package/packages/bundled-features/src/file-provider-s3/lib/env-helper.ts +21 -13
  183. package/packages/bundled-features/src/file-provider-s3/lib/s3-provider.ts +8 -1
  184. package/packages/bundled-features/src/files/changes.json +7 -0
  185. package/packages/bundled-features/src/folders/aggregate-id.ts +0 -1
  186. package/packages/bundled-features/src/folders/web/folder-manager.tsx +6 -6
  187. package/packages/bundled-features/src/folders-user-data/index.ts +12 -14
  188. package/packages/bundled-features/src/helpdesk/changes.json +62 -0
  189. package/packages/bundled-features/src/helpdesk/entity.ts +4 -1
  190. package/packages/bundled-features/src/helpdesk/feature.ts +41 -0
  191. package/packages/bundled-features/src/helpdesk/handlers/access.ts +0 -10
  192. package/packages/bundled-features/src/helpdesk/handlers/attempts.ts +7 -14
  193. package/packages/bundled-features/src/helpdesk/handlers/challenge.query.ts +1 -2
  194. package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +2 -9
  195. package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +2 -9
  196. package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +3 -11
  197. package/packages/bundled-features/src/helpdesk/index.ts +1 -0
  198. package/packages/bundled-features/src/helpdesk/legacy-contact-config.ts +61 -0
  199. package/packages/bundled-features/src/helpdesk/legacy-contact-erasure.ts +45 -0
  200. package/packages/bundled-features/src/helpdesk/legacy-contact-retention.ts +65 -0
  201. package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +185 -0
  202. package/packages/bundled-features/src/helpdesk/legacy-contact-user-data.ts +84 -0
  203. package/packages/bundled-features/src/helpdesk/lib.ts +47 -34
  204. package/packages/bundled-features/src/helpdesk/user-data-hooks.ts +89 -48
  205. package/packages/bundled-features/src/helpdesk/web/constants.ts +0 -1
  206. package/packages/bundled-features/src/inbound-mail-foundation/account-health.ts +1 -1
  207. package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +5 -1
  208. package/packages/bundled-features/src/inbound-mail-foundation/aggregate-id.ts +0 -2
  209. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +48 -0
  210. package/packages/bundled-features/src/inbound-mail-foundation/constants.ts +6 -0
  211. package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +15 -1
  212. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +64 -15
  213. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +15 -16
  214. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +3 -1
  215. package/packages/bundled-features/src/inbound-mail-foundation/handlers/account-address.ts +16 -2
  216. package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +10 -3
  217. package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +21 -8
  218. package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +73 -0
  219. package/packages/bundled-features/src/inbound-mail-foundation/i18n.ts +3 -0
  220. package/packages/bundled-features/src/inbound-mail-foundation/index.ts +1 -0
  221. package/packages/bundled-features/src/inbound-mail-foundation/oauth-access-token.ts +1 -1
  222. package/packages/bundled-features/src/inbound-mail-foundation/outbound-mail.ts +2 -0
  223. package/packages/bundled-features/src/inbound-mail-foundation/personal-address.ts +20 -0
  224. package/packages/bundled-features/src/inbound-mail-foundation/purge-messages.ts +54 -0
  225. package/packages/bundled-features/src/inbound-mail-foundation/quarantine.ts +15 -5
  226. package/packages/bundled-features/src/inbound-mail-foundation/retention-job.ts +1 -5
  227. package/packages/bundled-features/src/inbound-mail-foundation/retention-sweep.ts +21 -34
  228. package/packages/bundled-features/src/inbound-mail-foundation/send-from-account.ts +9 -1
  229. package/packages/bundled-features/src/inbound-mail-foundation/supervisor-ingest.ts +7 -1
  230. package/packages/bundled-features/src/inbound-mail-foundation/sync-account-now.ts +1 -1
  231. package/packages/bundled-features/src/inbound-mail-foundation/tenant-destroy-hook.ts +14 -17
  232. package/packages/bundled-features/src/inbound-mail-foundation/watch-supervisor.ts +1 -1
  233. package/packages/bundled-features/src/inbound-provider-imap/byte-budget.ts +80 -0
  234. package/packages/bundled-features/src/inbound-provider-imap/changes.json +13 -0
  235. package/packages/bundled-features/src/inbound-provider-imap/connect-mailbox.ts +8 -4
  236. package/packages/bundled-features/src/inbound-provider-imap/connect-my-mailbox.ts +23 -6
  237. package/packages/bundled-features/src/inbound-provider-imap/connect-target-rate-limit.ts +46 -0
  238. package/packages/bundled-features/src/inbound-provider-imap/download-batch.ts +47 -10
  239. package/packages/bundled-features/src/inbound-provider-imap/feature.ts +7 -4
  240. package/packages/bundled-features/src/inbound-provider-imap/fetch-content.ts +43 -29
  241. package/packages/bundled-features/src/inbound-provider-imap/i18n.ts +2 -2
  242. package/packages/bundled-features/src/inbound-provider-imap/parse-message.ts +14 -0
  243. package/packages/bundled-features/src/inbound-provider-imap/reconnect-mailbox.ts +5 -4
  244. package/packages/bundled-features/src/inbound-provider-imap/send-mail.ts +39 -7
  245. package/packages/bundled-features/src/inbound-provider-imap/smtp-client.ts +19 -4
  246. package/packages/bundled-features/src/inbound-provider-imap/watch-mailbox.ts +8 -23
  247. package/packages/bundled-features/src/inbound-provider-inmemory/feature.ts +1 -1
  248. package/packages/bundled-features/src/jobs/events.ts +10 -0
  249. package/packages/bundled-features/src/jobs/feature.ts +2 -0
  250. package/packages/bundled-features/src/jobs/handlers/consumer.write.ts +41 -16
  251. package/packages/bundled-features/src/jobs/web/constants.ts +4 -0
  252. package/packages/bundled-features/src/mail-foundation/changes.json +6 -0
  253. package/packages/bundled-features/src/mail-transport-inmemory/feature.ts +1 -1
  254. package/packages/bundled-features/src/mail-transport-smtp/feature.ts +3 -2
  255. package/packages/bundled-features/src/managed-pages/changes.json +12 -0
  256. package/packages/bundled-features/src/managed-pages/handlers/branding.query.ts +1 -1
  257. package/packages/bundled-features/src/managed-pages/handlers/by-slug.query.ts +1 -1
  258. package/packages/bundled-features/src/managed-pages/handlers/by-tenant-published.query.ts +1 -1
  259. package/packages/bundled-features/src/managed-pages/render-page-body.ts +18 -10
  260. package/packages/bundled-features/src/managed-pages/screens/page-screens.ts +18 -38
  261. package/packages/bundled-features/src/managed-pages/table.ts +1 -0
  262. package/packages/bundled-features/src/managed-pages/web/client-plugin.tsx +8 -6
  263. package/packages/bundled-features/src/managed-pages/web/constants.ts +8 -1
  264. package/packages/bundled-features/src/managed-pages/web/i18n.ts +11 -3
  265. package/packages/bundled-features/src/managed-pages/web/markdown-to-document.ts +1 -1
  266. package/packages/bundled-features/src/managed-pages/web/page-edit-draft.ts +108 -0
  267. package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +198 -0
  268. package/packages/bundled-features/src/managed-pages/web/page-settings-rail.tsx +117 -0
  269. package/packages/bundled-features/src/notes-history-user-data/index.ts +8 -14
  270. package/packages/bundled-features/src/personal-access-tokens/boot-rules.ts +5 -0
  271. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +0 -1
  272. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +31 -5
  273. package/packages/bundled-features/src/presence/changes.json +6 -0
  274. package/packages/bundled-features/src/presence/handlers/list.query.ts +28 -11
  275. package/packages/bundled-features/src/presence/room.ts +21 -7
  276. package/packages/bundled-features/src/presence/store.ts +79 -21
  277. package/packages/bundled-features/src/readiness/changes.json +25 -0
  278. package/packages/bundled-features/src/readiness/handlers/latest-summary.query.ts +11 -6
  279. package/packages/bundled-features/src/readiness/handlers/run-probes.write.ts +35 -5
  280. package/packages/bundled-features/src/readiness/handlers/run-tone.ts +3 -2
  281. package/packages/bundled-features/src/readiness/handlers/status.query.ts +15 -1
  282. package/packages/bundled-features/src/readiness/probe-context.ts +11 -10
  283. package/packages/bundled-features/src/readiness/screens.ts +4 -4
  284. package/packages/bundled-features/src/readiness/visible-results.ts +5 -3
  285. package/packages/bundled-features/src/renderer-foundation/api.ts +6 -13
  286. package/packages/bundled-features/src/renderer-foundation/types.ts +2 -2
  287. package/packages/bundled-features/src/secrets/changes.json +7 -0
  288. package/packages/bundled-features/src/secrets/db/queries/read.ts +18 -4
  289. package/packages/bundled-features/src/secrets/handlers/list.query.ts +8 -2
  290. package/packages/bundled-features/src/secrets/secret-scope.ts +2 -3
  291. package/packages/bundled-features/src/secrets/secrets-context.ts +6 -4
  292. package/packages/bundled-features/src/secrets/write-gate.ts +4 -2
  293. package/packages/bundled-features/src/seo/handlers/seo-config.query.ts +1 -1
  294. package/packages/bundled-features/src/shared/acknowledged-system-db.ts +20 -0
  295. package/packages/bundled-features/src/shared/assert-billing-live.ts +9 -2
  296. package/packages/bundled-features/src/shared/changes.json +6 -0
  297. package/packages/bundled-features/src/shared/index.ts +6 -1
  298. package/packages/bundled-features/src/shared/parent-visibility.ts +25 -1
  299. package/packages/bundled-features/src/shared/password-hashing.ts +0 -1
  300. package/packages/bundled-features/src/shared/price-env-shape.ts +1 -4
  301. package/packages/bundled-features/src/shared/register-user-data-hooks.ts +29 -0
  302. package/packages/bundled-features/src/shared/require-bootstrap-extension.ts +26 -0
  303. package/packages/bundled-features/src/shared/send-best-effort.ts +19 -0
  304. package/packages/bundled-features/src/shared/stream-tenant-backfill.ts +22 -1
  305. package/packages/bundled-features/src/shared/stream-tenant-derived-state.ts +31 -1
  306. package/packages/bundled-features/src/step-dispatcher/changes.json +12 -0
  307. package/packages/bundled-features/src/step-dispatcher/constants.ts +13 -0
  308. package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +47 -2
  309. package/packages/bundled-features/src/step-dispatcher/feature.ts +28 -1
  310. package/packages/bundled-features/src/step-dispatcher/mail-runner.ts +0 -1
  311. package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +57 -0
  312. package/packages/bundled-features/src/subscription-mollie/changes.json +7 -0
  313. package/packages/bundled-features/src/subscription-mollie/plugin-methods.ts +5 -3
  314. package/packages/bundled-features/src/subscription-mollie/verify-webhook.ts +5 -5
  315. package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +159 -0
  316. package/packages/bundled-features/src/subscription-paddle/changes.json +13 -0
  317. package/packages/bundled-features/src/subscription-paddle/checkout-config.query.ts +1 -1
  318. package/packages/bundled-features/src/subscription-paddle/checkout-methods.ts +2 -8
  319. package/packages/bundled-features/src/subscription-paddle/constants.ts +1 -2
  320. package/packages/bundled-features/src/subscription-paddle/feature.ts +26 -24
  321. package/packages/bundled-features/src/subscription-paddle/ledger-backfill-marker.ts +70 -0
  322. package/packages/bundled-features/src/subscription-paddle/plan-switch-methods.ts +2 -8
  323. package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +36 -0
  324. package/packages/bundled-features/src/subscription-paddle/runtime.ts +13 -24
  325. package/packages/bundled-features/src/subscription-paddle/subscription-state.ts +1 -0
  326. package/packages/bundled-features/src/subscription-paddle/webhook-events.ts +68 -21
  327. package/packages/bundled-features/src/subscription-stripe/changes.json +7 -0
  328. package/packages/bundled-features/src/subscription-stripe/feature.ts +5 -0
  329. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +6 -6
  330. package/packages/bundled-features/src/subscription-stripe/runtime.ts +8 -7
  331. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +24 -6
  332. package/packages/bundled-features/src/tags/aggregate-id.ts +0 -1
  333. package/packages/bundled-features/src/tags/web/tag-chip.tsx +4 -5
  334. package/packages/bundled-features/src/tags/web/tag-manager.tsx +2 -1
  335. package/packages/bundled-features/src/template-resolver/api.ts +6 -13
  336. package/packages/bundled-features/src/template-resolver/changes.json +36 -0
  337. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +25 -0
  338. package/packages/bundled-features/src/template-resolver/feature.ts +2 -0
  339. package/packages/bundled-features/src/template-resolver/handlers/body-preview.query.ts +41 -0
  340. package/packages/bundled-features/src/template-resolver/handlers/by-slug.query.ts +1 -1
  341. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +1 -1
  342. package/packages/bundled-features/src/template-resolver/handlers/collection-shared.ts +5 -11
  343. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +3 -2
  344. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +37 -8
  345. package/packages/bundled-features/src/template-resolver/linked-resources.ts +2 -5
  346. package/packages/bundled-features/src/template-resolver/seeding.ts +77 -0
  347. package/packages/bundled-features/src/template-resolver/table.ts +1 -0
  348. package/packages/bundled-features/src/template-resolver/template-draft.ts +2 -1
  349. package/packages/bundled-features/src/template-resolver/template-preview.ts +14 -3
  350. package/packages/bundled-features/src/template-resolver/testing.ts +0 -2
  351. package/packages/bundled-features/src/template-resolver/web/client-plugin.tsx +3 -0
  352. package/packages/bundled-features/src/template-resolver/web/collection-entry-create-form.tsx +33 -33
  353. package/packages/bundled-features/src/template-resolver/web/constants.ts +7 -0
  354. package/packages/bundled-features/src/template-resolver/web/content-tree-provider.ts +0 -1
  355. package/packages/bundled-features/src/template-resolver/web/content-workbench.tsx +142 -0
  356. package/packages/bundled-features/src/template-resolver/web/document-insert-model.ts +3 -8
  357. package/packages/bundled-features/src/template-resolver/web/document-link-policy.ts +58 -0
  358. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +11 -57
  359. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +2 -4
  360. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +4 -5
  361. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +2 -2
  362. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +6 -3
  363. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +2 -3
  364. package/packages/bundled-features/src/template-resolver/web/editor-handle.ts +1 -0
  365. package/packages/bundled-features/src/template-resolver/web/fill-document-variables.ts +24 -0
  366. package/packages/bundled-features/src/template-resolver/web/i18n.ts +14 -0
  367. package/packages/bundled-features/src/template-resolver/web/index.ts +3 -0
  368. package/packages/bundled-features/src/template-resolver/web/preview-targets.ts +25 -0
  369. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +1 -0
  370. package/packages/bundled-features/src/template-resolver/web/snippet-preview-renderer.tsx +24 -0
  371. package/packages/bundled-features/src/template-resolver/web/string-values.ts +7 -0
  372. package/packages/bundled-features/src/template-resolver/web/text-block-editor.tsx +38 -50
  373. package/packages/bundled-features/src/template-resolver/web/use-collection-entry-create.ts +7 -0
  374. package/packages/bundled-features/src/template-resolver/web/use-content-write.ts +1 -3
  375. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +1 -2
  376. package/packages/bundled-features/src/template-resolver/web/use-text-block-editor.ts +28 -7
  377. package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +126 -0
  378. package/packages/bundled-features/src/template-resolver-user-data/index.ts +11 -10
  379. package/packages/bundled-features/src/tenant/changes.json +6 -0
  380. package/packages/bundled-features/src/tenant/handlers/create.write.ts +7 -8
  381. package/packages/bundled-features/src/tenant/handlers/list.query.ts +7 -9
  382. package/packages/bundled-features/src/tenant/handlers/member-directory.query.ts +10 -4
  383. package/packages/bundled-features/src/tenant/handlers/toggle-enabled.write.ts +1 -1
  384. package/packages/bundled-features/src/tenant/invited-membership.ts +10 -1
  385. package/packages/bundled-features/src/tenant/seeding.ts +4 -2
  386. package/packages/bundled-features/src/tenant/stream-tenant-backfill.ts +5 -1
  387. package/packages/bundled-features/src/tenant/testing.ts +1 -1
  388. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +4 -3
  389. package/packages/bundled-features/src/tenant-inactivity/constants.ts +1 -2
  390. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +1 -2
  391. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +10 -1
  392. package/packages/bundled-features/src/tenant-lifecycle/changes.json +18 -0
  393. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +4 -0
  394. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +43 -6
  395. package/packages/bundled-features/src/tenant-lifecycle/stages.ts +15 -2
  396. package/packages/bundled-features/src/tier-engine/aggregate-id.ts +0 -1
  397. package/packages/bundled-features/src/tier-engine/changes.json +6 -0
  398. package/packages/bundled-features/src/tier-engine/feature.ts +8 -2
  399. package/packages/bundled-features/src/user/changes.json +6 -0
  400. package/packages/bundled-features/src/user/db/queries/stream-tenant-backfill.ts +2 -1
  401. package/packages/bundled-features/src/user/handlers/me.query.ts +3 -1
  402. package/packages/bundled-features/src/user/index.ts +1 -0
  403. package/packages/bundled-features/src/user/resolve-verified-user-email.ts +17 -0
  404. package/packages/bundled-features/src/user-data-rights/db/queries/export-jobs.ts +0 -1
  405. package/packages/bundled-features/src/user-data-rights/handlers/confirm-deletion-by-token.write.ts +1 -1
  406. package/packages/bundled-features/src/user-data-rights/handlers/download-by-token.query.ts +1 -1
  407. package/packages/bundled-features/src/user-data-rights/handlers/request-deletion-by-email.write.ts +1 -1
  408. package/packages/bundled-features/src/user-data-rights/run-export-jobs.ts +0 -2
  409. package/packages/bundled-features/src/user-data-rights/run-forget-cleanup.ts +3 -3
  410. package/packages/bundled-features/src/user-data-rights/schema/download-attempt.ts +3 -2
  411. package/packages/bundled-features/src/user-data-rights/web/confirm-deletion-screen.tsx +1 -1
  412. package/packages/bundled-features/src/user-data-rights/web/privacy-center-screen.tsx +1 -1
  413. package/packages/bundled-features/src/user-data-rights/web/request-deletion-screen.tsx +1 -1
  414. package/packages/bundled-features/src/user-data-rights-defaults/hooks/api-token.userdata-hook.ts +5 -5
  415. package/packages/bundled-features/src/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.ts +17 -0
  416. package/packages/bundled-features/src/user-data-rights-defaults/hooks/in-app-message.userdata-hook.ts +5 -5
  417. package/packages/bundled-features/src/user-data-rights-defaults/hooks/job-run.userdata-hook.ts +2 -1
  418. package/packages/bundled-features/src/user-data-rights-defaults/hooks/user-session.userdata-hook.ts +5 -5
  419. package/packages/bundled-features/src/user-profile/handlers/change-email.write.ts +0 -1
  420. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  421. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +4 -28
  422. package/packages/bundled-features/src/waitlist/lib.ts +2 -7
  423. package/packages/bundled-features/src/waitlist/user-data-hooks.ts +6 -19
  424. package/packages/bundled-features/src/workflow-runner/aggregate-id.ts +0 -1
  425. package/packages/bundled-features/src/workflow-runner/event-trigger.ts +6 -2
  426. package/packages/bundled-features/src/workflow-runner/feature.ts +1 -5
  427. package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +5 -4
  428. package/packages/bundled-features/src/workflow-runner/runner.ts +2 -0
  429. package/samples/apps/showcase/src/features/demos/web/pages/dialog.tsx +0 -1
  430. package/samples/apps/showcase/src/features/demos/web/pages/layout.tsx +1 -1
  431. package/samples/apps/showcase/src/features/demos/web/pages/sidebar-panel.tsx +0 -1
  432. package/samples/apps/styleguide/src/features/gallery/web/Gallery.tsx +1 -4
  433. package/samples/apps/ui-walkthrough/src/features/subscription-plans/feature.ts +6 -2
  434. package/samples/apps/use-all-bundled/e2e-billing-gallery/gallery-features.ts +12 -14
  435. package/samples/apps/use-all-bundled/feature-manifest.json +60 -29
  436. package/samples/apps/use-all-bundled/playwright.billing-docs.config.ts +1 -1
  437. package/samples/apps/use-all-bundled/playwright.config.ts +1 -0
  438. package/samples/apps/use-all-bundled/src/app/seed.ts +1 -1
  439. package/samples/apps/use-all-bundled/src/run-config.ts +2 -1
  440. package/samples/recipes/auth-mfa/src/web/confirmation-code-step.tsx +32 -10
  441. package/samples/recipes/chat-channels/README.md +2 -0
  442. package/samples/recipes/currencies-global/src/entities/currency.ts +1 -0
  443. package/samples/recipes/helpdesk/README.md +9 -5
  444. package/samples/recipes/helpdesk/src/feature.ts +6 -3
  445. package/samples/recipes/managed-pages/README.md +5 -1
  446. package/samples/recipes/managed-pages/package.json +3 -2
  447. package/samples/recipes/managed-pages/src/web/branded-preview.tsx +21 -0
  448. package/samples/recipes/managed-pages/tsconfig.json +8 -0
  449. package/samples/recipes/pwa-shell/README.md +52 -0
  450. package/samples/recipes/pwa-shell/bin/server.ts +12 -0
  451. package/samples/recipes/pwa-shell/package.json +13 -0
  452. package/samples/recipes/pwa-shell/src/app.ts +34 -0
  453. package/samples/recipes/rate-limiting/README.md +3 -3
  454. package/samples/recipes/record-detail-layout/README.md +33 -0
  455. package/samples/recipes/record-detail-layout/src/feature.ts +525 -44
  456. package/samples/recipes/record-detail-layout/src/order-board.ts +521 -0
  457. package/packages/bundled-features/src/managed-pages/web/page-body-section.tsx +0 -72
  458. package/packages/bundled-features/src/subscription-paddle/tenant-binding.ts +0 -34
  459. package/packages/bundled-features/src/template-resolver/web/content-field.tsx +0 -61
@@ -46,6 +46,7 @@ import { purgeSearchDocumentsForSubject } from "@cosmicdrift/kumiko-framework/se
46
46
  import { generateId } from "@cosmicdrift/kumiko-framework/utils";
47
47
  import * as z from "zod";
48
48
  import { resolveRetentionPolicyForTenant } from "../../data-retention/index.ts";
49
+ import { NOTES_HISTORY_FEATURE_NAME } from "../../notes-history/index.ts";
49
50
  import { eraseNoteBodiesReachingSubject } from "../../notes-history-user-data/index.ts";
50
51
  import { revokeAllPatTokensForUser } from "../../personal-access-tokens/index.ts";
51
52
  import { purgeFilesReachingSubject } from "../../shared/index.ts";
@@ -58,6 +59,7 @@ import {
58
59
  import {
59
60
  CRYPTO_SHREDDING_AGGREGATE_TYPE,
60
61
  CRYPTO_SHREDDING_FEATURE_NAME,
62
+ FORGET_SUBJECT_QUALIFIED_NAME,
61
63
  RECORD_ENTITY_NOT_REGISTERED,
62
64
  SUBJECT_FORGET_DENIED_EVENT_NAME,
63
65
  SUBJECT_FORGOTTEN_EVENT_NAME,
@@ -94,6 +96,31 @@ export const subjectForgetDeniedSchema = z.object({
94
96
 
95
97
  type SubjectIdInput = z.infer<typeof subjectIdSchema>;
96
98
 
99
+ function subjectOfInput(raw: SubjectIdInput): SubjectId {
100
+ switch (raw.kind) {
101
+ case "user":
102
+ return { kind: "user", userId: raw.userId };
103
+ case "tenant":
104
+ return { kind: "tenant", tenantId: raw.tenantId };
105
+ case "record":
106
+ return { kind: "record", entity: raw.entity, id: raw.id };
107
+ default: {
108
+ const unreachable: never = raw;
109
+ return unreachable;
110
+ }
111
+ }
112
+ }
113
+
114
+ // Called from another write handler (subjectForgetAfterDeleteHook), the caller's tx holds
115
+ // the uncommitted delete event on the subject's own stream; appending there from outside
116
+ // that tx would wait on it forever, so the event goes onto a fresh stream.
117
+ function forgottenEventAggregateId(raw: SubjectIdInput): string {
118
+ const entryHandlerQn = requestContext.get()?.entryHandler?.qn;
119
+ const nestedInCallerTransaction =
120
+ entryHandlerQn !== undefined && entryHandlerQn !== FORGET_SUBJECT_QUALIFIED_NAME;
121
+ return nestedInCallerTransaction ? generateId() : subjectAggregateId(raw);
122
+ }
123
+
97
124
  // Exhaustive switch so a 4th subject kind fails to compile instead of
98
125
  // silently aggregating under the wrong id.
99
126
  function subjectAggregateId(raw: SubjectIdInput): string {
@@ -340,7 +367,7 @@ async function sweepDerivedSubjectData(
340
367
  }
341
368
 
342
369
  // Note bodies are keyed per note, so the subject's own key never reaches them.
343
- if (ctx.registry.features.has("notes-history")) {
370
+ if (ctx.registry.features.has(NOTES_HISTORY_FEATURE_NAME)) {
344
371
  await eraseNoteBodiesReachingSubject({
345
372
  db: crossTenantSubjectRunner,
346
373
  subject,
@@ -489,12 +516,7 @@ export const forgetSubjectWrite = defineWriteHandler({
489
516
  }
490
517
 
491
518
  const raw = event.payload.subject;
492
- const subject: SubjectId =
493
- raw.kind === "user"
494
- ? { kind: "user", userId: raw.userId }
495
- : raw.kind === "tenant"
496
- ? { kind: "tenant", tenantId: raw.tenantId }
497
- : { kind: "record", entity: raw.entity, id: raw.id };
519
+ const subject = subjectOfInput(raw);
498
520
  const subjectKey = subjectIdToKey(subject);
499
521
 
500
522
  const tenantScopeDenial = await resolveTenantScopeDenial(
@@ -557,16 +579,14 @@ export const forgetSubjectWrite = defineWriteHandler({
557
579
  // crash recovery is safe. User-feature guard: without the user feature
558
580
  // read_users doesn't exist (crypto-only stack). Tenant subjects have no
559
581
  // credentials.
560
- // Runs before the sweep and in its own transaction: a failing sweep rolls the
561
- // handler transaction back, and the handler tx holds no lock on this user's
562
- // read_users row yet (only read gates ran), so there is no lock conflict.
582
+ // Door close and audit event commit on the outside-transaction db, before the sweep:
583
+ // the key erase above is irreversible, so neither may roll back with the handler tx
584
+ // (sweep failure, a later subject, a later hook, a failed commit). The handler tx holds
585
+ // no lock on this user's read_users row yet (only read gates ran).
586
+ const outsideRunner = ctx.db.outsideTransaction?.unsafeRaw();
587
+
563
588
  if (raw.kind === "user" && ctx.registry.features.has("user")) {
564
- await closeUserLoginDoor(
565
- ctx,
566
- raw.userId,
567
- ctx.db.outsideTransaction?.unsafeRaw(),
568
- ctx.db.unsafeRaw(),
569
- );
589
+ await closeUserLoginDoor(ctx, raw.userId, outsideRunner, ctx.db.unsafeRaw());
570
590
  }
571
591
 
572
592
  const cleanupError = await sweepDerivedSubjectData(
@@ -581,14 +601,14 @@ export const forgetSubjectWrite = defineWriteHandler({
581
601
  await appendSubjectForgotten(
582
602
  ctx,
583
603
  event,
584
- subjectAggregateId(raw),
604
+ forgottenEventAggregateId(raw),
585
605
  {
586
606
  subjectKey,
587
607
  reason: event.payload.reason,
588
608
  forgottenBy: event.user.id,
589
609
  ...(cleanupError !== undefined && { cleanupError }),
590
610
  },
591
- ctx.db.outsideTransaction?.unsafeRaw(),
611
+ outsideRunner,
592
612
  );
593
613
 
594
614
  if (cleanupError !== undefined) {
@@ -12,3 +12,7 @@ export {
12
12
  subjectForgottenSchema,
13
13
  subjectIdSchema,
14
14
  } from "./handlers/forget-subject.write.ts";
15
+ export {
16
+ type SubjectForgetAfterDeleteOptions,
17
+ subjectForgetAfterDeleteHook,
18
+ } from "./subject-forget-after-delete-hook.ts";
@@ -0,0 +1,49 @@
1
+ import { ROLES } from "@cosmicdrift/kumiko-framework/auth";
2
+ import type { SubjectId } from "@cosmicdrift/kumiko-framework/crypto";
3
+ import { createSystemUser, parseTenantId } from "@cosmicdrift/kumiko-framework/engine";
4
+ import { InternalError, reraiseAsKumikoError } from "@cosmicdrift/kumiko-framework/errors";
5
+ import type { HookDefinition } from "@cosmicdrift/kumiko-types/feature-registrar";
6
+ import { FORGET_SUBJECT_QUALIFIED_NAME } from "./constants.ts";
7
+
8
+ export type SubjectForgetAfterDeleteOptions = {
9
+ readonly target: Extract<HookDefinition, { type: "postDelete" }>["target"];
10
+ readonly subjectsOf: (deletedId: string) => readonly SubjectId[];
11
+ // forget-subject requires at least 10 characters.
12
+ readonly reason: string;
13
+ };
14
+
15
+ // A postDelete hook, not a step inside the delete handler: preDelete hooks run after the handler
16
+ // returns, and the key erase cannot be rolled back. Run here, in the delete's own transaction, the
17
+ // erase only happens once every preDelete hook has accepted the delete; a failed forget throws and
18
+ // rolls the delete back. The escalation stays in the tenant of the deleted row's own event.
19
+ // forget-subject is irreversible (assertIrreversibleOperationAllowed), so the consumer's delete
20
+ // handler (the entry handler) must resolve to agent risk "high", otherwise the hook fails.
21
+ export function subjectForgetAfterDeleteHook(
22
+ options: SubjectForgetAfterDeleteOptions,
23
+ ): Extract<HookDefinition, { type: "postDelete" }> {
24
+ return {
25
+ type: "postDelete",
26
+ target: options.target,
27
+ phase: "inTransaction",
28
+ escapeHatch: {
29
+ reason: `deleting the row escalates to the system identity to run crypto-shredding:forget-subject (DPO/SystemAdmin-only) for the subjects of the row just deleted in its own tenant: ${options.reason}`,
30
+ grants: ["systemIdentity"],
31
+ },
32
+ handler: async (deleted, ctx) => {
33
+ const tenantId = parseTenantId(deleted.event.tenantId);
34
+ if (tenantId === null) {
35
+ throw new InternalError({
36
+ message: "[crypto-shredding] subjectForgetAfterDeleteHook: deleted row has no tenant",
37
+ });
38
+ }
39
+ const systemAdmin = createSystemUser(tenantId, [ROLES.SystemAdmin]);
40
+ for (const subject of options.subjectsOf(String(deleted.id))) {
41
+ const forgotten = await ctx.dispatch.writeAs(systemAdmin, FORGET_SUBJECT_QUALIFIED_NAME, {
42
+ subject,
43
+ reason: options.reason,
44
+ });
45
+ if (!forgotten.isSuccess) throw reraiseAsKumikoError(forgotten.error);
46
+ }
47
+ },
48
+ };
49
+ }
@@ -23,7 +23,6 @@ const FIELD_DEFINITION_NAMESPACE = "f1d3b2c7-4e5a-4b9c-8d1f-2a3b4c5d6e7f";
23
23
  * define its own `customer.internalNumber` (422 `fieldKey_conflict`). This
24
24
  * prevents ambiguity when resolving the field during reads.
25
25
  */
26
- // @wrapper-known uuid-domain
27
26
  export function fieldDefinitionAggregateId(
28
27
  tenantId: string,
29
28
  entityName: string,
@@ -37,6 +37,7 @@ import {
37
37
  // columns and events.
38
38
  export const fieldDefinitionEntity = createEntity({
39
39
  table: "read_custom_field_definitions",
40
+ systemRowsReadable: true,
40
41
  description:
41
42
  "One custom-field definition: the host entity it extends, the field key, its type and required/searchable flags, a display order, and the serialized field builder that carries the type options, default value and labels. Rows owned by the system tenant apply to every tenant; all others belong to the tenant that defined them.",
42
43
  // softDelete is required, NOT cosmetic: the aggregate-id is deterministic
@@ -28,7 +28,6 @@ import { CUSTOM_FIELDS_EXTENSION, FIELD_DEFINITION_AGGREGATE_TYPE } from "./web/
28
28
  //
29
29
  // `customFields` follows the same contract as regular fields: default `{}` and
30
30
  // NOT NULL, like embedded columns.
31
- // @wrapper-known semantic-alias
32
31
  export function customFieldsField(): JsonbFieldDef {
33
32
  return createJsonbField();
34
33
  }
@@ -1,4 +1,22 @@
1
1
  [
2
+ {
3
+ "version": "0.414.0",
4
+ "type": "fix",
5
+ "title": "Retention anonymize compares decrypted values",
6
+ "detail": "Retention anonymize compares decrypted PII values and is covered by a test. The anonymize diff compares JSON values independent of key order, and the notes-history feature name comes from its constant."
7
+ },
8
+ {
9
+ "version": "0.414.0",
10
+ "type": "fix",
11
+ "title": "Retention hardDelete takes the notes of the deleted parent along",
12
+ "detail": "When the retention cleanup hard-deletes a row and notes-history is mounted, the note bodies attached to that row (note-entry, any tenant, including notes written in customer tenants on a global parent) are crypto-shredded in the same sub-transaction as the row's own keys. Before, the parent was gone but its notes stayed readable."
13
+ },
14
+ {
15
+ "version": "0.413.1",
16
+ "type": "fix",
17
+ "title": "Retention cleanup, upload sweep and soft-delete cleanup reach the system tenant",
18
+ "detail": "Jobs with `perTenant: true` can set `includeSystemTenant: true` to get one more run with `SYSTEM_TENANT_ID` after the active tenants (no duplicate if the app's `getActiveTenantIds` already returns it). `data-retention:job:retention-cleanup`, `files:job:sweep-orphaned-uploads` and `soft-delete:job:cleanup` set it, so helpdesk requests, replies and their attachments are deleted after `keepFor`. The retention run applies to every entity with a `retention` rule whose rows sit in the system tenant (for example download attempts or custom-field values written in a SystemAdmin session); they now expire after their declared `keepFor` like in any other tenant. Other per-tenant jobs (tenant inactivity, billing, workflows, reindex, inbound-mail retention) keep running for active tenants only. The soft-delete cleanup computes its grace cutoff from the job clock instead of the wall clock. Setting `includeSystemTenant` without `perTenant` fails at boot."
19
+ },
2
20
  {
3
21
  "version": "0.407.0",
4
22
  "type": "fix",
@@ -0,0 +1,23 @@
1
+ import type { DbRunner } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { Registry } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { NOTES_HISTORY_FEATURE_NAME } from "../notes-history/index.ts";
4
+ import { eraseNoteBodiesReachingSubject } from "../notes-history-user-data/index.ts";
5
+
6
+ // Note bodies are keyed per note, so a hardDeleted parent's own key never reaches them. The runner
7
+ // is the retention job's unfiltered one: notes of a global parent sit in whichever tenant wrote them.
8
+ export async function eraseNotesOfDeletedRow(args: {
9
+ readonly registry: Registry;
10
+ readonly tx: DbRunner;
11
+ readonly entityName: string;
12
+ readonly rowId: string;
13
+ readonly erasedBy: string;
14
+ }): Promise<void> {
15
+ // skip: without notes-history there are no notes hanging on the row
16
+ if (!args.registry.features.has(NOTES_HISTORY_FEATURE_NAME)) return;
17
+ await eraseNoteBodiesReachingSubject({
18
+ db: args.tx,
19
+ subject: { kind: "record", entity: args.entityName, id: args.rowId },
20
+ erasedBy: args.erasedBy,
21
+ requestId: `data-retention:hardDelete:${args.entityName}:${args.rowId}`,
22
+ });
23
+ }
@@ -65,8 +65,8 @@ export function createDataRetentionFeature(): FeatureDefinition {
65
65
  r.exposesApi("retention.policyFor");
66
66
  r.queryHandler(policyForQuery);
67
67
 
68
- // Autonomous retention cleanup. perTenant fan-out (one run per
69
- // active tenant, like soft-delete-cleanup): runRetentionCleanup's raw
68
+ // Autonomous retention cleanup. perTenant fan-out (one run per active
69
+ // tenant plus the system tenant, like soft-delete-cleanup): runRetentionCleanup's raw
70
70
  // query helpers need the unfiltered runner, so the handler declares
71
71
  // escapeHatch and reaches for ctx.db.unsafeRaw(). Without this cron,
72
72
  // retention rules are configured but never enforced.
@@ -74,6 +74,7 @@ export function createDataRetentionFeature(): FeatureDefinition {
74
74
  name: "retention-cleanup",
75
75
  trigger: { maintenance: true },
76
76
  perTenant: true,
77
+ includeSystemTenant: true,
77
78
  concurrency: "skip",
78
79
  escapeHatch: {
79
80
  reason:
@@ -83,11 +84,7 @@ export function createDataRetentionFeature(): FeatureDefinition {
83
84
  if (!ctx.registry) {
84
85
  throw new Error("retention-cleanup: ctx.registry required (JobContext incomplete)");
85
86
  }
86
- const tenantId = ctx.systemUser?.tenantId ?? ctx._tenantId;
87
- if (tenantId === undefined) {
88
- // skip: cron fired without a perTenant fan-out tenant — nothing scoped
89
- return;
90
- }
87
+ const tenantId = ctx.systemUser.tenantId;
91
88
  const cleanupDb =
92
89
  ctx.db.unsafeRaw() as import("@cosmicdrift/kumiko-framework/db").DbConnection; // @cast-boundary db-operator — jobs never run inside a DbTx
93
90
  const tenantPreset = await resolveTenantRetentionPreset({
@@ -65,6 +65,7 @@ import {
65
65
  type EntityDefinition,
66
66
  type EntityId,
67
67
  entityHasAnonymizableSubjectField,
68
+ isUnchangedValue,
68
69
  type Registry,
69
70
  type SessionUser,
70
71
  type TenantId,
@@ -85,6 +86,7 @@ import {
85
86
  runInSubTransaction,
86
87
  type SingleFileHolder,
87
88
  } from "../shared/index.ts";
89
+ import { eraseNotesOfDeletedRow } from "./erase-notes-of-deleted-row.ts";
88
90
  import { computeCutoff, type Instant } from "./keep-for.ts";
89
91
  import type { RetentionPresetKey } from "./presets.ts";
90
92
  import { resolveRetentionPolicyForTenant } from "./resolve-for-tenant.ts";
@@ -280,6 +282,13 @@ async function forgetRowAndEraseKeys(args: {
280
282
  tenantId: args.tenantId,
281
283
  row: args.row,
282
284
  });
285
+ await eraseNotesOfDeletedRow({
286
+ registry: args.registry,
287
+ tx: sp,
288
+ entityName: args.entityName,
289
+ rowId: String(args.rowId),
290
+ erasedBy: args.systemUser.id,
291
+ });
283
292
  return { isSuccess: true };
284
293
  });
285
294
  }
@@ -481,11 +490,19 @@ async function rowNeedsAnonymize(
481
490
  const current = isPiiCiphertext(stored)
482
491
  ? await decryptStoredPii(stored, field, "retention-anonymize")
483
492
  : stored;
484
- if (current !== PII_ERASED_SENTINEL && current !== target) return true;
493
+ if (current !== PII_ERASED_SENTINEL && !sameAnonymizedValue(current, target)) return true;
485
494
  }
486
495
  return false;
487
496
  }
488
497
 
498
+ // Objects and arrays (JSON fields) are never identical by reference, so they compare by content;
499
+ // jsonb returns keys in its own order, so the comparison must not depend on key order.
500
+ export function sameAnonymizedValue(current: unknown, target: unknown): boolean {
501
+ if (current === target) return true;
502
+ if (typeof target !== "object" || target === null) return false;
503
+ return isUnchangedValue(current, target);
504
+ }
505
+
489
506
  // Anonymize every matching row via the executor (event → rebuild-safe).
490
507
  // id-Cursor-paged because the where keeps matching already-anonymized rows;
491
508
  // the diff-check keeps the daily re-run event-free. batchLimit bounds the
@@ -717,23 +734,26 @@ export async function runRetentionCleanup(
717
734
  // A tenant held in destroyHeld has its expired blockDelete rows removed for good;
718
735
  // anonymizing them would keep the account's data stored for nothing.
719
736
  if (policy.strategy === "blockDelete" && args.purgeExpiredBlockDelete === true) {
720
- hardDeleted += await hardDeleteMatchingRows({
721
- db,
722
- table: proj.table,
723
- where,
724
- batchLimit,
725
- tenantId,
726
- entityName,
727
- entity,
728
- files: args.files,
729
- systemUser,
730
- tdb,
731
- kms,
732
- registry,
733
- fileHolders,
734
- deleteWithoutFileStorage: true,
735
- skipped,
736
- });
737
+ // A row whose reference was never set has no running keepFor, so it would block the release forever.
738
+ for (const expired of [where, { ...where, [referenceField]: null }]) {
739
+ hardDeleted += await hardDeleteMatchingRows({
740
+ db,
741
+ table: proj.table,
742
+ where: expired,
743
+ batchLimit,
744
+ tenantId,
745
+ entityName,
746
+ entity,
747
+ files: args.files,
748
+ systemUser,
749
+ tdb,
750
+ kms,
751
+ registry,
752
+ fileHolders,
753
+ deleteWithoutFileStorage: true,
754
+ skipped,
755
+ });
756
+ }
737
757
  break;
738
758
  }
739
759
  const targets = await resolveAnonymizeTargets(entity.fields);
@@ -169,6 +169,9 @@ export async function holdBlockDeleteRowsForDestruction(
169
169
  const targets = await resolveAnonymizeTargets(entity.fields);
170
170
  if (!targets) continue;
171
171
  const executor = createEventStoreExecutor(table, entity, { entityName });
172
+ // Every page restarts at the first row, so a row that is anonymized twice means the update does
173
+ // not converge (the loop would never see a short page).
174
+ const anonymizedIds = new Set<string>();
172
175
  let updated = ANONYMIZE_PAGE_SIZE;
173
176
  while (updated === ANONYMIZE_PAGE_SIZE) {
174
177
  updated = await anonymizeMatchingRows(
@@ -178,6 +181,12 @@ export async function holdBlockDeleteRowsForDestruction(
178
181
  ANONYMIZE_PAGE_SIZE,
179
182
  targets,
180
183
  async (id, changes) => {
184
+ if (anonymizedIds.has(String(id))) {
185
+ throw new Error(
186
+ `data-retention: anonymizing held ${entityName} row ${String(id)} does not converge, the anonymized value differs from the stored one`,
187
+ );
188
+ }
189
+ anonymizedIds.add(String(id));
181
190
  const result = await executor.update({ id, changes }, systemUser, tdb, {
182
191
  skipOptimisticLock: true,
183
192
  writePurpose: WritePurposes.retention,
@@ -0,0 +1,11 @@
1
+ import type { DeliveryAttemptLogFactory } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { DeliveryService } from "./types.ts";
3
+
4
+ // Tenant and recipient come from the binding, never from the entry, so a handler cannot log an
5
+ // attempt for another tenant or another recipient.
6
+ export function createDeliveryAttemptLogFactory(
7
+ deliveryService: Pick<DeliveryService, "logAttempt">,
8
+ ): DeliveryAttemptLogFactory {
9
+ return (user, tenantId, deliveryDb) => (entry) =>
10
+ deliveryService.logAttempt({ ...entry, tenantId, recipientId: user.id }, deliveryDb);
11
+ }
@@ -3,7 +3,7 @@
3
3
  // delivery.render / delivery.send job handlers — keeping the append +
4
4
  // inline-projection logic in one place so both paths produce identical rows.
5
5
 
6
- import type { DbConnection } from "@cosmicdrift/kumiko-framework/db";
6
+ import type { DbConnection, DbRunner } from "@cosmicdrift/kumiko-framework/db";
7
7
  import type { Registry } from "@cosmicdrift/kumiko-framework/engine";
8
8
  import { append, getStreamVersion } from "@cosmicdrift/kumiko-framework/event-store";
9
9
  import { runProjectionsForEvent } from "@cosmicdrift/kumiko-framework/pipeline";
@@ -55,7 +55,7 @@ export function projectedAttemptAddress(
55
55
  // Shared append + inline-projection write (low-level append() does not
56
56
  // auto-fire projections — only the dispatcher/executor paths do).
57
57
  async function writeAttemptEvent(
58
- db: DbConnection,
58
+ db: DbRunner,
59
59
  registry: Registry,
60
60
  attemptId: string,
61
61
  expectedVersion: number,
@@ -100,7 +100,7 @@ export async function appendAttemptEvent(
100
100
  // FRESH aggregate id is guaranteed version 0 — skip the getStreamVersion
101
101
  // round-trip that appendAttemptEvent needs for its follow-up-event case.
102
102
  export async function logAttempt(
103
- db: DbConnection,
103
+ db: DbRunner,
104
104
  registry: Registry,
105
105
  entry: DeliveryLogEntry,
106
106
  ): Promise<string> {
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.414.0",
4
+ "type": "improvement",
5
+ "title": "New job-only query opted-in-user-ids",
6
+ "detail": "The new query `delivery:query:opted-in-user-ids` (`{ notificationType, channel }`, answers `{ userIds }`) is open to system users only and lists, sorted and unique, the users of the caller's tenant whose preference row for exactly that notification type and channel is enabled. A job that sends an opt-in notification such as a daily digest uses it to address only the members who ordered it. Rows stored under a former name (`renamedFrom`) count under the current name; an exact row wins over a former-name row, as in `delivery:query:preferences`, and \"*\" wildcard rows never count as opt-in."
7
+ },
2
8
  {
3
9
  "version": "0.409.0",
4
10
  "type": "improvement",
@@ -2,7 +2,7 @@ import type { SseBroker } from "@cosmicdrift/kumiko-framework/api";
2
2
  import { createTenantDb, type DbConnection, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
3
3
  import type { ConfigAccessor, Registry, TenantId } from "@cosmicdrift/kumiko-framework/engine";
4
4
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
5
- import type { FileContext } from "@cosmicdrift/kumiko-framework/files";
5
+ import { type FileContext, FileObjectMissingError } from "@cosmicdrift/kumiko-framework/files";
6
6
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
7
7
  import type { SecretsContext } from "@cosmicdrift/kumiko-framework/secrets";
8
8
  import {
@@ -91,7 +91,8 @@ function createPdfRenderer(
91
91
  }
92
92
 
93
93
  // A decorative inline image (logo) of a tenant without file storage must not fail the whole mail;
94
- // transient read errors rethrow so the send job retries.
94
+ // a file ref whose object is gone is permanent, so it is skipped too; transient read errors rethrow
95
+ // so the send job retries.
95
96
  async function readInlineImageOrNull(
96
97
  fileRefId: string,
97
98
  read: () => Promise<FileRefContent | null>,
@@ -99,7 +100,9 @@ async function readInlineImageOrNull(
99
100
  try {
100
101
  return await read();
101
102
  } catch (err) {
102
- if (!(err instanceof FileStorageUnavailableError)) throw err;
103
+ if (!(err instanceof FileStorageUnavailableError || err instanceof FileObjectMissingError)) {
104
+ throw err;
105
+ }
103
106
  createFallbackLogger("delivery").warn("inline image could not be read, sending without it", {
104
107
  fileRefId,
105
108
  errorName: err.name,
@@ -8,7 +8,6 @@ export type NotificationPreferenceRow = {
8
8
  readonly enabled: boolean;
9
9
  };
10
10
 
11
- // @wrapper-known semantic-alias
12
11
  export async function selectNotificationPreferences(
13
12
  db: DbConnection,
14
13
  tenantId: TenantId,
@@ -1107,5 +1107,8 @@ export function createDeliveryService(options: DeliveryServiceOptions): Delivery
1107
1107
  await releaseIdempotencyIfNothingDelivered(tenantId, idempotencyKey, run, notificationType);
1108
1108
  return dispatched(run);
1109
1109
  },
1110
+ async logAttempt(entry, deliveryDb) {
1111
+ await logAttempt(deliveryDb ?? db, registry, entry);
1112
+ },
1110
1113
  };
1111
1114
  }
@@ -26,6 +26,7 @@ import {
26
26
  import { deliveryAttemptAddressErasedSchema, deliveryAttemptSchema } from "./events.ts";
27
27
  import { attemptsByKeysQuery } from "./handlers/attempts-by-keys.query.ts";
28
28
  import { logQuery } from "./handlers/log.query.ts";
29
+ import { optedInUserIdsQuery } from "./handlers/opted-in-user-ids.query.ts";
29
30
  import { preferencesQuery } from "./handlers/preferences.query.ts";
30
31
  import { resubscribeAddressWrite } from "./handlers/resubscribe-address.write.ts";
31
32
  import { resubscribeUserWrite } from "./handlers/resubscribe-user.write.ts";
@@ -35,6 +36,7 @@ import { unsubscribePageChromeQuery } from "./handlers/unsubscribe-page-chrome.q
35
36
  import { unsubscribeUserWrite } from "./handlers/unsubscribe-user.write.ts";
36
37
  import { DELIVERY_I18N } from "./i18n.ts";
37
38
  import { deliveryRenderJob, deliverySendJob } from "./jobs.ts";
39
+ import type { DeliveryFeatureOptions } from "./options.ts";
38
40
  import {
39
41
  deliveryAttemptsTable,
40
42
  deliveryAttemptsTableMeta,
@@ -44,18 +46,6 @@ import {
44
46
  notificationPreferencesTable,
45
47
  } from "./tables.ts";
46
48
 
47
- export type DeliveryFeatureOptions = {
48
- // Access gate for the delivery-log screen and the `log` query it reads —
49
- // both move together so the nav entry a role sees always matches a
50
- // callable handler. Default access.admin includes TenantAdmin,
51
- // who in a line-of-business app is the operator, not the platform — pass
52
- // access.systemAdmin to keep this platform-only and out of their nav.
53
- readonly access?: readonly string[];
54
- // Attempt events and log rows older than this many days are pruned by a daily job. Default 90;
55
- // `false` keeps the log forever.
56
- readonly attemptLogRetentionDays?: number | false;
57
- };
58
-
59
49
  const ATTEMPT_LOG_RETENTION_ESCAPE_HATCH_REASON =
60
50
  "prunes delivery attempt events and log rows of every tenant";
61
51
 
@@ -65,7 +55,7 @@ export function createDeliveryFeature(options?: DeliveryFeatureOptions): Feature
65
55
  return defineFeature("delivery", (r) => {
66
56
  r.adoptsBundledLists();
67
57
  r.describe(
68
- "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 \u2014 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.",
58
+ "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 \u2014 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 }`).",
69
59
  );
70
60
  r.uiHints({
71
61
  displayLabel: "Notifications \u00b7 Dispatch Core",
@@ -229,6 +219,7 @@ export function createDeliveryFeature(options?: DeliveryFeatureOptions): Feature
229
219
  log: r.queryHandler({ ...logQuery, access: { roles: resolvedAccess } }),
230
220
  preferences: r.queryHandler(preferencesQuery),
231
221
  attemptsByKeys: r.queryHandler(attemptsByKeysQuery),
222
+ optedInUserIds: r.queryHandler(optedInUserIdsQuery),
232
223
  unsubscribePageChrome: r.queryHandler(unsubscribePageChromeQuery),
233
224
  };
234
225
 
@@ -0,0 +1,45 @@
1
+ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineQueryHandler, SYSTEM_ROLE } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
4
+ import * as z from "zod";
5
+ import { tenantMembershipsTable } from "../../tenant/index.ts";
6
+ import { notificationTypeNames } from "../notification-type-aliases.ts";
7
+ import { collapsePreferenceRows } from "../preference-rows.ts";
8
+ import { notificationPreferencesTable } from "../tables.ts";
9
+
10
+ export const optedInUserIdsQuery = defineQueryHandler({
11
+ name: "opted-in-user-ids",
12
+ schema: z.object({ notificationType: z.string().min(1), channel: z.string().min(1) }).strict(),
13
+ access: { roles: [SYSTEM_ROLE] },
14
+ agent: { expose: false },
15
+ description:
16
+ "Job-only: returns the ids of the calling tenant's members who explicitly switched this notification type on for exactly this channel (a preference row with enabled = true), so a job sending an opt-in notification such as a daily digest addresses only the members who ordered it.",
17
+ handler: async (query, ctx) => {
18
+ if (!ctx.systemDb) {
19
+ throw new InternalError({
20
+ message: "opted-in-user-ids: ctx.systemDb missing on a system-scoped handler",
21
+ });
22
+ }
23
+ const db = ctx.systemDb.assertTenantMatch(query.user.tenantId);
24
+ const { notificationType, channel } = query.payload;
25
+
26
+ const rows = await selectMany(db, notificationPreferencesTable, {
27
+ tenantId: query.user.tenantId,
28
+ channel,
29
+ notificationType: { in: [...notificationTypeNames(ctx.registry, notificationType)] },
30
+ });
31
+
32
+ const userIds = collapsePreferenceRows(ctx.registry, rows)
33
+ .filter((row) => row.notificationType === notificationType && row.enabled === true)
34
+ .map((row) => row.userId);
35
+ const candidateIds = [...new Set(userIds)];
36
+ if (candidateIds.length === 0) return { userIds: [] };
37
+
38
+ // Removed members keep their preference rows; only live memberships may receive tenant data.
39
+ const memberships = await selectMany<{ userId: string }>(db, tenantMembershipsTable, {
40
+ tenantId: query.user.tenantId,
41
+ userId: { in: candidateIds },
42
+ });
43
+ return { userIds: memberships.map((membership) => membership.userId).sort() };
44
+ },
45
+ });
@@ -2,7 +2,7 @@ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import * as z from "zod";
5
- import { currentNotificationType } from "../notification-type-aliases.ts";
5
+ import { collapsePreferenceRows } from "../preference-rows.ts";
6
6
  import { notificationPreferencesTable } from "../tables.ts";
7
7
 
8
8
  export const preferencesQuery = defineQueryHandler({
@@ -38,24 +38,6 @@ export const preferencesQuery = defineQueryHandler({
38
38
  userId: query.user.id,
39
39
  });
40
40
 
41
- // Rows stored under a former notification name are reported under the current
42
- // one, collapsed with the same precedence as delivery: an exact row wins,
43
- // otherwise any disabled former-name row disables.
44
- const collapsed = new Map<string, { row: (typeof rows)[number]; isExact: boolean }>();
45
- for (const row of rows) {
46
- const notificationType = currentNotificationType(ctx.registry, row.notificationType);
47
- const key = `${notificationType}\u0000${row.channel}`;
48
- const isExact = row.notificationType === notificationType;
49
- const existing = collapsed.get(key);
50
- if (existing?.isExact) continue;
51
- const formerNameRowDisablesAlready =
52
- existing !== undefined &&
53
- !isExact &&
54
- (existing.row.enabled === false || row.enabled !== false);
55
- if (formerNameRowDisablesAlready) continue;
56
- collapsed.set(key, { row: { ...row, notificationType }, isExact });
57
- }
58
-
59
- return { rows: [...collapsed.values()].map((entry) => entry.row) };
41
+ return { rows: collapsePreferenceRows(ctx.registry, rows) };
60
42
  },
61
43
  });