@cosmicdrift/kumiko-bundled-features 0.413.1 → 0.414.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (588) hide show
  1. package/dist/admin-shell/feature.js +2 -2
  2. package/dist/agent-tools/agent-doc-lint.js +2 -1
  3. package/dist/agent-tools/agent-manifest.js +33 -25
  4. package/dist/agent-tools/api-docs/collect-events.js +4 -1
  5. package/dist/agent-tools/api-docs/collect.js +3 -3
  6. package/dist/agent-tools/api-docs/generate.js +4 -1
  7. package/dist/agent-tools/api-docs/index.d.ts +1 -0
  8. package/dist/agent-tools/api-docs/index.js +1 -0
  9. package/dist/agent-tools/api-docs/problems.d.ts +21 -0
  10. package/dist/agent-tools/api-docs/problems.js +11 -1
  11. package/dist/agent-tools/api-docs/render-openapi.js +2 -0
  12. package/dist/agent-tools/api-docs/resolve-config.d.ts +9 -0
  13. package/dist/agent-tools/api-docs/resolve-config.js +11 -0
  14. package/dist/agent-tools/api-docs/scope-slug-collisions.d.ts +4 -0
  15. package/dist/agent-tools/api-docs/scope-slug-collisions.js +10 -0
  16. package/dist/agent-tools/api-docs/translation-gaps.d.ts +4 -0
  17. package/dist/agent-tools/api-docs/translation-gaps.js +29 -0
  18. package/dist/agent-tools/api-docs/webhook-example-problems.d.ts +6 -0
  19. package/dist/agent-tools/api-docs/webhook-example-problems.js +25 -0
  20. package/dist/agent-tools/index.d.ts +1 -1
  21. package/dist/agent-tools/index.js +1 -1
  22. package/dist/agent-tools/labels.d.ts +3 -2
  23. package/dist/agent-tools/labels.js +21 -4
  24. package/dist/agent-tools/tool-catalog.d.ts +5 -5
  25. package/dist/agent-tools/tool-catalog.js +12 -10
  26. package/dist/agent-tools/tool-dispatch.js +11 -1
  27. package/dist/agent-tools/types.d.ts +4 -0
  28. package/dist/audit/event-classification.js +6 -0
  29. package/dist/audit/web/i18n.js +1 -0
  30. package/dist/auth-email-password/errors.js +0 -13
  31. package/dist/auth-email-password/handlers/invite-signup-complete.write.js +101 -84
  32. package/dist/auth-email-password/handlers/login-options.query.js +1 -1
  33. package/dist/auth-email-password/handlers/request-account-unlock.write.js +1 -1
  34. package/dist/auth-email-password/handlers/request-email-verification.write.js +0 -1
  35. package/dist/auth-email-password/handlers/request-password-reset.write.js +0 -1
  36. package/dist/auth-email-password/handlers/self-registration-status.query.js +1 -1
  37. package/dist/auth-email-password/reset-token.js +0 -2
  38. package/dist/auth-email-password/seeding.js +34 -8
  39. package/dist/auth-email-password/unlock-token.js +0 -2
  40. package/dist/auth-email-password/verification-token.js +0 -2
  41. package/dist/auth-email-password/web/auth-form-primitives.js +2 -2
  42. package/dist/auth-email-password/web/auth-gate.js +2 -2
  43. package/dist/auth-email-password/web/auth-redirect.d.ts +1 -0
  44. package/dist/auth-email-password/web/auth-redirect.js +4 -0
  45. package/dist/auth-email-password/web/forgot-password-screen.js +1 -5
  46. package/dist/auth-email-password/web/invite-accept-screen.js +1 -1
  47. package/dist/auth-email-password/web/return-path.d.ts +2 -1
  48. package/dist/auth-email-password/web/return-path.js +2 -1
  49. package/dist/auth-email-password/web/session.js +11 -12
  50. package/dist/auth-email-password/web/signup-screen.js +1 -5
  51. package/dist/auth-email-password/web/static-account.js +6 -2
  52. package/dist/auth-email-password/web/token-confirm-screen.js +4 -5
  53. package/dist/auth-mfa/web/mfa-code-or-recovery-field.d.ts +6 -1
  54. package/dist/auth-mfa/web/mfa-code-or-recovery-field.js +4 -2
  55. package/dist/auth-mfa/web/mfa-disable-dialog.js +1 -1
  56. package/dist/auth-mfa/web/mfa-regenerate-recovery-dialog.js +1 -1
  57. package/dist/auth-mfa/web/mfa-setup-preauth-screen.js +1 -1
  58. package/dist/auth-mfa/web/mfa-verify-screen.js +7 -11
  59. package/dist/auth-mfa-user-data/index.js +5 -6
  60. package/dist/billing-foundation/aggregate-id.js +0 -4
  61. package/dist/billing-foundation/checkout-core.js +8 -1
  62. package/dist/billing-foundation/checkout-ledger.d.ts +15 -0
  63. package/dist/billing-foundation/checkout-ledger.js +32 -0
  64. package/dist/billing-foundation/consumer-protection/consent-gate.d.ts +1 -1
  65. package/dist/billing-foundation/consumer-protection/consent-gate.js +2 -2
  66. package/dist/billing-foundation/consumer-protection/consent-text.d.ts +6 -2
  67. package/dist/billing-foundation/consumer-protection/consent-text.js +29 -3
  68. package/dist/billing-foundation/consumer-protection/termination-open-cancels.d.ts +2 -1
  69. package/dist/billing-foundation/consumer-protection/termination-open-cancels.js +5 -1
  70. package/dist/billing-foundation/consumer-protection/termination-provider-timeout.d.ts +2 -0
  71. package/dist/billing-foundation/consumer-protection/termination-provider-timeout.js +17 -0
  72. package/dist/billing-foundation/consumer-protection/termination-record.js +5 -4
  73. package/dist/billing-foundation/consumer-protection/termination-revoke.js +1 -1
  74. package/dist/billing-foundation/events.d.ts +22 -0
  75. package/dist/billing-foundation/events.js +38 -10
  76. package/dist/billing-foundation/feature.js +12 -1
  77. package/dist/billing-foundation/handlers/billing-plans.query.js +25 -15
  78. package/dist/billing-foundation/handlers/create-checkout-session.write.js +1 -1
  79. package/dist/billing-foundation/handlers/process-event.write.d.ts +2 -2
  80. package/dist/billing-foundation/handlers/process-event.write.js +94 -12
  81. package/dist/billing-foundation/handlers/process-payment-event.write.d.ts +1 -2
  82. package/dist/billing-foundation/handlers/process-payment-event.write.js +29 -9
  83. package/dist/billing-foundation/handlers/record-checkout-opened.write.d.ts +2 -0
  84. package/dist/billing-foundation/handlers/record-checkout-opened.write.js +22 -0
  85. package/dist/billing-foundation/handlers/start-plan-checkout.write.js +1 -1
  86. package/dist/billing-foundation/handlers/switch-plan.write.js +10 -4
  87. package/dist/billing-foundation/i18n.js +3 -0
  88. package/dist/billing-foundation/pending-plan-switch.d.ts +12 -0
  89. package/dist/billing-foundation/pending-plan-switch.js +57 -0
  90. package/dist/billing-foundation/scrub-raw-payload-headers.d.ts +4 -0
  91. package/dist/billing-foundation/scrub-raw-payload-headers.js +33 -0
  92. package/dist/billing-foundation/types.d.ts +40 -24
  93. package/dist/billing-foundation/validate-options.js +14 -0
  94. package/dist/billing-foundation/web/billing-plans-panel.js +8 -3
  95. package/dist/billing-foundation/web/cancel-contract-dialog.js +1 -1
  96. package/dist/billing-foundation/web/checkout-consent-dialog.js +1 -1
  97. package/dist/billing-foundation/web/constants.d.ts +3 -0
  98. package/dist/billing-foundation/web/constants.js +5 -2
  99. package/dist/billing-foundation/web/plan-switch-confirm-dialog.js +1 -1
  100. package/dist/billing-foundation/webhook-handler.js +53 -11
  101. package/dist/cap-counter/aggregate-id.js +0 -2
  102. package/dist/cap-counter/stock-cap-guard.d.ts +1 -0
  103. package/dist/cap-counter/stock-cap-guard.js +18 -4
  104. package/dist/cap-overview/handlers/tenant-caps-list.query.js +18 -4
  105. package/dist/cap-overview/i18n.js +1 -0
  106. package/dist/cap-overview/index.d.ts +1 -1
  107. package/dist/cap-overview/types.d.ts +4 -0
  108. package/dist/cap-overview/web/cap-cards-panel.js +6 -2
  109. package/dist/cap-overview/web/cap-usage-bar.js +6 -1
  110. package/dist/cap-overview/web/usage-math.d.ts +1 -0
  111. package/dist/cap-overview/web/usage-math.js +4 -0
  112. package/dist/channel-in-app/handlers/read-state-by-keys.query.js +2 -2
  113. package/dist/channel-whatsapp/aggregate-id.d.ts +8 -0
  114. package/dist/channel-whatsapp/aggregate-id.js +18 -0
  115. package/dist/channel-whatsapp/constants.d.ts +25 -0
  116. package/dist/channel-whatsapp/constants.js +36 -0
  117. package/dist/channel-whatsapp/events.d.ts +87 -0
  118. package/dist/channel-whatsapp/events.js +70 -0
  119. package/dist/channel-whatsapp/feature.d.ts +3 -0
  120. package/dist/channel-whatsapp/feature.js +56 -0
  121. package/dist/channel-whatsapp/graph-client.d.ts +85 -0
  122. package/dist/channel-whatsapp/graph-client.js +272 -0
  123. package/dist/channel-whatsapp/in-memory-meta.d.ts +83 -0
  124. package/dist/channel-whatsapp/in-memory-meta.js +181 -0
  125. package/dist/channel-whatsapp/inbound-handlers.d.ts +39 -0
  126. package/dist/channel-whatsapp/inbound-handlers.js +127 -0
  127. package/dist/channel-whatsapp/index.d.ts +10 -0
  128. package/dist/channel-whatsapp/index.js +10 -0
  129. package/dist/channel-whatsapp/meta-signature.d.ts +5 -0
  130. package/dist/channel-whatsapp/meta-signature.js +19 -0
  131. package/dist/channel-whatsapp/options.d.ts +32 -0
  132. package/dist/channel-whatsapp/options.js +83 -0
  133. package/dist/channel-whatsapp/pii.d.ts +32 -0
  134. package/dist/channel-whatsapp/pii.js +61 -0
  135. package/dist/channel-whatsapp/webhook-normalize.d.ts +7 -0
  136. package/dist/channel-whatsapp/webhook-normalize.js +185 -0
  137. package/dist/channel-whatsapp/webhook-routes.d.ts +10 -0
  138. package/dist/channel-whatsapp/webhook-routes.js +118 -0
  139. package/dist/compliance-profiles/handlers/sub-processors.query.js +1 -1
  140. package/dist/config/handlers/set.write.js +7 -0
  141. package/dist/config/handlers/values.query.js +8 -1
  142. package/dist/config/index.d.ts +1 -1
  143. package/dist/config/index.js +1 -1
  144. package/dist/config/read-redaction.d.ts +1 -0
  145. package/dist/config/read-redaction.js +5 -2
  146. package/dist/config/table.js +1 -0
  147. package/dist/config/write-helpers.js +3 -2
  148. package/dist/crypto-shredding/constants.d.ts +1 -0
  149. package/dist/crypto-shredding/constants.js +1 -0
  150. package/dist/crypto-shredding/handlers/forget-subject.write.js +34 -13
  151. package/dist/crypto-shredding/index.d.ts +1 -0
  152. package/dist/crypto-shredding/index.js +1 -0
  153. package/dist/crypto-shredding/subject-forget-after-delete-hook.d.ts +12 -0
  154. package/dist/crypto-shredding/subject-forget-after-delete-hook.js +38 -0
  155. package/dist/custom-fields/aggregate-id.js +0 -1
  156. package/dist/custom-fields/entity.js +1 -0
  157. package/dist/custom-fields/wire-for-entity.js +0 -1
  158. package/dist/data-retention/erase-notes-of-deleted-row.d.ts +9 -0
  159. package/dist/data-retention/erase-notes-of-deleted-row.js +15 -0
  160. package/dist/data-retention/feature.js +1 -5
  161. package/dist/data-retention/run-retention-cleanup.d.ts +1 -0
  162. package/dist/data-retention/run-retention-cleanup.js +39 -19
  163. package/dist/data-retention/tenant-destruction-hold.js +7 -0
  164. package/dist/delivery/attempt-log-factory.d.ts +3 -0
  165. package/dist/delivery/attempt-log-factory.js +5 -0
  166. package/dist/delivery/attempt-log.d.ts +2 -2
  167. package/dist/delivery/channel-context.d.ts +1 -1
  168. package/dist/delivery/channel-context.js +5 -2
  169. package/dist/delivery/db/queries/preferences.js +0 -1
  170. package/dist/delivery/delivery-service.js +3 -0
  171. package/dist/delivery/feature.d.ts +1 -4
  172. package/dist/delivery/feature.js +3 -1
  173. package/dist/delivery/handlers/attempts-by-keys.query.d.ts +1 -1
  174. package/dist/delivery/handlers/opted-in-user-ids.query.d.ts +7 -0
  175. package/dist/delivery/handlers/opted-in-user-ids.query.js +41 -0
  176. package/dist/delivery/handlers/preferences.query.js +2 -20
  177. package/dist/delivery/handlers/resubscribe-user.write.d.ts +2 -2
  178. package/dist/delivery/handlers/resubscribe-user.write.js +2 -24
  179. package/dist/delivery/handlers/unsubscribe-page-chrome.query.js +2 -0
  180. package/dist/delivery/handlers/unsubscribe-user.write.d.ts +2 -2
  181. package/dist/delivery/handlers/unsubscribe-user.write.js +2 -26
  182. package/dist/delivery/index.d.ts +3 -1
  183. package/dist/delivery/index.js +1 -0
  184. package/dist/delivery/options.d.ts +4 -0
  185. package/dist/delivery/options.js +1 -0
  186. package/dist/delivery/preference-rows.d.ts +9 -0
  187. package/dist/delivery/preference-rows.js +22 -0
  188. package/dist/delivery/set-preference-enabled.d.ts +17 -0
  189. package/dist/delivery/set-preference-enabled.js +26 -0
  190. package/dist/delivery/tables.d.ts +2 -2
  191. package/dist/delivery/testing.d.ts +1 -1
  192. package/dist/delivery/testing.js +3 -1
  193. package/dist/delivery/types.d.ts +1 -0
  194. package/dist/delivery/unsubscribe-page.js +5 -1
  195. package/dist/delivery/upsert-preference.js +0 -1
  196. package/dist/delivery/web/public-names.d.ts +1 -0
  197. package/dist/delivery/web/public-names.js +1 -0
  198. package/dist/derivatives-sharp/render.js +9 -9
  199. package/dist/document-ingest-foundation/aggregate-id.js +0 -1
  200. package/dist/document-ingest-foundation/append-missing-extract-event.d.ts +0 -1
  201. package/dist/document-ingest-foundation/append-missing-extract-event.js +32 -21
  202. package/dist/document-ingest-foundation/report-ingest-progress.d.ts +1 -1
  203. package/dist/document-ingest-foundation/report-ingest-progress.js +29 -13
  204. package/dist/documents/aggregate-id.js +0 -2
  205. package/dist/documents/constants.d.ts +6 -0
  206. package/dist/documents/constants.js +8 -2
  207. package/dist/documents/ensure-link.d.ts +5 -8
  208. package/dist/documents/ensure-link.js +4 -2
  209. package/dist/documents/feature.d.ts +3 -1
  210. package/dist/documents/feature.js +24 -5
  211. package/dist/documents/handlers/import.write.js +2 -2
  212. package/dist/documents/queries/expiry-overview.query.js +2 -1
  213. package/dist/documents/queries/for-record.query.js +3 -4
  214. package/dist/documents/queries/list-page.js +11 -3
  215. package/dist/documents/queries/overview.query.js +2 -2
  216. package/dist/documents/screens.js +3 -3
  217. package/dist/documents/tab.js +1 -1
  218. package/dist/feature-toggles/toggle-sync-signal.d.ts +2 -2
  219. package/dist/feature-toggles/toggle-sync-signal.js +3 -2
  220. package/dist/file-derivatives/handlers/public-variant-by-file-ref.query.js +1 -1
  221. package/dist/file-derivatives/handlers/public-variant.query.js +1 -1
  222. package/dist/file-foundation/probe.js +9 -3
  223. package/dist/file-foundation/read-file-ref-content.js +23 -11
  224. package/dist/file-provider-inmemory/feature.js +1 -1
  225. package/dist/file-provider-s3/env-feature.js +1 -1
  226. package/dist/file-provider-s3/env-named-feature.js +1 -1
  227. package/dist/file-provider-s3/env-schema.d.ts +10 -1
  228. package/dist/file-provider-s3/env-schema.js +20 -7
  229. package/dist/file-provider-s3/feature.js +1 -1
  230. package/dist/file-provider-s3/index.d.ts +1 -1
  231. package/dist/file-provider-s3/index.js +1 -1
  232. package/dist/file-provider-s3/lib/env-helper.d.ts +3 -2
  233. package/dist/file-provider-s3/lib/env-helper.js +13 -12
  234. package/dist/file-provider-s3/lib/s3-provider.js +10 -2
  235. package/dist/folders/aggregate-id.js +0 -1
  236. package/dist/folders/web/folder-manager.js +1 -1
  237. package/dist/folders-user-data/index.js +12 -14
  238. package/dist/helpdesk/entity.js +4 -1
  239. package/dist/helpdesk/feature.js +36 -0
  240. package/dist/helpdesk/handlers/access.d.ts +0 -1
  241. package/dist/helpdesk/handlers/access.js +0 -3
  242. package/dist/helpdesk/handlers/attempts.js +7 -13
  243. package/dist/helpdesk/handlers/challenge.query.js +1 -2
  244. package/dist/helpdesk/handlers/reply.write.js +4 -5
  245. package/dist/helpdesk/handlers/report.write.js +3 -7
  246. package/dist/helpdesk/handlers/submit.write.js +4 -9
  247. package/dist/helpdesk/index.d.ts +1 -1
  248. package/dist/helpdesk/index.js +1 -1
  249. package/dist/helpdesk/legacy-contact-config.d.ts +3 -0
  250. package/dist/helpdesk/legacy-contact-config.js +57 -0
  251. package/dist/helpdesk/legacy-contact-erasure.d.ts +9 -0
  252. package/dist/helpdesk/legacy-contact-erasure.js +19 -0
  253. package/dist/helpdesk/legacy-contact-retention.d.ts +2 -0
  254. package/dist/helpdesk/legacy-contact-retention.js +53 -0
  255. package/dist/helpdesk/legacy-contact-streams.d.ts +20 -0
  256. package/dist/helpdesk/legacy-contact-streams.js +121 -0
  257. package/dist/helpdesk/legacy-contact-user-data.d.ts +5 -0
  258. package/dist/helpdesk/legacy-contact-user-data.js +62 -0
  259. package/dist/helpdesk/lib.d.ts +7 -1
  260. package/dist/helpdesk/lib.js +29 -29
  261. package/dist/helpdesk/user-data-hooks.d.ts +10 -1
  262. package/dist/helpdesk/user-data-hooks.js +47 -36
  263. package/dist/helpdesk/web/constants.d.ts +0 -1
  264. package/dist/helpdesk/web/constants.js +0 -1
  265. package/dist/inbound-mail-foundation/account-health.js +1 -1
  266. package/dist/inbound-mail-foundation/account-poll.js +1 -1
  267. package/dist/inbound-mail-foundation/aggregate-id.js +0 -2
  268. package/dist/inbound-mail-foundation/constants.d.ts +6 -0
  269. package/dist/inbound-mail-foundation/constants.js +6 -0
  270. package/dist/inbound-mail-foundation/content-refetch.d.ts +1 -0
  271. package/dist/inbound-mail-foundation/content-refetch.js +15 -1
  272. package/dist/inbound-mail-foundation/entities.js +57 -15
  273. package/dist/inbound-mail-foundation/events.js +15 -16
  274. package/dist/inbound-mail-foundation/feature.js +3 -1
  275. package/dist/inbound-mail-foundation/handlers/account-address.d.ts +2 -2
  276. package/dist/inbound-mail-foundation/handlers/account-address.js +10 -2
  277. package/dist/inbound-mail-foundation/handlers/attach-message-content.write.js +8 -3
  278. package/dist/inbound-mail-foundation/handlers/connect-account.write.js +12 -7
  279. package/dist/inbound-mail-foundation/handlers/forget-message.write.d.ts +7 -0
  280. package/dist/inbound-mail-foundation/handlers/forget-message.write.js +54 -0
  281. package/dist/inbound-mail-foundation/i18n.js +3 -0
  282. package/dist/inbound-mail-foundation/index.d.ts +1 -0
  283. package/dist/inbound-mail-foundation/index.js +1 -0
  284. package/dist/inbound-mail-foundation/oauth-access-token.js +1 -1
  285. package/dist/inbound-mail-foundation/outbound-mail.d.ts +2 -0
  286. package/dist/inbound-mail-foundation/personal-address.d.ts +1 -0
  287. package/dist/inbound-mail-foundation/personal-address.js +16 -0
  288. package/dist/inbound-mail-foundation/purge-messages.d.ts +20 -0
  289. package/dist/inbound-mail-foundation/purge-messages.js +33 -0
  290. package/dist/inbound-mail-foundation/quarantine.d.ts +3 -2
  291. package/dist/inbound-mail-foundation/quarantine.js +9 -5
  292. package/dist/inbound-mail-foundation/retention-job.js +1 -5
  293. package/dist/inbound-mail-foundation/retention-sweep.js +17 -28
  294. package/dist/inbound-mail-foundation/send-from-account.js +9 -1
  295. package/dist/inbound-mail-foundation/supervisor-ingest.js +4 -1
  296. package/dist/inbound-mail-foundation/sync-account-now.js +1 -1
  297. package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -6
  298. package/dist/inbound-mail-foundation/watch-supervisor.js +1 -1
  299. package/dist/inbound-provider-imap/byte-budget.d.ts +14 -0
  300. package/dist/inbound-provider-imap/byte-budget.js +53 -0
  301. package/dist/inbound-provider-imap/connect-mailbox.d.ts +2 -4
  302. package/dist/inbound-provider-imap/connect-mailbox.js +8 -3
  303. package/dist/inbound-provider-imap/connect-my-mailbox.d.ts +1 -1
  304. package/dist/inbound-provider-imap/connect-my-mailbox.js +15 -4
  305. package/dist/inbound-provider-imap/connect-target-rate-limit.d.ts +3 -0
  306. package/dist/inbound-provider-imap/connect-target-rate-limit.js +37 -0
  307. package/dist/inbound-provider-imap/download-batch.d.ts +10 -0
  308. package/dist/inbound-provider-imap/download-batch.js +21 -6
  309. package/dist/inbound-provider-imap/feature.js +7 -4
  310. package/dist/inbound-provider-imap/fetch-content.js +35 -30
  311. package/dist/inbound-provider-imap/i18n.js +2 -2
  312. package/dist/inbound-provider-imap/parse-message.d.ts +7 -0
  313. package/dist/inbound-provider-imap/parse-message.js +8 -0
  314. package/dist/inbound-provider-imap/reconnect-mailbox.js +5 -4
  315. package/dist/inbound-provider-imap/send-mail.d.ts +2 -0
  316. package/dist/inbound-provider-imap/send-mail.js +32 -6
  317. package/dist/inbound-provider-imap/smtp-client.d.ts +9 -2
  318. package/dist/inbound-provider-imap/smtp-client.js +15 -3
  319. package/dist/inbound-provider-imap/watch-mailbox.js +3 -24
  320. package/dist/inbound-provider-inmemory/feature.js +1 -1
  321. package/dist/jobs/events.d.ts +13 -0
  322. package/dist/jobs/events.js +8 -0
  323. package/dist/jobs/feature.js +2 -0
  324. package/dist/jobs/handlers/consumer.write.js +31 -20
  325. package/dist/jobs/web/constants.d.ts +3 -0
  326. package/dist/jobs/web/constants.js +3 -0
  327. package/dist/mail-transport-inmemory/feature.js +1 -1
  328. package/dist/mail-transport-smtp/feature.js +3 -2
  329. package/dist/managed-pages/handlers/branding.query.js +1 -1
  330. package/dist/managed-pages/handlers/by-slug.query.js +1 -1
  331. package/dist/managed-pages/handlers/by-tenant-published.query.js +1 -1
  332. package/dist/managed-pages/render-page-body.d.ts +2 -0
  333. package/dist/managed-pages/render-page-body.js +12 -8
  334. package/dist/managed-pages/screens/page-screens.d.ts +3 -2
  335. package/dist/managed-pages/screens/page-screens.js +14 -33
  336. package/dist/managed-pages/table.js +1 -0
  337. package/dist/managed-pages/web/client-plugin.js +8 -6
  338. package/dist/managed-pages/web/constants.d.ts +5 -1
  339. package/dist/managed-pages/web/constants.js +6 -1
  340. package/dist/managed-pages/web/i18n.js +11 -3
  341. package/dist/managed-pages/web/markdown-to-document.js +1 -1
  342. package/dist/managed-pages/web/page-edit-draft.d.ts +32 -0
  343. package/dist/managed-pages/web/page-edit-draft.js +76 -0
  344. package/dist/managed-pages/web/page-edit-screen.d.ts +2 -0
  345. package/dist/managed-pages/web/page-edit-screen.js +106 -0
  346. package/dist/managed-pages/web/page-settings-rail.d.ts +11 -0
  347. package/dist/managed-pages/web/page-settings-rail.js +14 -0
  348. package/dist/notes-history-user-data/index.js +8 -14
  349. package/dist/personal-access-tokens/boot-rules.d.ts +5 -0
  350. package/dist/personal-access-tokens/boot-rules.js +5 -0
  351. package/dist/personal-access-tokens/handlers/create.write.js +0 -1
  352. package/dist/personal-access-tokens/scope-events-check.js +26 -6
  353. package/dist/presence/handlers/list.query.js +18 -8
  354. package/dist/presence/room.d.ts +2 -0
  355. package/dist/presence/room.js +8 -5
  356. package/dist/presence/store.d.ts +2 -0
  357. package/dist/presence/store.js +62 -26
  358. package/dist/readiness/handlers/latest-summary.query.js +10 -6
  359. package/dist/readiness/handlers/run-probes.write.js +24 -4
  360. package/dist/readiness/handlers/run-tone.js +3 -2
  361. package/dist/readiness/handlers/status.query.js +11 -3
  362. package/dist/readiness/probe-context.js +7 -10
  363. package/dist/readiness/screens.js +4 -4
  364. package/dist/readiness/visible-results.d.ts +1 -1
  365. package/dist/readiness/visible-results.js +5 -2
  366. package/dist/renderer-foundation/api.js +6 -12
  367. package/dist/renderer-foundation/types.d.ts +2 -2
  368. package/dist/secrets/db/queries/read.d.ts +2 -1
  369. package/dist/secrets/db/queries/read.js +10 -1
  370. package/dist/secrets/handlers/list.query.js +4 -2
  371. package/dist/secrets/secret-scope.d.ts +0 -1
  372. package/dist/secrets/secret-scope.js +2 -2
  373. package/dist/secrets/secrets-context.js +4 -4
  374. package/dist/secrets/table.d.ts +1 -1
  375. package/dist/secrets/write-gate.js +4 -2
  376. package/dist/seo/handlers/seo-config.query.js +1 -1
  377. package/dist/shared/acknowledged-system-db.d.ts +5 -0
  378. package/dist/shared/acknowledged-system-db.js +9 -0
  379. package/dist/shared/assert-billing-live.d.ts +1 -0
  380. package/dist/shared/assert-billing-live.js +5 -2
  381. package/dist/shared/index.d.ts +6 -2
  382. package/dist/shared/index.js +6 -2
  383. package/dist/shared/parent-visibility.d.ts +1 -0
  384. package/dist/shared/parent-visibility.js +16 -1
  385. package/dist/shared/password-hashing.js +0 -1
  386. package/dist/shared/price-env-shape.js +1 -1
  387. package/dist/shared/register-user-data-hooks.d.ts +11 -0
  388. package/dist/shared/register-user-data-hooks.js +11 -0
  389. package/dist/shared/require-bootstrap-extension.d.ts +9 -0
  390. package/dist/shared/require-bootstrap-extension.js +16 -0
  391. package/dist/shared/send-best-effort.d.ts +2 -0
  392. package/dist/shared/send-best-effort.js +14 -0
  393. package/dist/shared/stream-tenant-backfill.d.ts +1 -0
  394. package/dist/shared/stream-tenant-backfill.js +17 -1
  395. package/dist/shared/stream-tenant-derived-state.d.ts +5 -1
  396. package/dist/shared/stream-tenant-derived-state.js +19 -2
  397. package/dist/step-dispatcher/constants.d.ts +4 -0
  398. package/dist/step-dispatcher/constants.js +11 -0
  399. package/dist/step-dispatcher/deliver-dispatch-request.d.ts +1 -0
  400. package/dist/step-dispatcher/deliver-dispatch-request.js +38 -2
  401. package/dist/step-dispatcher/feature.js +20 -2
  402. package/dist/step-dispatcher/mail-runner.js +0 -1
  403. package/dist/step-dispatcher/sweep-abandoned.d.ts +10 -0
  404. package/dist/step-dispatcher/sweep-abandoned.js +43 -0
  405. package/dist/subscription-mollie/plugin-methods.d.ts +1 -0
  406. package/dist/subscription-mollie/plugin-methods.js +1 -2
  407. package/dist/subscription-mollie/verify-webhook.js +5 -5
  408. package/dist/subscription-paddle/backfill-checkout-ledger.d.ts +9 -0
  409. package/dist/subscription-paddle/backfill-checkout-ledger.js +110 -0
  410. package/dist/subscription-paddle/checkout-config.query.js +1 -1
  411. package/dist/subscription-paddle/checkout-methods.js +2 -8
  412. package/dist/subscription-paddle/constants.d.ts +0 -1
  413. package/dist/subscription-paddle/constants.js +1 -2
  414. package/dist/subscription-paddle/feature.d.ts +0 -4
  415. package/dist/subscription-paddle/feature.js +21 -20
  416. package/dist/subscription-paddle/ledger-backfill-marker.d.ts +17 -0
  417. package/dist/subscription-paddle/ledger-backfill-marker.js +53 -0
  418. package/dist/subscription-paddle/plan-switch-methods.js +2 -8
  419. package/dist/subscription-paddle/redeliver-legacy-checkout.d.ts +11 -0
  420. package/dist/subscription-paddle/redeliver-legacy-checkout.js +26 -0
  421. package/dist/subscription-paddle/runtime.d.ts +3 -5
  422. package/dist/subscription-paddle/runtime.js +4 -7
  423. package/dist/subscription-paddle/subscription-state.d.ts +1 -0
  424. package/dist/subscription-paddle/subscription-state.js +1 -0
  425. package/dist/subscription-paddle/webhook-events.d.ts +4 -0
  426. package/dist/subscription-paddle/webhook-events.js +40 -22
  427. package/dist/subscription-stripe/feature.d.ts +4 -0
  428. package/dist/subscription-stripe/feature.js +1 -0
  429. package/dist/subscription-stripe/plugin-methods.d.ts +1 -0
  430. package/dist/subscription-stripe/plugin-methods.js +2 -5
  431. package/dist/subscription-stripe/runtime.d.ts +2 -1
  432. package/dist/subscription-stripe/runtime.js +5 -7
  433. package/dist/subscription-stripe/verify-webhook.js +21 -6
  434. package/dist/tags/aggregate-id.js +0 -1
  435. package/dist/tags/web/tag-chip.js +0 -1
  436. package/dist/tags/web/tag-manager.js +3 -1
  437. package/dist/template-resolver/api.js +6 -12
  438. package/dist/template-resolver/document-sanitizer.d.ts +1 -1
  439. package/dist/template-resolver/document-sanitizer.js +18 -0
  440. package/dist/template-resolver/feature.d.ts +1 -0
  441. package/dist/template-resolver/feature.js +2 -0
  442. package/dist/template-resolver/handlers/body-preview.query.d.ts +11 -0
  443. package/dist/template-resolver/handlers/body-preview.query.js +41 -0
  444. package/dist/template-resolver/handlers/by-slug.query.js +1 -1
  445. package/dist/template-resolver/handlers/by-tenant.query.js +1 -1
  446. package/dist/template-resolver/handlers/collection-shared.js +5 -8
  447. package/dist/template-resolver/handlers/overview.query.d.ts +1 -0
  448. package/dist/template-resolver/handlers/overview.query.js +2 -1
  449. package/dist/template-resolver/handlers/send-test.write.js +27 -8
  450. package/dist/template-resolver/linked-resources.js +2 -6
  451. package/dist/template-resolver/seeding.js +67 -1
  452. package/dist/template-resolver/table.js +1 -0
  453. package/dist/template-resolver/template-draft.js +2 -1
  454. package/dist/template-resolver/template-preview.js +12 -3
  455. package/dist/template-resolver/testing.js +0 -2
  456. package/dist/template-resolver/web/client-plugin.js +3 -0
  457. package/dist/template-resolver/web/collection-entry-create-form.js +19 -9
  458. package/dist/template-resolver/web/constants.d.ts +2 -0
  459. package/dist/template-resolver/web/constants.js +2 -0
  460. package/dist/template-resolver/web/content-tree-provider.js +0 -1
  461. package/dist/template-resolver/web/content-workbench.d.ts +22 -0
  462. package/dist/template-resolver/web/content-workbench.js +32 -0
  463. package/dist/template-resolver/web/document-insert-model.d.ts +2 -4
  464. package/dist/template-resolver/web/document-insert-model.js +1 -2
  465. package/dist/template-resolver/web/document-link-policy.d.ts +3 -0
  466. package/dist/template-resolver/web/document-link-policy.js +53 -0
  467. package/dist/template-resolver/web/document-schema.d.ts +2 -4
  468. package/dist/template-resolver/web/document-schema.js +2 -53
  469. package/dist/template-resolver/web/document-tiptap-context.d.ts +2 -5
  470. package/dist/template-resolver/web/document-tiptap-context.js +2 -2
  471. package/dist/template-resolver/web/document-tiptap-editor.js +2 -2
  472. package/dist/template-resolver/web/document-tiptap-helpers.d.ts +7 -4
  473. package/dist/template-resolver/web/document-tiptap-toolbar-groups.js +3 -3
  474. package/dist/template-resolver/web/editor-handle.js +1 -0
  475. package/dist/template-resolver/web/fill-document-variables.d.ts +1 -0
  476. package/dist/template-resolver/web/fill-document-variables.js +22 -0
  477. package/dist/template-resolver/web/i18n.js +10 -0
  478. package/dist/template-resolver/web/index.d.ts +3 -0
  479. package/dist/template-resolver/web/index.js +2 -0
  480. package/dist/template-resolver/web/preview-targets.d.ts +5 -0
  481. package/dist/template-resolver/web/preview-targets.js +21 -0
  482. package/dist/template-resolver/web/qualified-names.d.ts +1 -0
  483. package/dist/template-resolver/web/qualified-names.js +1 -0
  484. package/dist/template-resolver/web/snippet-preview-renderer.d.ts +2 -0
  485. package/dist/template-resolver/web/snippet-preview-renderer.js +15 -0
  486. package/dist/template-resolver/web/string-values.d.ts +1 -0
  487. package/dist/template-resolver/web/string-values.js +8 -0
  488. package/dist/template-resolver/web/text-block-editor.js +18 -11
  489. package/dist/template-resolver/web/use-collection-entry-create.d.ts +1 -0
  490. package/dist/template-resolver/web/use-collection-entry-create.js +6 -0
  491. package/dist/template-resolver/web/use-document-tiptap-model.d.ts +2 -6
  492. package/dist/template-resolver/web/use-text-block-editor.d.ts +3 -0
  493. package/dist/template-resolver/web/use-text-block-editor.js +26 -5
  494. package/dist/template-resolver/web/web-preview-renderer.d.ts +12 -0
  495. package/dist/template-resolver/web/web-preview-renderer.js +41 -0
  496. package/dist/template-resolver-user-data/index.js +11 -10
  497. package/dist/tenant/handlers/create.write.js +3 -7
  498. package/dist/tenant/handlers/list.query.js +3 -8
  499. package/dist/tenant/handlers/member-directory.query.js +10 -5
  500. package/dist/tenant/handlers/toggle-enabled.write.js +1 -1
  501. package/dist/tenant/invited-membership.js +9 -1
  502. package/dist/tenant/seeding.d.ts +3 -0
  503. package/dist/tenant/seeding.js +3 -1
  504. package/dist/tenant/stream-tenant-backfill.js +5 -1
  505. package/dist/tenant/testing.js +1 -1
  506. package/dist/tenant-inactivity/check-inactive-tenants.js +5 -5
  507. package/dist/tenant-inactivity/constants.js +1 -2
  508. package/dist/tenant-inactivity/handlers/keep-account.write.js +1 -2
  509. package/dist/tenant-inactivity/state-store.d.ts +1 -0
  510. package/dist/tenant-inactivity/state-store.js +9 -1
  511. package/dist/tenant-lifecycle/constants.d.ts +1 -0
  512. package/dist/tenant-lifecycle/constants.js +3 -0
  513. package/dist/tenant-lifecycle/run-tenant-destroy.js +38 -5
  514. package/dist/tenant-lifecycle/stages.js +14 -2
  515. package/dist/tier-engine/aggregate-id.js +0 -1
  516. package/dist/tier-engine/feature.js +9 -2
  517. package/dist/user/db/queries/stream-tenant-backfill.js +2 -1
  518. package/dist/user/handlers/me.query.js +4 -1
  519. package/dist/user/index.d.ts +1 -0
  520. package/dist/user/index.js +1 -0
  521. package/dist/user/resolve-verified-user-email.d.ts +2 -0
  522. package/dist/user/resolve-verified-user-email.js +14 -0
  523. package/dist/user-data-rights/db/queries/export-jobs.js +0 -1
  524. package/dist/user-data-rights/handlers/confirm-deletion-by-token.write.js +1 -1
  525. package/dist/user-data-rights/handlers/download-by-token.query.js +1 -1
  526. package/dist/user-data-rights/handlers/request-deletion-by-email.write.js +1 -1
  527. package/dist/user-data-rights/run-export-jobs.js +0 -2
  528. package/dist/user-data-rights/run-forget-cleanup.js +2 -2
  529. package/dist/user-data-rights/schema/download-attempt.js +3 -2
  530. package/dist/user-data-rights/web/confirm-deletion-screen.js +2 -2
  531. package/dist/user-data-rights/web/privacy-center-screen.js +1 -1
  532. package/dist/user-data-rights/web/request-deletion-screen.js +2 -2
  533. package/dist/user-data-rights-defaults/hooks/api-token.userdata-hook.js +5 -6
  534. package/dist/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.d.ts +7 -0
  535. package/dist/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.js +11 -0
  536. package/dist/user-data-rights-defaults/hooks/in-app-message.userdata-hook.js +5 -6
  537. package/dist/user-data-rights-defaults/hooks/job-run.userdata-hook.js +2 -1
  538. package/dist/user-data-rights-defaults/hooks/user-session.userdata-hook.js +5 -6
  539. package/dist/user-profile/handlers/change-email.write.js +0 -1
  540. package/dist/waitlist/handlers/submit.write.js +5 -18
  541. package/dist/waitlist/lib.js +2 -7
  542. package/dist/waitlist/user-data-hooks.js +6 -20
  543. package/dist/workflow-runner/aggregate-id.js +0 -1
  544. package/dist/workflow-runner/event-trigger.js +6 -2
  545. package/dist/workflow-runner/feature.js +1 -5
  546. package/dist/workflow-runner/handlers/resume-run.write.js +4 -3
  547. package/dist/workflow-runner/runner.d.ts +1 -0
  548. package/package.json +35 -11
  549. package/src/admin-shell/changes.json +6 -0
  550. package/src/agent-tools/changes.json +12 -0
  551. package/src/auth-email-password/changes.json +18 -0
  552. package/src/billing-foundation/changes.json +37 -0
  553. package/src/cap-counter/changes.json +6 -0
  554. package/src/cap-overview/changes.json +6 -0
  555. package/src/channel-in-app/changes.json +6 -0
  556. package/src/channel-whatsapp/changes.json +8 -0
  557. package/src/config/changes.json +12 -0
  558. package/src/crypto-shredding/changes.json +18 -0
  559. package/src/data-retention/changes.json +12 -0
  560. package/src/delivery/changes.json +6 -0
  561. package/src/documents/changes.json +18 -0
  562. package/src/file-provider-s3/changes.json +14 -0
  563. package/src/files/changes.json +7 -0
  564. package/src/helpdesk/changes.json +50 -0
  565. package/src/inbound-mail-foundation/changes.json +48 -0
  566. package/src/inbound-provider-imap/changes.json +13 -0
  567. package/src/mail-foundation/changes.json +6 -0
  568. package/src/managed-pages/changes.json +12 -0
  569. package/src/presence/changes.json +6 -0
  570. package/src/readiness/changes.json +25 -0
  571. package/src/secrets/changes.json +7 -0
  572. package/src/shared/changes.json +6 -0
  573. package/src/step-dispatcher/changes.json +12 -0
  574. package/src/subscription-mollie/changes.json +7 -0
  575. package/src/subscription-paddle/changes.json +13 -0
  576. package/src/subscription-stripe/changes.json +7 -0
  577. package/src/template-resolver/changes.json +36 -0
  578. package/src/tenant/changes.json +6 -0
  579. package/src/tenant-lifecycle/changes.json +18 -0
  580. package/src/tier-engine/changes.json +6 -0
  581. package/src/user/changes.json +6 -0
  582. package/src/waitlist/changes.json +6 -0
  583. package/dist/managed-pages/web/page-body-section.d.ts +0 -3
  584. package/dist/managed-pages/web/page-body-section.js +0 -40
  585. package/dist/subscription-paddle/tenant-binding.d.ts +0 -8
  586. package/dist/subscription-paddle/tenant-binding.js +0 -26
  587. package/dist/template-resolver/web/content-field.d.ts +0 -9
  588. package/dist/template-resolver/web/content-field.js +0 -14
@@ -4,42 +4,33 @@ import { deleteStoredFileAndDerivatives } from "@cosmicdrift/kumiko-framework/de
4
4
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
5
5
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
6
6
  import { fileRefEntity, fileRefsTable } from "@cosmicdrift/kumiko-framework/files";
7
- import { collectErasureFailure, decryptStoredPii, throwIfErasureFailed } from "../shared/index.js";
8
- import { userTable } from "../user/index.js";
9
- import { normalizeEmail, platformActor, replyExecutor, requestExecutor } from "./lib.js";
7
+ import { systemTenantReadDb, systemTenantWriteRunner, } from "@cosmicdrift/kumiko-framework/internal/row-level-security";
8
+ import { eraseNoteBodiesReachingSubject } from "../notes-history-user-data/index.js";
9
+ import { collectErasureFailure, throwIfErasureFailed } from "../shared/index.js";
10
+ import { resolveVerifiedUserEmail } from "../user/index.js";
11
+ import { listAllPages, platformActor, replyExecutor, requestExecutor } from "./lib.js";
10
12
  import { HELPDESK_REPLY_ENTITY, HELPDESK_REQUEST_ENTITY, HELPDESK_UPLOAD_FIELD, } from "./web/constants.js";
11
13
  const PII_DECRYPT_REASON = "helpdesk:user-data";
12
14
  const ERASE_REASON = "helpdesk:user-data-forget";
13
- const LOOKUP_LIMIT = 200;
14
- // Anonymous requests are matched by email, so the user must have proven they own it: otherwise
15
- // registering with someone else's address would expose or erase that person's requests.
16
- async function resolveVerifiedUserEmail(ctx) {
17
- const row = await ctx.db.fetchOne(userTable, {
18
- id: ctx.userId,
19
- });
20
- if (row?.emailVerified !== true)
21
- return null;
22
- if (ctx.userEmailBeforeDelete)
23
- return normalizeEmail(ctx.userEmailBeforeDelete);
24
- return normalizeEmail(await decryptStoredPii(row.email, "email", PII_DECRYPT_REASON));
25
- }
15
+ const NOTE_ERASE_WRITE_REASON = "erases the note bodies SystemAdmins wrote in the system tenant on a request of an erased subject";
26
16
  async function findRequests(ctx) {
27
- const byUser = await requestExecutor.list({ filter: { field: "reporterUserId", op: "eq", value: ctx.userId }, limit: LOOKUP_LIMIT }, platformActor(), ctx.db);
28
- const email = await resolveVerifiedUserEmail(ctx);
17
+ const byUser = await listAllPages((page) => requestExecutor.list({ filter: { field: "reporterUserId", op: "eq", value: ctx.userId }, ...page }, platformActor(), ctx.db));
18
+ const email = await resolveVerifiedUserEmail(ctx, PII_DECRYPT_REASON);
29
19
  const byEmail = email
30
- ? await requestExecutor.list({ filter: { field: "email", op: "eq", value: email }, limit: LOOKUP_LIMIT }, platformActor(), ctx.db)
31
- : { rows: [] };
32
- const unique = new Map(byUser.rows.map((row) => [row.id, row]));
33
- for (const row of byEmail.rows)
20
+ ? await listAllPages((page) => requestExecutor.list({ filter: { field: "email", op: "eq", value: email }, ...page }, platformActor(), ctx.db))
21
+ : [];
22
+ const unique = new Map(byUser.map((row) => [row.id, row]));
23
+ for (const row of byEmail)
34
24
  unique.set(row.id, row);
35
25
  return [...unique.values()];
36
26
  }
37
27
  const fileRefExecutor = createEventStoreExecutor(fileRefsTable, fileRefEntity, {
38
28
  entityName: "fileRef",
39
29
  });
40
- // Attachments are copied into the system tenant and bound to the request or reply row.
41
- async function findAttachments(ctx, entity, id) {
42
- return ctx.db.selectMany(fileRefsTable, {
30
+ // Attachments are copied into the system tenant and bound to the request or reply row; a tenant
31
+ // session cannot read those file_refs, so the lookup uses the system-tenant read handle.
32
+ export async function findAttachments(ctx, entity, id) {
33
+ return systemTenantReadDb(ctx.db).selectMany(fileRefsTable, {
43
34
  tenantId: SYSTEM_TENANT_ID,
44
35
  entityType: entity,
45
36
  entityId: id,
@@ -48,19 +39,15 @@ async function findAttachments(ctx, entity, id) {
48
39
  }
49
40
  // Bytes first, then the fileRef row: a crash in between leaves a row whose delete converges on the
50
41
  // next run, never bytes without a row. A failing byte delete aborts, like the generic fileRef hook.
51
- async function purgeAttachments(ctx, entity, id) {
42
+ // The deleter is resolved lazily, so a row without attachments needs no storage provider.
43
+ export async function purgeAttachmentsWith(ctx, entity, id, resolveByteDeleter) {
52
44
  const attachments = await findAttachments(ctx, entity, id);
53
45
  // skip: a row without attachments has no bytes to erase and needs no storage provider
54
46
  if (attachments.length === 0)
55
47
  return;
56
- const provider = await ctx.buildStorageProvider?.(SYSTEM_TENANT_ID);
57
- if (!provider) {
58
- throw new InternalError({
59
- message: `[helpdesk:user-data] no file storage resolvable, attachments of ${entity} ${id} cannot be erased`,
60
- });
61
- }
48
+ const deleteBytes = await resolveByteDeleter();
62
49
  for (const attachment of attachments) {
63
- const failed = await deleteStoredFileAndDerivatives(attachment.storageKey, provider, "helpdesk:user-data");
50
+ const failed = await deleteBytes(attachment.storageKey);
64
51
  if (failed.length > 0) {
65
52
  throw new InternalError({
66
53
  message: `[helpdesk:user-data] ${failed.length} attachment byte delete(s) failed for ${entity} ${id}`,
@@ -73,9 +60,32 @@ async function purgeAttachments(ctx, entity, id) {
73
60
  }
74
61
  throwIfErasureFailed(failures);
75
62
  }
76
- async function findReplies(ctx, requestId) {
77
- const found = await replyExecutor.list({ filter: { field: "requestId", op: "eq", value: requestId }, limit: LOOKUP_LIMIT }, platformActor(), ctx.db);
78
- return found.rows;
63
+ export function purgeAttachments(ctx, entity, id) {
64
+ return purgeAttachmentsWith(ctx, entity, id, async () => {
65
+ const provider = await ctx.buildStorageProvider?.(SYSTEM_TENANT_ID);
66
+ if (!provider) {
67
+ throw new InternalError({
68
+ message: `[helpdesk:user-data] no file storage resolvable, attachments of ${entity} ${id} cannot be erased`,
69
+ });
70
+ }
71
+ return (storageKey) => deleteStoredFileAndDerivatives(storageKey, provider, "helpdesk:user-data");
72
+ });
73
+ }
74
+ // Note bodies hang on the request as host. Notes written by SystemAdmins live in the system tenant,
75
+ // which a tenant-scoped hook db cannot see, so both handles are swept.
76
+ export async function eraseNotesOnRequest(ctx, entity, id, erasedBy) {
77
+ for (const db of [ctx.db, systemTenantWriteRunner(ctx.db, NOTE_ERASE_WRITE_REASON)]) {
78
+ await eraseNoteBodiesReachingSubject({
79
+ db,
80
+ subject: { kind: "record", entity, id },
81
+ erasedBy,
82
+ requestId: ERASE_REASON,
83
+ });
84
+ }
85
+ }
86
+ // guard:dup-ok executor and foreign-key field differ; a generic executor abstraction would obscure row types.
87
+ function findReplies(ctx, requestId) {
88
+ return listAllPages((page) => replyExecutor.list({ filter: { field: "requestId", op: "eq", value: requestId }, ...page }, platformActor(), ctx.db));
79
89
  }
80
90
  export const helpdeskExportHook = async (ctx) => {
81
91
  const requests = await findRequests(ctx);
@@ -122,6 +132,7 @@ export const helpdeskDeleteHook = async (ctx) => {
122
132
  await purgeAttachments(ctx, HELPDESK_REPLY_ENTITY, reply.id);
123
133
  await erase(HELPDESK_REPLY_ENTITY, reply.id, await replyExecutor.forget({ id: reply.id }, platformActor(), ctx.db));
124
134
  }
135
+ await eraseNotesOnRequest(ctx, HELPDESK_REQUEST_ENTITY, request.id, ctx.userId);
125
136
  await purgeAttachments(ctx, HELPDESK_REQUEST_ENTITY, request.id);
126
137
  await erase(HELPDESK_REQUEST_ENTITY, request.id, await requestExecutor.forget({ id: request.id }, platformActor(), ctx.db));
127
138
  }
@@ -83,7 +83,6 @@ export declare const HelpdeskErrors: {
83
83
  readonly phoneNotAllowed: "helpdesk_phone_not_allowed";
84
84
  readonly phoneRequired: "helpdesk_phone_required";
85
85
  readonly reporterEmailMissing: "helpdesk_reporter_email_missing";
86
- readonly attachmentNotFound: "helpdesk_attachment_not_found";
87
86
  };
88
87
  export declare const HELPDESK_NOTIFICATION_TYPES: {
89
88
  readonly newRequest: "helpdesk:notify:new-request";
@@ -86,7 +86,6 @@ export const HelpdeskErrors = {
86
86
  phoneNotAllowed: "helpdesk_phone_not_allowed",
87
87
  phoneRequired: "helpdesk_phone_required",
88
88
  reporterEmailMissing: "helpdesk_reporter_email_missing",
89
- attachmentNotFound: "helpdesk_attachment_not_found",
90
89
  };
91
90
  export const HELPDESK_NOTIFICATION_TYPES = {
92
91
  newRequest: "helpdesk:notify:new-request",
@@ -39,7 +39,7 @@ export function createAccountHealth(deps) {
39
39
  applied.set(account.id, { status, lastError });
40
40
  }
41
41
  async function lastErrorWithoutOutage(account) {
42
- if (await hasOpenQuarantine(deps.db, account.id)) {
42
+ if (await hasOpenQuarantine(deps.db, { tenantId: account.tenantId, accountId: account.id })) {
43
43
  return InboundMailLastErrors.messageQuarantined;
44
44
  }
45
45
  if (storageUnavailable.has(account.id))
@@ -26,7 +26,7 @@ export function createAccountPoller(deps) {
26
26
  seenIds.add(row.providerMessageId);
27
27
  }
28
28
  // A quarantined message counts as seen: re-fetching it would only fail the same way again.
29
- for (const id of await quarantinedMessageIds(systemDb, account.id, providerMessageIds)) {
29
+ for (const id of await quarantinedMessageIds(systemDb, { tenantId: account.tenantId, accountId: account.id }, providerMessageIds)) {
30
30
  seenIds.add(id);
31
31
  }
32
32
  return new Set(providerMessageIds.filter((id) => !seenIds.has(id)));
@@ -18,7 +18,6 @@ const MAIL_THREAD_NAMESPACE = "b48d1e72-5c9a-4f36-8e0d-6a3f9b2c7e15";
18
18
  * the same tenant can receive the same email (CC'd to both inboxes); these
19
19
  * are two distinct inbound messages.
20
20
  */
21
- // @wrapper-known uuid-domain
22
21
  export function inboundMessageAggregateId(accountId, providerMessageId) {
23
22
  return uuidv5(`${accountId}:${providerMessageId}`, INBOUND_MESSAGE_NAMESPACE);
24
23
  }
@@ -29,7 +28,6 @@ export function inboundMessageAggregateId(accountId, providerMessageId) {
29
28
  * normalized by the provider (References/In-Reply-To chain or provider
30
29
  * thread ID).
31
30
  */
32
- // @wrapper-known uuid-domain
33
31
  export function mailThreadAggregateId(tenantId, threadKey) {
34
32
  return uuidv5(`${tenantId}:${threadKey}`, MAIL_THREAD_NAMESPACE);
35
33
  }
@@ -22,6 +22,8 @@ export declare const InboundMailFoundationHandlers: {
22
22
  readonly retryQuarantinedMessage: "inbound-mail-foundation:write:retry-quarantined-message";
23
23
  /** Marks all open quarantine entries of a mailbox as acknowledged. */
24
24
  readonly acknowledgeQuarantine: "inbound-mail-foundation:write:acknowledge-quarantine";
25
+ /** Permanently removes one imported mail with its original and attachments. */
26
+ readonly forgetMessage: "inbound-mail-foundation:write:forget-message";
25
27
  /** Supervisor-only: stores the content of an already imported snippet mail. */
26
28
  readonly attachMessageContent: "inbound-mail-foundation:write:attach-message-content";
27
29
  /** OAuth callback only: the refresh token is stored now, so an active account can sync. */
@@ -67,6 +69,10 @@ export declare const InboundMailConnectErrors: {
67
69
  readonly reason: "address_disconnected";
68
70
  readonly i18nKey: "inboundMail.accounts.errors.addressDisconnected";
69
71
  };
72
+ readonly personalAddressNotOwn: {
73
+ readonly reason: "personal_address_not_own";
74
+ readonly i18nKey: "inboundMail.accounts.errors.personalAddressNotOwn";
75
+ };
70
76
  readonly credentialRequired: {
71
77
  readonly reason: "credential_required";
72
78
  readonly i18nKey: "inboundMail.accounts.errors.credentialRequired";
@@ -26,6 +26,8 @@ export const InboundMailFoundationHandlers = {
26
26
  retryQuarantinedMessage: "inbound-mail-foundation:write:retry-quarantined-message",
27
27
  /** Marks all open quarantine entries of a mailbox as acknowledged. */
28
28
  acknowledgeQuarantine: "inbound-mail-foundation:write:acknowledge-quarantine",
29
+ /** Permanently removes one imported mail with its original and attachments. */
30
+ forgetMessage: "inbound-mail-foundation:write:forget-message",
29
31
  /** Supervisor-only: stores the content of an already imported snippet mail. */
30
32
  attachMessageContent: "inbound-mail-foundation:write:attach-message-content",
31
33
  /** OAuth callback only: the refresh token is stored now, so an active account can sync. */
@@ -73,6 +75,10 @@ export const InboundMailConnectErrors = {
73
75
  reason: "address_disconnected",
74
76
  i18nKey: "inboundMail.accounts.errors.addressDisconnected",
75
77
  },
78
+ personalAddressNotOwn: {
79
+ reason: "personal_address_not_own",
80
+ i18nKey: "inboundMail.accounts.errors.personalAddressNotOwn",
81
+ },
76
82
  credentialRequired: {
77
83
  reason: "credential_required",
78
84
  i18nKey: "inboundMail.accounts.errors.credentialRequired",
@@ -2,6 +2,7 @@ import type { DbConnection } from "@cosmicdrift/kumiko-framework/db";
2
2
  import type { DispatchWrite } from "./supervisor-ingest.ts";
3
3
  import type { InboundMailContext, InboundMailProviderPlugin, MailAccountRecord } from "./types.ts";
4
4
  export declare const CONTENT_REFETCH_BUDGET_PER_TICK = 50;
5
+ export declare const CONTENT_REFETCH_SCAN_ROWS_PER_TICK: number;
5
6
  export declare function refetchSnippetOnlyMessages(args: {
6
7
  readonly db: DbConnection;
7
8
  readonly dispatchWrite: DispatchWrite;
@@ -12,6 +12,11 @@ import { inboundMessagesProjectionTable } from "./projection.js";
12
12
  export const CONTENT_REFETCH_BUDGET_PER_TICK = 50;
13
13
  const SEEN_PAGE_SIZE = 250;
14
14
  const SEEN_MAX_PAGES = 4;
15
+ export const CONTENT_REFETCH_SCAN_ROWS_PER_TICK = SEEN_PAGE_SIZE * SEEN_MAX_PAGES;
16
+ // Where the previous tick stopped scanning, per account. Without it every tick re-reads the newest
17
+ // rows and snippet-only mails further back would never be reached. Lost on restart, which only
18
+ // means the scan starts at the newest mail again.
19
+ const scanResumePoint = new Map();
15
20
  function needsContent(row) {
16
21
  const bodyMissing = row.bodyRef === undefined || row.bodyRef === null || row.bodyRef === "";
17
22
  return bodyMissing && (row.contentState == null || row.contentState === "snippet");
@@ -19,7 +24,8 @@ function needsContent(row) {
19
24
  async function findSnippetOnlyMessageIds(db, account, windowDays) {
20
25
  const cutoff = Temporal.Now.instant().subtract({ hours: windowDays * 24 });
21
26
  const found = [];
22
- let before;
27
+ let before = scanResumePoint.get(account.id);
28
+ scanResumePoint.delete(account.id);
23
29
  for (let page = 0; page < SEEN_MAX_PAGES && found.length < CONTENT_REFETCH_BUDGET_PER_TICK; page++) {
24
30
  const seen = await selectMany(db, seenMessageTable, {
25
31
  tenantId: account.tenantId,
@@ -32,6 +38,7 @@ async function findSnippetOnlyMessageIds(db, account, windowDays) {
32
38
  });
33
39
  if (seen.length === 0)
34
40
  break;
41
+ const pageStart = before;
35
42
  const aggregateToProvider = new Map(seen.map((row) => [
36
43
  inboundMessageAggregateId(account.id, row.providerMessageId),
37
44
  row.providerMessageId,
@@ -45,7 +52,14 @@ async function findSnippetOnlyMessageIds(db, account, windowDays) {
45
52
  const oldest = seen[seen.length - 1];
46
53
  if (seen.length < SEEN_PAGE_SIZE || !oldest)
47
54
  break;
55
+ if (found.length >= CONTENT_REFETCH_BUDGET_PER_TICK) {
56
+ // Reloaded mails stop being candidates, so the page can be read again without looping.
57
+ if (pageStart)
58
+ scanResumePoint.set(account.id, pageStart);
59
+ break;
60
+ }
48
61
  before = oldest.seenAt;
62
+ scanResumePoint.set(account.id, before);
49
63
  }
50
64
  return found.slice(0, CONTENT_REFETCH_BUDGET_PER_TICK);
51
65
  }
@@ -1,5 +1,5 @@
1
- import { collectPiiSubjectFields } from "@cosmicdrift/kumiko-framework/crypto";
2
- import { deriveEntityTableMeta, physicalColumnName } from "@cosmicdrift/kumiko-framework/db";
1
+ import { collectPiiSubjectFields, piiCiphertextMaxLengthFor, } from "@cosmicdrift/kumiko-framework/crypto";
2
+ import { deriveEntityTableMeta, isSchemaTable, physicalColumnName, } from "@cosmicdrift/kumiko-framework/db";
3
3
  import { access, createBooleanField, createEntity, createFilesField, createLongTextField, createNumberField, createTextField, createTimestampField, } from "@cosmicdrift/kumiko-framework/engine";
4
4
  import { DEFAULT_INBOUND_MAIL_ADMIN_ROLES, DEFAULT_INBOUND_MAIL_USER_ROLES } from "./mail-roles.js";
5
5
  // ============================================================================
@@ -14,8 +14,8 @@ import { DEFAULT_INBOUND_MAIL_ADMIN_ROLES, DEFAULT_INBOUND_MAIL_USER_ROLES } fro
14
14
  // **PII convention:** `personal: "tenant"` (not `encrypted`): fields must
15
15
  // be crypto-shredded when eraseSubjectKeys deletes the tenant subject key on
16
16
  // tenant destruction (pattern from billing-foundation).
17
- // maxLength is budgeted for ciphertext (`kumiko-pii:v1:<subject>:
18
- // <blob>` — Plaintext×~2.3 + envelope overhead).
17
+ // The projection holds ciphertext, so these fields' maxLength comes from
18
+ // piiCiphertextMaxLengthFor(<plaintext limit>).
19
19
  //
20
20
  // **Design decision:** The PII subject of an inbound mail is currently the
21
21
  // TENANT (mailbox owner), not the external sender. A sender-forget flow would
@@ -50,7 +50,12 @@ export const mailAccountEntity = createEntity({
50
50
  reason: "tenant_config_not_personal",
51
51
  }),
52
52
  // Mailbox address — tenant PII.
53
- address: createTextField({ required: true, maxLength: 1000, personal: "tenant", find: "none" }),
53
+ address: createTextField({
54
+ required: true,
55
+ maxLength: piiCiphertextMaxLengthFor(320),
56
+ personal: "tenant",
57
+ find: "none",
58
+ }),
54
59
  status: createTextField({
55
60
  required: true,
56
61
  maxLength: 30,
@@ -76,6 +81,9 @@ function ownMailboxOrSharedRead(memberRoles) {
76
81
  const rule = {
77
82
  kind: "where",
78
83
  where: (user, ctx) => {
84
+ if (!isSchemaTable(ctx.table)) {
85
+ throw new Error(`${ctx.tableName}: ownership rule received a table not built by table()`);
86
+ }
79
87
  const owner = `"${ctx.tableName}"."${physicalColumnName(ctx.table, "ownerUserId")}"`;
80
88
  return {
81
89
  sqlText: `(${owner} IS NULL OR ${owner} = '' OR ${owner} = $${ctx.paramStart})`,
@@ -114,21 +122,51 @@ export function createInboundMessageEntity(memberRoles) {
114
122
  personal: false,
115
123
  reason: "technical_reference",
116
124
  }),
117
- from: createTextField({ required: true, maxLength: 2000, personal: "tenant", find: "none" }),
125
+ from: createTextField({
126
+ required: true,
127
+ maxLength: piiCiphertextMaxLengthFor(2000),
128
+ personal: "tenant",
129
+ find: "none",
130
+ }),
118
131
  // JSON-stringified string[] — als Ganzes encrypted.
119
- to: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
120
- cc: createTextField({ maxLength: 8000, personal: "tenant", find: "none" }),
121
- subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
122
- snippet: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
132
+ to: createTextField({
133
+ maxLength: piiCiphertextMaxLengthFor(8000),
134
+ personal: "tenant",
135
+ find: "none",
136
+ }),
137
+ cc: createTextField({
138
+ maxLength: piiCiphertextMaxLengthFor(8000),
139
+ personal: "tenant",
140
+ find: "none",
141
+ }),
142
+ subject: createTextField({
143
+ maxLength: piiCiphertextMaxLengthFor(4000),
144
+ personal: "tenant",
145
+ find: "none",
146
+ }),
147
+ snippet: createTextField({
148
+ maxLength: piiCiphertextMaxLengthFor(4000),
149
+ personal: "tenant",
150
+ find: "none",
151
+ }),
123
152
  receivedAt: createTimestampField({ required: true }),
124
153
  bodyRef: createTextField({ maxLength: 500, personal: false, reason: "technical_reference" }),
125
154
  scope: createTextField({ maxLength: 200, personal: false, reason: "technical_reference" }),
126
- // Full plaintext, capped at 32_000 characters before encryption (ciphertext is ~2.3x plus envelope).
127
155
  // Null on rows from before the column; list-messages never selects it.
128
- bodyText: createLongTextField({ maxLength: 200_000, personal: "tenant", find: "none" }),
156
+ // Plaintext is clipped to INBOUND_BODY_TEXT_MAX_CHARS (32_000) before encryption.
157
+ bodyText: createLongTextField({
158
+ maxLength: piiCiphertextMaxLengthFor(32_000),
159
+ personal: "tenant",
160
+ find: "none",
161
+ }),
129
162
  bodyTextTruncated: createBooleanField(),
130
- // Sanitized HTML of the mail (sanitizeInboundHtml), null when the mail has none or it was too large.
131
- bodyHtml: createLongTextField({ maxLength: 500_000, personal: "tenant", find: "none" }),
163
+ // Sanitized HTML of the mail, null when the mail has none or it was too large: sanitizeInboundHtml
164
+ // drops anything over 500_000 bytes after sanitizing, before encryption.
165
+ bodyHtml: createLongTextField({
166
+ maxLength: piiCiphertextMaxLengthFor(500_000),
167
+ personal: "tenant",
168
+ find: "none",
169
+ }),
132
170
  // Bound to the message (entityType = the aggregate type), so the file guard answers with the
133
171
  // mail's visibility. The fileRefs are bound at ingest, the projection copies the ids.
134
172
  attachmentFileIds: createFilesField({ personal: false, reason: "technical_reference" }),
@@ -177,7 +215,11 @@ export const mailThreadEntity = createEntity({
177
215
  personal: false,
178
216
  reason: "technical_reference",
179
217
  }),
180
- subject: createTextField({ maxLength: 4000, personal: "tenant", find: "none" }),
218
+ subject: createTextField({
219
+ maxLength: piiCiphertextMaxLengthFor(4000),
220
+ personal: "tenant",
221
+ find: "none",
222
+ }),
181
223
  lastMessageAt: createTimestampField({ required: true }),
182
224
  messageCount: createNumberField({ required: true, integer: true }),
183
225
  },
@@ -19,6 +19,7 @@
19
19
  // write handler — the subject key is the tenant, and tenant destruction's
20
20
  // eraseSubjectKeys makes both the event log and projection unreadable
21
21
  // (crypto-shredding, the billing-foundation pattern).
22
+ import { piiCiphertextMaxLengthFor } from "@cosmicdrift/kumiko-framework/crypto";
22
23
  import * as z from "zod";
23
24
  import { INBOUND_MAIL_FOUNDATION_FEATURE, InboundMailAccountStatuses } from "./constants.js";
24
25
  import { senderAuthenticationFieldSchema } from "./sender-auth.js";
@@ -51,9 +52,7 @@ const accountStatusEnum = z.enum([
51
52
  // ============================================================================
52
53
  //
53
54
  // One stream per mailbox (aggregateId = accountId, random UUID on connect).
54
- // address is PII, so maxLength is 1000 to allow for ciphertext expansion
55
- // (a 200-character plaintext becomes ~460+ characters in a JSON envelope;
56
- // see billing-foundation events.ts).
55
+ // address is PII ciphertext; its plaintext is capped at 320 characters by connect-account.write.ts.
57
56
  export const mailAccountEventPayloadSchema = z.object({
58
57
  provider: z.string().min(1).max(50),
59
58
  /** "password" | "xoauth2" | "oauth" (InboundMailAuthMethods) — deliberately
@@ -63,7 +62,7 @@ export const mailAccountEventPayloadSchema = z.object({
63
62
  /** null = shared by the tenant; otherwise, this user's personal mailbox. */
64
63
  ownerUserId: z.string().max(36).nullable(),
65
64
  displayName: z.string().max(200),
66
- address: z.string().min(1).max(1000),
65
+ address: z.string().min(1).max(piiCiphertextMaxLengthFor(320)),
67
66
  status: accountStatusEnum,
68
67
  /** Provider-agnostic watch state ("idle", "watching", "backoff:3", ...)
69
68
  * — an operational signal only, not PII. */
@@ -94,12 +93,12 @@ export const skippedAttachmentSchema = z.object({
94
93
  ]),
95
94
  });
96
95
  // Shared by inbound-message-received (v2+) and inbound-message-content-fetched.
97
- // bodyText is ciphertext: 32_000 characters become roughly 75 KB, hence the generous max.
96
+ // bodyText is ciphertext of at most INBOUND_BODY_TEXT_MAX_CHARS (32_000) characters.
98
97
  const inboundMessageContentShape = {
99
- bodyText: z.string().max(200_000),
98
+ bodyText: z.string().max(piiCiphertextMaxLengthFor(32_000)),
100
99
  bodyTextTruncated: z.boolean(),
101
- /** Sanitized HTML body, PII ciphertext (500_000 characters become roughly 1.2 MB). Null: none or too large. */
102
- bodyHtml: z.string().max(1_500_000).nullable(),
100
+ /** Sanitized HTML body as PII ciphertext. sanitizeInboundHtml drops anything over 500_000 bytes after sanitizing. Null: none or too large. */
101
+ bodyHtml: z.string().max(piiCiphertextMaxLengthFor(500_000)).nullable(),
103
102
  /** file-foundation FileRef ids (plaintext uuids). Attachments outlive the mail: apps turn them
104
103
  * into documents, so the retention sweep never deletes them. */
105
104
  attachmentFileIds: z.array(z.uuid()).max(50),
@@ -114,8 +113,8 @@ const inboundMessageContentShape = {
114
113
  // aggregateId = inboundMessageAggregateId(accountId, providerMessageId)
115
114
  // → deterministic, so provider replays collide on the same stream.
116
115
  //
117
- // PII fields (from/to/cc/subject/snippet): ciphertext with generous
118
- // maximum lengths. to/cc are JSON-stringified string[] BEFORE encryption;
116
+ // PII fields (from/to/cc/subject/snippet): the maxima are the ciphertext
117
+ // size of the plaintext limits in ingest-message-schema.ts. to/cc are JSON-stringified string[] BEFORE encryption;
119
118
  // the payload contains the ciphertext string, not the array (primitives only,
120
119
  // upcaster-safe).
121
120
  export const inboundMessageEventPayloadSchema = z.object({
@@ -128,13 +127,13 @@ export const inboundMessageEventPayloadSchema = z.object({
128
127
  /** Normalized thread key (References-chain root or provider thread ID,
129
128
  * prefixed by the provider). */
130
129
  threadKey: z.string().min(1).max(500),
131
- from: z.string().min(1).max(2000),
130
+ from: z.string().min(1).max(piiCiphertextMaxLengthFor(2000)),
132
131
  /** JSON-stringified string[], dann PII-encrypted. */
133
- to: z.string().max(8000),
132
+ to: z.string().max(piiCiphertextMaxLengthFor(8000)),
134
133
  /** JSON-stringified string[], dann PII-encrypted. */
135
- cc: z.string().max(8000),
136
- subject: z.string().max(4000),
137
- snippet: z.string().max(4000),
134
+ cc: z.string().max(piiCiphertextMaxLengthFor(8000)),
135
+ subject: z.string().max(piiCiphertextMaxLengthFor(4000)),
136
+ snippet: z.string().max(piiCiphertextMaxLengthFor(4000)),
138
137
  /** ISO instant — receipt time reported by the provider (INTERNALDATE or
139
138
  * receivedDateTime), not ingest time. */
140
139
  receivedAtIso: z.string().min(1),
@@ -166,7 +165,7 @@ export const inboundMessageContentFetchedEventPayloadSchema = z.object({
166
165
  // ============================================================================
167
166
  export const mailThreadEventPayloadSchema = z.object({
168
167
  threadKey: z.string().min(1).max(500),
169
- subject: z.string().max(4000),
168
+ subject: z.string().max(piiCiphertextMaxLengthFor(4000)),
170
169
  lastMessageAtIso: z.string().min(1),
171
170
  messageCount: z.number().int().min(1),
172
171
  });
@@ -28,6 +28,7 @@ import { createAcknowledgeQuarantineHandler } from "./handlers/acknowledge-quara
28
28
  import { attachMessageContentHandler } from "./handlers/attach-message-content.write.js";
29
29
  import { createConnectAccountHandler } from "./handlers/connect-account.write.js";
30
30
  import { createDisconnectAccountHandler } from "./handlers/disconnect-account.write.js";
31
+ import { createForgetMessageHandler } from "./handlers/forget-message.write.js";
31
32
  import { ingestMessageHandler } from "./handlers/ingest-message.write.js";
32
33
  import { createListAccountsQuery } from "./handlers/list-accounts.query.js";
33
34
  import { createListMessagesQuery } from "./handlers/list-messages.query.js";
@@ -54,7 +55,7 @@ export function createInboundMailFoundationFeature(options = {}) {
54
55
  const roles = resolveInboundMailRoles(options);
55
56
  return defineFeature(INBOUND_MAIL_FOUNDATION_FEATURE, (r) => {
56
57
  r.adoptsBundledLists();
57
- r.describe("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.");
58
+ r.describe("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.");
58
59
  r.uiHints({
59
60
  displayLabel: "Inbound Mail · Foundation",
60
61
  category: "notifications",
@@ -194,6 +195,7 @@ export function createInboundMailFoundationFeature(options = {}) {
194
195
  r.writeHandler(createReactivateAccountHandler(roles));
195
196
  r.writeHandler(createSetTrustedAuthservIdHandler(roles));
196
197
  r.writeHandler(createAcknowledgeQuarantineHandler(roles));
198
+ r.writeHandler(createForgetMessageHandler(roles));
197
199
  r.writeHandler(createRetryQuarantinedMessageHandler(roles));
198
200
  r.writeHandler(attachMessageContentHandler);
199
201
  r.writeHandler(markCredentialStoredHandler);
@@ -7,8 +7,8 @@ export type AddressMatch = {
7
7
  readonly status: string;
8
8
  };
9
9
  export declare function normalizeMailAddress(address: string): string;
10
- export declare function findMailboxByAddress(ctx: Pick<HandlerContext, "db">, tenantId: string, address: string): Promise<AddressMatch | undefined>;
11
- export type ConnectConflict = "already_connected" | "address_disconnected" | "reopen_in_place";
10
+ export declare function findMailboxByAddress(ctx: Pick<HandlerContext, "db">, tenantId: string, address: string, wantedOwnerUserId: string | null): Promise<AddressMatch | undefined>;
11
+ export type ConnectConflict = "already_connected" | "address_disconnected" | "reopen_in_place" | "replace_disconnected_personal";
12
12
  export declare function connectConflictOf(existing: AddressMatch, wanted: {
13
13
  readonly authMethod: string;
14
14
  readonly provider: string;
@@ -11,7 +11,9 @@ function textOf(value) {
11
11
  return typeof value === "string" ? value : "";
12
12
  }
13
13
  // A live mailbox wins over a disconnected one: connecting next to a live mailbox is always a duplicate.
14
- export async function findMailboxByAddress(ctx, tenantId, address) {
14
+ // Among equals the mailbox of the wanted owner kind (shared or personal) wins, then the smallest id,
15
+ // so the outcome does not depend on projection row order.
16
+ export async function findMailboxByAddress(ctx, tenantId, address, wantedOwnerUserId) {
15
17
  const wanted = normalizeMailAddress(address);
16
18
  const rows = await ctx.db.selectMany(mailAccountsProjectionTable, { tenantId });
17
19
  const piiKms = configuredPiiSubjectKms();
@@ -32,7 +34,9 @@ export async function findMailboxByAddress(ctx, tenantId, address) {
32
34
  status: textOf(row["status"]),
33
35
  });
34
36
  }
35
- return matches.find((m) => m.status !== InboundMailAccountStatuses.disconnected) ?? matches[0];
37
+ const rank = (m) => (m.status === InboundMailAccountStatuses.disconnected ? 2 : 0) +
38
+ ((m.ownerUserId === null) === (wantedOwnerUserId === null) ? 0 : 1);
39
+ return [...matches].sort((a, b) => rank(a) - rank(b) || a.id.localeCompare(b.id))[0];
36
40
  }
37
41
  // A disconnected or sign-in-failed OAuth mailbox of the same provider and owner is reopened (the
38
42
  // callback writes the new token into the same slot); everything else must not silently create a second stream for one address.
@@ -42,6 +46,10 @@ export function connectConflictOf(existing, wanted) {
42
46
  const signInFailed = existing.status === InboundMailAccountStatuses.authError;
43
47
  if (!disconnected && !signInFailed)
44
48
  return "already_connected";
49
+ // A member's disconnected personal mailbox must not lock the address for the team's shared one.
50
+ if (disconnected && wanted.ownerUserId === null && existing.ownerUserId !== null) {
51
+ return "replace_disconnected_personal";
52
+ }
45
53
  const bothOauth = wanted.authMethod === InboundMailAuthMethods.oauth &&
46
54
  existing.authMethod === InboundMailAuthMethods.oauth &&
47
55
  existing.provider === wanted.provider;
@@ -28,10 +28,12 @@ function hasContentAlready(events) {
28
28
  });
29
29
  }
30
30
  const receivedOwnerSchema = z.object({ ownerUserId: z.string().nullable() });
31
- function ownerUserIdOfStream(events) {
31
+ // `null` inside the result means a shared mailbox; an unreadable stream has no result at all, so a
32
+ // personal mail can never fall through to the shared routing.
33
+ function ownerOfStream(events) {
32
34
  const received = events.find((e) => e.type === INBOUND_MESSAGE_RECEIVED_EVENT_QN);
33
35
  const parsed = receivedOwnerSchema.safeParse(received?.payload);
34
- return parsed.success ? parsed.data.ownerUserId : null;
36
+ return parsed.success ? { ownerUserId: parsed.data.ownerUserId } : undefined;
35
37
  }
36
38
  // Read before the transaction, so it can only skip work: a row that already shows attached content
37
39
  // spares parallel refetches the upload. The event check under the message lock stays authoritative.
@@ -108,12 +110,15 @@ export const attachMessageContentHandler = defineWriteHandler({
108
110
  if (hasContentAlready(events)) {
109
111
  return { isSuccess: true, data: { duplicate: true } };
110
112
  }
113
+ const owner = ownerOfStream(events);
114
+ if (owner === undefined)
115
+ return failNotFound("inbound-message-received-event", messageAggId);
111
116
  const content = payload.outcome !== "fetched"
112
117
  ? undefined
113
118
  : prepared
114
119
  ? await finalizePreparedContent(ctx, prepared)
115
120
  : await storeInboundMessageContent(ctx, contentInputOf(payload, messageAggId));
116
- const eventPayload = await contentEventPayloadOf(payload, content, tenantId, messageAggId, ownerUserIdOfStream(events));
121
+ const eventPayload = await contentEventPayloadOf(payload, content, tenantId, messageAggId, owner.ownerUserId);
117
122
  const appended = await ctx.events.tryAppend({
118
123
  aggregateId: messageAggId,
119
124
  aggregateType: INBOUND_MESSAGE_AGGREGATE_TYPE,