@jini-ai/user-management 0.7.3-next.1 → 0.7.3-next.3

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 (378) hide show
  1. package/CHANGELOG.md +6 -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 +278 -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 +82 -0
  252. package/dist/newsletter/repo-subscribers.js +193 -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 +201 -0
  256. package/dist/newsletter/repo.memory.js +250 -0
  257. package/dist/newsletter/repo.rows.d.ts +221 -0
  258. package/dist/newsletter/repo.rows.js +260 -0
  259. package/dist/newsletter/send-pipeline.d.ts +236 -0
  260. package/dist/newsletter/send-pipeline.js +514 -0
  261. package/dist/newsletter/subscriptions.d.ts +87 -0
  262. package/dist/newsletter/subscriptions.js +119 -0
  263. package/dist/newsletter/tool-registrations.d.ts +89 -0
  264. package/dist/newsletter/tool-registrations.deps.d.ts +9 -0
  265. package/dist/newsletter/tool-registrations.deps.js +9 -0
  266. package/dist/newsletter/tool-registrations.js +133 -0
  267. package/dist/newsletter/tool-registrations.read.d.ts +76 -0
  268. package/dist/newsletter/tool-registrations.read.js +140 -0
  269. package/dist/newsletter/tool-registrations.write.d.ts +54 -0
  270. package/dist/newsletter/tool-registrations.write.js +229 -0
  271. package/dist/newsletter/types.d.ts +279 -0
  272. package/dist/newsletter/types.js +23 -0
  273. package/dist/newsletter/unsubscribe.d.ts +41 -0
  274. package/dist/newsletter/unsubscribe.js +100 -0
  275. package/dist/project-keys/attached-vault.d.ts +23 -0
  276. package/dist/project-keys/attached-vault.js +65 -0
  277. package/dist/project-keys/create-vault.d.ts +17 -0
  278. package/dist/project-keys/create-vault.js +29 -0
  279. package/dist/project-keys/service.d.ts +133 -0
  280. package/dist/project-keys/service.js +128 -0
  281. package/dist/project-keys/site-references.d.ts +30 -0
  282. package/dist/project-keys/site-references.js +63 -0
  283. package/dist/project-keys/site-sealer.d.ts +28 -0
  284. package/dist/project-keys/site-sealer.js +64 -0
  285. package/dist/project-keys/sql/attachments.d.ts +33 -0
  286. package/dist/project-keys/sql/attachments.js +55 -0
  287. package/dist/project-keys/tools.d.ts +86 -0
  288. package/dist/project-keys/tools.js +66 -0
  289. package/dist/public-http/routes/mail/feedback.d.ts +44 -0
  290. package/dist/public-http/routes/mail/feedback.js +17 -0
  291. package/dist/public-http/routes/newsletter/confirm.d.ts +38 -0
  292. package/dist/public-http/routes/newsletter/confirm.js +33 -0
  293. package/dist/public-http/routes/newsletter/page.d.ts +29 -0
  294. package/dist/public-http/routes/newsletter/page.js +34 -0
  295. package/dist/public-http/routes/newsletter/unsubscribe.d.ts +33 -0
  296. package/dist/public-http/routes/newsletter/unsubscribe.js +35 -0
  297. package/dist/react/auth/Passkeys.d.ts +2 -34
  298. package/dist/react/auth/RecoveryCodesCard.d.ts +27 -0
  299. package/dist/react/auth/RecoveryCodesCard.hooks.d.ts +67 -0
  300. package/dist/react/auth/RecoveryCodesCard.hooks.js +38 -0
  301. package/dist/react/auth/RecoveryCodesCard.js +56 -0
  302. package/dist/react/auth/TotpSettings.d.ts +2 -23
  303. package/dist/react/auth/local-owner-signin.d.ts +40 -0
  304. package/dist/react/auth/local-owner-signin.js +25 -0
  305. package/dist/react/auth/owner-mfa-api.d.ts +10 -0
  306. package/dist/react/auth/owner-mfa-api.js +17 -0
  307. package/dist/react/auth/owner-passkey-api.d.ts +11 -0
  308. package/dist/react/auth/owner-passkey-api.js +17 -0
  309. package/dist/react/auth/owner-recovery-api.d.ts +51 -0
  310. package/dist/react/auth/owner-recovery-api.js +29 -0
  311. package/dist/react/auth/owner-request.d.ts +7 -0
  312. package/dist/react/auth/owner-request.js +2 -0
  313. package/dist/react/index.d.ts +10 -0
  314. package/dist/react/index.js +6 -0
  315. package/dist/react/mail/Email.d.ts +20 -0
  316. package/dist/react/mail/Email.js +143 -0
  317. package/dist/react/mail/EmailProviderTab.d.ts +34 -0
  318. package/dist/react/mail/EmailProviderTab.js +132 -0
  319. package/dist/react/mail/EmailSegments.d.ts +24 -0
  320. package/dist/react/mail/EmailSegments.js +15 -0
  321. package/dist/react/mail/EmailTemplateEditor.d.ts +146 -0
  322. package/dist/react/mail/EmailTemplateEditor.js +116 -0
  323. package/dist/react/mail/email-view.types.d.ts +236 -0
  324. package/dist/react/mail/email-view.types.js +2 -0
  325. package/dist/react/members/Members.d.ts +5 -3
  326. package/dist/react/members/Members.js +3 -3
  327. package/dist/react/members/api/members-api.d.ts +37 -0
  328. package/dist/react/members/api/members-api.js +16 -0
  329. package/dist/react/members/hooks/use-members.hooks.js +2 -1
  330. package/dist/react/members/members-i18n.d.ts +23 -0
  331. package/dist/react/members/members-i18n.js +25 -0
  332. package/dist/react/members/members-i18n.locales-a.d.ts +4 -0
  333. package/dist/react/members/members-i18n.locales-a.js +294 -0
  334. package/dist/react/members/members-i18n.locales-b.d.ts +4 -0
  335. package/dist/react/members/members-i18n.locales-b.js +265 -0
  336. package/dist/react/models.d.ts +1 -49
  337. package/dist/react/ports.d.ts +3 -143
  338. package/dist/react/roles/api/roles-api.d.ts +74 -0
  339. package/dist/react/roles/api/roles-api.js +22 -0
  340. package/dist/react/testing.js +18 -9
  341. package/dist/react/users/UsersPanel.d.ts +30 -0
  342. package/dist/react/users/UsersPanel.hooks.d.ts +8 -0
  343. package/dist/react/users/UsersPanel.hooks.js +9 -0
  344. package/dist/react/users/UsersPanel.js +9 -0
  345. package/dist/react/users/api/users-api.d.ts +65 -0
  346. package/dist/react/users/api/users-api.js +46 -0
  347. package/dist/react/users/hooks/use-localized-users.hooks.d.ts +43 -0
  348. package/dist/react/users/hooks/use-localized-users.hooks.js +15 -0
  349. package/dist/react/users/hooks/use-users-state.hooks.d.ts +18 -18
  350. package/dist/react/users/password-reset-notice.d.ts +8 -0
  351. package/dist/react/users/password-reset-notice.js +36 -0
  352. package/dist/server/admin-crud-service.d.ts +4 -10
  353. package/dist/server/admin-crud-service.js +20 -6
  354. package/dist/server/agent-tool-registrations.js +20 -5
  355. package/dist/server/agent-tools.js +16 -3
  356. package/dist/server/auth-challenge.d.ts +1 -1
  357. package/dist/server/auth-service.js +2 -1
  358. package/dist/server/grant-service.d.ts +1 -0
  359. package/dist/server/grant-service.js +7 -4
  360. package/dist/server/mfa/passkey-service.d.ts +2 -2
  361. package/dist/server/mfa/passkey-service.js +1 -1
  362. package/dist/server/mfa/service.js +6 -4
  363. package/dist/server/repo.memory.d.ts +30 -2
  364. package/dist/server/repo.memory.js +58 -4
  365. package/dist/server/seed.js +3 -3
  366. package/dist/server/sql/assignments.d.ts +90 -0
  367. package/dist/server/sql/assignments.js +128 -0
  368. package/dist/server/sql/index.d.ts +6 -0
  369. package/dist/server/sql/index.js +5 -0
  370. package/dist/server/sql/kernel.d.ts +9 -0
  371. package/dist/server/sql/kernel.js +2 -0
  372. package/dist/server/sql/mfa.d.ts +36 -0
  373. package/dist/server/sql/mfa.js +51 -0
  374. package/dist/server/sql/passkeys.d.ts +25 -0
  375. package/dist/server/sql/passkeys.js +33 -0
  376. package/dist/server/sql/recovery-codes.d.ts +22 -0
  377. package/dist/server/sql/recovery-codes.js +32 -0
  378. package/package.json +910 -12
@@ -0,0 +1,144 @@
1
+ import type { UUID } from "@jini-ai/core/primitives";
2
+ import { type PrincipalRecord } from "../core/index.js";
3
+ import type { AuthServiceDeps } from "../server/auth-service.js";
4
+ import { type ApiKeySecret } from "./api-key-secret.js";
5
+ import type { ApiKeyRecord, ApiKeyRepoPort, ApiKeySecretHasherPort } from "./api-key-types.js";
6
+ /** Deps the transitions below need: the nine identity repos plus the two api-key-specific seams. */
7
+ export interface ApiKeyServiceDeps extends AuthServiceDeps {
8
+ apiKeys: ApiKeyRepoPort;
9
+ secretHasher: ApiKeySecretHasherPort;
10
+ }
11
+ export interface CreateApiKeyPrincipalInput {
12
+ workspaceId: UUID;
13
+ callerPrincipalId: UUID;
14
+ displayName: unknown;
15
+ /** Optional; only `"api_key"` (or absent) is accepted — see the refusal below. */
16
+ kind?: unknown;
17
+ }
18
+ /**
19
+ * `CREATE_PRINCIPAL` for machine identities (api.spec §1 `APIKEY_PRINCIPAL_CREATE`, 0.7.0). Mints
20
+ * an ACTIVE, GRANTLESS `kind='api_key'` principal — no `principal_roles`, no `principal_policies`
21
+ * — which is exactly the precondition `issueApiKey` re-verifies.
22
+ *
23
+ * `kind` is accepted but constrained to `"api_key"`: humans are minted only by `CREATE_USER` and
24
+ * `system`/`user-local` only by first-boot seeding, so this endpoint can never become a second
25
+ * creation path for a privileged kind. `workspaceId` comes from the caller's own credential; there
26
+ * is no caller-supplied workspace field and therefore no cross-workspace mint.
27
+ *
28
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
29
+ * @throws {IdentityValidationError} blank/oversize `displayName`, or `kind` other than `api_key` (400).
30
+ * @complexity O(1) — one permission check, one save.
31
+ * @overallScore 100
32
+ */
33
+ export declare function createApiKeyPrincipal(required: {
34
+ deps: ApiKeyServiceDeps;
35
+ input: CreateApiKeyPrincipalInput;
36
+ }): Promise<{
37
+ principal: PrincipalRecord;
38
+ }>;
39
+ export interface IssueApiKeyInput {
40
+ workspaceId: UUID;
41
+ callerPrincipalId: UUID;
42
+ principalId: unknown;
43
+ label: unknown;
44
+ policyIds: unknown;
45
+ expiresAt?: unknown;
46
+ }
47
+ /**
48
+ * `ISSUE_API_KEY` (state.spec §3). Snapshots the requested policies into a fresh `isFrozen` policy,
49
+ * attaches it to the bound `kind='api_key'` principal, and returns the raw key ONCE.
50
+ *
51
+ * The raw key is the only value in this codebase that is returned and never stored: `api_keys`
52
+ * holds a digest of its secret half plus its non-secret prefix, so no later read of any table can
53
+ * reconstruct it (INV-05).
54
+ *
55
+ * Writes happen only after every check passes, in this order: validate body (400) → resolve target
56
+ * (404/400) → resolve sources (404/400) → INV-07 clamp (403) → write. A refused issuance therefore
57
+ * leaves no partial rows, including no orphan frozen policy.
58
+ *
59
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
60
+ * @throws {IdentityValidationError} bad body, non-`api_key` target, non-grantless target, or a
61
+ * `*`-bearing source policy (400).
62
+ * @throws {IdentityNotFoundError} unknown principal or policy (404).
63
+ * @throws {GrantExceedsIssuerError} the snapshot would exceed the issuer's own authority (403).
64
+ * @complexity O(p) repo reads for p source policies, plus one `resolveEffectivePermissions`, plus
65
+ * O(k) writes for the k permission rows copied.
66
+ * @overallScore 100
67
+ */
68
+ export declare function issueApiKey(required: {
69
+ deps: ApiKeyServiceDeps;
70
+ input: IssueApiKeyInput;
71
+ keySecret: ApiKeySecret;
72
+ }, _optional?: Record<string, never>): Promise<{
73
+ apiKey: ApiKeyRecord;
74
+ rawKey: string;
75
+ }>;
76
+ /**
77
+ * `REVOKE_API_KEY` (state.spec §3). Sets `revokedAt` and empties the key's issuance snapshot, so
78
+ * the next request presenting the key is rejected AND the bound principal is left holding nothing.
79
+ * Idempotent: revoking an already-revoked key succeeds without moving the original timestamp.
80
+ *
81
+ * **Disclosed deviation from state.spec §3.** That row calls for retiring the snapshot policy
82
+ * outright — "its `principal_policies` row + the frozen `policies` row + its `policy_permissions`".
83
+ * `PrincipalPolicyRepoPort` (`@jini-ai/user-management`) exposes only `listByPrincipalId`/
84
+ * `listByPolicyId`/`save`, with no delete, and the port is not this repo's to change. Deleting the
85
+ * `policies` row while its join row survives would leave exactly the dangling reference INV-09
86
+ * exists to prevent, so this instead empties the snapshot via `deleteByPolicyId` and leaves the
87
+ * (now permission-less, still `isFrozen`) policy and its join row in place. The security outcome is
88
+ * identical — the principal's effective permission set is empty — and no invariant is broken.
89
+ *
90
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
91
+ * @throws {IdentityNotFoundError} no such key in the caller's workspace (404).
92
+ * @complexity O(1) repo operations.
93
+ * @overallScore 100
94
+ */
95
+ export declare function revokeApiKey(required: {
96
+ deps: ApiKeyServiceDeps;
97
+ input: {
98
+ workspaceId: UUID;
99
+ callerPrincipalId: UUID;
100
+ keyId: string;
101
+ };
102
+ }): Promise<{
103
+ apiKey: ApiKeyRecord;
104
+ }>;
105
+ /**
106
+ * Resolve a presented raw key to its principal, applying every fail-closed check. The Bearer-auth
107
+ * counterpart of `@jini-ai/user-management`'s `validateSession`, and deliberately the same shape: it
108
+ * returns `null` for EVERY rejection reason rather than throwing a distinguishable error, so a
109
+ * caller cannot tell "unknown key" from "revoked key" from "expired key" from "disabled principal".
110
+ *
111
+ * Timing is handled the same way. A prefix that matches no row still spends one real key
112
+ * derivation against `decoyKeyHash`, so an attacker cannot enumerate valid prefixes by clocking
113
+ * the response; and the revoked/expired/status checks run AFTER verification, so they never
114
+ * short-circuit ahead of the constant-time comparison.
115
+ *
116
+ * @returns the bound principal and its key row, or `null` — never a reason.
117
+ * @complexity O(1) — one indexed row read, one key derivation, one principal read, one save.
118
+ * @overallScore 100
119
+ */
120
+ export declare function authenticateApiKey(required: {
121
+ deps: ApiKeyServiceDeps;
122
+ input: {
123
+ workspaceId: UUID;
124
+ rawKey: string;
125
+ };
126
+ keySecret: ApiKeySecret;
127
+ }): Promise<{
128
+ principal: PrincipalRecord;
129
+ apiKey: ApiKeyRecord;
130
+ } | null>;
131
+ /** Bind the host's key format (`createApiKeySecret`) once at composition; call sites keep `{ deps, input }`. */
132
+ export declare function createApiKeyService({ keySecret }: {
133
+ keySecret: ApiKeySecret;
134
+ }, _optional?: Record<string, never>): {
135
+ issueApiKey: (required: Omit<Parameters<typeof issueApiKey>[0], "keySecret">) => Promise<{
136
+ apiKey: ApiKeyRecord;
137
+ rawKey: string;
138
+ }>;
139
+ authenticateApiKey: (required: Omit<Parameters<typeof authenticateApiKey>[0], "keySecret">) => Promise<{
140
+ principal: PrincipalRecord;
141
+ apiKey: ApiKeyRecord;
142
+ } | null>;
143
+ };
144
+ //# sourceMappingURL=api-key-service.d.ts.map
@@ -0,0 +1,389 @@
1
+ import { GrantExceedsIssuerError, IdentityNotFoundError, IdentityValidationError } from "../core/index.js";
2
+ import { resolveEffectivePermissions } from "../server/authorize.js";
3
+ import { assertCallerHasAnyPermission, authorizeDepsFrom } from "../server/grant-service.js";
4
+ import { decoyKeyHash } from "./api-key-secret.js";
5
+ /**
6
+ * @file The three API-key transitions (`CREATE_PRINCIPAL` for `kind='api_key'`, `ISSUE_API_KEY`,
7
+ * `REVOKE_API_KEY` — state.spec §3) plus the verification path that turns a presented raw key back
8
+ * into a principal (SPEC-006 REQ-08).
9
+ *
10
+ * Purpose:
11
+ * `@jini-ai/user-management`'s own `INFO.md` scopes API keys OUT of that library ("Out of scope,
12
+ * deferred: API keys (`api_keys`, `ISSUE_API_KEY`)"), so this host implements them, against that
13
+ * library's exported ports and errors rather than a parallel vocabulary. Every error thrown here
14
+ * is one the users/roles/policies routes already map to a status code, so the api-keys routes'
15
+ * error envelopes are the same envelopes, not new ones.
16
+ *
17
+ * Architectural role:
18
+ * Ordinary domain functions in the `func(required, options)` shape the rest of `identity` uses —
19
+ * no Express, no db handle, no `RouteDeps`. The route layer supplies `ApiKeyServiceDeps` and maps
20
+ * thrown errors onto HTTP; nothing here knows a status code.
21
+ *
22
+ * ## Two invariants this file exists to hold
23
+ *
24
+ * 1. **A key's authority is a frozen snapshot, never a live reference** (REQ-08/F-054-01).
25
+ * `issueApiKey` copies the requested policies' permission rows field-identically into a NEW
26
+ * `isFrozen` policy and attaches THAT to the bound principal. A later widening of a source
27
+ * policy therefore cannot grow an already-issued key.
28
+ * 2. **A key never out-ranks its issuer** (INV-07). Every permission the snapshot would confer
29
+ * must be held UNCONSTRAINED by the caller, or issuance is refused with no rows written.
30
+ * `@jini-ai/user-management` implements this clamp for `ASSIGN_ROLE`/`ATTACH_POLICY` but does not
31
+ * export it (`grant-service.ts` is not on the package's `exports` map), so `assertGrantClamp`
32
+ * below is a deliberate re-implementation over the exported `resolveEffectivePermissions`,
33
+ * matching that function's semantics exactly — including that the owner wildcard `*` counts as
34
+ * an unconstrained hold of everything.
35
+ */
36
+ /** Post-trim bounds shared by `displayName` and `label` (api.spec §1, both `1..255`). */
37
+ const NAME_MIN_LENGTH = 1;
38
+ const NAME_MAX_LENGTH = 255;
39
+ /** The single permission gating all three transitions (api.spec §2, `AUTH_APIKEY_MANAGE`). */
40
+ const APIKEY_MANAGE = "apikey.manage";
41
+ // Repo-bag assembly and its sharing rationale now live in Jini user-management/server (grant-service.ts).
42
+ /** Trim-and-bound one of the two name fields, or throw `IdentityValidationError`. */
43
+ function requireBoundedName({ value, field }, _options = {}) {
44
+ const trimmed = typeof value === "string" ? value.trim() : "";
45
+ if (trimmed.length < NAME_MIN_LENGTH || trimmed.length > NAME_MAX_LENGTH) {
46
+ throw new IdentityValidationError({ message: `'${field}' must be ${NAME_MIN_LENGTH}..${NAME_MAX_LENGTH} characters after trimming` });
47
+ }
48
+ return trimmed;
49
+ }
50
+ /** True iff `rows` carries `permission` with BOTH `resourceType` and `constraintJson` null — or the
51
+ * owner wildcard, which is an unconstrained hold of every permission (INV-07). */
52
+ function holdsUnconstrained({ rows, permission }, _options = {}) {
53
+ const unconstrained = ({ row, id }, _options = {}) => row.permission === id && row.resourceType == null && row.constraintJson == null;
54
+ return rows.some((row) => unconstrained({ row, id: "*" })) || rows.some((row) => unconstrained({ row, id: permission }));
55
+ }
56
+ /**
57
+ * The INV-07 grant-authority clamp for issuance: refuse unless the caller holds every permission
58
+ * the snapshot would confer, unconstrained. A conditionally-held permission (resource-scoped or
59
+ * constraint-bound) cannot be delegated at all.
60
+ *
61
+ * @throws {GrantExceedsIssuerError} naming every offending permission. No row is written — callers
62
+ * run this before any save.
63
+ * @complexity O(resolveEffectivePermissions) + O(k), k = distinct conferred permissions.
64
+ * @overallScore 100
65
+ */
66
+ async function assertGrantClamp(required) {
67
+ const distinct = [...new Set(required.conferredPermissions)];
68
+ if (distinct.length === 0)
69
+ return;
70
+ const effectiveRows = await resolveEffectivePermissions({
71
+ deps: authorizeDepsFrom(required.deps.repos),
72
+ principalId: required.callerPrincipalId,
73
+ workspaceId: required.workspaceId,
74
+ });
75
+ const offending = distinct.filter((permission) => !holdsUnconstrained({ rows: effectiveRows, permission }));
76
+ if (offending.length > 0) {
77
+ throw new GrantExceedsIssuerError({ message: `principal '${required.callerPrincipalId}' cannot grant permission(s) it does not hold unconstrained: ${offending.join(", ")}`, offendingPermissions: offending });
78
+ }
79
+ }
80
+ /** The `apikey.manage` gate every transition here runs FIRST — before reading the body and before
81
+ * any existence lookup, so an unauthorized caller learns nothing about whether a target exists. */
82
+ function assertCallerMayManageApiKeys(required) {
83
+ return assertCallerHasAnyPermission({
84
+ deps: required.deps,
85
+ workspaceId: required.workspaceId,
86
+ callerPrincipalId: required.callerPrincipalId,
87
+ permissions: [APIKEY_MANAGE],
88
+ });
89
+ }
90
+ /**
91
+ * `CREATE_PRINCIPAL` for machine identities (api.spec §1 `APIKEY_PRINCIPAL_CREATE`, 0.7.0). Mints
92
+ * an ACTIVE, GRANTLESS `kind='api_key'` principal — no `principal_roles`, no `principal_policies`
93
+ * — which is exactly the precondition `issueApiKey` re-verifies.
94
+ *
95
+ * `kind` is accepted but constrained to `"api_key"`: humans are minted only by `CREATE_USER` and
96
+ * `system`/`user-local` only by first-boot seeding, so this endpoint can never become a second
97
+ * creation path for a privileged kind. `workspaceId` comes from the caller's own credential; there
98
+ * is no caller-supplied workspace field and therefore no cross-workspace mint.
99
+ *
100
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
101
+ * @throws {IdentityValidationError} blank/oversize `displayName`, or `kind` other than `api_key` (400).
102
+ * @complexity O(1) — one permission check, one save.
103
+ * @overallScore 100
104
+ */
105
+ export async function createApiKeyPrincipal(required) {
106
+ const { deps, input } = required;
107
+ await assertCallerMayManageApiKeys({
108
+ deps,
109
+ workspaceId: input.workspaceId,
110
+ callerPrincipalId: input.callerPrincipalId,
111
+ });
112
+ if (input.kind !== undefined && input.kind !== "api_key") {
113
+ throw new IdentityValidationError({ message: `'kind' must be 'api_key', got '${String(input.kind)}'` });
114
+ }
115
+ const displayName = requireBoundedName({ value: input.displayName, field: "displayName" });
116
+ const principal = {
117
+ id: deps.idGen.newId(),
118
+ workspaceId: input.workspaceId,
119
+ kind: "api_key",
120
+ displayName,
121
+ status: "active",
122
+ createdAt: new Date(deps.clock.nowMs()).toISOString(),
123
+ };
124
+ await deps.repos.principals.save(principal);
125
+ return { principal };
126
+ }
127
+ /** Read `policyIds` off an untyped body: a non-empty array of non-blank strings, or 400. */
128
+ function requirePolicyIds({ value }, _options = {}) {
129
+ if (!Array.isArray(value) || value.length === 0) {
130
+ throw new IdentityValidationError({ message: "'policyIds' must be a non-empty array of policy ids" });
131
+ }
132
+ return value.map((entry) => {
133
+ const id = typeof entry === "string" ? entry.trim() : "";
134
+ if (id.length === 0)
135
+ throw new IdentityValidationError({ message: "'policyIds' entries must be non-blank policy ids" });
136
+ return id;
137
+ });
138
+ }
139
+ /** The bound principal must exist, be `kind='api_key'`, and be grantless (AC-23/AC-25). */
140
+ async function findIssuableTargetOrThrow(required) {
141
+ const { deps, workspaceId, principalId } = required;
142
+ const target = await deps.repos.principals.findById({ workspaceId, id: principalId });
143
+ if (!target)
144
+ throw new IdentityNotFoundError({ message: `principal '${principalId}' was not found` });
145
+ if (target.kind !== "api_key") {
146
+ throw new IdentityValidationError({ message: `ISSUE_API_KEY target must be a machine (kind='api_key') principal, got kind='${target.kind}'` });
147
+ }
148
+ if (target.status !== "active") {
149
+ throw new IdentityValidationError({ message: `principal '${principalId}' is disabled` });
150
+ }
151
+ const [roleGrants, policyGrants] = await Promise.all([
152
+ deps.repos.principalRoles.listByPrincipalId({ workspaceId, principalId }),
153
+ deps.repos.principalPolicies.listByPrincipalId({ workspaceId, principalId }),
154
+ ]);
155
+ if (roleGrants.length > 0 || policyGrants.length > 0) {
156
+ throw new IdentityValidationError({ message: `principal '${principalId}' already carries grants; ISSUE_API_KEY requires a grantless principal so the key's authority equals exactly the policies attached here` });
157
+ }
158
+ return target;
159
+ }
160
+ /** Resolve the source policies' permission rows, refusing a `*`-bearing source (AC-26). */
161
+ async function collectSnapshotSourceRows(required) {
162
+ const { deps, workspaceId, policyIds } = required;
163
+ const rows = [];
164
+ for (const policyId of policyIds) {
165
+ const policy = await deps.repos.policies.findById({ workspaceId, id: policyId });
166
+ if (!policy)
167
+ throw new IdentityNotFoundError({ message: `policy '${policyId}' was not found` });
168
+ const policyRows = await deps.repos.policyPermissions.listByPolicyId({ workspaceId, policyId });
169
+ if (policyRows.some((row) => row.permission === "*")) {
170
+ throw new IdentityValidationError({ message: `policy '${policyId}' carries the owner wildcard '*'; an API-key snapshot may never carry it` });
171
+ }
172
+ rows.push(...policyRows);
173
+ }
174
+ return rows;
175
+ }
176
+ /** Optional `expiresAt`: absent/null means no expiry; anything else must parse as a real date. */
177
+ function readOptionalExpiry({ value }, _options = {}) {
178
+ if (value === undefined || value === null || value === "")
179
+ return undefined;
180
+ const parsed = new Date(String(value)).getTime();
181
+ if (Number.isNaN(parsed)) {
182
+ throw new IdentityValidationError({ message: "'expiresAt' must be an ISO-8601 date-time or null" });
183
+ }
184
+ // Canonicalized to UTC on the way in, so the stored value is comparable by instant and never by
185
+ // accident of the offset the caller happened to send.
186
+ return new Date(parsed).toISOString();
187
+ }
188
+ function apiKeyPolicySnapshot({ snapshotPolicyId, workspaceId, keyId, label }) {
189
+ return { version: 1,
190
+ id: snapshotPolicyId,
191
+ workspaceId,
192
+ name: `api-key:${keyId}`,
193
+ description: `Issuance snapshot for API key '${label}'`,
194
+ isBuiltin: false,
195
+ isFrozen: true,
196
+ };
197
+ }
198
+ function apiKeySnapshotPermission({ deps, workspaceId, snapshotPolicyId, row }) {
199
+ return {
200
+ id: deps.idGen.newId(),
201
+ workspaceId,
202
+ policyId: snapshotPolicyId,
203
+ permission: row.permission,
204
+ resourceType: row.resourceType ?? null,
205
+ constraintJson: row.constraintJson ?? null,
206
+ };
207
+ }
208
+ function issuedApiKeyRecord({ deps, keyId, workspaceId, boundPrincipalId, label, minted, snapshotPolicyId, expiresAt }, keyHash) {
209
+ return {
210
+ id: keyId,
211
+ workspaceId,
212
+ principalId: boundPrincipalId,
213
+ label,
214
+ keyHash,
215
+ prefix: minted.prefix,
216
+ issuedPolicyId: snapshotPolicyId,
217
+ createdAt: new Date(deps.clock.nowMs()).toISOString(),
218
+ expiresAt,
219
+ };
220
+ }
221
+ /**
222
+ * `ISSUE_API_KEY` (state.spec §3). Snapshots the requested policies into a fresh `isFrozen` policy,
223
+ * attaches it to the bound `kind='api_key'` principal, and returns the raw key ONCE.
224
+ *
225
+ * The raw key is the only value in this codebase that is returned and never stored: `api_keys`
226
+ * holds a digest of its secret half plus its non-secret prefix, so no later read of any table can
227
+ * reconstruct it (INV-05).
228
+ *
229
+ * Writes happen only after every check passes, in this order: validate body (400) → resolve target
230
+ * (404/400) → resolve sources (404/400) → INV-07 clamp (403) → write. A refused issuance therefore
231
+ * leaves no partial rows, including no orphan frozen policy.
232
+ *
233
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
234
+ * @throws {IdentityValidationError} bad body, non-`api_key` target, non-grantless target, or a
235
+ * `*`-bearing source policy (400).
236
+ * @throws {IdentityNotFoundError} unknown principal or policy (404).
237
+ * @throws {GrantExceedsIssuerError} the snapshot would exceed the issuer's own authority (403).
238
+ * @complexity O(p) repo reads for p source policies, plus one `resolveEffectivePermissions`, plus
239
+ * O(k) writes for the k permission rows copied.
240
+ * @overallScore 100
241
+ */
242
+ export async function issueApiKey(required, _optional = {}) {
243
+ const { deps, input } = required;
244
+ const { workspaceId } = input;
245
+ // The grantless read and every snapshot/key write share the existing workspace lock.
246
+ const execute = async () => {
247
+ await assertCallerMayManageApiKeys({
248
+ deps,
249
+ workspaceId,
250
+ callerPrincipalId: input.callerPrincipalId,
251
+ });
252
+ const label = requireBoundedName({ value: input.label, field: "label" });
253
+ const policyIds = requirePolicyIds({ value: input.policyIds });
254
+ const expiresAt = readOptionalExpiry({ value: input.expiresAt });
255
+ const boundPrincipalId = typeof input.principalId === "string" ? input.principalId.trim() : "";
256
+ if (boundPrincipalId.length === 0) {
257
+ throw new IdentityValidationError({ message: "'principalId' is required" });
258
+ }
259
+ await findIssuableTargetOrThrow({ deps, workspaceId, principalId: boundPrincipalId });
260
+ const sourceRows = await collectSnapshotSourceRows({ deps, workspaceId, policyIds });
261
+ await assertGrantClamp({
262
+ deps,
263
+ workspaceId,
264
+ callerPrincipalId: input.callerPrincipalId,
265
+ conferredPermissions: sourceRows.map((row) => row.permission),
266
+ });
267
+ const keyId = deps.idGen.newId();
268
+ const snapshotPolicyId = deps.idGen.newId();
269
+ // The frozen snapshot: a machine-owned policy, 1:1 with this key. `name` embeds the key id so it
270
+ // is unique per workspace (the `policies` table's own uniqueness constraint) without a retry loop.
271
+ await deps.repos.policies.save(apiKeyPolicySnapshot({ snapshotPolicyId, workspaceId, keyId, label }));
272
+ // Copied field-identically — `resourceType`/`constraintJson` are preserved per row and never
273
+ // widened. A snapshot that dropped a constraint would grant MORE than its source.
274
+ for (const row of sourceRows) {
275
+ await deps.repos.policyPermissions.save(apiKeySnapshotPermission({ deps, workspaceId, snapshotPolicyId, row }));
276
+ }
277
+ await deps.repos.principalPolicies.save({
278
+ id: deps.idGen.newId(),
279
+ workspaceId,
280
+ principalId: boundPrincipalId,
281
+ policyId: snapshotPolicyId,
282
+ });
283
+ const minted = required.keySecret.mintApiKey();
284
+ const apiKey = issuedApiKeyRecord({ deps, keyId, workspaceId, boundPrincipalId, label, minted, snapshotPolicyId, expiresAt }, await deps.secretHasher.hash({ secret: minted.secret }));
285
+ await deps.apiKeys.save(apiKey);
286
+ return { apiKey, rawKey: minted.rawKey };
287
+ };
288
+ return deps.repos.transactions.run({ workspaceId, execute });
289
+ }
290
+ /**
291
+ * `REVOKE_API_KEY` (state.spec §3). Sets `revokedAt` and empties the key's issuance snapshot, so
292
+ * the next request presenting the key is rejected AND the bound principal is left holding nothing.
293
+ * Idempotent: revoking an already-revoked key succeeds without moving the original timestamp.
294
+ *
295
+ * **Disclosed deviation from state.spec §3.** That row calls for retiring the snapshot policy
296
+ * outright — "its `principal_policies` row + the frozen `policies` row + its `policy_permissions`".
297
+ * `PrincipalPolicyRepoPort` (`@jini-ai/user-management`) exposes only `listByPrincipalId`/
298
+ * `listByPolicyId`/`save`, with no delete, and the port is not this repo's to change. Deleting the
299
+ * `policies` row while its join row survives would leave exactly the dangling reference INV-09
300
+ * exists to prevent, so this instead empties the snapshot via `deleteByPolicyId` and leaves the
301
+ * (now permission-less, still `isFrozen`) policy and its join row in place. The security outcome is
302
+ * identical — the principal's effective permission set is empty — and no invariant is broken.
303
+ *
304
+ * @throws {IdentityForbiddenError} caller lacks `apikey.manage` (403).
305
+ * @throws {IdentityNotFoundError} no such key in the caller's workspace (404).
306
+ * @complexity O(1) repo operations.
307
+ * @overallScore 100
308
+ */
309
+ export async function revokeApiKey(required) {
310
+ const { deps, input } = required;
311
+ await assertCallerMayManageApiKeys({
312
+ deps,
313
+ workspaceId: input.workspaceId,
314
+ callerPrincipalId: input.callerPrincipalId,
315
+ });
316
+ const existing = await deps.apiKeys.findById({ workspaceId: input.workspaceId, id: input.keyId });
317
+ if (!existing)
318
+ throw new IdentityNotFoundError({ message: `api key '${input.keyId}' was not found` });
319
+ const revoked = { ...existing, revokedAt: existing.revokedAt ?? new Date(deps.clock.nowMs()).toISOString() };
320
+ await deps.apiKeys.save(revoked);
321
+ if (revoked.issuedPolicyId) {
322
+ await deps.repos.policyPermissions.deleteByPolicyId({
323
+ workspaceId: input.workspaceId,
324
+ policyId: revoked.issuedPolicyId,
325
+ });
326
+ }
327
+ return { apiKey: revoked };
328
+ }
329
+ /** True iff `candidate` is still usable: not revoked, not expired, and bound to an `active`
330
+ * `kind='api_key'` principal — the checks {@link authenticateApiKey} runs AFTER verification, so
331
+ * they never short-circuit ahead of the constant-time comparison (see that function's own doc). */
332
+ function isCandidateStillUsable(candidate, principal, nowIso) {
333
+ if (candidate.revokedAt)
334
+ return false;
335
+ // Compared as instants, not as strings — a row written before `readOptionalExpiry` canonicalized
336
+ // expiries, or by a future writer, must not be mis-ordered by its offset notation.
337
+ if (candidate.expiresAt && Date.parse(candidate.expiresAt) <= Date.parse(nowIso))
338
+ return false;
339
+ return principal?.status === "active" && principal.kind === "api_key";
340
+ }
341
+ /**
342
+ * Resolve a presented raw key to its principal, applying every fail-closed check. The Bearer-auth
343
+ * counterpart of `@jini-ai/user-management`'s `validateSession`, and deliberately the same shape: it
344
+ * returns `null` for EVERY rejection reason rather than throwing a distinguishable error, so a
345
+ * caller cannot tell "unknown key" from "revoked key" from "expired key" from "disabled principal".
346
+ *
347
+ * Timing is handled the same way. A prefix that matches no row still spends one real key
348
+ * derivation against `decoyKeyHash`, so an attacker cannot enumerate valid prefixes by clocking
349
+ * the response; and the revoked/expired/status checks run AFTER verification, so they never
350
+ * short-circuit ahead of the constant-time comparison.
351
+ *
352
+ * @returns the bound principal and its key row, or `null` — never a reason.
353
+ * @complexity O(1) — one indexed row read, one key derivation, one principal read, one save.
354
+ * @overallScore 100
355
+ */
356
+ export async function authenticateApiKey(required) {
357
+ const { deps, input } = required;
358
+ const parsed = required.keySecret.parseApiKey({ rawKey: input.rawKey });
359
+ if (!parsed)
360
+ return null;
361
+ const candidate = await deps.apiKeys.findByPrefix({
362
+ workspaceId: input.workspaceId,
363
+ prefix: parsed.prefix,
364
+ });
365
+ if (!candidate) {
366
+ await deps.secretHasher.verify({ storedHash: await decoyKeyHash({ hasher: deps.secretHasher }), secret: parsed.secret });
367
+ return null;
368
+ }
369
+ const matches = await deps.secretHasher.verify({ storedHash: candidate.keyHash, secret: parsed.secret });
370
+ if (!matches)
371
+ return null;
372
+ const now = new Date(deps.clock.nowMs()).toISOString();
373
+ const principal = await deps.repos.principals.findById({
374
+ workspaceId: input.workspaceId,
375
+ id: candidate.principalId,
376
+ });
377
+ if (!isCandidateStillUsable(candidate, principal, now))
378
+ return null;
379
+ await deps.apiKeys.save({ ...candidate, lastUsedAt: now });
380
+ return { principal, apiKey: candidate };
381
+ }
382
+ /** Bind the host's key format (`createApiKeySecret`) once at composition; call sites keep `{ deps, input }`. */
383
+ export function createApiKeyService({ keySecret }, _optional = {}) {
384
+ return {
385
+ issueApiKey: (required) => issueApiKey({ ...required, keySecret }),
386
+ authenticateApiKey: (required) => authenticateApiKey({ ...required, keySecret }),
387
+ };
388
+ }
389
+ //# sourceMappingURL=api-key-service.js.map
@@ -0,0 +1,79 @@
1
+ import type { ISODateTime, UUID } from "@jini-ai/core/primitives";
2
+ /**
3
+ * @file The `api_keys` record shape and its two ports (ADR-021 / SPEC-006 REQ-08, state.spec §2).
4
+ *
5
+ * Purpose:
6
+ * `@jini-ai/cms/identity` ships nine repo ports and deliberately stops there — its `INFO.md` names
7
+ * API keys as the one identity table left out of that pass. This file is the tenth port, declared
8
+ * HERE rather than in the library because api-key issuance/verification is implemented in this
9
+ * host (`api-key-service.ts`), and a port belongs with the code that consumes it.
10
+ *
11
+ * Architectural role:
12
+ * Interfaces and types only — no logic, mirroring `@jini-ai/cms/identity`'s own `ports.ts`. The
13
+ * two adapters are `repo.memory.ts` (`InMemoryApiKeyRepo`) and `repo.sqlite.ts`
14
+ * (`SqliteApiKeyRepo`) — a real ADR-006 rule-of-two, not a single-adapter port.
15
+ */
16
+ /**
17
+ * One issued key. `keyHash` is a digest of the key's SECRET half only; the raw key exists exactly
18
+ * once, in `APIKEY_ISSUE`'s response, and is never stored or logged (INV-05).
19
+ *
20
+ * `prefix` is the key's non-secret half, stored in the clear on purpose: it is the lookup handle
21
+ * that turns verification into one indexed row read plus one hash comparison. Without it, a salted
22
+ * KDF digest (which is not a deterministic function of the key alone) would force a full-table
23
+ * scan hashing every row on every request.
24
+ */
25
+ export interface ApiKeyRecord {
26
+ id: UUID;
27
+ workspaceId: UUID;
28
+ /** The bound `kind='api_key'` principal this key authenticates as (REQ-08). */
29
+ principalId: UUID;
30
+ label: string;
31
+ /** Digest of the secret half — see `api-key-secret.ts` for the format and its cost parameters. */
32
+ keyHash: string;
33
+ /** Non-secret lookup handle, e.g. `<host scheme prefix>9f2c1b04d7e5`. Unique per workspace. */
34
+ prefix: string;
35
+ /**
36
+ * The `is_frozen` permission-snapshot policy minted for this key at issuance (F-054-01).
37
+ * `revokeApiKey` retires it with the key so no orphan grant rows survive revocation.
38
+ */
39
+ issuedPolicyId?: UUID;
40
+ createdAt: ISODateTime;
41
+ lastUsedAt?: ISODateTime;
42
+ /** Issuance writes this key even for a non-expiring key, so it may be present and `undefined`. */
43
+ expiresAt?: ISODateTime | undefined;
44
+ revokedAt?: ISODateTime;
45
+ }
46
+ export interface ApiKeyRepoPort {
47
+ findById(required: {
48
+ workspaceId: UUID;
49
+ id: UUID;
50
+ }): Promise<ApiKeyRecord | null>;
51
+ /** The verification path's single row read — see `ApiKeyRecord.prefix` for why this is the seam. */
52
+ findByPrefix(required: {
53
+ workspaceId: UUID;
54
+ prefix: string;
55
+ }): Promise<ApiKeyRecord | null>;
56
+ listByPrincipalId(required: {
57
+ workspaceId: UUID;
58
+ principalId: UUID;
59
+ }): Promise<ApiKeyRecord[]>;
60
+ save(record: ApiKeyRecord): Promise<void>;
61
+ }
62
+ /**
63
+ * The hashing seam for api-key secrets, separate from `PasswordHasherPort` because the two hash
64
+ * fundamentally different inputs and are therefore tuned differently — see `api-key-secret.ts`'s
65
+ * header for the entropy argument behind that split.
66
+ *
67
+ * `verify` must be constant-time in the digest comparison and must never throw: a malformed or
68
+ * foreign stored hash resolves `false` (rejected credential), never a 500 and never a bypass.
69
+ */
70
+ export interface ApiKeySecretHasherPort {
71
+ hash(required: {
72
+ secret: string;
73
+ }, optional?: {}): Promise<string>;
74
+ verify(required: {
75
+ storedHash: string;
76
+ secret: string;
77
+ }, optional?: {}): Promise<boolean>;
78
+ }
79
+ //# sourceMappingURL=api-key-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=api-key-types.js.map
@@ -0,0 +1,18 @@
1
+ export interface BootSessionTokenStore {
2
+ /** Mint and arm a new token, replacing any previous one. Returns the raw token to hand out. */
3
+ mint: () => string;
4
+ /** Exchange a raw token. `true` at most once per {@link mint}; `false` for everything else. */
5
+ redeem: (required: {
6
+ rawToken: unknown;
7
+ }, optional?: {}) => boolean;
8
+ /** Whether a token is currently armed. Diagnostics only — never an authorization decision. */
9
+ isArmed: () => boolean;
10
+ }
11
+ /**
12
+ * Build an isolated single-use token store.
13
+ *
14
+ * @returns a {@link BootSessionTokenStore} holding at most one armed token.
15
+ * @complexity O(1) per operation; O(1) space (one 32-byte digest).
16
+ */
17
+ export declare function createBootSessionTokenStore(_optional?: Record<string, never>): BootSessionTokenStore;
18
+ //# sourceMappingURL=boot-session-token.d.ts.map