@jini-ai/user-management 0.7.3-next.2 → 0.7.4

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 (380) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +55 -2
  3. package/dist/admin/adapters/memory.js +4 -4
  4. package/dist/admin-http/auth/auth-request.d.ts +112 -0
  5. package/dist/admin-http/auth/auth-request.js +32 -0
  6. package/dist/admin-http/auth/boot-redemption.d.ts +9 -0
  7. package/dist/admin-http/auth/boot-redemption.js +17 -0
  8. package/dist/admin-http/auth/boot-session.d.ts +30 -0
  9. package/dist/admin-http/auth/boot-session.js +40 -0
  10. package/dist/admin-http/auth/current-user.d.ts +28 -0
  11. package/dist/admin-http/auth/current-user.js +34 -0
  12. package/dist/admin-http/auth/index.d.ts +17 -0
  13. package/dist/admin-http/auth/index.js +9 -0
  14. package/dist/admin-http/auth/local-boot-session.d.ts +9 -0
  15. package/dist/admin-http/auth/local-boot-session.js +30 -0
  16. package/dist/admin-http/auth/logout.d.ts +10 -0
  17. package/dist/admin-http/auth/logout.js +17 -0
  18. package/dist/admin-http/auth/mfa-login.d.ts +30 -0
  19. package/dist/admin-http/auth/mfa-login.js +43 -0
  20. package/dist/admin-http/auth/password-login.d.ts +35 -0
  21. package/dist/admin-http/auth/password-login.js +52 -0
  22. package/dist/admin-http/auth/password-status.d.ts +34 -0
  23. package/dist/admin-http/auth/password-status.js +42 -0
  24. package/dist/admin-http/http/api-keys.d.ts +45 -0
  25. package/dist/admin-http/http/api-keys.js +28 -0
  26. package/dist/admin-http/http/users.d.ts +71 -0
  27. package/dist/admin-http/http/users.js +42 -0
  28. package/dist/admin-http/owner/mfa-deps.d.ts +41 -0
  29. package/dist/admin-http/owner/mfa-deps.js +26 -0
  30. package/dist/admin-http/owner/mfa-routes.d.ts +72 -0
  31. package/dist/admin-http/owner/mfa-routes.js +105 -0
  32. package/dist/admin-http/owner/passkey-admission.d.ts +46 -0
  33. package/dist/admin-http/owner/passkey-admission.js +23 -0
  34. package/dist/admin-http/owner/passkey-route-deps.d.ts +53 -0
  35. package/dist/admin-http/owner/passkey-route-deps.js +33 -0
  36. package/dist/admin-http/owner/passkey-routes.d.ts +146 -0
  37. package/dist/admin-http/owner/passkey-routes.js +98 -0
  38. package/dist/admin-http/owner/recovery-routes.d.ts +71 -0
  39. package/dist/admin-http/owner/recovery-routes.js +112 -0
  40. package/dist/admin-http/routes/api-keys/create-principal.d.ts +26 -0
  41. package/dist/admin-http/routes/api-keys/create-principal.js +37 -0
  42. package/dist/admin-http/routes/api-keys/issue.d.ts +32 -0
  43. package/dist/admin-http/routes/api-keys/issue.js +38 -0
  44. package/dist/admin-http/routes/api-keys/revoke.d.ts +26 -0
  45. package/dist/admin-http/routes/api-keys/revoke.js +31 -0
  46. package/dist/admin-http/routes/api-keys/shared.d.ts +46 -0
  47. package/dist/admin-http/routes/api-keys/shared.js +38 -0
  48. package/dist/admin-http/routes/users/access-shared.d.ts +103 -0
  49. package/dist/admin-http/routes/users/access-shared.js +85 -0
  50. package/dist/admin-http/routes/users/assign-role.d.ts +24 -0
  51. package/dist/admin-http/routes/users/assign-role.js +30 -0
  52. package/dist/admin-http/routes/users/attach-policy.d.ts +25 -0
  53. package/dist/admin-http/routes/users/attach-policy.js +31 -0
  54. package/dist/admin-http/routes/users/create-policy.d.ts +19 -0
  55. package/dist/admin-http/routes/users/create-policy.js +28 -0
  56. package/dist/admin-http/routes/users/create-role.d.ts +15 -0
  57. package/dist/admin-http/routes/users/create-role.js +21 -0
  58. package/dist/admin-http/routes/users/create.d.ts +32 -0
  59. package/dist/admin-http/routes/users/create.js +67 -0
  60. package/dist/admin-http/routes/users/delete-policy.d.ts +16 -0
  61. package/dist/admin-http/routes/users/delete-policy.js +24 -0
  62. package/dist/admin-http/routes/users/delete-role.d.ts +16 -0
  63. package/dist/admin-http/routes/users/delete-role.js +24 -0
  64. package/dist/admin-http/routes/users/delete.d.ts +35 -0
  65. package/dist/admin-http/routes/users/delete.js +35 -0
  66. package/dist/admin-http/routes/users/disable.d.ts +31 -0
  67. package/dist/admin-http/routes/users/disable.js +38 -0
  68. package/dist/admin-http/routes/users/enable.d.ts +32 -0
  69. package/dist/admin-http/routes/users/enable.js +45 -0
  70. package/dist/admin-http/routes/users/list-policies.d.ts +18 -0
  71. package/dist/admin-http/routes/users/list-policies.js +20 -0
  72. package/dist/admin-http/routes/users/list-policy-permissions.d.ts +28 -0
  73. package/dist/admin-http/routes/users/list-policy-permissions.js +30 -0
  74. package/dist/admin-http/routes/users/list-roles.d.ts +18 -0
  75. package/dist/admin-http/routes/users/list-roles.js +20 -0
  76. package/dist/admin-http/routes/users/list.d.ts +40 -0
  77. package/dist/admin-http/routes/users/list.js +82 -0
  78. package/dist/admin-http/routes/users/remove-policy-permission.d.ts +48 -0
  79. package/dist/admin-http/routes/users/remove-policy-permission.js +62 -0
  80. package/dist/admin-http/routes/users/reset-password.d.ts +33 -0
  81. package/dist/admin-http/routes/users/reset-password.js +52 -0
  82. package/dist/admin-http/routes/users/shared.d.ts +124 -0
  83. package/dist/admin-http/routes/users/shared.js +93 -0
  84. package/dist/admin-http/routes/users/update-policy.d.ts +25 -0
  85. package/dist/admin-http/routes/users/update-policy.js +30 -0
  86. package/dist/admin-http/routes/users/update-role.d.ts +23 -0
  87. package/dist/admin-http/routes/users/update-role.js +29 -0
  88. package/dist/admin-http/routes/users/update.d.ts +35 -0
  89. package/dist/admin-http/routes/users/update.js +78 -0
  90. package/dist/admin-http/routes/users/write-policy-permission.d.ts +31 -0
  91. package/dist/admin-http/routes/users/write-policy-permission.js +45 -0
  92. package/dist/core/ports.d.ts +22 -3
  93. package/dist/core/types.d.ts +17 -5
  94. package/dist/core/types.js +12 -0
  95. package/dist/identity/api-key-secret.d.ts +68 -0
  96. package/dist/identity/api-key-secret.js +229 -0
  97. package/dist/identity/api-key-service.d.ts +144 -0
  98. package/dist/identity/api-key-service.js +389 -0
  99. package/dist/identity/api-key-types.d.ts +79 -0
  100. package/dist/identity/api-key-types.js +2 -0
  101. package/dist/identity/boot-session-token.d.ts +18 -0
  102. package/dist/identity/boot-session-token.js +92 -0
  103. package/dist/identity/builtin-role-grants.d.ts +120 -0
  104. package/dist/identity/builtin-role-grants.js +88 -0
  105. package/dist/identity/delete-user-service.d.ts +195 -0
  106. package/dist/identity/delete-user-service.js +275 -0
  107. package/dist/identity/owner-reset-env.d.ts +37 -0
  108. package/dist/identity/owner-reset-env.js +38 -0
  109. package/dist/identity/permission-grants.d.ts +31 -0
  110. package/dist/identity/permission-grants.js +12 -0
  111. package/dist/identity/permission-list-tool.d.ts +35 -0
  112. package/dist/identity/permission-list-tool.js +47 -0
  113. package/dist/identity/repo.authentication.d.ts +57 -0
  114. package/dist/identity/repo.authentication.js +153 -0
  115. package/dist/identity/repo.authorization.d.ts +82 -0
  116. package/dist/identity/repo.authorization.js +203 -0
  117. package/dist/identity/repo.d.ts +87 -0
  118. package/dist/identity/repo.js +167 -0
  119. package/dist/identity/repo.memory.d.ts +31 -0
  120. package/dist/identity/repo.memory.js +37 -0
  121. package/dist/identity/role-manage-permission.d.ts +34 -0
  122. package/dist/identity/role-manage-permission.js +39 -0
  123. package/dist/identity/site-key-permission.d.ts +66 -0
  124. package/dist/identity/site-key-permission.js +92 -0
  125. package/dist/identity/sql/kernel-user-purge.d.ts +19 -0
  126. package/dist/identity/sql/kernel-user-purge.js +34 -0
  127. package/dist/identity/sql/kernel-user-trash-store.d.ts +15 -0
  128. package/dist/identity/sql/kernel-user-trash-store.js +41 -0
  129. package/dist/identity/sql/user-trash-adapter.d.ts +87 -0
  130. package/dist/identity/sql/user-trash-adapter.js +124 -0
  131. package/dist/identity/tool-registrations.d.ts +100 -0
  132. package/dist/identity/tool-registrations.js +257 -0
  133. package/dist/identity/user-manage-permission.d.ts +8 -0
  134. package/dist/identity/user-manage-permission.js +8 -0
  135. package/dist/identity/user-purge-types.d.ts +85 -0
  136. package/dist/identity/user-purge-types.js +17 -0
  137. package/dist/identity/user-purge.d.ts +69 -0
  138. package/dist/identity/user-purge.js +46 -0
  139. package/dist/identity/username-change-ports.d.ts +15 -0
  140. package/dist/identity/username-change-ports.js +22 -0
  141. package/dist/mail/site/capture-clear.d.ts +58 -0
  142. package/dist/mail/site/capture-clear.js +21 -0
  143. package/dist/mail/status/agent-tools.d.ts +65 -0
  144. package/dist/mail/status/agent-tools.js +22 -0
  145. package/dist/mail/status/delivery-agent-tools.d.ts +206 -0
  146. package/dist/mail/status/delivery-agent-tools.js +63 -0
  147. package/dist/mail/status/delivery-tool-registrations.d.ts +216 -0
  148. package/dist/mail/status/delivery-tool-registrations.js +110 -0
  149. package/dist/mail/status/domain-deps.d.ts +25 -0
  150. package/dist/mail/status/domain-deps.js +23 -0
  151. package/dist/mail/status/permissions.d.ts +43 -0
  152. package/dist/mail/status/permissions.js +45 -0
  153. package/dist/mail/status/provider-agent-tools.d.ts +38 -0
  154. package/dist/mail/status/provider-agent-tools.js +17 -0
  155. package/dist/mail/status/provider-operations.d.ts +166 -0
  156. package/dist/mail/status/provider-operations.js +121 -0
  157. package/dist/mail/status/provider-tool-registrations.d.ts +65 -0
  158. package/dist/mail/status/provider-tool-registrations.js +106 -0
  159. package/dist/mail/status/tool-registrations.d.ts +152 -0
  160. package/dist/mail/status/tool-registrations.js +112 -0
  161. package/dist/member-login/credentials.d.ts +40 -0
  162. package/dist/member-login/credentials.js +26 -0
  163. package/dist/member-login/link-service.d.ts +66 -0
  164. package/dist/member-login/link-service.js +141 -0
  165. package/dist/member-login/oidc-login.d.ts +132 -0
  166. package/dist/member-login/oidc-login.js +206 -0
  167. package/dist/member-login/oidc-request.d.ts +80 -0
  168. package/dist/member-login/oidc-request.js +86 -0
  169. package/dist/member-login/providers.d.ts +79 -0
  170. package/dist/member-login/providers.js +41 -0
  171. package/dist/member-login/ready-providers.d.ts +17 -0
  172. package/dist/member-login/ready-providers.js +11 -0
  173. package/dist/member-login/unlink-identity.d.ts +26 -0
  174. package/dist/member-login/unlink-identity.js +59 -0
  175. package/dist/members/access-resolver.d.ts +107 -0
  176. package/dist/members/access-resolver.js +231 -0
  177. package/dist/members/agent-tools.d.ts +14 -0
  178. package/dist/members/agent-tools.js +139 -0
  179. package/dist/members/auth-mail.d.ts +27 -0
  180. package/dist/members/auth-mail.js +21 -0
  181. package/dist/members/capability-card.d.ts +18 -0
  182. package/dist/members/capability-card.js +27 -0
  183. package/dist/members/consent-service.d.ts +115 -0
  184. package/dist/members/consent-service.js +179 -0
  185. package/dist/members/member-admin-writes.d.ts +73 -0
  186. package/dist/members/member-admin-writes.js +149 -0
  187. package/dist/members/member-challenge-request.d.ts +59 -0
  188. package/dist/members/member-challenge-request.js +145 -0
  189. package/dist/members/member-challenge.d.ts +37 -0
  190. package/dist/members/member-challenge.js +84 -0
  191. package/dist/members/member-credentials.d.ts +35 -0
  192. package/dist/members/member-credentials.js +57 -0
  193. package/dist/members/member-sign-in.d.ts +44 -0
  194. package/dist/members/member-sign-in.js +130 -0
  195. package/dist/members/member-validation.d.ts +5 -0
  196. package/dist/members/member-validation.js +13 -0
  197. package/dist/members/password-auth.d.ts +55 -0
  198. package/dist/members/password-auth.js +177 -0
  199. package/dist/members/ports.d.ts +455 -0
  200. package/dist/members/ports.js +21 -0
  201. package/dist/members/public-member-auth-response.d.ts +68 -0
  202. package/dist/members/public-member-auth-response.js +45 -0
  203. package/dist/members/public-member-response.d.ts +25 -0
  204. package/dist/members/public-member-response.js +15 -0
  205. package/dist/members/repo.d.ts +199 -0
  206. package/dist/members/repo.js +324 -0
  207. package/dist/members/repo.memory.d.ts +276 -0
  208. package/dist/members/repo.memory.js +395 -0
  209. package/dist/members/repo.rows.d.ts +153 -0
  210. package/dist/members/repo.rows.js +250 -0
  211. package/dist/members/repo.sessions.d.ts +80 -0
  212. package/dist/members/repo.sessions.js +166 -0
  213. package/dist/members/repo.sql.d.ts +9 -0
  214. package/dist/members/repo.sql.js +11 -0
  215. package/dist/members/subscriber-directory.d.ts +85 -0
  216. package/dist/members/subscriber-directory.js +70 -0
  217. package/dist/members/tool-registrations.d.ts +143 -0
  218. package/dist/members/tool-registrations.js +247 -0
  219. package/dist/members/trash-member.d.ts +24 -0
  220. package/dist/members/trash-member.js +24 -0
  221. package/dist/members/types.d.ts +321 -0
  222. package/dist/members/types.js +34 -0
  223. package/dist/members/write-service.d.ts +17 -0
  224. package/dist/members/write-service.js +15 -0
  225. package/dist/newsletter/agent-tools.d.ts +20 -0
  226. package/dist/newsletter/agent-tools.js +236 -0
  227. package/dist/newsletter/campaign-write-service.d.ts +92 -0
  228. package/dist/newsletter/campaign-write-service.js +190 -0
  229. package/dist/newsletter/campaign.d.ts +53 -0
  230. package/dist/newsletter/campaign.js +95 -0
  231. package/dist/newsletter/confirmation.d.ts +75 -0
  232. package/dist/newsletter/confirmation.js +142 -0
  233. package/dist/newsletter/data-module-manifest.d.ts +68 -0
  234. package/dist/newsletter/data-module-manifest.js +126 -0
  235. package/dist/newsletter/delivery/tool-registrations.d.ts +67 -0
  236. package/dist/newsletter/delivery/tool-registrations.js +229 -0
  237. package/dist/newsletter/errors.d.ts +93 -0
  238. package/dist/newsletter/errors.js +93 -0
  239. package/dist/newsletter/hooks.d.ts +59 -0
  240. package/dist/newsletter/hooks.js +49 -0
  241. package/dist/newsletter/http-error-responses.d.ts +17 -0
  242. package/dist/newsletter/http-error-responses.js +96 -0
  243. package/dist/newsletter/launch-gate.d.ts +62 -0
  244. package/dist/newsletter/launch-gate.js +29 -0
  245. package/dist/newsletter/lists.d.ts +60 -0
  246. package/dist/newsletter/lists.js +83 -0
  247. package/dist/newsletter/ports.d.ts +283 -0
  248. package/dist/newsletter/ports.js +2 -0
  249. package/dist/newsletter/repo-sends.d.ts +82 -0
  250. package/dist/newsletter/repo-sends.js +178 -0
  251. package/dist/newsletter/repo-subscribers.d.ts +83 -0
  252. package/dist/newsletter/repo-subscribers.js +215 -0
  253. package/dist/newsletter/repo.d.ts +61 -0
  254. package/dist/newsletter/repo.js +147 -0
  255. package/dist/newsletter/repo.memory.d.ts +202 -0
  256. package/dist/newsletter/repo.memory.js +260 -0
  257. package/dist/newsletter/repo.rows.d.ts +221 -0
  258. package/dist/newsletter/repo.rows.js +260 -0
  259. package/dist/newsletter/save-guard.d.ts +32 -0
  260. package/dist/newsletter/save-guard.js +27 -0
  261. package/dist/newsletter/send-pipeline.d.ts +240 -0
  262. package/dist/newsletter/send-pipeline.js +514 -0
  263. package/dist/newsletter/subscriptions.d.ts +87 -0
  264. package/dist/newsletter/subscriptions.js +119 -0
  265. package/dist/newsletter/tool-registrations.d.ts +89 -0
  266. package/dist/newsletter/tool-registrations.deps.d.ts +9 -0
  267. package/dist/newsletter/tool-registrations.deps.js +9 -0
  268. package/dist/newsletter/tool-registrations.js +133 -0
  269. package/dist/newsletter/tool-registrations.read.d.ts +76 -0
  270. package/dist/newsletter/tool-registrations.read.js +140 -0
  271. package/dist/newsletter/tool-registrations.write.d.ts +54 -0
  272. package/dist/newsletter/tool-registrations.write.js +229 -0
  273. package/dist/newsletter/types.d.ts +279 -0
  274. package/dist/newsletter/types.js +23 -0
  275. package/dist/newsletter/unsubscribe.d.ts +41 -0
  276. package/dist/newsletter/unsubscribe.js +100 -0
  277. package/dist/project-keys/attached-vault.d.ts +23 -0
  278. package/dist/project-keys/attached-vault.js +65 -0
  279. package/dist/project-keys/create-vault.d.ts +17 -0
  280. package/dist/project-keys/create-vault.js +29 -0
  281. package/dist/project-keys/service.d.ts +133 -0
  282. package/dist/project-keys/service.js +128 -0
  283. package/dist/project-keys/site-references.d.ts +30 -0
  284. package/dist/project-keys/site-references.js +63 -0
  285. package/dist/project-keys/site-sealer.d.ts +28 -0
  286. package/dist/project-keys/site-sealer.js +64 -0
  287. package/dist/project-keys/sql/attachments.d.ts +33 -0
  288. package/dist/project-keys/sql/attachments.js +55 -0
  289. package/dist/project-keys/tools.d.ts +86 -0
  290. package/dist/project-keys/tools.js +66 -0
  291. package/dist/public-http/routes/mail/feedback.d.ts +44 -0
  292. package/dist/public-http/routes/mail/feedback.js +17 -0
  293. package/dist/public-http/routes/newsletter/confirm.d.ts +38 -0
  294. package/dist/public-http/routes/newsletter/confirm.js +33 -0
  295. package/dist/public-http/routes/newsletter/page.d.ts +29 -0
  296. package/dist/public-http/routes/newsletter/page.js +34 -0
  297. package/dist/public-http/routes/newsletter/unsubscribe.d.ts +33 -0
  298. package/dist/public-http/routes/newsletter/unsubscribe.js +35 -0
  299. package/dist/react/auth/Passkeys.d.ts +2 -34
  300. package/dist/react/auth/RecoveryCodesCard.d.ts +27 -0
  301. package/dist/react/auth/RecoveryCodesCard.hooks.d.ts +67 -0
  302. package/dist/react/auth/RecoveryCodesCard.hooks.js +38 -0
  303. package/dist/react/auth/RecoveryCodesCard.js +56 -0
  304. package/dist/react/auth/TotpSettings.d.ts +2 -23
  305. package/dist/react/auth/local-owner-signin.d.ts +40 -0
  306. package/dist/react/auth/local-owner-signin.js +25 -0
  307. package/dist/react/auth/owner-mfa-api.d.ts +10 -0
  308. package/dist/react/auth/owner-mfa-api.js +17 -0
  309. package/dist/react/auth/owner-passkey-api.d.ts +11 -0
  310. package/dist/react/auth/owner-passkey-api.js +17 -0
  311. package/dist/react/auth/owner-recovery-api.d.ts +51 -0
  312. package/dist/react/auth/owner-recovery-api.js +29 -0
  313. package/dist/react/auth/owner-request.d.ts +7 -0
  314. package/dist/react/auth/owner-request.js +2 -0
  315. package/dist/react/index.d.ts +10 -0
  316. package/dist/react/index.js +6 -0
  317. package/dist/react/mail/Email.d.ts +20 -0
  318. package/dist/react/mail/Email.js +143 -0
  319. package/dist/react/mail/EmailProviderTab.d.ts +34 -0
  320. package/dist/react/mail/EmailProviderTab.js +132 -0
  321. package/dist/react/mail/EmailSegments.d.ts +24 -0
  322. package/dist/react/mail/EmailSegments.js +15 -0
  323. package/dist/react/mail/EmailTemplateEditor.d.ts +146 -0
  324. package/dist/react/mail/EmailTemplateEditor.js +116 -0
  325. package/dist/react/mail/email-view.types.d.ts +236 -0
  326. package/dist/react/mail/email-view.types.js +2 -0
  327. package/dist/react/members/Members.d.ts +5 -3
  328. package/dist/react/members/Members.js +3 -3
  329. package/dist/react/members/api/members-api.d.ts +37 -0
  330. package/dist/react/members/api/members-api.js +16 -0
  331. package/dist/react/members/hooks/use-members.hooks.js +2 -1
  332. package/dist/react/members/members-i18n.d.ts +23 -0
  333. package/dist/react/members/members-i18n.js +25 -0
  334. package/dist/react/members/members-i18n.locales-a.d.ts +4 -0
  335. package/dist/react/members/members-i18n.locales-a.js +294 -0
  336. package/dist/react/members/members-i18n.locales-b.d.ts +4 -0
  337. package/dist/react/members/members-i18n.locales-b.js +265 -0
  338. package/dist/react/models.d.ts +1 -49
  339. package/dist/react/ports.d.ts +3 -143
  340. package/dist/react/roles/api/roles-api.d.ts +74 -0
  341. package/dist/react/roles/api/roles-api.js +22 -0
  342. package/dist/react/testing.js +18 -9
  343. package/dist/react/users/UsersPanel.d.ts +30 -0
  344. package/dist/react/users/UsersPanel.hooks.d.ts +8 -0
  345. package/dist/react/users/UsersPanel.hooks.js +9 -0
  346. package/dist/react/users/UsersPanel.js +9 -0
  347. package/dist/react/users/api/users-api.d.ts +65 -0
  348. package/dist/react/users/api/users-api.js +46 -0
  349. package/dist/react/users/hooks/use-localized-users.hooks.d.ts +43 -0
  350. package/dist/react/users/hooks/use-localized-users.hooks.js +15 -0
  351. package/dist/react/users/hooks/use-users-state.hooks.d.ts +18 -18
  352. package/dist/react/users/password-reset-notice.d.ts +8 -0
  353. package/dist/react/users/password-reset-notice.js +36 -0
  354. package/dist/server/admin-crud-service.d.ts +4 -10
  355. package/dist/server/admin-crud-service.js +20 -6
  356. package/dist/server/agent-tool-registrations.js +26 -7
  357. package/dist/server/agent-tools.js +22 -7
  358. package/dist/server/auth-challenge.d.ts +1 -1
  359. package/dist/server/auth-service.js +2 -1
  360. package/dist/server/grant-service.d.ts +1 -0
  361. package/dist/server/grant-service.js +7 -4
  362. package/dist/server/mfa/passkey-service.d.ts +2 -2
  363. package/dist/server/mfa/passkey-service.js +1 -1
  364. package/dist/server/mfa/service.js +6 -4
  365. package/dist/server/repo.memory.d.ts +30 -2
  366. package/dist/server/repo.memory.js +58 -4
  367. package/dist/server/seed.js +3 -3
  368. package/dist/server/sql/assignments.d.ts +90 -0
  369. package/dist/server/sql/assignments.js +128 -0
  370. package/dist/server/sql/index.d.ts +6 -0
  371. package/dist/server/sql/index.js +5 -0
  372. package/dist/server/sql/kernel.d.ts +9 -0
  373. package/dist/server/sql/kernel.js +2 -0
  374. package/dist/server/sql/mfa.d.ts +36 -0
  375. package/dist/server/sql/mfa.js +51 -0
  376. package/dist/server/sql/passkeys.d.ts +25 -0
  377. package/dist/server/sql/passkeys.js +33 -0
  378. package/dist/server/sql/recovery-codes.d.ts +22 -0
  379. package/dist/server/sql/recovery-codes.js +32 -0
  380. package/package.json +909 -11
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @file `campaign-write-service.ts` — THE campaign write chokepoint (ADR-PIPE-011 C-009/C-010/C-011,
3
+ * REQ-01/06/09, INV-01).
4
+ *
5
+ * The ONLY writer of `newsletter_campaigns`/`newsletter_campaign_revisions` — repo write methods
6
+ * (`saveCampaignRow`/`appendRevision`) must never be called from outside this file (Code Review
7
+ * enforces this as a file-boundary check, mirrors `SettingsWriteService`'s identical convention).
8
+ * Calls `campaign.ts`'s `transitionCampaignStatus` before every status-affecting write; campaign +
9
+ * revision write in the SAME transaction (INV-01: a campaign row must never exist without a
10
+ * same-tx revision row).
11
+ */
12
+ import type { CreatorKind, UUID } from "@jini-ai/core/primitives";
13
+ import type { NewsletterCampaignRepoPort, NewsletterListRepoPort } from "./ports.js";
14
+ import type { CampaignRecord } from "./types.js";
15
+ export declare const SUBJECT_MIN = 1;
16
+ export declare const SUBJECT_MAX = 998;
17
+ export declare const PREHEADER_MAX = 300;
18
+ export interface CampaignWriteServiceDeps {
19
+ campaignRepo: NewsletterCampaignRepoPort;
20
+ listRepo: NewsletterListRepoPort;
21
+ clock: {
22
+ nowIso(): string;
23
+ };
24
+ ids: {
25
+ newId(): string;
26
+ };
27
+ }
28
+ /**
29
+ * C-009 — create or edit a campaign's editorial fields (REQ-01/06/09). Never touches `status`
30
+ * directly (no `status` field accepted — matches `UPDATE_CAMPAIGN`'s body schema, which does not
31
+ * accept a status field at all per behavior.spec.md §1.1).
32
+ *
33
+ * @complexity O(1) DB round trips (bounded revision-listing to compute the next `seq`).
34
+ * @overallScore 100
35
+ */
36
+ export declare function saveCampaign(required: {
37
+ deps: CampaignWriteServiceDeps;
38
+ input: {
39
+ workspaceId: UUID;
40
+ id?: UUID;
41
+ actorId: UUID;
42
+ /** Who is creating the campaign, recorded once as `created_by_kind` (H4, 2026-11-24). Omitted
43
+ * means `"person"`: the admin routes pass nothing, the agent tools pass `"agent"` (an agent
44
+ * acts under the real human's `actorId`, so the kind cannot be recovered from it later).
45
+ * Ignored on a re-save — the stored kind is write-once. */
46
+ creatorKind?: CreatorKind;
47
+ expectedVersion?: number;
48
+ fields: {
49
+ subject: string;
50
+ bodyJson?: Record<string, unknown>;
51
+ preheader?: string | null;
52
+ fromName: string;
53
+ fromEmail: string;
54
+ replyTo: string;
55
+ listId: UUID;
56
+ };
57
+ };
58
+ }, _optional?: Record<string, never>): Promise<{
59
+ campaign: CampaignRecord;
60
+ revisionSeq: number;
61
+ }>;
62
+ /** C-010 — cancel a campaign (`admin.newsletter.campaign.compose` tier). */
63
+ export declare function cancelCampaign(required: {
64
+ deps: CampaignWriteServiceDeps;
65
+ input: {
66
+ workspaceId: UUID;
67
+ id: UUID;
68
+ actorId: UUID;
69
+ };
70
+ }, _optional?: Record<string, never>): Promise<{
71
+ campaign: CampaignRecord;
72
+ }>;
73
+ /** Validates a timezone-qualified ISO timestamp, including the calendar date that Date.parse normalizes.
74
+ * @param required.value - Caller-supplied schedule timestamp, shared by routes, tools and the write service.
75
+ * @returns False for malformed dates, missing timezone or impossible calendar dates.
76
+ * @complexity O(n) in timestamp length, O(1) auxiliary space. */
77
+ export declare function isValidScheduleTimestamp({ value }: {
78
+ value: string;
79
+ }, _optional?: Record<string, never>): boolean;
80
+ /** C-011 — schedule a draft campaign (`admin.newsletter.campaign.schedule` tier). */
81
+ export declare function scheduleCampaign(required: {
82
+ deps: CampaignWriteServiceDeps;
83
+ input: {
84
+ workspaceId: UUID;
85
+ id: UUID;
86
+ actorId: UUID;
87
+ scheduledAt: string;
88
+ };
89
+ }, _optional?: Record<string, never>): Promise<{
90
+ campaign: CampaignRecord;
91
+ }>;
92
+ //# sourceMappingURL=campaign-write-service.d.ts.map
@@ -0,0 +1,190 @@
1
+ import { transitionCampaignStatus } from "./campaign.js";
2
+ import { NewsletterCampaignNotEditableError, NewsletterCampaignNotFoundError, NewsletterConflictError, NewsletterListNotFoundError, NewsletterValidationError, } from "./errors.js";
3
+ // Exported (not just module-local) so `agent-tools.ts`'s published `inputSchema` bounds import
4
+ // these single sources rather than restating the numbers — the same discipline
5
+ // `forms/agent-tools.ts` applies to `forms.ts`'s field constants.
6
+ export const SUBJECT_MIN = 1;
7
+ export const SUBJECT_MAX = 998;
8
+ export const PREHEADER_MAX = 300;
9
+ const ZERO_COUNTERS = {
10
+ recipients: 0,
11
+ delivered: 0,
12
+ failed: 0,
13
+ bounced: 0,
14
+ complained: 0,
15
+ unsubscribed: 0,
16
+ };
17
+ function validateFields(fields) {
18
+ if (fields.subject.length < SUBJECT_MIN || fields.subject.length > SUBJECT_MAX) {
19
+ throw new NewsletterValidationError({
20
+ message: `subject must be between ${SUBJECT_MIN} and ${SUBJECT_MAX} characters`,
21
+ field: "subject",
22
+ reason: "length",
23
+ });
24
+ }
25
+ if (fields.preheader != null && fields.preheader.length > PREHEADER_MAX) {
26
+ throw new NewsletterValidationError({ message: `preheader must be at most ${PREHEADER_MAX} characters`, field: "preheader", reason: "length" });
27
+ }
28
+ }
29
+ async function requireEditableListId({ deps, workspaceId, listId }, _options = {}) {
30
+ const list = await deps.listRepo.findById({ workspaceId, id: listId });
31
+ if (!list)
32
+ throw new NewsletterListNotFoundError(`list ${listId} was not found`);
33
+ // Archiving a list restricts writes; it does not remove campaigns from history.
34
+ if (list.status === "archived") {
35
+ throw new NewsletterValidationError({ field: "listId", reason: "archived", message: "This list is archived." });
36
+ }
37
+ }
38
+ async function writeRevision({ deps, campaign, actorId }, _options = {}) {
39
+ const priorRevisions = await deps.campaignRepo.listRevisions({ workspaceId: campaign.workspaceId, campaignId: campaign.id });
40
+ const seq = priorRevisions.length > 0 ? Math.max(...priorRevisions.map((r) => r.seq)) + 1 : 1;
41
+ await deps.campaignRepo.saveCampaignRow(campaign);
42
+ await deps.campaignRepo.appendRevision({
43
+ campaignId: campaign.id,
44
+ workspaceId: campaign.workspaceId,
45
+ seq,
46
+ state: campaign,
47
+ actorId,
48
+ recordedAt: deps.clock.nowIso(),
49
+ });
50
+ }
51
+ /**
52
+ * C-009 — create or edit a campaign's editorial fields (REQ-01/06/09). Never touches `status`
53
+ * directly (no `status` field accepted — matches `UPDATE_CAMPAIGN`'s body schema, which does not
54
+ * accept a status field at all per behavior.spec.md §1.1).
55
+ *
56
+ * @complexity O(1) DB round trips (bounded revision-listing to compute the next `seq`).
57
+ * @overallScore 100
58
+ */
59
+ export async function saveCampaign(required, _optional = {}) {
60
+ const { deps, input } = required;
61
+ validateFields(input.fields);
62
+ await requireEditableListId({ deps, workspaceId: input.workspaceId, listId: input.fields.listId });
63
+ return deps.campaignRepo.transaction({ fn: async () => {
64
+ const now = deps.clock.nowIso();
65
+ let campaign = input.id
66
+ ? await editDraftCampaign({ deps, input, id: input.id, now })
67
+ : newDraftCampaign({ deps, input, now });
68
+ if (input.fields.bodyJson !== undefined)
69
+ campaign = { ...campaign, bodyJson: input.fields.bodyJson };
70
+ await writeRevision({ deps, campaign, actorId: input.actorId });
71
+ const revisions = await deps.campaignRepo.listRevisions({ workspaceId: campaign.workspaceId, campaignId: campaign.id });
72
+ return { campaign, revisionSeq: Math.max(...revisions.map((r) => r.seq)) };
73
+ } });
74
+ }
75
+ /** Load a draft campaign for editing, enforcing editable status and the optimistic-version check. */
76
+ async function editDraftCampaign(required) {
77
+ const { deps, input, id, now } = required;
78
+ const existing = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id });
79
+ if (!existing)
80
+ throw new NewsletterCampaignNotFoundError(`campaign ${id} was not found`);
81
+ if (existing.status !== "draft") {
82
+ throw new NewsletterCampaignNotEditableError({
83
+ message: `campaign is '${existing.status}' and cannot be edited`,
84
+ currentStatus: existing.status,
85
+ attemptedAction: "update",
86
+ });
87
+ }
88
+ if (input.expectedVersion !== undefined && input.expectedVersion !== existing.version) {
89
+ throw new NewsletterConflictError({
90
+ message: "campaign was modified concurrently (EC-06)",
91
+ entity: "campaign",
92
+ id: existing.id,
93
+ expectedVersion: input.expectedVersion,
94
+ actualVersion: existing.version,
95
+ });
96
+ }
97
+ return {
98
+ ...existing,
99
+ subject: input.fields.subject,
100
+ preheader: input.fields.preheader ?? null,
101
+ fromName: input.fields.fromName,
102
+ fromEmail: input.fields.fromEmail,
103
+ replyTo: input.fields.replyTo,
104
+ listId: input.fields.listId,
105
+ version: existing.version + 1,
106
+ updatedAt: now,
107
+ };
108
+ }
109
+ /** Build a fresh draft campaign record from the editorial fields. */
110
+ function newDraftCampaign(required) {
111
+ const { deps, input, now } = required;
112
+ return {
113
+ id: deps.ids.newId(),
114
+ workspaceId: input.workspaceId,
115
+ status: "draft",
116
+ subject: input.fields.subject,
117
+ preheader: input.fields.preheader ?? null,
118
+ fromName: input.fields.fromName,
119
+ fromEmail: input.fields.fromEmail,
120
+ replyTo: input.fields.replyTo,
121
+ listId: input.fields.listId,
122
+ scheduledAt: null,
123
+ sendStartedAt: null,
124
+ audienceSnapshotId: null,
125
+ counters: ZERO_COUNTERS,
126
+ version: 1,
127
+ createdByPrincipal: input.actorId,
128
+ createdByKind: input.creatorKind ?? "person",
129
+ createdAt: now,
130
+ updatedAt: now,
131
+ };
132
+ }
133
+ async function transitionAndWrite(deps, required) {
134
+ return deps.campaignRepo.transaction({ fn: async () => {
135
+ const existing = await deps.campaignRepo.findById({ workspaceId: required.workspaceId, id: required.id });
136
+ if (!existing)
137
+ throw new NewsletterCampaignNotFoundError(`campaign ${required.id} was not found`);
138
+ const decision = transitionCampaignStatus({ from: existing.status, to: required.to, actorTier: required.actorTier });
139
+ if (!decision.allowed) {
140
+ throw new NewsletterCampaignNotEditableError({ message: decision.reason, currentStatus: existing.status, attemptedAction: `transition-to-${required.to}` });
141
+ }
142
+ const campaign = { ...existing, status: required.to, updatedAt: deps.clock.nowIso() };
143
+ await writeRevision({ deps, campaign, actorId: required.actorId });
144
+ return campaign;
145
+ } });
146
+ }
147
+ /** C-010 — cancel a campaign (`admin.newsletter.campaign.compose` tier). */
148
+ export async function cancelCampaign(required, _optional = {}) {
149
+ const campaign = await transitionAndWrite(required.deps, { ...required.input, to: "canceled", actorTier: "compose" });
150
+ return { campaign };
151
+ }
152
+ /** Validates a timezone-qualified ISO timestamp, including the calendar date that Date.parse normalizes.
153
+ * @param required.value - Caller-supplied schedule timestamp, shared by routes, tools and the write service.
154
+ * @returns False for malformed dates, missing timezone or impossible calendar dates.
155
+ * @complexity O(n) in timestamp length, O(1) auxiliary space. */
156
+ export function isValidScheduleTimestamp({ value }, _optional = {}) {
157
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value))
158
+ return false;
159
+ if (!Number.isFinite(Date.parse(value)))
160
+ return false;
161
+ const datePart = value.slice(0, 10);
162
+ return new Date(`${datePart}T00:00:00.000Z`).toISOString().slice(0, 10) === datePart;
163
+ }
164
+ /** C-011 — schedule a draft campaign (`admin.newsletter.campaign.schedule` tier). */
165
+ export async function scheduleCampaign(required, _optional = {}) {
166
+ const { deps, input } = required;
167
+ if (!isValidScheduleTimestamp({ value: input.scheduledAt })) {
168
+ throw new NewsletterValidationError({ message: "scheduledAt must be a valid ISO date-time string", field: "scheduledAt", reason: "format" });
169
+ }
170
+ const campaign = await deps.campaignRepo.transaction({ fn: async () => {
171
+ const existing = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.id });
172
+ if (!existing)
173
+ throw new NewsletterCampaignNotFoundError(`campaign ${input.id} was not found`);
174
+ await requireEditableListId({ deps, workspaceId: input.workspaceId, listId: existing.listId });
175
+ const decision = transitionCampaignStatus({ from: existing.status, to: "scheduled", actorTier: "schedule" });
176
+ if (!decision.allowed) {
177
+ throw new NewsletterCampaignNotEditableError({ message: decision.reason, currentStatus: existing.status, attemptedAction: "schedule" });
178
+ }
179
+ const updated = {
180
+ ...existing,
181
+ status: "scheduled",
182
+ scheduledAt: input.scheduledAt,
183
+ updatedAt: deps.clock.nowIso(),
184
+ };
185
+ await writeRevision({ deps, campaign: updated, actorId: input.actorId });
186
+ return updated;
187
+ } });
188
+ return { campaign };
189
+ }
190
+ //# sourceMappingURL=campaign-write-service.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @file `transitionCampaignStatus` — the campaign status-machine guard (ADR-PIPE-011 C-008,
3
+ * behavior.spec.md §1.1, REQ-04/05/07/18).
4
+ *
5
+ * `[internal-invariant]`: a divergence between this function and any route-layer re-implementation
6
+ * of the transition-authority rule is a fail-open authorization bug, same class as SPEC-007's
7
+ * `deriveRequiredPermission` (ADR-PIPE-011 Contract Map C-008). `campaign-write-service.ts` calls
8
+ * this before every status-affecting write; no other call site may re-implement it.
9
+ *
10
+ * Precedence (highest to lowest — behavior.spec.md §1.1's transition-authority table):
11
+ * 1. `pipeline` tier (the send pipeline's own internal actions, never a direct HTTP caller) —
12
+ * the ONLY actor that may set `scheduled -> sending` or `sending -> sent`.
13
+ * 2. `send` tier (`admin.newsletter.campaign.send`) — may set `sending <-> paused` only (via
14
+ * `PAUSE_CAMPAIGN`/`RESUME_CAMPAIGN`); never sets `sending`/`sent` directly (those stay
15
+ * pipeline-only, reached only by triggering `authorizeSend`, which runs as `pipeline` tier).
16
+ * 3. `schedule` tier (`admin.newsletter.campaign.schedule`) — may set `draft -> scheduled` only
17
+ * (via `SCHEDULE_CAMPAIGN`).
18
+ * 4. `compose` tier (`admin.newsletter.campaign.compose`) — may set `draft -> canceled` or
19
+ * `scheduled -> canceled` only (via `CANCEL_CAMPAIGN`); `UPDATE_CAMPAIGN`'s body schema does not
20
+ * accept a `status` field at all (no direct status transition from plain field edits).
21
+ *
22
+ * DEVIATION DISCLOSED: `api.spec.md` has no dedicated "unschedule"/revert-to-draft endpoint in its
23
+ * 19-route list — only `CANCEL_CAMPAIGN`/`SCHEDULE_CAMPAIGN`/`SEND_CAMPAIGN`/`SEND_TEST_CAMPAIGN`/
24
+ * `PAUSE_CAMPAIGN`/`RESUME_CAMPAIGN` exist. This implementation therefore maps each real endpoint to
25
+ * exactly one transition family and does NOT implement a `scheduled -> draft` transition for any
26
+ * tier (there is no endpoint that would call it). If a future endpoint needs that transition, add it
27
+ * here explicitly rather than widening `compose`'s existing grant.
28
+ */
29
+ import type { CampaignStatus } from "./types.js";
30
+ export type CampaignActorTier = "pipeline" | "send" | "schedule" | "compose";
31
+ export type TransitionResult = {
32
+ allowed: true;
33
+ } | {
34
+ allowed: false;
35
+ reason: string;
36
+ };
37
+ /**
38
+ * Decides whether `actorTier` may move a campaign from `from` to `to`.
39
+ *
40
+ * Deny-by-default: an edge no rule below matches falls through to the closing rejection, so adding
41
+ * a status to `CampaignStatus` cannot silently open a transition. The rules are ordered, not
42
+ * independent — `to === "sent"` deliberately sits between the send-start and pause/resume rules
43
+ * (see this file's header for the full precedence table).
44
+ *
45
+ * @complexity O(1), pure, total function (every input produces a result, never throws).
46
+ * @overallScore 100
47
+ */
48
+ export declare function transitionCampaignStatus(input: {
49
+ from: CampaignStatus;
50
+ to: CampaignStatus;
51
+ actorTier: CampaignActorTier;
52
+ }, _optional?: Record<string, never>): TransitionResult;
53
+ //# sourceMappingURL=campaign.d.ts.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Who may perform each edge, one named grant per rule below. Named rather than inlined into a
3
+ * boolean chain so that widening a grant is a one-line, greppable change to a list, and so the
4
+ * grant sits next to the denial text that explains it — the two drifting apart is how a fail-open
5
+ * authorization bug reads to a reviewer.
6
+ */
7
+ const PIPELINE_ONLY = ["pipeline"];
8
+ const SEND_OR_PIPELINE = ["send", "pipeline"];
9
+ const SCHEDULE_ONLY = ["schedule"];
10
+ const COMPOSE_ONLY = ["compose"];
11
+ /**
12
+ * Allows an already-matched edge when the actor holds a permitted tier, else denies it with the
13
+ * rule's own explanatory text.
14
+ *
15
+ * @complexity O(t) in the (fixed, ≤4) size of `permitted`.
16
+ */
17
+ function requireTier({ actorTier, permitted, reason }, _options = {}) {
18
+ if (!permitted.includes(actorTier))
19
+ return { allowed: false, reason };
20
+ return { allowed: true };
21
+ }
22
+ /**
23
+ * The initial send start. NOTE: `paused -> sending` (resume) is a DIFFERENT edge, matched by
24
+ * {@link isPauseOrResume} below — it must not be folded into this one by relaxing the `from` check
25
+ * to a blanket `to === "sending"`, which would hand the resume path to the pipeline tier alone.
26
+ */
27
+ function isSendStart(from, to) {
28
+ return from === "scheduled" && to === "sending";
29
+ }
30
+ /**
31
+ * Admin-triggered pause/resume via `PAUSE_CAMPAIGN`/`RESUME_CAMPAIGN`. Resume CONTINUES a send the
32
+ * pipeline already started, which is why it is grouped with the send tier rather than treated as a
33
+ * second way to reach `sending`.
34
+ */
35
+ function isPauseOrResume(from, to) {
36
+ return (from === "sending" && to === "paused") || (from === "paused" && to === "sending");
37
+ }
38
+ /** `SCHEDULE_CAMPAIGN`'s only edge. */
39
+ function isScheduling(from, to) {
40
+ return from === "draft" && to === "scheduled";
41
+ }
42
+ /** `CANCEL_CAMPAIGN`'s edges — a campaign is cancellable only before the send pipeline touches it. */
43
+ function isCancellation(from, to) {
44
+ return to === "canceled" && (from === "draft" || from === "scheduled");
45
+ }
46
+ /**
47
+ * Drain completion. The only rule with two distinct denials, because `sent` is guarded on both the
48
+ * actor (pipeline-only) and the origin state (`sending` only), and a caller needs to know which of
49
+ * the two it tripped.
50
+ *
51
+ * @complexity O(1).
52
+ */
53
+ function authorizeSendCompletion(from, actorTier) {
54
+ if (actorTier !== "pipeline") {
55
+ return { allowed: false, reason: "only the send pipeline may set status to 'sent'" };
56
+ }
57
+ if (from !== "sending") {
58
+ return { allowed: false, reason: "'sent' may only be entered from 'sending'" };
59
+ }
60
+ return { allowed: true };
61
+ }
62
+ /**
63
+ * Decides whether `actorTier` may move a campaign from `from` to `to`.
64
+ *
65
+ * Deny-by-default: an edge no rule below matches falls through to the closing rejection, so adding
66
+ * a status to `CampaignStatus` cannot silently open a transition. The rules are ordered, not
67
+ * independent — `to === "sent"` deliberately sits between the send-start and pause/resume rules
68
+ * (see this file's header for the full precedence table).
69
+ *
70
+ * @complexity O(1), pure, total function (every input produces a result, never throws).
71
+ * @overallScore 100
72
+ */
73
+ export function transitionCampaignStatus(input, _optional = {}) {
74
+ const { from, to, actorTier } = input;
75
+ if (from === to) {
76
+ return { allowed: false, reason: `'${from}' -> '${to}' is not a transition (no-op)` };
77
+ }
78
+ if (isSendStart(from, to)) {
79
+ return requireTier({ actorTier, permitted: PIPELINE_ONLY, reason: "only the send pipeline may set status to 'sending'" });
80
+ }
81
+ if (to === "sent") {
82
+ return authorizeSendCompletion(from, actorTier);
83
+ }
84
+ if (isPauseOrResume(from, to)) {
85
+ return requireTier({ actorTier, permitted: SEND_OR_PIPELINE, reason: `only 'admin.newsletter.campaign.send' may transition '${from}' -> '${to}'` });
86
+ }
87
+ if (isScheduling(from, to)) {
88
+ return requireTier({ actorTier, permitted: SCHEDULE_ONLY, reason: "only 'admin.newsletter.campaign.schedule' may set draft -> scheduled" });
89
+ }
90
+ if (isCancellation(from, to)) {
91
+ return requireTier({ actorTier, permitted: COMPOSE_ONLY, reason: "only 'admin.newsletter.campaign.compose' may cancel a campaign" });
92
+ }
93
+ return { allowed: false, reason: `'${from}' -> '${to}' is not a permitted transition for any actor tier` };
94
+ }
95
+ //# sourceMappingURL=campaign.js.map
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @file `confirmation.ts` — ISSUE_CONFIRMATION_TOKEN / CONSUME_CONFIRMATION_TOKEN chokepoint
3
+ * (ADR-PIPE-011 C-014, REQ-11/12/13/32, INV-03).
4
+ *
5
+ * `consumeConfirmationToken` must NEVER flip `SubscriptionRow.status` to `subscribed` before
6
+ * `MembersConsentCapability.confirm` reports `granted` — reversing this order breaks REQ-11/REQ-32's
7
+ * "Members is the source of truth" guarantee (INV-03: Newsletter never writes a Members consent
8
+ * record directly, it only supplies evidence and observes the result).
9
+ */
10
+ import type { UUID } from "@jini-ai/core/primitives";
11
+ import type { PositionalMailer as MailerPort, OutboundEmail } from "@jini-ai/core/contracts/mail";
12
+ import type { OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
13
+ import type { MembersConsentCapability, NewsletterConfirmationTokenRepoPort, NewsletterSubscriptionRepoPort } from "./ports.js";
14
+ import type { SubscriptionRow } from "./types.js";
15
+ /** behavior.spec.md §3 — confirmation-token TTL, fixed at 72 hours. */
16
+ export declare const CONFIRMATION_TOKEN_TTL_MS: number;
17
+ export interface ConfirmationDeps {
18
+ tokenRepo: NewsletterConfirmationTokenRepoPort;
19
+ subscriptionRepo: NewsletterSubscriptionRepoPort;
20
+ mailer: MailerPort;
21
+ /** `null` = unbound — see `launch-gate.ts`'s file header on why this must never be stubbed to succeed. */
22
+ consentCapability: MembersConsentCapability | null;
23
+ originRegistry: OriginRegistryPort;
24
+ clock: {
25
+ nowIso(): string;
26
+ };
27
+ ids: {
28
+ newId(): string;
29
+ };
30
+ /** Resolves the confirmation email's From (`platform/mail/sender-identity.ts`); absent, the
31
+ * `no-reply@newsletter.local` placeholder is used only while `mailer` is non-delivering. */
32
+ resolveFrom(required: {
33
+ workspaceId: string;
34
+ }, optional?: Record<string, never>): Promise<OutboundEmail["from"]>;
35
+ mintRawToken(required: Record<string, never>, optional?: Record<string, never>): string;
36
+ hashToken(required: {
37
+ raw: string;
38
+ }, optional?: Record<string, never>): string;
39
+ }
40
+ /**
41
+ * Mint a new confirmation token, invalidating every prior unconsumed token for this subscription
42
+ * first ("newest wins" — behavior.spec.md §2.1), then send the confirm email. Does NOT change
43
+ * `SubscriptionRow.status` (stays `pending` until `consumeConfirmationToken` succeeds).
44
+ *
45
+ * @throws SenderIdentityNotConfiguredError When a delivering mailer is active and the site has no
46
+ * sender configured — before any token is written.
47
+ */
48
+ export declare function issueConfirmationToken(required: {
49
+ deps: ConfirmationDeps;
50
+ input: {
51
+ workspaceId: UUID;
52
+ subscriptionId: UUID;
53
+ recipientEmail: string;
54
+ };
55
+ }, _optional?: Record<string, never>): Promise<{
56
+ tokenId: UUID;
57
+ expiresAt: string;
58
+ }>;
59
+ /**
60
+ * Validate the raw token, then call `MembersConsentCapability.request`/`.confirm` — the local
61
+ * `SubscriptionRow.status` flip to `subscribed` happens STRICTLY AFTER a `granted` response, never
62
+ * before or regardless of it (INV-03, AC-15).
63
+ */
64
+ export declare function consumeConfirmationToken(required: {
65
+ deps: ConfirmationDeps;
66
+ input: {
67
+ workspaceId: UUID;
68
+ rawToken: string;
69
+ };
70
+ }, _optional?: Record<string, never>): Promise<{
71
+ subscription: SubscriptionRow;
72
+ changed: boolean;
73
+ eventId: string;
74
+ }>;
75
+ //# sourceMappingURL=confirmation.d.ts.map
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @file `confirmation.ts` — ISSUE_CONFIRMATION_TOKEN / CONSUME_CONFIRMATION_TOKEN chokepoint
3
+ * (ADR-PIPE-011 C-014, REQ-11/12/13/32, INV-03).
4
+ *
5
+ * `consumeConfirmationToken` must NEVER flip `SubscriptionRow.status` to `subscribed` before
6
+ * `MembersConsentCapability.confirm` reports `granted` — reversing this order breaks REQ-11/REQ-32's
7
+ * "Members is the source of truth" guarantee (INV-03: Newsletter never writes a Members consent
8
+ * record directly, it only supplies evidence and observes the result).
9
+ */
10
+ import { NewsletterConfirmTokenInvalidError } from "./errors.js";
11
+ /** behavior.spec.md §3 — confirmation-token TTL, fixed at 72 hours. */
12
+ export const CONFIRMATION_TOKEN_TTL_MS = 72 * 60 * 60 * 1000;
13
+ /** Compose an absolute origin URL from a `VerifiedOrigin` — mirrors `redirects/phase-handler.ts`'s local `composeOriginUrl`. */
14
+ function composeOriginUrl(origin) {
15
+ const matchesSchemePort = (origin.scheme === "https" && origin.port === 443) || (origin.scheme === "http" && origin.port === 80);
16
+ const isDefaultPort = origin.port === undefined || matchesSchemePort;
17
+ const authority = isDefaultPort ? origin.host : `${origin.host}:${origin.port}`;
18
+ return `${origin.scheme}://${authority}${origin.basePath ?? ""}`;
19
+ }
20
+ async function supersedeConfirmationTokens({ deps, input, now }) {
21
+ // "Newest wins": mark every prior unconsumed token superseded (consumed) before minting the new one.
22
+ const prior = await deps.tokenRepo.findUnconsumedBySubscription({
23
+ workspaceId: input.workspaceId,
24
+ subscriptionId: input.subscriptionId,
25
+ });
26
+ for (const token of prior) {
27
+ await deps.tokenRepo.save({ ...token, consumedAt: now });
28
+ }
29
+ }
30
+ /**
31
+ * Mint a new confirmation token, invalidating every prior unconsumed token for this subscription
32
+ * first ("newest wins" — behavior.spec.md §2.1), then send the confirm email. Does NOT change
33
+ * `SubscriptionRow.status` (stays `pending` until `consumeConfirmationToken` succeeds).
34
+ *
35
+ * @throws SenderIdentityNotConfiguredError When a delivering mailer is active and the site has no
36
+ * sender configured — before any token is written.
37
+ */
38
+ export async function issueConfirmationToken(required, _optional = {}) {
39
+ const { deps, input } = required;
40
+ const now = deps.clock.nowIso();
41
+ // Resolved first: a missing sender refuses before any prior token is superseded, so the
42
+ // subscriber's last working link survives a send that could never have gone out.
43
+ const from = await deps.resolveFrom({ workspaceId: input.workspaceId });
44
+ await supersedeConfirmationTokens({ deps, input, now });
45
+ const rawToken = deps.mintRawToken({});
46
+ if (!/^[0-9a-f]{64}$/.test(rawToken))
47
+ throw new Error("mintRawToken must return 64 lowercase hex characters");
48
+ const tokenHash = deps.hashToken({ raw: rawToken });
49
+ if (!/^[0-9a-f]{64}$/.test(tokenHash))
50
+ throw new Error("hashToken must return 64 lowercase hex characters");
51
+ const tokenId = deps.ids.newId();
52
+ const expiresAt = new Date(Date.parse(now) + CONFIRMATION_TOKEN_TTL_MS).toISOString();
53
+ const record = {
54
+ id: tokenId,
55
+ workspaceId: input.workspaceId,
56
+ subscriptionId: input.subscriptionId,
57
+ tokenHash,
58
+ purpose: "newsletter_subscription_confirm",
59
+ createdAt: now,
60
+ expiresAt,
61
+ consumedAt: null,
62
+ };
63
+ await deps.tokenRepo.save(record);
64
+ const origin = await deps.originRegistry.canonicalOrigin({ workspaceId: input.workspaceId });
65
+ const confirmUrl = `${composeOriginUrl(origin)}/newsletter/confirm?token=${rawToken}`;
66
+ await deps.mailer.send({
67
+ workspaceId: input.workspaceId,
68
+ to: { email: input.recipientEmail },
69
+ from,
70
+ subject: "Confirm your subscription",
71
+ text: `Please confirm your subscription: ${confirmUrl}`,
72
+ html: `<p>Please confirm your subscription: <a href="${confirmUrl}">${confirmUrl}</a></p>`,
73
+ }, {
74
+ idempotencyKey: `newsletter:confirm-email:${tokenId}`,
75
+ workspaceId: input.workspaceId,
76
+ sourceContext: { module: "newsletter", ref: tokenId },
77
+ // A double-opt-in confirmation is transactional mail the subscriber is waiting on right
78
+ // now, sent synchronously like the members sign-in link — the interactive lane, not the
79
+ // background-notification lane (SPEC-022 REQ-09; `members/write-service.ts`).
80
+ purpose: "transactional",
81
+ lane: "interactive",
82
+ });
83
+ return { tokenId, expiresAt };
84
+ }
85
+ /** The two consent-capability calls a bound capability gets, in order; the verdict is the caller's to act on. */
86
+ async function requestAndConfirmConsent({ capability, subscription, tokenId, workspaceId }) {
87
+ await capability.request({
88
+ workspaceId,
89
+ subscriberId: subscription.subscriberId,
90
+ evidence: { consentTextRef: "newsletter-subscription-confirm-v1", source: subscription.source, confirmTokenId: tokenId },
91
+ });
92
+ const result = await capability.confirm({ workspaceId, subscriberId: subscription.subscriberId, confirmTokenId: tokenId });
93
+ return { status: result.status, revisionId: result.consentRevisionId };
94
+ }
95
+ function requireUnconsumedConfirmationToken({ token }) {
96
+ if (!token)
97
+ throw new NewsletterConfirmTokenInvalidError({ message: "confirmation token was not found", reason: "not_found" });
98
+ // EC-02: a second click on an already-consumed token is invalid, not a repeat success (unlike
99
+ // the unsubscribe EC-03 carve-out — deliberately different semantics, see `unsubscribe.ts`).
100
+ if (token.consumedAt !== null) {
101
+ throw new NewsletterConfirmTokenInvalidError({ message: "confirmation token was already consumed", reason: "already_consumed" });
102
+ }
103
+ return token;
104
+ }
105
+ /**
106
+ * Validate the raw token, then call `MembersConsentCapability.request`/`.confirm` — the local
107
+ * `SubscriptionRow.status` flip to `subscribed` happens STRICTLY AFTER a `granted` response, never
108
+ * before or regardless of it (INV-03, AC-15).
109
+ */
110
+ export async function consumeConfirmationToken(required, _optional = {}) {
111
+ const { deps, input } = required;
112
+ const tokenHash = deps.hashToken({ raw: input.rawToken });
113
+ const token = requireUnconsumedConfirmationToken({
114
+ token: await deps.tokenRepo.findByTokenHash({ workspaceId: input.workspaceId, tokenHash }),
115
+ });
116
+ const now = deps.clock.nowIso();
117
+ // Boundary rule: a token submitted at EXACTLY `expiresAt` is treated as expired (closed-below/open-above).
118
+ if (Date.parse(now) >= Date.parse(token.expiresAt)) {
119
+ throw new NewsletterConfirmTokenInvalidError({ message: "confirmation token has expired", reason: "expired" });
120
+ }
121
+ const subscription = await deps.subscriptionRepo.findById({ workspaceId: input.workspaceId, id: token.subscriptionId });
122
+ if (!subscription)
123
+ throw new NewsletterConfirmTokenInvalidError({ message: "subscription was not found", reason: "not_found" });
124
+ // B176: consent is enforced when a capability is bound; with none configured the confirmation
125
+ // still completes (today's behaviour) and simply records no consent revision.
126
+ const consent = deps.consentCapability ? await requestAndConfirmConsent({ capability: deps.consentCapability, subscription, tokenId: token.id, workspaceId: input.workspaceId }) : null;
127
+ // The token is single-use regardless of the consent outcome — mark consumed either way.
128
+ await deps.tokenRepo.save({ ...token, consumedAt: now });
129
+ if (consent && consent.status !== "granted") {
130
+ throw new NewsletterConfirmTokenInvalidError({ message: `consent was not granted (status: ${consent.status})`, reason: "expired" });
131
+ }
132
+ const updated = {
133
+ ...subscription,
134
+ status: "subscribed",
135
+ consentRevisionIdAtSubscribe: consent?.revisionId ?? null,
136
+ subscribedAt: now,
137
+ updatedAt: now,
138
+ };
139
+ await deps.subscriptionRepo.save(updated, { expected: subscription });
140
+ return { subscription: updated, changed: subscription.status !== "subscribed", eventId: `newsletter-subscribed:${token.id}` };
141
+ }
142
+ //# sourceMappingURL=confirmation.js.map