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

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 (155) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +9 -5
  3. package/dist/admin/adapters/http.js +25 -20
  4. package/dist/admin/adapters/memory.js +164 -82
  5. package/dist/admin/auth.module.d.ts +2 -2
  6. package/dist/admin/auth.module.js +1 -1
  7. package/dist/admin/conformance/index.js +40 -18
  8. package/dist/admin/controllers/auth.controller.js +3 -1
  9. package/dist/admin/controllers/members.controller.js +56 -31
  10. package/dist/admin/controllers/roles.controller.d.ts +3 -3
  11. package/dist/admin/controllers/roles.controller.js +188 -122
  12. package/dist/admin/controllers/users.controller.js +151 -72
  13. package/dist/admin/members.module.d.ts +2 -2
  14. package/dist/admin/members.module.js +1 -1
  15. package/dist/admin/models.d.ts +1 -0
  16. package/dist/admin/ports.d.ts +3 -0
  17. package/dist/admin/react/components/DestructiveDialog.d.ts +1 -1
  18. package/dist/admin/react/components/DestructiveDialog.js +1 -1
  19. package/dist/admin/react/components/MemberRow.d.ts +3 -1
  20. package/dist/admin/react/components/MemberRow.js +2 -2
  21. package/dist/admin/react/components/MembersConfirmation.d.ts +4 -1
  22. package/dist/admin/react/components/MembersConfirmation.js +2 -2
  23. package/dist/admin/react/components/PermissionPanel.d.ts +4 -2
  24. package/dist/admin/react/components/PermissionPanel.js +2 -2
  25. package/dist/admin/react/components/PolicyRow.d.ts +4 -2
  26. package/dist/admin/react/components/PolicyRow.js +2 -2
  27. package/dist/admin/react/components/RoleRow.d.ts +4 -2
  28. package/dist/admin/react/components/RoleRow.js +2 -2
  29. package/dist/admin/react/components/UserRow.d.ts +3 -1
  30. package/dist/admin/react/components/UserRow.js +2 -2
  31. package/dist/admin/react/components/UsersConfirmation.d.ts +4 -1
  32. package/dist/admin/react/components/UsersConfirmation.js +2 -2
  33. package/dist/admin/react/hooks/AuthBinding.hooks.d.ts +1 -1
  34. package/dist/admin/react/hooks/AuthScope.hooks.d.ts +1 -1
  35. package/dist/admin/react/hooks/MembersBinding.hooks.d.ts +1 -1
  36. package/dist/admin/react/hooks/MembersScope.hooks.d.ts +1 -1
  37. package/dist/admin/react/hooks/PeopleController.hooks.js +6 -4
  38. package/dist/admin/react/hooks/RolesBinding.hooks.d.ts +1 -1
  39. package/dist/admin/react/hooks/RolesController.hooks.d.ts +4 -4
  40. package/dist/admin/react/hooks/RolesController.hooks.js +4 -3
  41. package/dist/admin/react/hooks/RolesPage.hooks.d.ts +8 -8
  42. package/dist/admin/react/hooks/RolesScope.hooks.d.ts +1 -1
  43. package/dist/admin/react/hooks/UsersBinding.hooks.d.ts +1 -1
  44. package/dist/admin/react/hooks/UsersScope.hooks.d.ts +1 -1
  45. package/dist/admin/react/index.d.ts +9 -9
  46. package/dist/admin/react/pages/LoginPage.d.ts +4 -1
  47. package/dist/admin/react/pages/LoginPage.js +2 -2
  48. package/dist/admin/react/pages/MembersPage.d.ts +4 -1
  49. package/dist/admin/react/pages/MembersPage.js +2 -2
  50. package/dist/admin/react/pages/RolesPage.d.ts +4 -1
  51. package/dist/admin/react/pages/RolesPage.js +2 -2
  52. package/dist/admin/react/pages/UsersPage.d.ts +4 -1
  53. package/dist/admin/react/pages/UsersPage.js +2 -2
  54. package/dist/admin/react/tabs/AuthTab.d.ts +4 -2
  55. package/dist/admin/react/tabs/AuthTab.js +2 -2
  56. package/dist/admin/react/tabs/MembersTab.d.ts +4 -2
  57. package/dist/admin/react/tabs/MembersTab.js +2 -2
  58. package/dist/admin/react/tabs/PoliciesTab.d.ts +4 -2
  59. package/dist/admin/react/tabs/PoliciesTab.js +2 -2
  60. package/dist/admin/react/tabs/RolesTab.d.ts +4 -2
  61. package/dist/admin/react/tabs/RolesTab.js +2 -2
  62. package/dist/admin/react/tabs/UsersTab.d.ts +3 -1
  63. package/dist/admin/react/tabs/UsersTab.js +2 -2
  64. package/dist/admin/roles.module.d.ts +2 -2
  65. package/dist/admin/roles.module.js +1 -1
  66. package/dist/admin/users.module.d.ts +4 -4
  67. package/dist/admin/users.module.js +1 -1
  68. package/dist/react/auth/Login.js +1 -1
  69. package/dist/react/auth/OwnerRecovery.hooks.d.ts +93 -0
  70. package/dist/react/auth/OwnerRecovery.hooks.js +105 -0
  71. package/dist/react/auth/Passkeys.d.ts +8 -3
  72. package/dist/react/auth/Passkeys.hooks.d.ts +38 -0
  73. package/dist/react/auth/Passkeys.hooks.js +72 -0
  74. package/dist/react/auth/Passkeys.js +6 -64
  75. package/dist/react/auth/TotpSettings.d.ts +5 -2
  76. package/dist/react/auth/TotpSettings.hooks.d.ts +41 -0
  77. package/dist/react/auth/TotpSettings.hooks.js +82 -0
  78. package/dist/react/auth/TotpSettings.js +10 -77
  79. package/dist/react/auth/hooks/use-login.hooks.d.ts +1 -1
  80. package/dist/react/auth/hooks/use-login.hooks.js +1 -0
  81. package/dist/react/errors.d.ts +1 -1
  82. package/dist/react/errors.js +1 -0
  83. package/dist/react/index.d.ts +6 -2
  84. package/dist/react/index.js +3 -1
  85. package/dist/react/kit.d.ts +91 -0
  86. package/dist/react/kit.js +63 -0
  87. package/dist/react/members/Members.d.ts +1 -1
  88. package/dist/react/members/Members.js +19 -5
  89. package/dist/react/members/hooks/use-members.hooks.d.ts +1 -1
  90. package/dist/react/members/hooks/use-members.hooks.js +49 -27
  91. package/dist/react/members/rules.d.ts +2 -2
  92. package/dist/react/members/rules.js +1 -0
  93. package/dist/react/ports.d.ts +2 -0
  94. package/dist/react/testing.js +47 -22
  95. package/dist/react/users/ChangeUsernameDialog.d.ts +2 -2
  96. package/dist/react/users/ChangeUsernameDialog.js +4 -3
  97. package/dist/react/users/UserRowParts.d.ts +3 -3
  98. package/dist/react/users/UserRowParts.js +2 -1
  99. package/dist/react/users/Users.d.ts +3 -3
  100. package/dist/react/users/Users.js +14 -27
  101. package/dist/react/users/UsersDialogs.d.ts +7 -0
  102. package/dist/react/users/UsersDialogs.js +64 -0
  103. package/dist/react/users/UsersTable.d.ts +118 -0
  104. package/dist/react/users/UsersTable.js +55 -0
  105. package/dist/react/users/hooks/use-change-username.hooks.d.ts +1 -1
  106. package/dist/react/users/hooks/use-change-username.hooks.js +2 -1
  107. package/dist/react/users/hooks/use-reset-password-fields.hooks.d.ts +8 -0
  108. package/dist/react/users/hooks/use-reset-password-fields.hooks.js +11 -0
  109. package/dist/react/users/hooks/use-users-form-state.hooks.d.ts +81 -0
  110. package/dist/react/users/hooks/use-users-form-state.hooks.js +68 -0
  111. package/dist/react/users/hooks/use-users-password.hooks.d.ts +24 -0
  112. package/dist/react/users/hooks/use-users-password.hooks.js +85 -0
  113. package/dist/react/users/hooks/use-users-roster.hooks.d.ts +42 -0
  114. package/dist/react/users/hooks/use-users-roster.hooks.js +133 -0
  115. package/dist/react/users/hooks/use-users-state.hooks.d.ts +102 -0
  116. package/dist/react/users/hooks/use-users-state.hooks.js +19 -0
  117. package/dist/react/users/hooks/use-users-status.hooks.d.ts +26 -0
  118. package/dist/react/users/hooks/use-users-status.hooks.js +97 -0
  119. package/dist/react/users/hooks/use-users.hooks.d.ts +13 -5
  120. package/dist/react/users/hooks/use-users.hooks.js +23 -503
  121. package/dist/react/users/hooks/users-controller.d.ts +14 -0
  122. package/dist/react/users/hooks/users-controller.js +29 -0
  123. package/dist/react/users/hooks/users-grant-actions.d.ts +26 -0
  124. package/dist/react/users/hooks/users-grant-actions.js +124 -0
  125. package/dist/react/users/rules.d.ts +5 -4
  126. package/dist/react/users/rules.js +3 -2
  127. package/dist/server/admin-crud-service.d.ts +2 -2
  128. package/dist/server/admin-crud-service.js +38 -71
  129. package/dist/server/agent-tool-input.d.ts +7 -3
  130. package/dist/server/agent-tool-input.js +47 -14
  131. package/dist/server/agent-tool-registrations.d.ts +5 -2
  132. package/dist/server/agent-tool-registrations.js +250 -199
  133. package/dist/server/agent-tools.d.ts +1 -1
  134. package/dist/server/auth-service.js +1 -1
  135. package/dist/server/grant-service.d.ts +8 -0
  136. package/dist/server/grant-service.js +24 -22
  137. package/dist/server/index.d.ts +1 -0
  138. package/dist/server/index.js +1 -0
  139. package/dist/server/link-policy.d.ts +23 -0
  140. package/dist/server/link-policy.js +30 -0
  141. package/dist/server/permission-migrations.d.ts +3 -3
  142. package/dist/server/repo.memory-transactions.js +24 -20
  143. package/dist/server/repo.memory.d.ts +21 -33
  144. package/dist/server/repo.memory.js +13 -34
  145. package/dist/server/seed.d.ts +3 -3
  146. package/dist/server/seed.js +10 -10
  147. package/dist/session-bootstrap/ensure.d.ts +13 -0
  148. package/dist/session-bootstrap/ensure.js +11 -0
  149. package/dist/session-bootstrap/index.d.ts +5 -0
  150. package/dist/session-bootstrap/index.js +4 -0
  151. package/dist/session-bootstrap/loopback.d.ts +14 -0
  152. package/dist/session-bootstrap/loopback.js +25 -0
  153. package/dist/session-bootstrap/read-initial.d.ts +25 -0
  154. package/dist/session-bootstrap/read-initial.js +27 -0
  155. package/package.json +21 -25
@@ -0,0 +1,124 @@
1
+ /** The shape `onAssignRole`/`onAttachPolicy` both repeat: set the shared `grantSaving`/`grantError`
2
+ * pair, run one mutation, do a success-only side effect, and clear saving in a `finally` — the
3
+ * "whole-hook" complexity view (brief §2) rolls every closure inside a hook into one score, so two
4
+ * near-identical blocks count against `useUsers` even though `grantError`/`grantSaving` are
5
+ * deliberately NOT a fit for `useAsyncAction` (see that file's own header: shared across three
6
+ * handlers on purpose, not one action's own slot — `onSaveEmail` is the third, kept separate below
7
+ * since it tracks its OWN `emailSaving`). Reproducing the shared-state shape as a local top-level
8
+ * helper — rather than importing the generic primitive — collapses the two call sites without
9
+ * forcing that mismatch onto them. `mutate` itself `invalidates: [KEYS.list]`, replacing the
10
+ * pre-migration `reload()` call this helper used to make explicitly.
11
+ *
12
+ * `onSuccess` (2026-09-05 fix, same bug class as `use-roles.hooks.ts`'s `onSaveRole`/
13
+ * `onWritePermission`): nothing gates opening a DIFFERENT user's Manage panel
14
+ * (`toggleExpanded`) while a grant for the previously expanded one is still in flight, and
15
+ * `onSuccess` clears `pendingRoleId`/`pendingPolicyId` — a shared field, not keyed by principal.
16
+ * `toggleGenerationRef` (bumped once per `toggleExpanded` call, regardless of which panel — see
17
+ * that function) lets a stale grant tell whether the operator switched panels at ALL while it was
18
+ * in flight, independent of which principal is currently expanded: comparing against the panel's
19
+ * OWN identity would wrongly refuse a grant issued before any panel was ever expanded (a
20
+ * legitimate, already-certified call shape), where `expandedId` never gets set to begin with.
21
+ * `onSuccess` is skipped only when a switch actually happened since this call started — otherwise
22
+ * a stale grant's success would erase a NEW, unrelated selection the operator has since made for
23
+ * the panel they actually have open now. */
24
+ async function runGrantMutation({ toggleGenerationRef, mutate, onSuccess, setGrantSaving, setGrantError, describeError }) {
25
+ // Read synchronously, before the first `await` — the same instant both callers used to read and
26
+ // pass in themselves, so this is still the generation this call STARTED under.
27
+ const generationAtStart = toggleGenerationRef.current;
28
+ setGrantSaving(true);
29
+ setGrantError(null);
30
+ try {
31
+ await mutate();
32
+ if (toggleGenerationRef.current === generationAtStart)
33
+ onSuccess();
34
+ }
35
+ catch (e) {
36
+ // Same generation check as the success branch above (C8, plan-access.md §8, N3): a stale
37
+ // failure must not paint onto a DIFFERENT user's panel the operator has since opened.
38
+ if (toggleGenerationRef.current === generationAtStart)
39
+ setGrantError(describeError(e));
40
+ }
41
+ finally {
42
+ // Guarded the same way — a stale call's `finally` must not clear a NEWER call's own saving
43
+ // flag. `toggleExpanded` resets `grantSaving` itself when it bumps the generation, so a panel
44
+ // switch still leaves the new panel un-stuck even though this skip means THIS call no longer
45
+ // clears it.
46
+ if (toggleGenerationRef.current === generationAtStart)
47
+ setGrantSaving(false);
48
+ }
49
+ }
50
+ export function createUsersCreateAction({ state }, _optional = {}) {
51
+ const { createUser, createUserMutation, username, password, email, setUsername, setEmail, setPassword, setFormOpen, describeError, translate } = state;
52
+ async function onCreate(e) {
53
+ e.preventDefault();
54
+ await createUser.run({ action: async () => {
55
+ await createUserMutation.mutate({ input: { username, password, email: email || undefined } });
56
+ setUsername("");
57
+ setEmail("");
58
+ setPassword("");
59
+ setFormOpen(false);
60
+ }, describeError: (e) => describeError(e, translate("failed to create user")) });
61
+ }
62
+ return onCreate;
63
+ }
64
+ export function createUsersPanelActions({ state }, _optional = {}) {
65
+ const { setGrantError, setGrantSaving, setPendingRoleId, setPendingPolicyId, setEditEmail, toggleGenerationRef, setExpandedId, updateEmailMutation, editEmail, describeError, translate } = state;
66
+ function toggleExpanded(user) {
67
+ setGrantError(null);
68
+ // A still-in-flight grant for the panel being LEFT can no longer clear this itself
69
+ // (`runGrantMutation`'s `finally` now skips a stale call's own generation) — reset it here so
70
+ // the newly opened panel never inherits a stuck "saving" indicator from the old one.
71
+ setGrantSaving(false);
72
+ setPendingRoleId("");
73
+ setPendingPolicyId("");
74
+ setEditEmail(user.email ?? "");
75
+ toggleGenerationRef.current += 1;
76
+ setExpandedId((current) => (current === user.principalId ? null : user.principalId));
77
+ }
78
+ // `onSaveEmail` was left out of the `runGrantMutation` fold above on purpose: it tracks its OWN
79
+ // `emailSaving` flag rather than the shared `grantSaving` `onAssignRole`/`onAttachPolicy` use, so
80
+ // routing it through the same helper would mean passing a no-op in place of `setGrantSaving` —
81
+ // extraction for the sake of a shared call site, not a shared shape. Left hand-rolled; `emailSaving`
82
+ // now derives from `updateEmailMutation.status` since (unlike `grantSaving`) it was already this
83
+ // one mutation's own dedicated flag.
84
+ async function onSaveEmail({ principalId }) {
85
+ setGrantError(null);
86
+ try {
87
+ await updateEmailMutation.mutate({ input: { principalId, email: editEmail } });
88
+ }
89
+ catch (e) {
90
+ setGrantError(describeError(e, translate("failed to update email")));
91
+ }
92
+ }
93
+ const emailSaving = updateEmailMutation.status === "pending";
94
+ return { toggleExpanded, onSaveEmail, emailSaving };
95
+ }
96
+ export function createUsersGrantActions({ state }, _optional = {}) {
97
+ const { pendingRoleId, pendingPolicyId, toggleGenerationRef, assignRoleMutation, attachPolicyMutation, setPendingRoleId, setPendingPolicyId, setGrantSaving, setGrantError, describeError, translate } = state;
98
+ async function onAssignRole({ principalId }) {
99
+ if (!pendingRoleId)
100
+ return;
101
+ await runGrantMutation({
102
+ toggleGenerationRef,
103
+ mutate: () => assignRoleMutation.mutate({ input: { principalId, roleId: pendingRoleId } }),
104
+ onSuccess: () => setPendingRoleId(""),
105
+ setGrantSaving,
106
+ setGrantError,
107
+ describeError: (e) => describeError(e, translate("failed to assign role")),
108
+ });
109
+ }
110
+ async function onAttachPolicy({ principalId }) {
111
+ if (!pendingPolicyId)
112
+ return;
113
+ await runGrantMutation({
114
+ toggleGenerationRef,
115
+ mutate: () => attachPolicyMutation.mutate({ input: { principalId, policyId: pendingPolicyId } }),
116
+ onSuccess: () => setPendingPolicyId(""),
117
+ setGrantSaving,
118
+ setGrantError,
119
+ describeError: (e) => describeError(e, translate("failed to attach policy")),
120
+ });
121
+ }
122
+ return { onAssignRole, onAttachPolicy };
123
+ }
124
+ //# sourceMappingURL=users-grant-actions.js.map
@@ -1,6 +1,7 @@
1
1
  import type { AdminIdentityUser } from "../models.js";
2
- import type { Translate, QueryKey } from "@jini-ai/ui/panel-kit";
3
- import type { RowMenuItem } from "@jini-ai/admin/react";
2
+ import type { QueryKey } from "@jini-ai/core/fetch";
3
+ import type { RowMenuItem } from "../kit.js";
4
+ import { type Translate } from '@jini-ai/core/text';
4
5
  /**
5
6
  * @file Pure logic for the `users` feature — everything that computes a value rather than
6
7
  * rendering one. Follows the `posts/rules.ts` convention: no React import, no hooks, directly
@@ -18,7 +19,7 @@ import type { RowMenuItem } from "@jini-ai/admin/react";
18
19
  export declare const KEYS: {
19
20
  list: QueryKey;
20
21
  };
21
- /** Server error `code` -> a plain-language prefix (SPEC-006 errors.spec.md §2), layered on the
22
+ /** Server error `code` -> a plain-language prefix, layered on the
22
23
  * shared default (`lib/api.ts`'s `describeApiError`) — this screen's `RESOURCE_CONFLICT` means
23
24
  * "username already in use", a different meaning than `Roles.tsx`'s "still referenced" or
24
25
  * `Workspace.tsx`'s "slug already taken" for the same code (audit cross-cutting finding #2 —
@@ -87,7 +88,7 @@ export declare function isOwnerAccount(required: {
87
88
  * `use-users.hooks.ts` — see that hook's `canManageUserTrash` state for where it comes from.
88
89
  *
89
90
  * Disable/Enable share a single "toggle" item (label follows status, same shape as
90
- * `Redirects.tsx`'s own toggle item) — Disable confirms via the modal below; Enable fires
91
+ * `packages/admin/src/redirects/rules.ts`'s own toggle item) — Disable confirms via the modal below; Enable fires
91
92
  * immediately, matching this screen's existing behavior (Enable was never confirm-gated). The
92
93
  * `toggleSaving` guard reproduces the original inline check (`if (toggleSavingId) return`) against
93
94
  * whatever row action is currently in flight, read fresh at click time.
@@ -1,4 +1,5 @@
1
1
  import { describeIdentityError } from "../errors.js";
2
+ import {} from '@jini-ai/core/text';
2
3
  /**
3
4
  * @file Pure logic for the `users` feature — everything that computes a value rather than
4
5
  * rendering one. Follows the `posts/rules.ts` convention: no React import, no hooks, directly
@@ -34,7 +35,7 @@ const STATIC_ERROR_MESSAGES = {
34
35
  USER_IN_TRASH: "This user is in the Trash; restore them first.",
35
36
  USERNAME_IN_TRASH: "A user with this username is in the Trash; restore or delete them permanently first.",
36
37
  };
37
- /** Server error `code` -> a plain-language prefix (SPEC-006 errors.spec.md §2), layered on the
38
+ /** Server error `code` -> a plain-language prefix, layered on the
38
39
  * shared default (`lib/api.ts`'s `describeApiError`) — this screen's `RESOURCE_CONFLICT` means
39
40
  * "username already in use", a different meaning than `Roles.tsx`'s "still referenced" or
40
41
  * `Workspace.tsx`'s "slug already taken" for the same code (audit cross-cutting finding #2 —
@@ -80,7 +81,7 @@ export function isOwnerAccount(required, _optional = {}) {
80
81
  * `use-users.hooks.ts` — see that hook's `canManageUserTrash` state for where it comes from.
81
82
  *
82
83
  * Disable/Enable share a single "toggle" item (label follows status, same shape as
83
- * `Redirects.tsx`'s own toggle item) — Disable confirms via the modal below; Enable fires
84
+ * `packages/admin/src/redirects/rules.ts`'s own toggle item) — Disable confirms via the modal below; Enable fires
84
85
  * immediately, matching this screen's existing behavior (Enable was never confirm-gated). The
85
86
  * `toggleSaving` guard reproduces the original inline check (`if (toggleSavingId) return`) against
86
87
  * whatever row action is currently in flight, read fresh at click time.
@@ -114,8 +114,8 @@ export declare function updateUser(required: {
114
114
  * Deliberately NOT unconditional the way `disablePrincipal`'s owner check is: the owner resetting
115
115
  * ITS OWN password (`callerPrincipalId === principalId === seededOwnerPrincipalId`) is refused
116
116
  * nothing — that self-service path is real, shipped infrastructure
117
- * (`reset-admin-password-self-verified.ts`, driven by both the `HOST_ADMIN_RESET_PASSWORD`
118
- * boot-time incident-recovery hook and the `backfill-reset-admin-password.ts` CLI script), added
117
+ * (`packages/user-management/src/server/recovery-codes.ts`, driven by both the `HOST_ADMIN_RESET_PASSWORD`
118
+ * boot-time incident-recovery hook and the `password backfill` CLI script), added
119
119
  * specifically to let an operator recover a locked-out owner account out-of-band. Disabling has no
120
120
  * legitimate self-case (an owner disabling itself only ever stands the workspace down), so
121
121
  * `disablePrincipal` can refuse unconditionally; a credential rotation the owner performs on itself
@@ -1,6 +1,5 @@
1
1
  import { nowIso as kernelNowIso } from "@jini-ai/core/primitives";
2
- import { inIdentityTransaction } from "./identity-transaction.js";
3
- import { assertCallerHasAnyPermission, assertGrantClamp, assertOwnerTargetMayBeModified, principalHoldsOwnerWildcard } from "./grant-service.js";
2
+ import { inAuthorizedIdentityTransaction, assertCallerHasAnyPermission, assertGrantClamp, assertOwnerTargetMayBeModified, principalHoldsOwnerWildcard } from "./grant-service.js";
4
3
  import { validatePasswordPolicy } from "./password-policy.js";
5
4
  import { normalizeUsername } from "./username.js";
6
5
  import { isKnownPermission } from "../core/permissions.js";
@@ -50,16 +49,12 @@ const ROLE_MANAGE = "role.manage";
50
49
  */
51
50
  export async function disablePrincipal(required) {
52
51
  const { deps, input } = required;
53
- return inIdentityTransaction({
54
- transactions: deps.repos.transactions,
52
+ return inAuthorizedIdentityTransaction({
53
+ deps,
55
54
  workspaceId: input.workspaceId,
55
+ callerPrincipalId: input.callerPrincipalId,
56
+ permissions: [USER_MANAGE],
56
57
  execute: async () => {
57
- await assertCallerHasAnyPermission({
58
- deps,
59
- workspaceId: input.workspaceId,
60
- callerPrincipalId: input.callerPrincipalId,
61
- permissions: [USER_MANAGE],
62
- });
63
58
  const target = await deps.repos.principals.findById({ workspaceId: input.workspaceId, id: input.principalId });
64
59
  if (!target)
65
60
  throw new IdentityNotFoundError({ message: `principal '${input.principalId}' was not found` });
@@ -108,16 +103,12 @@ export async function disablePrincipal(required) {
108
103
  */
109
104
  export async function enablePrincipal(required) {
110
105
  const { deps, input } = required;
111
- return inIdentityTransaction({
112
- transactions: deps.repos.transactions,
106
+ return inAuthorizedIdentityTransaction({
107
+ deps,
113
108
  workspaceId: input.workspaceId,
109
+ callerPrincipalId: input.callerPrincipalId,
110
+ permissions: [USER_MANAGE],
114
111
  execute: async () => {
115
- await assertCallerHasAnyPermission({
116
- deps,
117
- workspaceId: input.workspaceId,
118
- callerPrincipalId: input.callerPrincipalId,
119
- permissions: [USER_MANAGE],
120
- });
121
112
  const target = await deps.repos.principals.findById({ workspaceId: input.workspaceId, id: input.principalId });
122
113
  if (!target)
123
114
  throw new IdentityNotFoundError({ message: `principal '${input.principalId}' was not found` });
@@ -153,19 +144,15 @@ export async function enablePrincipal(required) {
153
144
  export async function updateUser(required, optional = {}) {
154
145
  const { deps } = required;
155
146
  const input = { ...required.input, ...optional };
156
- return inIdentityTransaction({
157
- transactions: deps.repos.transactions,
147
+ return inAuthorizedIdentityTransaction({
148
+ deps,
158
149
  workspaceId: input.workspaceId,
150
+ callerPrincipalId: input.callerPrincipalId,
151
+ // Preserve existing self-profile access without letting member.manage edit other operators.
152
+ permissions: input.username === undefined && input.callerPrincipalId === input.principalId
153
+ ? [USER_MANAGE, "member.manage"]
154
+ : [USER_MANAGE],
159
155
  execute: async () => {
160
- await assertCallerHasAnyPermission({
161
- deps,
162
- workspaceId: input.workspaceId,
163
- callerPrincipalId: input.callerPrincipalId,
164
- // Preserve existing self-profile access without letting member.manage edit other operators.
165
- permissions: input.username === undefined && input.callerPrincipalId === input.principalId
166
- ? [USER_MANAGE, "member.manage"]
167
- : [USER_MANAGE],
168
- });
169
156
  const target = await deps.repos.users.findByPrincipalId({
170
157
  workspaceId: input.workspaceId,
171
158
  principalId: input.principalId,
@@ -256,8 +243,8 @@ async function assertUsernameAvailable(required) {
256
243
  * Deliberately NOT unconditional the way `disablePrincipal`'s owner check is: the owner resetting
257
244
  * ITS OWN password (`callerPrincipalId === principalId === seededOwnerPrincipalId`) is refused
258
245
  * nothing — that self-service path is real, shipped infrastructure
259
- * (`reset-admin-password-self-verified.ts`, driven by both the `HOST_ADMIN_RESET_PASSWORD`
260
- * boot-time incident-recovery hook and the `backfill-reset-admin-password.ts` CLI script), added
246
+ * (`packages/user-management/src/server/recovery-codes.ts`, driven by both the `HOST_ADMIN_RESET_PASSWORD`
247
+ * boot-time incident-recovery hook and the `password backfill` CLI script), added
261
248
  * specifically to let an operator recover a locked-out owner account out-of-band. Disabling has no
262
249
  * legitimate self-case (an owner disabling itself only ever stands the workspace down), so
263
250
  * `disablePrincipal` can refuse unconditionally; a credential rotation the owner performs on itself
@@ -279,16 +266,12 @@ async function assertUsernameAvailable(required) {
279
266
  */
280
267
  export async function resetUserPassword(required) {
281
268
  const { deps, input } = required;
282
- return inIdentityTransaction({
283
- transactions: deps.repos.transactions,
269
+ return inAuthorizedIdentityTransaction({
270
+ deps,
284
271
  workspaceId: input.workspaceId,
272
+ callerPrincipalId: input.callerPrincipalId,
273
+ permissions: [USER_MANAGE],
285
274
  execute: async () => {
286
- await assertCallerHasAnyPermission({
287
- deps,
288
- workspaceId: input.workspaceId,
289
- callerPrincipalId: input.callerPrincipalId,
290
- permissions: [USER_MANAGE],
291
- });
292
275
  const target = await deps.repos.users.findByPrincipalId({
293
276
  workspaceId: input.workspaceId,
294
277
  principalId: input.principalId,
@@ -422,16 +405,12 @@ export async function updatePolicy(required, optional = {}) {
422
405
  */
423
406
  export async function deleteRole(required) {
424
407
  const { deps, input } = required;
425
- return inIdentityTransaction({
426
- transactions: deps.repos.transactions,
408
+ return inAuthorizedIdentityTransaction({
409
+ deps,
427
410
  workspaceId: input.workspaceId,
411
+ callerPrincipalId: input.callerPrincipalId,
412
+ permissions: [ROLE_MANAGE],
428
413
  execute: async () => {
429
- await assertCallerHasAnyPermission({
430
- deps,
431
- workspaceId: input.workspaceId,
432
- callerPrincipalId: input.callerPrincipalId,
433
- permissions: [ROLE_MANAGE],
434
- });
435
414
  const target = await deps.repos.roles.findById({ workspaceId: input.workspaceId, id: input.roleId });
436
415
  if (!target)
437
416
  throw new IdentityNotFoundError({ message: `role '${input.roleId}' was not found` });
@@ -466,16 +445,12 @@ export async function deleteRole(required) {
466
445
  */
467
446
  export async function deletePolicy(required) {
468
447
  const { deps, input } = required;
469
- return inIdentityTransaction({
470
- transactions: deps.repos.transactions,
448
+ return inAuthorizedIdentityTransaction({
449
+ deps,
471
450
  workspaceId: input.workspaceId,
451
+ callerPrincipalId: input.callerPrincipalId,
452
+ permissions: [ROLE_MANAGE],
472
453
  execute: async () => {
473
- await assertCallerHasAnyPermission({
474
- deps,
475
- workspaceId: input.workspaceId,
476
- callerPrincipalId: input.callerPrincipalId,
477
- permissions: [ROLE_MANAGE],
478
- });
479
454
  const target = await deps.repos.policies.findById({ workspaceId: input.workspaceId, id: input.policyId });
480
455
  if (!target)
481
456
  throw new IdentityNotFoundError({ message: `policy '${input.policyId}' was not found` });
@@ -513,16 +488,12 @@ export async function deletePolicy(required) {
513
488
  export async function writePolicyPermission(required, optional = {}) {
514
489
  const { deps } = required;
515
490
  const input = { ...required.input, ...optional };
516
- return inIdentityTransaction({
517
- transactions: deps.repos.transactions,
491
+ return inAuthorizedIdentityTransaction({
492
+ deps,
518
493
  workspaceId: input.workspaceId,
494
+ callerPrincipalId: input.callerPrincipalId,
495
+ permissions: [ROLE_MANAGE],
519
496
  execute: async () => {
520
- await assertCallerHasAnyPermission({
521
- deps,
522
- workspaceId: input.workspaceId,
523
- callerPrincipalId: input.callerPrincipalId,
524
- permissions: [ROLE_MANAGE],
525
- });
526
497
  if (!isKnownPermission({ id: input.permission })) {
527
498
  throw new PermissionUnknownError({ message: `permission '${input.permission}' is not in the registered catalog` });
528
499
  }
@@ -578,16 +549,12 @@ export async function writePolicyPermission(required, optional = {}) {
578
549
  */
579
550
  export async function removePolicyPermission(required) {
580
551
  const { deps, input } = required;
581
- return inIdentityTransaction({
582
- transactions: deps.repos.transactions,
552
+ return inAuthorizedIdentityTransaction({
553
+ deps,
583
554
  workspaceId: input.workspaceId,
555
+ callerPrincipalId: input.callerPrincipalId,
556
+ permissions: [ROLE_MANAGE],
584
557
  execute: async () => {
585
- await assertCallerHasAnyPermission({
586
- deps,
587
- workspaceId: input.workspaceId,
588
- callerPrincipalId: input.callerPrincipalId,
589
- permissions: [ROLE_MANAGE],
590
- });
591
558
  const policy = await deps.repos.policies.findById({ workspaceId: input.workspaceId, id: input.policyId });
592
559
  if (!policy)
593
560
  throw new IdentityNotFoundError({ message: `policy '${input.policyId}' was not found` });
@@ -1,14 +1,15 @@
1
1
  /**
2
2
  * @file The enforcing boundary parser for identity agent-tool input — the identity domain's
3
- * analogue of `features/content-types/field-defs.ts`.
3
+ * analogue of `packages/cms/src/content-types/field-defs.ts`.
4
4
  *
5
5
  * Deliberate divergence from content-types, disclosed:
6
6
  * content-types hand-authors its published `inputSchema` and hand-authors `field-defs.ts`
7
7
  * separately, then pins the two together with a fixture corpus
8
- * (`agent-tools.schema-agreement.unit.test.ts`) because deriving one from the other would have
8
+ * (`packages/user-management/src/server/__tests__/agent-tools.schema-agreement.test.ts`) because deriving one from the other would have
9
9
  * needed either a JSON Schema library this project does not depend on or a code generator. That
10
10
  * reasoning does not carry over here: identity's schemas use a small keyword subset and describe
11
- * flat objects of strings, so this file INTERPRETS that published schema directly rather than
11
+ * flat objects of strings (plus integer `expectedVersion` basis fields for the lost-update guard),
12
+ * so this file INTERPRETS that published schema directly rather than
12
13
  * duplicating it. Sharing the artifact prevents metadata drift; the independent agreement tests
13
14
  * still verify interpreter semantics, including Unicode length and unsupported schema shapes.
14
15
  *
@@ -22,9 +23,12 @@
22
23
  * `identity` library, pure. No I/O, no enforcement of permissions — this is shape validation only.
23
24
  * Returns a `Result` rather than throwing so the caller decides how a rejection is surfaced.
24
25
  */
26
+ /** Strings stay in `value` (its shape predates integers); integer properties come back in the
27
+ * additive `integers` map, so existing readers of `value` keep their `string` typing. */
25
28
  export type IdentityToolInputResult = {
26
29
  ok: true;
27
30
  value: Readonly<Record<string, string>>;
31
+ integers: Readonly<Record<string, number>>;
28
32
  } | {
29
33
  ok: false;
30
34
  error: Error;
@@ -1,14 +1,15 @@
1
1
  /**
2
2
  * @file The enforcing boundary parser for identity agent-tool input — the identity domain's
3
- * analogue of `features/content-types/field-defs.ts`.
3
+ * analogue of `packages/cms/src/content-types/field-defs.ts`.
4
4
  *
5
5
  * Deliberate divergence from content-types, disclosed:
6
6
  * content-types hand-authors its published `inputSchema` and hand-authors `field-defs.ts`
7
7
  * separately, then pins the two together with a fixture corpus
8
- * (`agent-tools.schema-agreement.unit.test.ts`) because deriving one from the other would have
8
+ * (`packages/user-management/src/server/__tests__/agent-tools.schema-agreement.test.ts`) because deriving one from the other would have
9
9
  * needed either a JSON Schema library this project does not depend on or a code generator. That
10
10
  * reasoning does not carry over here: identity's schemas use a small keyword subset and describe
11
- * flat objects of strings, so this file INTERPRETS that published schema directly rather than
11
+ * flat objects of strings (plus integer `expectedVersion` basis fields for the lost-update guard),
12
+ * so this file INTERPRETS that published schema directly rather than
12
13
  * duplicating it. Sharing the artifact prevents metadata drift; the independent agreement tests
13
14
  * still verify interpreter semantics, including Unicode length and unsupported schema shapes.
14
15
  *
@@ -25,6 +26,7 @@
25
26
  /** The keywords this interpreter implements. Anything else in a schema is a hard error, never ignored. */
26
27
  const OBJECT_KEYWORDS = new Set(["type", "properties", "required", "additionalProperties", "description"]);
27
28
  const STRING_KEYWORDS = new Set(["type", "minLength", "description"]);
29
+ const INTEGER_KEYWORDS = new Set(["type", "minimum", "description"]);
28
30
  /**
29
31
  * Asserts a schema uses only keywords {@link parseIdentityToolInput} implements.
30
32
  *
@@ -56,7 +58,7 @@ function assertSchemaIsInterpretable(schema) {
56
58
  throw new Error("identity agent-tool schema properties must be an object");
57
59
  assertRequiredIsDeclared(Object.hasOwn(schema, "required") ? schema.required : [], properties);
58
60
  for (const [key, sub] of Object.entries(properties))
59
- assertStringPropertySchema(key, sub);
61
+ assertPropertySchema(key, sub);
60
62
  }
61
63
  /** `required` must be unique strings, each naming an OWN declared property. */
62
64
  function assertRequiredIsDeclared(required, properties) {
@@ -71,13 +73,21 @@ function assertRequiredIsDeclared(required, properties) {
71
73
  function isUniqueStringArray(value) {
72
74
  return Array.isArray(value) && value.every(key => typeof key === "string") && new Set(value).size === value.length;
73
75
  }
74
- /** A property sub-schema must be a string schema whose optional `minLength` is a nonnegative integer. */
75
- function assertStringPropertySchema(key, sub) {
76
+ /** A property sub-schema is a string schema whose optional `minLength` is a nonnegative integer, or
77
+ * an integer schema whose optional `minimum` is an integer. */
78
+ function assertPropertySchema(key, sub) {
76
79
  if (!isSchemaObject(sub))
77
80
  throw new Error(`identity agent-tool schema property '${key}' must be an object`);
81
+ if (sub.type === "integer") {
82
+ assertKeywords(sub, INTEGER_KEYWORDS);
83
+ if (Object.hasOwn(sub, "minimum") && !(typeof sub.minimum === "number" && Number.isInteger(sub.minimum))) {
84
+ throw new Error(`identity agent-tool schema minimum for '${key}' must be an integer`);
85
+ }
86
+ return;
87
+ }
78
88
  assertKeywords(sub, STRING_KEYWORDS);
79
89
  if (sub.type !== "string") {
80
- throw new Error(`identity agent-tool schema declares non-string property '${key}' — this parser only implements string properties`);
90
+ throw new Error(`identity agent-tool schema declares property '${key}' of unsupported type '${String(sub.type)}' — this parser implements string and integer properties`);
81
91
  }
82
92
  if (Object.hasOwn(sub, "minLength") && !isNonNegativeInteger(sub.minLength)) {
83
93
  throw new Error(`identity agent-tool schema minLength for '${key}' must be a nonnegative integer`);
@@ -141,7 +151,7 @@ export function parseIdentityToolInput(required) {
141
151
  ?? findMissingRequiredKey(input, schema.required ?? []);
142
152
  if (violation !== undefined)
143
153
  return rejected(violation);
144
- return extractStrings(input, properties);
154
+ return extractValues(input, properties);
145
155
  }
146
156
  function rejected(message) {
147
157
  return { ok: false, error: new Error(message) };
@@ -157,21 +167,44 @@ function findMissingRequiredKey(record, requiredKeys) {
157
167
  return key === undefined ? undefined : `'${key}' is required`;
158
168
  }
159
169
  /** Extracts every present declared key, in declaration order, rejecting the first non-conforming value. */
160
- function extractStrings(record, properties) {
170
+ function extractValues(record, properties) {
161
171
  const value = {};
172
+ const integers = {};
162
173
  for (const [key, sub] of Object.entries(properties)) {
163
174
  if (!Object.hasOwn(record, key))
164
175
  continue;
165
176
  const candidate = record[key];
166
- if (typeof candidate !== "string")
167
- return rejected(`'${key}' must be a string, received ${describeType(candidate)}`);
168
- if (typeof sub.minLength === "number" && Array.from(candidate).length < sub.minLength) {
169
- return rejected(`'${key}' must contain at least ${sub.minLength} Unicode code point(s)`);
177
+ if (sub.type === "integer") {
178
+ const integerViolation = findIntegerViolation(key, sub, candidate);
179
+ if (integerViolation !== undefined)
180
+ return rejected(integerViolation);
181
+ Object.defineProperty(integers, key, { value: candidate, enumerable: true, writable: true, configurable: true });
182
+ continue;
170
183
  }
184
+ const stringViolation = findStringViolation(key, sub, candidate);
185
+ if (stringViolation !== undefined)
186
+ return rejected(stringViolation);
171
187
  // defineProperty keeps a `__proto__` key as plain own data rather than invoking the setter.
172
188
  Object.defineProperty(value, key, { value: candidate, enumerable: true, writable: true, configurable: true });
173
189
  }
174
- return { ok: true, value };
190
+ return { ok: true, value, integers };
191
+ }
192
+ /** Rejection message for a non-integer value or one below `minimum`; undefined when it conforms. */
193
+ function findIntegerViolation(key, sub, candidate) {
194
+ if (typeof candidate !== "number" || !Number.isSafeInteger(candidate))
195
+ return `'${key}' must be an integer, received ${describeType(candidate)}`;
196
+ if (typeof sub.minimum === "number" && candidate < sub.minimum)
197
+ return `'${key}' must be at least ${sub.minimum}`;
198
+ return undefined;
199
+ }
200
+ /** Rejection message for a non-string value or one shorter than `minLength`; undefined when it conforms. */
201
+ function findStringViolation(key, sub, candidate) {
202
+ if (typeof candidate !== "string")
203
+ return `'${key}' must be a string, received ${describeType(candidate)}`;
204
+ if (typeof sub.minLength === "number" && Array.from(candidate).length < sub.minLength) {
205
+ return `'${key}' must contain at least ${sub.minLength} Unicode code point(s)`;
206
+ }
207
+ return undefined;
175
208
  }
176
209
  /** Names a value's type for a rejection message WITHOUT echoing the value itself. */
177
210
  function describeType(value) {
@@ -12,7 +12,7 @@ import type { Clock, IdGenerator } from "@jini-ai/core/primitives";
12
12
  * duplicate evaluator, and one any non-tool caller of the same service function would bypass. See
13
13
  * `assistant/__tests__/tool-registrations.identity-authorization.test.ts`.
14
14
  */
15
- import { type DerivedRiskByToolId, type ToolRegistration } from "@jini-ai/core";
15
+ import { type AgentToolSideEffect, type ToolRegistration } from "@jini-ai/core";
16
16
  import { type IdentityAgentToolDefinition } from "./agent-tools.js";
17
17
  import type { AuthServiceDeps } from "./auth-service.js";
18
18
  import type { IdentityRepos, PasswordHasherPort, PolicyPermissionRepoPort, PolicyRepoPort, PrincipalPolicyRepoPort, PrincipalRepoPort, PrincipalRoleRepoPort, RolePolicyRepoPort, RoleRepoPort, SessionRepoPort, UserRepoPort } from "../core/index.js";
@@ -48,7 +48,7 @@ export interface IdentityToolDeps {
48
48
  * calls. See `DerivedRiskByToolId` in the kit for why it is independent of the catalog's own
49
49
  * `sideEffects` declaration.
50
50
  */
51
- export declare const identityDerivedRisk: DerivedRiskByToolId;
51
+ export declare const identityDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
52
52
  /**
53
53
  * Catalog lookup that fails loudly on drift between a handler's tool id and the published catalog.
54
54
  * Exported for this module's tests only — the package entry does not re-export it.
@@ -85,6 +85,9 @@ export interface ValidatedIdentityInput {
85
85
  req(field: string): string;
86
86
  /** A field the schema leaves optional. `undefined` means the caller omitted it. */
87
87
  opt(field: string): string | undefined;
88
+ /** An integer field (e.g. `expectedVersion`); `undefined` means the caller omitted it. The
89
+ * parser already enforced `required`, the integer type and `minimum`. */
90
+ int(field: string): number | undefined;
88
91
  }
89
92
  /**
90
93
  * Parses `input` against `toolId`'s published schema and returns the split required/optional reader.