@open-mercato/core 0.7.1-develop.7154.1.981330c924 → 0.7.1-develop.7171.1.9b31dbba45

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/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +2 -2
  3. package/dist/modules/auth/commands/users.js +14 -1
  4. package/dist/modules/auth/commands/users.js.map +2 -2
  5. package/dist/modules/auth/data/entities.js +2 -2
  6. package/dist/modules/auth/data/entities.js.map +2 -2
  7. package/dist/modules/auth/lib/backendChrome.js +26 -3
  8. package/dist/modules/auth/lib/backendChrome.js.map +2 -2
  9. package/dist/modules/auth/lib/profile-sections.js +1 -1
  10. package/dist/modules/auth/lib/profile-sections.js.map +2 -2
  11. package/dist/modules/auth/migrations/Migration20260907120000_auth.js +19 -0
  12. package/dist/modules/auth/migrations/Migration20260907120000_auth.js.map +7 -0
  13. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js +2 -2
  14. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js.map +1 -1
  15. package/dist/modules/customer_accounts/api/admin/demo-accounts.js +118 -0
  16. package/dist/modules/customer_accounts/api/admin/demo-accounts.js.map +7 -0
  17. package/dist/modules/customer_accounts/api/invitations/accept.js +23 -6
  18. package/dist/modules/customer_accounts/api/invitations/accept.js.map +2 -2
  19. package/dist/modules/customer_accounts/backend/customer_accounts/settings/CustomerAccountsSettingsPageClient.js +10 -13
  20. package/dist/modules/customer_accounts/backend/customer_accounts/settings/CustomerAccountsSettingsPageClient.js.map +2 -2
  21. package/dist/modules/customer_accounts/backend/customer_accounts/useDemoPortalAccounts.js +28 -0
  22. package/dist/modules/customer_accounts/backend/customer_accounts/useDemoPortalAccounts.js.map +7 -0
  23. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js +6 -1
  24. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js.map +2 -2
  25. package/dist/modules/customer_accounts/data/entities.js +4 -1
  26. package/dist/modules/customer_accounts/data/entities.js.map +2 -2
  27. package/dist/modules/customer_accounts/lib/exampleAccounts.js +9 -0
  28. package/dist/modules/customer_accounts/lib/exampleAccounts.js.map +7 -0
  29. package/dist/modules/customer_accounts/migrations/Migration20260827160000_customer_accounts.js +16 -0
  30. package/dist/modules/customer_accounts/migrations/Migration20260827160000_customer_accounts.js.map +7 -0
  31. package/dist/modules/customer_accounts/services/customerInvitationService.js +53 -6
  32. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  33. package/dist/modules/customer_accounts/setup.js +2 -6
  34. package/dist/modules/customer_accounts/setup.js.map +2 -2
  35. package/dist/modules/customer_accounts/widgets/injection/account-status/widget.client.js +55 -40
  36. package/dist/modules/customer_accounts/widgets/injection/account-status/widget.client.js.map +2 -2
  37. package/dist/modules/customers/commands/people.js +16 -1
  38. package/dist/modules/customers/commands/people.js.map +2 -2
  39. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js +18 -36
  40. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js.map +2 -2
  41. package/dist/modules/entities/api/records.js +18 -15
  42. package/dist/modules/entities/api/records.js.map +3 -3
  43. package/dist/modules/entities/lib/scoped-field-defs.js +52 -0
  44. package/dist/modules/entities/lib/scoped-field-defs.js.map +7 -0
  45. package/dist/modules/entities/lib/validation.js +4 -35
  46. package/dist/modules/entities/lib/validation.js.map +2 -2
  47. package/dist/modules/integrations/backend/integrations/[id]/page.js +32 -54
  48. package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
  49. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js +12 -29
  50. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js.map +2 -2
  51. package/dist/modules/notifications/backend/profile/notification-preferences/page.meta.js +2 -2
  52. package/dist/modules/notifications/backend/profile/notification-preferences/page.meta.js.map +1 -1
  53. package/dist/modules/progress/lib/progressServiceImpl.js +14 -3
  54. package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
  55. package/dist/modules/sales/backend/sales/documents/[id]/page.js +9 -9
  56. package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
  57. package/dist/modules/sales/components/documents/LineItemDialog.js +50 -10
  58. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  59. package/dist/modules/sales/components/documents/PaymentsSection.js +8 -3
  60. package/dist/modules/sales/components/documents/PaymentsSection.js.map +2 -2
  61. package/dist/modules/sales/components/documents/ReturnEditDialog.js +2 -7
  62. package/dist/modules/sales/components/documents/ReturnEditDialog.js.map +2 -2
  63. package/dist/modules/sales/components/documents/ReturnsSection.js +2 -7
  64. package/dist/modules/sales/components/documents/ReturnsSection.js.map +2 -2
  65. package/dist/modules/sales/components/documents/ShipmentsSection.js +3 -8
  66. package/dist/modules/sales/components/documents/ShipmentsSection.js.map +2 -2
  67. package/dist/modules/wms/commands/sales-order-assignment.js +12 -0
  68. package/dist/modules/wms/commands/sales-order-assignment.js.map +2 -2
  69. package/dist/modules/wms/data/enrichers.js +25 -0
  70. package/dist/modules/wms/data/enrichers.js.map +2 -2
  71. package/dist/modules/wms/lib/enricherCacheTags.js +9 -0
  72. package/dist/modules/wms/lib/enricherCacheTags.js.map +7 -0
  73. package/dist/modules/wms/lib/invalidateInventoryEnricherCache.js +37 -0
  74. package/dist/modules/wms/lib/invalidateInventoryEnricherCache.js.map +7 -0
  75. package/dist/modules/wms/lib/inventoryEnricherCacheSubscriber.js +14 -0
  76. package/dist/modules/wms/lib/inventoryEnricherCacheSubscriber.js.map +7 -0
  77. package/dist/modules/wms/subscribers/invalidate-enricher-cache-balance.js +12 -0
  78. package/dist/modules/wms/subscribers/invalidate-enricher-cache-balance.js.map +7 -0
  79. package/dist/modules/wms/subscribers/invalidate-enricher-cache-inventory.js +12 -0
  80. package/dist/modules/wms/subscribers/invalidate-enricher-cache-inventory.js.map +7 -0
  81. package/dist/modules/wms/subscribers/invalidate-enricher-cache-movement.js +12 -0
  82. package/dist/modules/wms/subscribers/invalidate-enricher-cache-movement.js.map +7 -0
  83. package/dist/modules/wms/subscribers/invalidate-enricher-cache-profile.js +12 -0
  84. package/dist/modules/wms/subscribers/invalidate-enricher-cache-profile.js.map +7 -0
  85. package/dist/modules/wms/subscribers/invalidate-enricher-cache-reservation.js +12 -0
  86. package/dist/modules/wms/subscribers/invalidate-enricher-cache-reservation.js.map +7 -0
  87. package/dist/modules/wms/subscribers/invalidate-enricher-cache-sales-line.js +12 -0
  88. package/dist/modules/wms/subscribers/invalidate-enricher-cache-sales-line.js.map +7 -0
  89. package/dist/modules/wms/subscribers/invalidate-enricher-cache-sales-order.js +12 -0
  90. package/dist/modules/wms/subscribers/invalidate-enricher-cache-sales-order.js.map +7 -0
  91. package/dist/modules/wms/subscribers/invalidate-enricher-cache-variant.js +12 -0
  92. package/dist/modules/wms/subscribers/invalidate-enricher-cache-variant.js.map +7 -0
  93. package/dist/modules/wms/subscribers/invalidate-enricher-cache-warehouse.js +12 -0
  94. package/dist/modules/wms/subscribers/invalidate-enricher-cache-warehouse.js.map +7 -0
  95. package/package.json +7 -7
  96. package/src/modules/auth/commands/users.ts +14 -1
  97. package/src/modules/auth/data/entities.ts +2 -2
  98. package/src/modules/auth/lib/backendChrome.tsx +46 -2
  99. package/src/modules/auth/lib/profile-sections.tsx +14 -3
  100. package/src/modules/auth/migrations/.snapshot-open-mercato.json +4 -2
  101. package/src/modules/auth/migrations/Migration20260907120000_auth.ts +21 -0
  102. package/src/modules/communication_channels/backend/profile/communication-channels/page.meta.ts +2 -2
  103. package/src/modules/customer_accounts/AGENTS.md +3 -1
  104. package/src/modules/customer_accounts/api/admin/demo-accounts.ts +149 -0
  105. package/src/modules/customer_accounts/api/invitations/accept.ts +23 -6
  106. package/src/modules/customer_accounts/backend/customer_accounts/settings/CustomerAccountsSettingsPageClient.tsx +43 -41
  107. package/src/modules/customer_accounts/backend/customer_accounts/useDemoPortalAccounts.ts +42 -0
  108. package/src/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.tsx +10 -3
  109. package/src/modules/customer_accounts/data/entities.ts +5 -1
  110. package/src/modules/customer_accounts/i18n/de.json +4 -2
  111. package/src/modules/customer_accounts/i18n/en.json +4 -2
  112. package/src/modules/customer_accounts/i18n/es.json +4 -2
  113. package/src/modules/customer_accounts/i18n/ko.json +4 -2
  114. package/src/modules/customer_accounts/i18n/pl.json +4 -2
  115. package/src/modules/customer_accounts/lib/exampleAccounts.ts +18 -0
  116. package/src/modules/customer_accounts/migrations/.snapshot-open-mercato.json +5 -7
  117. package/src/modules/customer_accounts/migrations/Migration20260827160000_customer_accounts.ts +23 -0
  118. package/src/modules/customer_accounts/services/customerInvitationService.ts +89 -5
  119. package/src/modules/customer_accounts/setup.ts +2 -6
  120. package/src/modules/customer_accounts/widgets/injection/account-status/widget.client.tsx +74 -41
  121. package/src/modules/customers/commands/people.ts +15 -0
  122. package/src/modules/data_sync/backend/data-sync/runs/[id]/page.tsx +19 -44
  123. package/src/modules/entities/api/records.ts +24 -15
  124. package/src/modules/entities/lib/scoped-field-defs.ts +76 -0
  125. package/src/modules/entities/lib/validation.ts +5 -45
  126. package/src/modules/integrations/backend/integrations/[id]/page.tsx +33 -62
  127. package/src/modules/integrations/backend/integrations/bundle/[id]/page.tsx +13 -37
  128. package/src/modules/notifications/backend/profile/notification-preferences/page.meta.ts +2 -2
  129. package/src/modules/progress/AGENTS.md +1 -1
  130. package/src/modules/progress/lib/progressServiceImpl.ts +26 -3
  131. package/src/modules/sales/backend/sales/documents/[id]/page.tsx +19 -25
  132. package/src/modules/sales/components/documents/LineItemDialog.tsx +53 -9
  133. package/src/modules/sales/components/documents/PaymentsSection.tsx +8 -8
  134. package/src/modules/sales/components/documents/ReturnEditDialog.tsx +2 -8
  135. package/src/modules/sales/components/documents/ReturnsSection.tsx +8 -7
  136. package/src/modules/sales/components/documents/ShipmentsSection.tsx +9 -8
  137. package/src/modules/sales/i18n/de.json +2 -0
  138. package/src/modules/sales/i18n/en.json +2 -0
  139. package/src/modules/sales/i18n/es.json +2 -0
  140. package/src/modules/sales/i18n/ko.json +2 -0
  141. package/src/modules/sales/i18n/pl.json +2 -0
  142. package/src/modules/wms/commands/sales-order-assignment.ts +20 -0
  143. package/src/modules/wms/data/enrichers.ts +25 -0
  144. package/src/modules/wms/lib/enricherCacheTags.ts +29 -0
  145. package/src/modules/wms/lib/invalidateInventoryEnricherCache.ts +71 -0
  146. package/src/modules/wms/lib/inventoryEnricherCacheSubscriber.ts +30 -0
  147. package/src/modules/wms/subscribers/invalidate-enricher-cache-balance.ts +9 -0
  148. package/src/modules/wms/subscribers/invalidate-enricher-cache-inventory.ts +9 -0
  149. package/src/modules/wms/subscribers/invalidate-enricher-cache-movement.ts +9 -0
  150. package/src/modules/wms/subscribers/invalidate-enricher-cache-profile.ts +9 -0
  151. package/src/modules/wms/subscribers/invalidate-enricher-cache-reservation.ts +9 -0
  152. package/src/modules/wms/subscribers/invalidate-enricher-cache-sales-line.ts +14 -0
  153. package/src/modules/wms/subscribers/invalidate-enricher-cache-sales-order.ts +18 -0
  154. package/src/modules/wms/subscribers/invalidate-enricher-cache-variant.ts +9 -0
  155. package/src/modules/wms/subscribers/invalidate-enricher-cache-warehouse.ts +9 -0
@@ -1,4 +1,4 @@
1
- [build:core] found 4388 entry points
1
+ [build:core] found 4409 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 218 entry points
4
4
  [build:core:generated] built successfully
package/AGENTS.md CHANGED
@@ -657,7 +657,7 @@ Run `yarn generate` or rely on `predev`/`prebuild`.
657
657
 
658
658
  ## Response Enrichers
659
659
 
660
- Response enrichers let a module add computed fields to another module's CRUD API responses (similar to GraphQL Federation).
660
+ Response enrichers add computed fields to other modules' CRUD API responses.
661
661
 
662
662
  ### Creating an Enricher
663
663
 
@@ -668,7 +668,7 @@ import type { ResponseEnricher } from '@open-mercato/shared/lib/crud/response-en
668
668
 
669
669
  const myEnricher: ResponseEnricher = {
670
670
  id: 'mymodule.customer-metrics',
671
- targetEntity: 'customers.person', // entity to enrich
671
+ targetEntity: 'customers.person', // use '*' for all; context.targetEntity stays concrete
672
672
  features: ['mymodule.view'], // required ACL features
673
673
  priority: 10, // higher runs first
674
674
  timeout: 2000, // ms, default 2000
@@ -10,7 +10,16 @@ import {
10
10
  import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
11
11
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
12
12
  import { UniqueConstraintViolationException, LockMode } from "@mikro-orm/core";
13
- import { User, UserRole, Role, UserAcl, Session, PasswordReset } from "@open-mercato/core/modules/auth/data/entities";
13
+ import {
14
+ User,
15
+ UserRole,
16
+ Role,
17
+ UserAcl,
18
+ Session,
19
+ PasswordReset,
20
+ UserSidebarPreference,
21
+ SidebarVariant
22
+ } from "@open-mercato/core/modules/auth/data/entities";
14
23
  import { Organization } from "@open-mercato/core/modules/directory/data/entities";
15
24
  import { resolveOrganizationScope } from "@open-mercato/core/modules/directory/utils/organizationScope";
16
25
  import { E } from "../../../generated/entities.ids.generated.js";
@@ -271,6 +280,8 @@ const createUserCommand = {
271
280
  await em.nativeDelete(UserRole, { user: userId });
272
281
  await em.nativeDelete(Session, { user: userId });
273
282
  await em.nativeDelete(PasswordReset, { user: userId });
283
+ await em.nativeDelete(UserSidebarPreference, { user: userId });
284
+ await em.nativeDelete(SidebarVariant, { user: userId });
274
285
  if (snapshot?.custom && Object.keys(snapshot.custom).length) {
275
286
  const reset = buildCustomFieldResetMap(void 0, snapshot.custom);
276
287
  if (Object.keys(reset).length) {
@@ -774,6 +785,8 @@ const deleteUserCommand = {
774
785
  await em.nativeDelete(UserRole, { user: id });
775
786
  await em.nativeDelete(Session, { user: id });
776
787
  await em.nativeDelete(PasswordReset, { user: id });
788
+ await em.nativeDelete(UserSidebarPreference, { user: id });
789
+ await em.nativeDelete(SidebarVariant, { user: id });
777
790
  const removed = await de.deleteOrmEntity({
778
791
  entity: User,
779
792
  where: deleteWhere,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/commands/users.ts"],
4
- "sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n buildChanges,\n requireId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudEventsConfig, CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { UniqueConstraintViolationException, LockMode } from '@mikro-orm/core'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { User, UserRole, Role, UserAcl, Session, PasswordReset } from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { resolveOrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { E } from '#generated/entities.ids.generated'\nimport { z } from 'zod'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n diffCustomFieldChanges,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { normalizeTenantId } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport InviteUserEmail from '@open-mercato/core/modules/auth/emails/InviteUserEmail'\nimport { INVITE_TOKEN_TTL_MS } from '@open-mercato/core/modules/auth/lib/inviteToken'\nimport { getSecurityEmailBaseUrl } from '@open-mercato/shared/lib/url'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { normalizeDisplayNameInput } from '@open-mercato/core/modules/auth/lib/displayName'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n assertActorCanAssignUserDestination,\n resolveUserDestinationRoles,\n throwUserDestinationOrganizationNotFound,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('auth').child({ component: 'users-commands' })\n\ntype SerializedUser = {\n email: string\n organizationId: string | null\n tenantId: string | null\n roles: string[]\n name: string | null\n isConfirmed: boolean\n custom?: Record<string, unknown>\n}\n\ntype UserAclSnapshot = {\n tenantId: string\n features: string[] | null\n isSuperAdmin: boolean\n organizations: string[] | null\n}\n\ntype UserUndoSnapshot = {\n id: string\n email: string\n organizationId: string | null\n tenantId: string | null\n passwordHash: string | null\n name: string | null\n isConfirmed: boolean\n roles: string[]\n acls: UserAclSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype UserSnapshots = {\n view: SerializedUser\n undo: UserUndoSnapshot\n}\n\nfunction resolveActorTenantScope(ctx: CommandRuntimeContext): string | null {\n if (ctx.systemActor === true) return null\n const auth = ctx.auth\n if (!auth) return null\n if ((auth as { isSuperAdmin?: boolean }).isSuperAdmin === true) return null\n const actorTenantId = normalizeTenantId(auth.tenantId ?? null) ?? null\n return actorTenantId\n}\n\nfunction assertTargetTenantInScope(actorTenantScope: string | null, targetTenantId: unknown, notFoundError: string): void {\n if (!actorTenantScope) return\n const targetTenant = normalizeTenantId(targetTenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) {\n throw new CrudHttpError(404, { error: notFoundError })\n }\n}\n\nconst passwordSchema = buildPasswordSchema()\n\nconst displayNameSchema = z.preprocess(\n normalizeDisplayNameInput,\n z.string().trim().min(1).max(120).nullable().optional(),\n)\n\nconst createSchema = z.object({\n email: z.string().email(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n sendInviteEmail: z.boolean().optional(),\n organizationId: z.string().uuid(),\n roles: z.array(z.string()).optional(),\n}).refine(\n (data) => data.password || data.sendInviteEmail,\n { message: 'Either password or sendInviteEmail is required', path: ['password'] },\n)\n\nconst updateSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email().optional(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n organizationId: z.string().uuid().optional(),\n roles: z.array(z.string()).optional(),\n isConfirmed: z.boolean().optional(),\n})\n\nexport const userCrudEvents: CrudEventsConfig = {\n module: 'auth',\n entity: 'user',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nexport const userCrudIndexer: CrudIndexerConfig = {\n entityType: E.auth.user,\n buildUpsertPayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n buildDeletePayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nasync function notifyRoleChanges(\n ctx: CommandRuntimeContext,\n user: User,\n assignedRoles: string[],\n revokedRoles: string[],\n): Promise<void> {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (!tenantId) return\n const organizationId = user.organizationId ? String(user.organizationId) : null\n\n try {\n const notificationService = resolveNotificationService(ctx.container)\n if (assignedRoles.length) {\n const assignedType = notificationTypes.find((type) => type.type === 'auth.role.assigned')\n if (assignedType) {\n const notificationInput = buildNotificationFromType(assignedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n\n if (revokedRoles.length) {\n const revokedType = notificationTypes.find((type) => type.type === 'auth.role.revoked')\n if (revokedType) {\n const notificationInput = buildNotificationFromType(revokedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n}\n\ntype CreateUserResult = { user: User; warning?: 'invite_email_failed' }\n\nconst createUserCommand: CommandHandler<Record<string, unknown>, CreateUserResult> = {\n id: 'auth.users.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(createSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId },\n )\n if (!organization) throw new CrudHttpError(400, { error: 'Organization not found' })\n const tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n assertTargetTenantInScope(resolveActorTenantScope(ctx), tenantId, 'Organization not found')\n\n const emailHash = computeEmailHash(parsed.email)\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq). Scope the duplicate check to the target tenant so the same\n // email may legitimately exist in other tenants without blocking creation or leaking\n // cross-tenant account existence (#2934).\n const duplicate = await findOneWithDecryption(em, User, { $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }], deletedAt: null, tenantId } as any, {}, { tenantId: null, organizationId: null })\n if (duplicate) await throwDuplicateEmailError()\n\n let passwordHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n passwordHash = await hash(parsed.password, 10)\n }\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user: User\n try {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n email: parsed.email,\n name: parsed.name,\n emailHash,\n passwordHash,\n isConfirmed: true,\n organizationId: parsed.organizationId,\n tenantId,\n },\n })\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n\n let assignedRoles: string[] = []\n if (Array.isArray(parsed.roles) && parsed.roles.length) {\n await syncUserRoles(em, user, parsed.roles, tenantId)\n assignedRoles = await loadUserRoleNames(em, String(user.id))\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: tenantId,\n values: custom,\n })\n\n let inviteEmailSent = false\n if (parsed.sendInviteEmail) {\n const inviteResult = await sendInviteToUser(em, user)\n inviteEmailSent = inviteResult.emailSent\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (assignedRoles.length && !parsed.sendInviteEmail) {\n await notifyRoleChanges(ctx, user, assignedRoles, [])\n }\n\n const warning = (parsed.sendInviteEmail && !inviteEmailSent) ? 'invite_email_failed' as const : undefined\n\n return { user, warning }\n },\n captureAfter: async (_input, { user }, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n return serializeUser(user, roles, custom)\n },\n buildLog: async ({ result: { user }, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n const snapshot = captureUserSnapshots(user, roles, undefined, custom)\n return {\n actionLabel: translate('auth.audit.users.create', 'Create user'),\n resourceKind: 'auth.user',\n resourceId: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n snapshotAfter: snapshot.view,\n payload: {\n undo: {\n after: snapshot.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const userId = typeof logEntry?.resourceId === 'string' ? logEntry.resourceId : null\n if (!userId) return\n const snapshot = logEntry?.snapshotAfter as SerializedUser | undefined\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Evaluate the floor against the user's CURRENT tenant, not the one recorded at\n // creation. A user moved to another tenant after being created would otherwise be\n // checked against the origin tenant \u2014 where they no longer hold anything \u2014 and the\n // undo would hard-delete the destination tenant's last administrator unchecked.\n // The create snapshot is only a fallback for a row that is already gone.\n let removed: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const floorTenantId = current?.tenantId ? String(current.tenantId) : (snapshot?.tenantId ?? null)\n\n // Undoing a create hard-deletes the user, so it can strip a tenant's last active\n // admin exactly like `auth.users.delete` can \u2014 promote a second admin, delete the\n // first, then undo the promotion's create. Same guard applies.\n await enforceProtectedRoleFloor(em, floorTenantId, userId, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: userId })\n await em.nativeDelete(UserRole, { user: userId })\n await em.nativeDelete(Session, { user: userId })\n await em.nativeDelete(PasswordReset, { user: userId })\n\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const reset = buildCustomFieldResetMap(undefined, snapshot.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: userId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: reset,\n notify: false,\n })\n }\n }\n removed = await de.deleteOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n soft: false,\n })\n },\n ], { transaction: true, label: 'auth.users.create.undo' })\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: removed,\n identifiers: {\n id: userId,\n organizationId: snapshot?.organizationId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n // The create-undo hard-deletes the user, but the after-snapshot persists the\n // original passwordHash (see captureUserSnapshots), so redo restores the row\n // with the SAME id and the SAME hash \u2014 never fabricating credentials (#2506).\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<UserUndoSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for user create' })\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const emailHash = computeEmailHash(after.email)\n\n let user = await findOneWithDecryption(em, User, { id: after.id }, {}, { tenantId: null, organizationId: null })\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n user.deletedAt = null\n user.email = after.email\n user.emailHash = emailHash\n user.organizationId = after.organizationId ?? null\n user.tenantId = after.tenantId ?? null\n user.passwordHash = after.passwordHash ?? null\n user.name = after.name ?? null\n user.isConfirmed = after.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: after.id,\n email: after.email,\n emailHash,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n passwordHash: after.passwordHash ?? null,\n name: after.name ?? null,\n isConfirmed: after.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: after.id })\n await syncUserRoles(em, user, after.roles, after.tenantId)\n await restoreUserAcls(em, user, after.acls)\n\n if (after.custom && Object.keys(after.custom).length) {\n const reset = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n }\n },\n ], { transaction: true })\n\n if (!user) throw new CrudHttpError(400, { error: '[internal] redo failed to restore user row' })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, after.id)\n\n return { user }\n },\n}\n\nasync function sendInviteToUser(\n em: EntityManager,\n user: User,\n): Promise<{ emailSent: boolean }> {\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + INVITE_TOKEN_TTL_MS)\n const row = em.create(PasswordReset, { user, token: tokenHash, expiresAt, createdAt: new Date() })\n await em.persist(row).flush()\n\n const base = getSecurityEmailBaseUrl()\n const inviteUrl = `${base}/reset/${rawToken}`\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.invite.subject', 'You have been invited')\n const copy = {\n preview: translate('auth.email.invite.preview', 'Set up your account'),\n title: translate('auth.email.invite.title', 'You have been invited'),\n body: translate('auth.email.invite.body', 'An administrator has created an account for you. Click the link below to set your password. This link will expire in 48 hours.'),\n cta: translate('auth.email.invite.cta', 'Set up your password'),\n hint: translate('auth.email.invite.hint', 'If you did not expect this invitation, you can safely ignore this email.'),\n }\n\n let emailSent = true\n try {\n await sendEmail({\n to: user.email,\n subject,\n react: InviteUserEmail({ inviteUrl, copy }),\n tenantId: user.tenantId ? String(user.tenantId) : undefined,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n } catch (err) {\n logger.error('Failed to send invitation email', { err })\n emailSent = false\n }\n\n return { emailSent }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const code = (error as { code?: string }).code\n if (code === '23505') return true\n const messageRaw = (error as { message?: string })?.message\n const message = typeof messageRaw === 'string' ? messageRaw : ''\n return message.toLowerCase().includes('duplicate key')\n}\n\nconst updateUserCommand: CommandHandler<Record<string, unknown>, User> = {\n id: 'auth.users.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n assertTargetTenantInScope(resolveActorTenantScope(ctx), existing.tenantId, 'User not found')\n const roles = await loadUserRoleNames(em, parsed.id)\n const acls = await loadUserAclSnapshots(em, parsed.id)\n const custom = await loadUserCustomSnapshot(\n em,\n parsed.id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const actorTenantScope = resolveActorTenantScope(ctx)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const rolesBefore = Array.isArray(parsed.roles)\n ? await loadUserRoleNames(em, parsed.id)\n : null\n\n let tenantId: string | null | undefined\n let destinationChanged = false\n if (parsed.organizationId !== undefined) {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId ?? null },\n )\n if (!organization) return throwUserDestinationOrganizationNotFound(400)\n tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n if (!tenantId) return throwUserDestinationOrganizationNotFound(400)\n const currentUser = await findOneWithDecryption(\n em,\n User,\n { id: parsed.id, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!currentUser) throw new CrudHttpError(404, { error: 'User not found' })\n const currentOrganizationId = currentUser.organizationId ? String(currentUser.organizationId) : null\n const currentTenantId = currentUser.tenantId ? String(currentUser.tenantId) : null\n destinationChanged = currentOrganizationId !== parsed.organizationId || currentTenantId !== tenantId\n if (destinationChanged) {\n const rbacService = ctx.container.resolve('rbacService') as RbacService\n const destinationRoles = await resolveUserDestinationRoles({\n em,\n targetUserId: parsed.id,\n destinationTenantId: tenantId,\n roleTokens: parsed.roles,\n })\n const actorIsSuperAdmin = ctx.systemActor === true || ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope?.tenantId === tenantId\n ? ctx.organizationScope\n : !actorIsSuperAdmin && ctx.auth?.sub\n ? await resolveOrganizationScope({\n em,\n rbac: rbacService,\n auth: ctx.auth,\n tenantId,\n })\n : null\n await assertActorCanAssignUserDestination({\n em,\n rbacService,\n actorUserId: ctx.auth?.sub,\n actorIsSuperAdmin,\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n allowedOrganizationIds: organizationScope?.allowedIds,\n destinationTenantId: tenantId,\n destinationOrganizationId: parsed.organizationId,\n roles: destinationRoles,\n })\n }\n }\n\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n const targetTenantId = tenantId !== undefined ? tenantId : userTenantId\n const isTenantChanging = targetTenantId !== userTenantId\n\n // Hash password BEFORE transaction begins to avoid holding locks during CPU-heavy tasks\n let hashed: string | null = null\n let emailHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n hashed = await hash(parsed.password, 10)\n }\n if (parsed.email !== undefined) {\n emailHash = computeEmailHash(parsed.email)\n }\n\n const updateWhere: Record<string, unknown> = { id: parsed.id, deletedAt: null }\n if (actorTenantScope) updateWhere.tenantId = actorTenantScope\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user!: User\n\n await withAtomicFlush(em, [\n async () => {\n // Floor check must run inside the transaction so that LockMode.PESSIMISTIC_WRITE locks Role rows properly\n await enforceProtectedRoleFloor(em, userTenantId, parsed.id, {\n deactivating: parsed.isConfirmed === false || isTenantChanging,\n newRoles: parsed.roles,\n }, ctx)\n\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq) \u2014 a matching email in another tenant must not block\n // the update or leak cross-tenant account existence (#2934). `targetTenantId` is the\n // tenant the user will belong to after this update, so the check follows a move.\n if (parsed.email !== undefined) {\n const duplicate = await findOneWithDecryption(\n em,\n User,\n {\n $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }],\n deletedAt: null,\n tenantId: targetTenantId,\n id: { $ne: parsed.id } as any,\n } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n if (duplicate) await throwDuplicateEmailError()\n }\n\n try {\n const updated = await de.updateOrmEntity({\n entity: User,\n where: updateWhere as FilterQuery<User>,\n apply: (entity) => {\n if (parsed.email !== undefined) {\n entity.email = parsed.email\n entity.emailHash = emailHash\n }\n if (parsed.name !== undefined) {\n entity.name = parsed.name\n }\n if (parsed.organizationId !== undefined) {\n entity.organizationId = parsed.organizationId\n entity.tenantId = tenantId ?? null\n }\n if (parsed.isConfirmed !== undefined) {\n entity.isConfirmed = parsed.isConfirmed\n }\n if (hashed) entity.passwordHash = hashed\n },\n })\n if (updated) user = updated\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n if (!user) throw new CrudHttpError(404, { error: 'User not found' })\n\n if (hashed || parsed.isConfirmed === false) {\n await em.nativeDelete(Session, { user: parsed.id })\n }\n\n if (Array.isArray(parsed.roles)) {\n await syncUserRoles(em, user, parsed.roles, user.tenantId ? String(user.tenantId) : tenantId ?? null)\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n values: custom,\n })\n }\n ], { transaction: true, label: destinationChanged ? 'auth.users.update.destination' : 'auth.users.update' })\n\n const identifiers = {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: user,\n identifiers,\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (hashed) {\n const actorId = ctx.auth?.sub ? String(ctx.auth.sub) : null\n // `system` covers a command invocation with no auth context and one running under\n // `ctx.systemActor`. Without it those writes would be indistinguishable from an\n // administrator setting someone else's password, which is exactly the case security\n // alerting escalates on. Password writes that never reach this command \u2014 `mercato\n // auth set-password`, tenant provisioning \u2014 set `passwordHash` directly and emit\n // nothing, so a subscriber cannot treat this event as covering every credential change.\n const changedBy = ctx.systemActor === true || !actorId\n ? 'system'\n : actorId === identifiers.id ? 'self' : 'admin'\n void emitAuthEvent('auth.password.changed', {\n id: identifiers.id,\n tenantId: identifiers.tenantId,\n organizationId: identifiers.organizationId,\n changedBy,\n changedById: actorId,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n\n if (Array.isArray(parsed.roles) && rolesBefore) {\n const rolesAfter = await loadUserRoleNames(em, String(user.id))\n const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter)\n if (assigned.length || revoked.length) {\n await notifyRoleChanges(ctx, user, assigned, revoked)\n }\n }\n\n await invalidateUserCache(ctx, parsed.id)\n\n return user\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(result.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n return serializeUser(result, roles, custom)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterRoles = await loadUserRoleNames(em, String(result.id))\n const afterCustom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n const afterSnapshots = captureUserSnapshots(result, afterRoles, undefined, afterCustom)\n const after = afterSnapshots.view\n const changes = buildChanges(before ?? null, after as Record<string, unknown>, ['email', 'organizationId', 'tenantId', 'name', 'isConfirmed'])\n if (before && !arrayEquals(before.roles, afterRoles)) {\n changes.roles = { from: before.roles, to: afterRoles }\n }\n const customDiff = diffCustomFieldChanges(before?.custom, afterCustom)\n for (const [key, diff] of Object.entries(customDiff)) {\n changes[`cf_${key}`] = diff\n }\n return {\n actionLabel: translate('auth.audit.users.update', 'Update user'),\n resourceKind: 'auth.user',\n resourceId: String(result.id),\n tenantId: result.tenantId ? String(result.tenantId) : null,\n organizationId: result.organizationId ? String(result.organizationId) : null,\n changes,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: {\n before: beforeUndo,\n after: afterSnapshots.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n const after = payload?.after\n if (!before) return\n const userId = before.id\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Reverting an update can drop the tenant below a protected role's floor just as the\n // forward path can \u2014 restoring an empty `before.roles` on what is now the last admin,\n // or restoring `isConfirmed: false`. Undo is reachable from the audit-log UI, so the\n // guard has to run here too, inside a transaction so the row lock is valid.\n const restoredTenantId = before.tenantId ? String(before.tenantId) : null\n\n let updated: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const currentTenantId = current?.tenantId ? String(current.tenantId) : null\n\n await enforceProtectedRoleFloor(em, currentTenantId, userId, {\n deactivating: before.isConfirmed === false || restoredTenantId !== currentTenantId,\n newRoles: before.roles,\n }, ctx)\n\n updated = await de.updateOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n apply: (entity) => {\n entity.email = before.email\n entity.organizationId = before.organizationId ?? null\n entity.tenantId = before.tenantId ?? null\n entity.passwordHash = before.passwordHash ?? null\n entity.name = before.name ?? null\n entity.isConfirmed = before.isConfirmed\n },\n })\n\n if (updated) {\n await syncUserRoles(em, updated, before.roles, before.tenantId)\n }\n },\n ], { transaction: true, label: 'auth.users.update.undo' })\n\n const reset = buildCustomFieldResetMap(before.custom, after?.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: updated,\n identifiers: {\n id: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n}\n\nconst deleteUserCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, User> = {\n id: 'auth.users.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) return {}\n const actorTenantScope = resolveActorTenantScope(ctx)\n if (actorTenantScope) {\n const targetTenant = normalizeTenantId(existing.tenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) return {}\n }\n const roles = await loadUserRoleNames(em, id)\n const acls = await loadUserAclSnapshots(em, id)\n const custom = await loadUserCustomSnapshot(\n em,\n id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const actorTenantScope = resolveActorTenantScope(ctx)\n\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const deleteWhere: Record<string, unknown> = { id, deletedAt: null }\n if (actorTenantScope) deleteWhere.tenantId = actorTenantScope\n\n let user!: User\n await withAtomicFlush(em, [\n async () => {\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n await enforceProtectedRoleFloor(em, userTenantId, id, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: id })\n await em.nativeDelete(UserRole, { user: id })\n await em.nativeDelete(Session, { user: id })\n await em.nativeDelete(PasswordReset, { user: id })\n const removed = await de.deleteOrmEntity({\n entity: User,\n where: deleteWhere as FilterQuery<User>,\n soft: false,\n })\n if (!removed) throw new CrudHttpError(404, { error: 'User not found' })\n user = removed\n },\n ], { transaction: true })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: user,\n identifiers: {\n id: String(id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, id)\n\n return user\n },\n buildLog: async ({ snapshots, input, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const id = requireId(input, 'User id required')\n return {\n actionLabel: translate('auth.audit.users.delete', 'Delete user'),\n resourceKind: 'auth.user',\n resourceId: id,\n snapshotBefore: before ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n payload: {\n undo: {\n before: beforeUndo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager)\n let user = await findOneWithDecryption(em, User, { id: before.id }, {}, { tenantId: null, organizationId: null })\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n if (user.deletedAt) {\n user.deletedAt = null\n }\n user.email = before.email\n user.organizationId = before.organizationId ?? null\n user.tenantId = before.tenantId ?? null\n user.passwordHash = before.passwordHash ?? null\n user.name = before.name ?? null\n user.isConfirmed = before.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: before.id,\n email: before.email,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n passwordHash: before.passwordHash ?? null,\n name: before.name ?? null,\n isConfirmed: before.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: before.id })\n await syncUserRoles(em, user, before.roles, before.tenantId)\n\n await restoreUserAcls(em, user, before.acls)\n\n const reset = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n },\n ], { transaction: true })\n\n await invalidateUserCache(ctx, before.id)\n },\n}\n\nregisterCommand(createUserCommand)\nregisterCommand(updateUserCommand)\nregisterCommand(deleteUserCommand)\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nasync function resolveRole(\n em: EntityManager,\n value: string,\n normalizedTenantId: string | null,\n): Promise<Role | null> {\n if (UUID_RE.test(value)) {\n const where: Record<string, unknown> = { id: value }\n if (normalizedTenantId !== null) {\n where.tenantId = normalizedTenantId\n }\n return findOneWithDecryption(em, Role, where as any, {}, { tenantId: normalizedTenantId, organizationId: null })\n }\n return findOneWithDecryption(em, Role, { name: value, tenantId: normalizedTenantId }, {}, { tenantId: normalizedTenantId, organizationId: null })\n}\n\nasync function syncUserRoles(em: EntityManager, user: User, desiredRoles: string[], tenantId: string | null) {\n const unique = Array.from(new Set(desiredRoles.map((role) => role.trim()).filter(Boolean)))\n const normalizedTenantId = normalizeTenantId(tenantId ?? null) ?? null\n\n const resolvedRoles: Role[] = []\n const missingRoles: string[] = []\n for (const value of unique) {\n const role = await resolveRole(em, value, normalizedTenantId)\n if (!role) {\n missingRoles.push(value)\n } else {\n resolvedRoles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((n) => `\"${n}\"`).join(', ')\n throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })\n }\n\n const desiredIds = new Set(resolvedRoles.map((r) => String(r.id)))\n const currentLinks = await findWithDecryption(em, UserRole, { user }, {}, { tenantId: null, organizationId: null })\n const currentRoleIds = new Map(\n currentLinks.map((link) => {\n const roleId = String(link.role?.id ?? (link.role as unknown as string) ?? '')\n return [roleId, link] as const\n }),\n )\n\n for (const [roleId, link] of currentRoleIds.entries()) {\n if (!desiredIds.has(roleId) && link) {\n em.remove(link)\n }\n }\n\n for (const role of resolvedRoles) {\n if (!currentRoleIds.has(String(role.id))) {\n em.persist(em.create(UserRole, { user, role, createdAt: new Date() }))\n }\n }\n\n await em.flush()\n}\n\nasync function loadUserRoleNames(em: EntityManager, userId: string): Promise<string[]> {\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as unknown as User },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const names = links\n .map((link) => link.role?.name ?? '')\n .filter((name): name is string => !!name)\n return Array.from(new Set(names)).sort((a, b) => a.localeCompare(b))\n}\n\nfunction serializeUser(user: User, roles: string[], custom?: Record<string, unknown> | null): SerializedUser {\n const payload: SerializedUser = {\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n roles,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n }\n if (custom && Object.keys(custom).length) payload.custom = custom\n return payload\n}\n\nfunction captureUserSnapshots(\n user: User,\n roles: string[],\n acls: UserAclSnapshot[] = [],\n custom?: Record<string, unknown> | null\n): UserSnapshots {\n return {\n view: serializeUser(user, roles, custom),\n undo: {\n id: String(user.id),\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n passwordHash: user.passwordHash ? String(user.passwordHash) : null,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n roles: [...roles],\n acls,\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n },\n }\n}\n\nasync function loadUserAclSnapshots(em: EntityManager, userId: string): Promise<UserAclSnapshot[]> {\n const list = await findWithDecryption(em, UserAcl, { user: userId as unknown as User }, {}, { tenantId: null, organizationId: null })\n return list.map((acl) => ({\n tenantId: String(acl.tenantId),\n features: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n isSuperAdmin: Boolean(acl.isSuperAdmin),\n organizations: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }))\n}\n\nasync function restoreUserAcls(em: EntityManager, user: User, acls: UserAclSnapshot[]) {\n await em.nativeDelete(UserAcl, { user: String(user.id) })\n for (const acl of acls) {\n const entity = em.create(UserAcl, {\n user,\n tenantId: acl.tenantId,\n featuresJson: acl.features ?? null,\n isSuperAdmin: acl.isSuperAdmin,\n organizationsJson: acl.organizations ?? null,\n createdAt: new Date(),\n })\n em.persist(entity)\n }\n await em.flush()\n}\n\nasync function loadUserCustomSnapshot(\n em: EntityManager,\n id: string,\n tenantId: string | null,\n organizationId: string | null\n): Promise<Record<string, unknown>> {\n return await loadCustomFieldSnapshot(em, {\n entityId: E.auth.user,\n recordId: id,\n tenantId,\n organizationId,\n })\n}\n\nasync function invalidateUserCache(ctx: CommandRuntimeContext, userId: string) {\n try {\n const rbacService = ctx.container.resolve('rbacService') as { invalidateUserCache: (uid: string) => Promise<void> }\n await rbacService.invalidateUserCache(userId)\n } catch {\n // RBAC not available\n }\n\n try {\n const cache = ctx.container.resolve('cache') as { deleteByTags?: (tags: string[]) => Promise<void> }\n if (cache?.deleteByTags) await cache.deleteByTags([`rbac:user:${userId}`])\n } catch {\n // cache not available\n }\n}\n\nfunction diffRoleChanges(before: string[], after: string[]) {\n const beforeSet = new Set(before)\n const afterSet = new Set(after)\n const assigned = after.filter((role) => !beforeSet.has(role))\n const revoked = before.filter((role) => !afterSet.has(role))\n return { assigned, revoked }\n}\n\nfunction arrayEquals(left: string[] | undefined, right: string[]): boolean {\n if (!left) return false\n if (left.length !== right.length) return false\n return left.every((value, idx) => value === right[idx])\n}\n\nasync function throwDuplicateEmailError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('auth.users.errors.emailExists', 'Email already in use')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { email: message },\n details: [{ path: ['email'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\ntype ProtectedRoleFloorOptions = {\n deactivating?: boolean\n newRoles?: string[]\n deleting?: boolean\n}\n\n/**\n * True when the requested mutation can lower a role's active holder count. Guards the\n * floor check so that ordinary edits (display name, password, email) never take the\n * tenant-wide role lock \u2014 `PUT /api/auth/profile` routes every self-service password\n * change through `auth.users.update`, so an unconditional lock would serialize them.\n */\nfunction couldReduceActiveHolders(options: ProtectedRoleFloorOptions): boolean {\n return options.deleting === true || options.deactivating === true || options.newRoles !== undefined\n}\n\nasync function enforceProtectedRoleFloor(\n em: EntityManager,\n tenantId: string | null,\n userId: string,\n options: ProtectedRoleFloorOptions,\n ctx?: CommandRuntimeContext,\n): Promise<void> {\n // Internal automation (CLI, migrations, tenant teardown) must never be blocked by the\n // floor. Superadmins are deliberately NOT exempt \u2014 see the spec's Risks section.\n if (ctx?.systemActor === true) return\n if (!couldReduceActiveHolders(options)) return\n\n const normalizedTenantId = normalizeTenantId(tenantId) ?? null\n if (!normalizedTenantId) return\n\n // Find all protected roles in this tenant, acquiring a pessimistic write lock in a deterministic primary key order\n const protectedRoles = await findWithDecryption(em, Role, {\n tenantId: normalizedTenantId,\n minActiveHolders: { $gt: 0 },\n deletedAt: null\n }, {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n orderBy: { id: 'ASC' }\n }, { tenantId: normalizedTenantId, organizationId: null })\n\n if (protectedRoles.length === 0) return\n\n const { translate } = await resolveTranslations()\n\n for (const role of protectedRoles) {\n const minFloor = role.minActiveHolders ?? 0\n if (minFloor <= 0) continue\n\n // Active links for this role, scoped to the tenant by the nested user filter so the\n // database \u2014 not a post-filter \u2014 enforces isolation. Deliberately NOT populated:\n // `findWithDecryption` runs `decryptEntityGraph` over loaded relations, which would\n // decrypt every admin's email and name on each check just to read their ids.\n const activeLinks = await findWithDecryption(em, UserRole, {\n role: role.id,\n deletedAt: null,\n user: {\n deletedAt: null,\n isConfirmed: true,\n tenantId: normalizedTenantId\n }\n }, {}, { tenantId: null, organizationId: null })\n\n // Count distinct user IDs in the tenant holding this role to prevent overcounting due to duplicate links\n const activeUserIds = Array.from(\n new Set(\n activeLinks\n .map((link) => {\n const userRef = link.user as unknown as { id?: string } | string | null | undefined\n const linkedUserId = typeof userRef === 'string' ? userRef : userRef?.id\n return linkedUserId ? String(linkedUserId) : null\n })\n .filter((id): id is string => !!id)\n )\n )\n\n // Is the target user currently one of the active holders?\n if (activeUserIds.includes(userId)) {\n // Determine if they will remain an active holder\n let willStillBeActiveHolder = true\n\n if (options.deleting || options.deactivating) {\n willStillBeActiveHolder = false\n } else if (options.newRoles !== undefined) {\n // Checking role list\n const desiredUnique = Array.from(new Set(options.newRoles.map((r) => r.trim().toLowerCase()).filter(Boolean)))\n const roleNameLower = role.name.toLowerCase()\n const hasRoleByName = desiredUnique.includes(roleNameLower) || desiredUnique.includes(String(role.id).toLowerCase())\n if (!hasRoleByName) {\n willStillBeActiveHolder = false\n }\n }\n\n if (!willStillBeActiveHolder) {\n const remaining = activeUserIds.length - 1\n if (remaining < minFloor) {\n throw new CrudHttpError(400, {\n error: translate('auth.users.errors.lastHolderOfCriticalRole', 'Cannot remove the last active holder of role \"{roleName}\"', { roleName: role.name })\n })\n }\n }\n }\n }\n}\n"],
5
- "mappings": "AACA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAI9B,SAAS,2BAA2B;AACpC,SAAS,oCAAoC,gBAAgB;AAE7D,SAAS,MAAM,UAAU,MAAM,SAAS,SAAS,qBAAqB;AACtE,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,SAAS;AAClB,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA4C;AACrD,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,kBAAkB,6BAA6B;AACxD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;A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AAE;AAAA,MACtC;AAAA,IACF;AAGA,QAAI,cAAc,SAAS,MAAM,GAAG;AAElC,UAAI,0BAA0B;AAE9B,UAAI,QAAQ,YAAY,QAAQ,cAAc;AAC5C,kCAA0B;AAAA,MAC5B,WAAW,QAAQ,aAAa,QAAW;AAEzC,cAAM,gBAAgB,MAAM,KAAK,IAAI,IAAI,QAAQ,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC;AAC7G,cAAM,gBAAgB,KAAK,KAAK,YAAY;AAC5C,cAAM,gBAAgB,cAAc,SAAS,aAAa,KAAK,cAAc,SAAS,OAAO,KAAK,EAAE,EAAE,YAAY,CAAC;AACnH,YAAI,CAAC,eAAe;AAClB,oCAA0B;AAAA,QAC5B;AAAA,MACF;AAEA,UAAI,CAAC,yBAAyB;AAC5B,cAAM,YAAY,cAAc,SAAS;AACzC,YAAI,YAAY,UAAU;AACxB,gBAAM,IAAI,cAAc,KAAK;AAAA,YAC3B,OAAO,UAAU,8CAA8C,6DAA6D,EAAE,UAAU,KAAK,KAAK,CAAC;AAAA,UACrJ,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n buildChanges,\n requireId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudEventsConfig, CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { UniqueConstraintViolationException, LockMode } from '@mikro-orm/core'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport {\n User,\n UserRole,\n Role,\n UserAcl,\n Session,\n PasswordReset,\n UserSidebarPreference,\n SidebarVariant,\n} from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { resolveOrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { E } from '#generated/entities.ids.generated'\nimport { z } from 'zod'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n diffCustomFieldChanges,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { normalizeTenantId } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport InviteUserEmail from '@open-mercato/core/modules/auth/emails/InviteUserEmail'\nimport { INVITE_TOKEN_TTL_MS } from '@open-mercato/core/modules/auth/lib/inviteToken'\nimport { getSecurityEmailBaseUrl } from '@open-mercato/shared/lib/url'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { normalizeDisplayNameInput } from '@open-mercato/core/modules/auth/lib/displayName'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n assertActorCanAssignUserDestination,\n resolveUserDestinationRoles,\n throwUserDestinationOrganizationNotFound,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('auth').child({ component: 'users-commands' })\n\ntype SerializedUser = {\n email: string\n organizationId: string | null\n tenantId: string | null\n roles: string[]\n name: string | null\n isConfirmed: boolean\n custom?: Record<string, unknown>\n}\n\ntype UserAclSnapshot = {\n tenantId: string\n features: string[] | null\n isSuperAdmin: boolean\n organizations: string[] | null\n}\n\ntype UserUndoSnapshot = {\n id: string\n email: string\n organizationId: string | null\n tenantId: string | null\n passwordHash: string | null\n name: string | null\n isConfirmed: boolean\n roles: string[]\n acls: UserAclSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype UserSnapshots = {\n view: SerializedUser\n undo: UserUndoSnapshot\n}\n\nfunction resolveActorTenantScope(ctx: CommandRuntimeContext): string | null {\n if (ctx.systemActor === true) return null\n const auth = ctx.auth\n if (!auth) return null\n if ((auth as { isSuperAdmin?: boolean }).isSuperAdmin === true) return null\n const actorTenantId = normalizeTenantId(auth.tenantId ?? null) ?? null\n return actorTenantId\n}\n\nfunction assertTargetTenantInScope(actorTenantScope: string | null, targetTenantId: unknown, notFoundError: string): void {\n if (!actorTenantScope) return\n const targetTenant = normalizeTenantId(targetTenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) {\n throw new CrudHttpError(404, { error: notFoundError })\n }\n}\n\nconst passwordSchema = buildPasswordSchema()\n\nconst displayNameSchema = z.preprocess(\n normalizeDisplayNameInput,\n z.string().trim().min(1).max(120).nullable().optional(),\n)\n\nconst createSchema = z.object({\n email: z.string().email(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n sendInviteEmail: z.boolean().optional(),\n organizationId: z.string().uuid(),\n roles: z.array(z.string()).optional(),\n}).refine(\n (data) => data.password || data.sendInviteEmail,\n { message: 'Either password or sendInviteEmail is required', path: ['password'] },\n)\n\nconst updateSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email().optional(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n organizationId: z.string().uuid().optional(),\n roles: z.array(z.string()).optional(),\n isConfirmed: z.boolean().optional(),\n})\n\nexport const userCrudEvents: CrudEventsConfig = {\n module: 'auth',\n entity: 'user',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nexport const userCrudIndexer: CrudIndexerConfig = {\n entityType: E.auth.user,\n buildUpsertPayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n buildDeletePayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nasync function notifyRoleChanges(\n ctx: CommandRuntimeContext,\n user: User,\n assignedRoles: string[],\n revokedRoles: string[],\n): Promise<void> {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (!tenantId) return\n const organizationId = user.organizationId ? String(user.organizationId) : null\n\n try {\n const notificationService = resolveNotificationService(ctx.container)\n if (assignedRoles.length) {\n const assignedType = notificationTypes.find((type) => type.type === 'auth.role.assigned')\n if (assignedType) {\n const notificationInput = buildNotificationFromType(assignedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n\n if (revokedRoles.length) {\n const revokedType = notificationTypes.find((type) => type.type === 'auth.role.revoked')\n if (revokedType) {\n const notificationInput = buildNotificationFromType(revokedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n}\n\ntype CreateUserResult = { user: User; warning?: 'invite_email_failed' }\n\nconst createUserCommand: CommandHandler<Record<string, unknown>, CreateUserResult> = {\n id: 'auth.users.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(createSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId },\n )\n if (!organization) throw new CrudHttpError(400, { error: 'Organization not found' })\n const tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n assertTargetTenantInScope(resolveActorTenantScope(ctx), tenantId, 'Organization not found')\n\n const emailHash = computeEmailHash(parsed.email)\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq). Scope the duplicate check to the target tenant so the same\n // email may legitimately exist in other tenants without blocking creation or leaking\n // cross-tenant account existence (#2934).\n const duplicate = await findOneWithDecryption(em, User, { $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }], deletedAt: null, tenantId } as any, {}, { tenantId: null, organizationId: null })\n if (duplicate) await throwDuplicateEmailError()\n\n let passwordHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n passwordHash = await hash(parsed.password, 10)\n }\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user: User\n try {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n email: parsed.email,\n name: parsed.name,\n emailHash,\n passwordHash,\n isConfirmed: true,\n organizationId: parsed.organizationId,\n tenantId,\n },\n })\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n\n let assignedRoles: string[] = []\n if (Array.isArray(parsed.roles) && parsed.roles.length) {\n await syncUserRoles(em, user, parsed.roles, tenantId)\n assignedRoles = await loadUserRoleNames(em, String(user.id))\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: tenantId,\n values: custom,\n })\n\n let inviteEmailSent = false\n if (parsed.sendInviteEmail) {\n const inviteResult = await sendInviteToUser(em, user)\n inviteEmailSent = inviteResult.emailSent\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (assignedRoles.length && !parsed.sendInviteEmail) {\n await notifyRoleChanges(ctx, user, assignedRoles, [])\n }\n\n const warning = (parsed.sendInviteEmail && !inviteEmailSent) ? 'invite_email_failed' as const : undefined\n\n return { user, warning }\n },\n captureAfter: async (_input, { user }, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n return serializeUser(user, roles, custom)\n },\n buildLog: async ({ result: { user }, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n const snapshot = captureUserSnapshots(user, roles, undefined, custom)\n return {\n actionLabel: translate('auth.audit.users.create', 'Create user'),\n resourceKind: 'auth.user',\n resourceId: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n snapshotAfter: snapshot.view,\n payload: {\n undo: {\n after: snapshot.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const userId = typeof logEntry?.resourceId === 'string' ? logEntry.resourceId : null\n if (!userId) return\n const snapshot = logEntry?.snapshotAfter as SerializedUser | undefined\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Evaluate the floor against the user's CURRENT tenant, not the one recorded at\n // creation. A user moved to another tenant after being created would otherwise be\n // checked against the origin tenant \u2014 where they no longer hold anything \u2014 and the\n // undo would hard-delete the destination tenant's last administrator unchecked.\n // The create snapshot is only a fallback for a row that is already gone.\n let removed: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const floorTenantId = current?.tenantId ? String(current.tenantId) : (snapshot?.tenantId ?? null)\n\n // Undoing a create hard-deletes the user, so it can strip a tenant's last active\n // admin exactly like `auth.users.delete` can \u2014 promote a second admin, delete the\n // first, then undo the promotion's create. Same guard applies.\n await enforceProtectedRoleFloor(em, floorTenantId, userId, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: userId })\n await em.nativeDelete(UserRole, { user: userId })\n await em.nativeDelete(Session, { user: userId })\n await em.nativeDelete(PasswordReset, { user: userId })\n await em.nativeDelete(UserSidebarPreference, { user: userId })\n await em.nativeDelete(SidebarVariant, { user: userId })\n\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const reset = buildCustomFieldResetMap(undefined, snapshot.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: userId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: reset,\n notify: false,\n })\n }\n }\n removed = await de.deleteOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n soft: false,\n })\n },\n ], { transaction: true, label: 'auth.users.create.undo' })\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: removed,\n identifiers: {\n id: userId,\n organizationId: snapshot?.organizationId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n // The create-undo hard-deletes the user, but the after-snapshot persists the\n // original passwordHash (see captureUserSnapshots), so redo restores the row\n // with the SAME id and the SAME hash \u2014 never fabricating credentials (#2506).\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<UserUndoSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for user create' })\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const emailHash = computeEmailHash(after.email)\n\n let user = await findOneWithDecryption(em, User, { id: after.id }, {}, { tenantId: null, organizationId: null })\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n user.deletedAt = null\n user.email = after.email\n user.emailHash = emailHash\n user.organizationId = after.organizationId ?? null\n user.tenantId = after.tenantId ?? null\n user.passwordHash = after.passwordHash ?? null\n user.name = after.name ?? null\n user.isConfirmed = after.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: after.id,\n email: after.email,\n emailHash,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n passwordHash: after.passwordHash ?? null,\n name: after.name ?? null,\n isConfirmed: after.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: after.id })\n await syncUserRoles(em, user, after.roles, after.tenantId)\n await restoreUserAcls(em, user, after.acls)\n\n if (after.custom && Object.keys(after.custom).length) {\n const reset = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n }\n },\n ], { transaction: true })\n\n if (!user) throw new CrudHttpError(400, { error: '[internal] redo failed to restore user row' })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, after.id)\n\n return { user }\n },\n}\n\nasync function sendInviteToUser(\n em: EntityManager,\n user: User,\n): Promise<{ emailSent: boolean }> {\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + INVITE_TOKEN_TTL_MS)\n const row = em.create(PasswordReset, { user, token: tokenHash, expiresAt, createdAt: new Date() })\n await em.persist(row).flush()\n\n const base = getSecurityEmailBaseUrl()\n const inviteUrl = `${base}/reset/${rawToken}`\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.invite.subject', 'You have been invited')\n const copy = {\n preview: translate('auth.email.invite.preview', 'Set up your account'),\n title: translate('auth.email.invite.title', 'You have been invited'),\n body: translate('auth.email.invite.body', 'An administrator has created an account for you. Click the link below to set your password. This link will expire in 48 hours.'),\n cta: translate('auth.email.invite.cta', 'Set up your password'),\n hint: translate('auth.email.invite.hint', 'If you did not expect this invitation, you can safely ignore this email.'),\n }\n\n let emailSent = true\n try {\n await sendEmail({\n to: user.email,\n subject,\n react: InviteUserEmail({ inviteUrl, copy }),\n tenantId: user.tenantId ? String(user.tenantId) : undefined,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n } catch (err) {\n logger.error('Failed to send invitation email', { err })\n emailSent = false\n }\n\n return { emailSent }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const code = (error as { code?: string }).code\n if (code === '23505') return true\n const messageRaw = (error as { message?: string })?.message\n const message = typeof messageRaw === 'string' ? messageRaw : ''\n return message.toLowerCase().includes('duplicate key')\n}\n\nconst updateUserCommand: CommandHandler<Record<string, unknown>, User> = {\n id: 'auth.users.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n assertTargetTenantInScope(resolveActorTenantScope(ctx), existing.tenantId, 'User not found')\n const roles = await loadUserRoleNames(em, parsed.id)\n const acls = await loadUserAclSnapshots(em, parsed.id)\n const custom = await loadUserCustomSnapshot(\n em,\n parsed.id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const actorTenantScope = resolveActorTenantScope(ctx)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const rolesBefore = Array.isArray(parsed.roles)\n ? await loadUserRoleNames(em, parsed.id)\n : null\n\n let tenantId: string | null | undefined\n let destinationChanged = false\n if (parsed.organizationId !== undefined) {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId ?? null },\n )\n if (!organization) return throwUserDestinationOrganizationNotFound(400)\n tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n if (!tenantId) return throwUserDestinationOrganizationNotFound(400)\n const currentUser = await findOneWithDecryption(\n em,\n User,\n { id: parsed.id, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!currentUser) throw new CrudHttpError(404, { error: 'User not found' })\n const currentOrganizationId = currentUser.organizationId ? String(currentUser.organizationId) : null\n const currentTenantId = currentUser.tenantId ? String(currentUser.tenantId) : null\n destinationChanged = currentOrganizationId !== parsed.organizationId || currentTenantId !== tenantId\n if (destinationChanged) {\n const rbacService = ctx.container.resolve('rbacService') as RbacService\n const destinationRoles = await resolveUserDestinationRoles({\n em,\n targetUserId: parsed.id,\n destinationTenantId: tenantId,\n roleTokens: parsed.roles,\n })\n const actorIsSuperAdmin = ctx.systemActor === true || ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope?.tenantId === tenantId\n ? ctx.organizationScope\n : !actorIsSuperAdmin && ctx.auth?.sub\n ? await resolveOrganizationScope({\n em,\n rbac: rbacService,\n auth: ctx.auth,\n tenantId,\n })\n : null\n await assertActorCanAssignUserDestination({\n em,\n rbacService,\n actorUserId: ctx.auth?.sub,\n actorIsSuperAdmin,\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n allowedOrganizationIds: organizationScope?.allowedIds,\n destinationTenantId: tenantId,\n destinationOrganizationId: parsed.organizationId,\n roles: destinationRoles,\n })\n }\n }\n\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n const targetTenantId = tenantId !== undefined ? tenantId : userTenantId\n const isTenantChanging = targetTenantId !== userTenantId\n\n // Hash password BEFORE transaction begins to avoid holding locks during CPU-heavy tasks\n let hashed: string | null = null\n let emailHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n hashed = await hash(parsed.password, 10)\n }\n if (parsed.email !== undefined) {\n emailHash = computeEmailHash(parsed.email)\n }\n\n const updateWhere: Record<string, unknown> = { id: parsed.id, deletedAt: null }\n if (actorTenantScope) updateWhere.tenantId = actorTenantScope\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user!: User\n\n await withAtomicFlush(em, [\n async () => {\n // Floor check must run inside the transaction so that LockMode.PESSIMISTIC_WRITE locks Role rows properly\n await enforceProtectedRoleFloor(em, userTenantId, parsed.id, {\n deactivating: parsed.isConfirmed === false || isTenantChanging,\n newRoles: parsed.roles,\n }, ctx)\n\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq) \u2014 a matching email in another tenant must not block\n // the update or leak cross-tenant account existence (#2934). `targetTenantId` is the\n // tenant the user will belong to after this update, so the check follows a move.\n if (parsed.email !== undefined) {\n const duplicate = await findOneWithDecryption(\n em,\n User,\n {\n $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }],\n deletedAt: null,\n tenantId: targetTenantId,\n id: { $ne: parsed.id } as any,\n } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n if (duplicate) await throwDuplicateEmailError()\n }\n\n try {\n const updated = await de.updateOrmEntity({\n entity: User,\n where: updateWhere as FilterQuery<User>,\n apply: (entity) => {\n if (parsed.email !== undefined) {\n entity.email = parsed.email\n entity.emailHash = emailHash\n }\n if (parsed.name !== undefined) {\n entity.name = parsed.name\n }\n if (parsed.organizationId !== undefined) {\n entity.organizationId = parsed.organizationId\n entity.tenantId = tenantId ?? null\n }\n if (parsed.isConfirmed !== undefined) {\n entity.isConfirmed = parsed.isConfirmed\n }\n if (hashed) entity.passwordHash = hashed\n },\n })\n if (updated) user = updated\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n if (!user) throw new CrudHttpError(404, { error: 'User not found' })\n\n if (hashed || parsed.isConfirmed === false) {\n await em.nativeDelete(Session, { user: parsed.id })\n }\n\n if (Array.isArray(parsed.roles)) {\n await syncUserRoles(em, user, parsed.roles, user.tenantId ? String(user.tenantId) : tenantId ?? null)\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n values: custom,\n })\n }\n ], { transaction: true, label: destinationChanged ? 'auth.users.update.destination' : 'auth.users.update' })\n\n const identifiers = {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: user,\n identifiers,\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (hashed) {\n const actorId = ctx.auth?.sub ? String(ctx.auth.sub) : null\n // `system` covers a command invocation with no auth context and one running under\n // `ctx.systemActor`. Without it those writes would be indistinguishable from an\n // administrator setting someone else's password, which is exactly the case security\n // alerting escalates on. Password writes that never reach this command \u2014 `mercato\n // auth set-password`, tenant provisioning \u2014 set `passwordHash` directly and emit\n // nothing, so a subscriber cannot treat this event as covering every credential change.\n const changedBy = ctx.systemActor === true || !actorId\n ? 'system'\n : actorId === identifiers.id ? 'self' : 'admin'\n void emitAuthEvent('auth.password.changed', {\n id: identifiers.id,\n tenantId: identifiers.tenantId,\n organizationId: identifiers.organizationId,\n changedBy,\n changedById: actorId,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n\n if (Array.isArray(parsed.roles) && rolesBefore) {\n const rolesAfter = await loadUserRoleNames(em, String(user.id))\n const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter)\n if (assigned.length || revoked.length) {\n await notifyRoleChanges(ctx, user, assigned, revoked)\n }\n }\n\n await invalidateUserCache(ctx, parsed.id)\n\n return user\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(result.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n return serializeUser(result, roles, custom)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterRoles = await loadUserRoleNames(em, String(result.id))\n const afterCustom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n const afterSnapshots = captureUserSnapshots(result, afterRoles, undefined, afterCustom)\n const after = afterSnapshots.view\n const changes = buildChanges(before ?? null, after as Record<string, unknown>, ['email', 'organizationId', 'tenantId', 'name', 'isConfirmed'])\n if (before && !arrayEquals(before.roles, afterRoles)) {\n changes.roles = { from: before.roles, to: afterRoles }\n }\n const customDiff = diffCustomFieldChanges(before?.custom, afterCustom)\n for (const [key, diff] of Object.entries(customDiff)) {\n changes[`cf_${key}`] = diff\n }\n return {\n actionLabel: translate('auth.audit.users.update', 'Update user'),\n resourceKind: 'auth.user',\n resourceId: String(result.id),\n tenantId: result.tenantId ? String(result.tenantId) : null,\n organizationId: result.organizationId ? String(result.organizationId) : null,\n changes,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: {\n before: beforeUndo,\n after: afterSnapshots.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n const after = payload?.after\n if (!before) return\n const userId = before.id\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Reverting an update can drop the tenant below a protected role's floor just as the\n // forward path can \u2014 restoring an empty `before.roles` on what is now the last admin,\n // or restoring `isConfirmed: false`. Undo is reachable from the audit-log UI, so the\n // guard has to run here too, inside a transaction so the row lock is valid.\n const restoredTenantId = before.tenantId ? String(before.tenantId) : null\n\n let updated: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const currentTenantId = current?.tenantId ? String(current.tenantId) : null\n\n await enforceProtectedRoleFloor(em, currentTenantId, userId, {\n deactivating: before.isConfirmed === false || restoredTenantId !== currentTenantId,\n newRoles: before.roles,\n }, ctx)\n\n updated = await de.updateOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n apply: (entity) => {\n entity.email = before.email\n entity.organizationId = before.organizationId ?? null\n entity.tenantId = before.tenantId ?? null\n entity.passwordHash = before.passwordHash ?? null\n entity.name = before.name ?? null\n entity.isConfirmed = before.isConfirmed\n },\n })\n\n if (updated) {\n await syncUserRoles(em, updated, before.roles, before.tenantId)\n }\n },\n ], { transaction: true, label: 'auth.users.update.undo' })\n\n const reset = buildCustomFieldResetMap(before.custom, after?.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: updated,\n identifiers: {\n id: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n}\n\nconst deleteUserCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, User> = {\n id: 'auth.users.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) return {}\n const actorTenantScope = resolveActorTenantScope(ctx)\n if (actorTenantScope) {\n const targetTenant = normalizeTenantId(existing.tenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) return {}\n }\n const roles = await loadUserRoleNames(em, id)\n const acls = await loadUserAclSnapshots(em, id)\n const custom = await loadUserCustomSnapshot(\n em,\n id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const actorTenantScope = resolveActorTenantScope(ctx)\n\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const deleteWhere: Record<string, unknown> = { id, deletedAt: null }\n if (actorTenantScope) deleteWhere.tenantId = actorTenantScope\n\n let user!: User\n await withAtomicFlush(em, [\n async () => {\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n await enforceProtectedRoleFloor(em, userTenantId, id, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: id })\n await em.nativeDelete(UserRole, { user: id })\n await em.nativeDelete(Session, { user: id })\n await em.nativeDelete(PasswordReset, { user: id })\n await em.nativeDelete(UserSidebarPreference, { user: id })\n await em.nativeDelete(SidebarVariant, { user: id })\n const removed = await de.deleteOrmEntity({\n entity: User,\n where: deleteWhere as FilterQuery<User>,\n soft: false,\n })\n if (!removed) throw new CrudHttpError(404, { error: 'User not found' })\n user = removed\n },\n ], { transaction: true })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: user,\n identifiers: {\n id: String(id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, id)\n\n return user\n },\n buildLog: async ({ snapshots, input, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const id = requireId(input, 'User id required')\n return {\n actionLabel: translate('auth.audit.users.delete', 'Delete user'),\n resourceKind: 'auth.user',\n resourceId: id,\n snapshotBefore: before ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n payload: {\n undo: {\n before: beforeUndo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager)\n let user = await findOneWithDecryption(em, User, { id: before.id }, {}, { tenantId: null, organizationId: null })\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n if (user.deletedAt) {\n user.deletedAt = null\n }\n user.email = before.email\n user.organizationId = before.organizationId ?? null\n user.tenantId = before.tenantId ?? null\n user.passwordHash = before.passwordHash ?? null\n user.name = before.name ?? null\n user.isConfirmed = before.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: before.id,\n email: before.email,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n passwordHash: before.passwordHash ?? null,\n name: before.name ?? null,\n isConfirmed: before.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: before.id })\n await syncUserRoles(em, user, before.roles, before.tenantId)\n\n await restoreUserAcls(em, user, before.acls)\n\n const reset = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n },\n ], { transaction: true })\n\n await invalidateUserCache(ctx, before.id)\n },\n}\n\nregisterCommand(createUserCommand)\nregisterCommand(updateUserCommand)\nregisterCommand(deleteUserCommand)\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nasync function resolveRole(\n em: EntityManager,\n value: string,\n normalizedTenantId: string | null,\n): Promise<Role | null> {\n if (UUID_RE.test(value)) {\n const where: Record<string, unknown> = { id: value }\n if (normalizedTenantId !== null) {\n where.tenantId = normalizedTenantId\n }\n return findOneWithDecryption(em, Role, where as any, {}, { tenantId: normalizedTenantId, organizationId: null })\n }\n return findOneWithDecryption(em, Role, { name: value, tenantId: normalizedTenantId }, {}, { tenantId: normalizedTenantId, organizationId: null })\n}\n\nasync function syncUserRoles(em: EntityManager, user: User, desiredRoles: string[], tenantId: string | null) {\n const unique = Array.from(new Set(desiredRoles.map((role) => role.trim()).filter(Boolean)))\n const normalizedTenantId = normalizeTenantId(tenantId ?? null) ?? null\n\n const resolvedRoles: Role[] = []\n const missingRoles: string[] = []\n for (const value of unique) {\n const role = await resolveRole(em, value, normalizedTenantId)\n if (!role) {\n missingRoles.push(value)\n } else {\n resolvedRoles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((n) => `\"${n}\"`).join(', ')\n throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })\n }\n\n const desiredIds = new Set(resolvedRoles.map((r) => String(r.id)))\n const currentLinks = await findWithDecryption(em, UserRole, { user }, {}, { tenantId: null, organizationId: null })\n const currentRoleIds = new Map(\n currentLinks.map((link) => {\n const roleId = String(link.role?.id ?? (link.role as unknown as string) ?? '')\n return [roleId, link] as const\n }),\n )\n\n for (const [roleId, link] of currentRoleIds.entries()) {\n if (!desiredIds.has(roleId) && link) {\n em.remove(link)\n }\n }\n\n for (const role of resolvedRoles) {\n if (!currentRoleIds.has(String(role.id))) {\n em.persist(em.create(UserRole, { user, role, createdAt: new Date() }))\n }\n }\n\n await em.flush()\n}\n\nasync function loadUserRoleNames(em: EntityManager, userId: string): Promise<string[]> {\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as unknown as User },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const names = links\n .map((link) => link.role?.name ?? '')\n .filter((name): name is string => !!name)\n return Array.from(new Set(names)).sort((a, b) => a.localeCompare(b))\n}\n\nfunction serializeUser(user: User, roles: string[], custom?: Record<string, unknown> | null): SerializedUser {\n const payload: SerializedUser = {\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n roles,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n }\n if (custom && Object.keys(custom).length) payload.custom = custom\n return payload\n}\n\nfunction captureUserSnapshots(\n user: User,\n roles: string[],\n acls: UserAclSnapshot[] = [],\n custom?: Record<string, unknown> | null\n): UserSnapshots {\n return {\n view: serializeUser(user, roles, custom),\n undo: {\n id: String(user.id),\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n passwordHash: user.passwordHash ? String(user.passwordHash) : null,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n roles: [...roles],\n acls,\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n },\n }\n}\n\nasync function loadUserAclSnapshots(em: EntityManager, userId: string): Promise<UserAclSnapshot[]> {\n const list = await findWithDecryption(em, UserAcl, { user: userId as unknown as User }, {}, { tenantId: null, organizationId: null })\n return list.map((acl) => ({\n tenantId: String(acl.tenantId),\n features: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n isSuperAdmin: Boolean(acl.isSuperAdmin),\n organizations: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }))\n}\n\nasync function restoreUserAcls(em: EntityManager, user: User, acls: UserAclSnapshot[]) {\n await em.nativeDelete(UserAcl, { user: String(user.id) })\n for (const acl of acls) {\n const entity = em.create(UserAcl, {\n user,\n tenantId: acl.tenantId,\n featuresJson: acl.features ?? null,\n isSuperAdmin: acl.isSuperAdmin,\n organizationsJson: acl.organizations ?? null,\n createdAt: new Date(),\n })\n em.persist(entity)\n }\n await em.flush()\n}\n\nasync function loadUserCustomSnapshot(\n em: EntityManager,\n id: string,\n tenantId: string | null,\n organizationId: string | null\n): Promise<Record<string, unknown>> {\n return await loadCustomFieldSnapshot(em, {\n entityId: E.auth.user,\n recordId: id,\n tenantId,\n organizationId,\n })\n}\n\nasync function invalidateUserCache(ctx: CommandRuntimeContext, userId: string) {\n try {\n const rbacService = ctx.container.resolve('rbacService') as { invalidateUserCache: (uid: string) => Promise<void> }\n await rbacService.invalidateUserCache(userId)\n } catch {\n // RBAC not available\n }\n\n try {\n const cache = ctx.container.resolve('cache') as { deleteByTags?: (tags: string[]) => Promise<void> }\n if (cache?.deleteByTags) await cache.deleteByTags([`rbac:user:${userId}`])\n } catch {\n // cache not available\n }\n}\n\nfunction diffRoleChanges(before: string[], after: string[]) {\n const beforeSet = new Set(before)\n const afterSet = new Set(after)\n const assigned = after.filter((role) => !beforeSet.has(role))\n const revoked = before.filter((role) => !afterSet.has(role))\n return { assigned, revoked }\n}\n\nfunction arrayEquals(left: string[] | undefined, right: string[]): boolean {\n if (!left) return false\n if (left.length !== right.length) return false\n return left.every((value, idx) => value === right[idx])\n}\n\nasync function throwDuplicateEmailError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('auth.users.errors.emailExists', 'Email already in use')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { email: message },\n details: [{ path: ['email'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\ntype ProtectedRoleFloorOptions = {\n deactivating?: boolean\n newRoles?: string[]\n deleting?: boolean\n}\n\n/**\n * True when the requested mutation can lower a role's active holder count. Guards the\n * floor check so that ordinary edits (display name, password, email) never take the\n * tenant-wide role lock \u2014 `PUT /api/auth/profile` routes every self-service password\n * change through `auth.users.update`, so an unconditional lock would serialize them.\n */\nfunction couldReduceActiveHolders(options: ProtectedRoleFloorOptions): boolean {\n return options.deleting === true || options.deactivating === true || options.newRoles !== undefined\n}\n\nasync function enforceProtectedRoleFloor(\n em: EntityManager,\n tenantId: string | null,\n userId: string,\n options: ProtectedRoleFloorOptions,\n ctx?: CommandRuntimeContext,\n): Promise<void> {\n // Internal automation (CLI, migrations, tenant teardown) must never be blocked by the\n // floor. Superadmins are deliberately NOT exempt \u2014 see the spec's Risks section.\n if (ctx?.systemActor === true) return\n if (!couldReduceActiveHolders(options)) return\n\n const normalizedTenantId = normalizeTenantId(tenantId) ?? null\n if (!normalizedTenantId) return\n\n // Find all protected roles in this tenant, acquiring a pessimistic write lock in a deterministic primary key order\n const protectedRoles = await findWithDecryption(em, Role, {\n tenantId: normalizedTenantId,\n minActiveHolders: { $gt: 0 },\n deletedAt: null\n }, {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n orderBy: { id: 'ASC' }\n }, { tenantId: normalizedTenantId, organizationId: null })\n\n if (protectedRoles.length === 0) return\n\n const { translate } = await resolveTranslations()\n\n for (const role of protectedRoles) {\n const minFloor = role.minActiveHolders ?? 0\n if (minFloor <= 0) continue\n\n // Active links for this role, scoped to the tenant by the nested user filter so the\n // database \u2014 not a post-filter \u2014 enforces isolation. Deliberately NOT populated:\n // `findWithDecryption` runs `decryptEntityGraph` over loaded relations, which would\n // decrypt every admin's email and name on each check just to read their ids.\n const activeLinks = await findWithDecryption(em, UserRole, {\n role: role.id,\n deletedAt: null,\n user: {\n deletedAt: null,\n isConfirmed: true,\n tenantId: normalizedTenantId\n }\n }, {}, { tenantId: null, organizationId: null })\n\n // Count distinct user IDs in the tenant holding this role to prevent overcounting due to duplicate links\n const activeUserIds = Array.from(\n new Set(\n activeLinks\n .map((link) => {\n const userRef = link.user as unknown as { id?: string } | string | null | undefined\n const linkedUserId = typeof userRef === 'string' ? userRef : userRef?.id\n return linkedUserId ? String(linkedUserId) : null\n })\n .filter((id): id is string => !!id)\n )\n )\n\n // Is the target user currently one of the active holders?\n if (activeUserIds.includes(userId)) {\n // Determine if they will remain an active holder\n let willStillBeActiveHolder = true\n\n if (options.deleting || options.deactivating) {\n willStillBeActiveHolder = false\n } else if (options.newRoles !== undefined) {\n // Checking role list\n const desiredUnique = Array.from(new Set(options.newRoles.map((r) => r.trim().toLowerCase()).filter(Boolean)))\n const roleNameLower = role.name.toLowerCase()\n const hasRoleByName = desiredUnique.includes(roleNameLower) || desiredUnique.includes(String(role.id).toLowerCase())\n if (!hasRoleByName) {\n willStillBeActiveHolder = false\n }\n }\n\n if (!willStillBeActiveHolder) {\n const remaining = activeUserIds.length - 1\n if (remaining < minFloor) {\n throw new CrudHttpError(400, {\n error: translate('auth.users.errors.lastHolderOfCriticalRole', 'Cannot remove the last active holder of role \"{roleName}\"', { roleName: role.name })\n })\n }\n }\n }\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAI9B,SAAS,2BAA2B;AACpC,SAAS,oCAAoC,gBAAgB;AAE7D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,SAAS;AAClB,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA4C;AACrD,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,kBAAkB,6BAA6B;AACxD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,OAAO,uBAAuB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAC1B,OAAO,qBAAqB;AAC5B,SAAS,2BAA2B;AACpC,SAAS,+BAA+B;AACxC,SAAS,mBAAmB,qBAAqB;AACjD,SAAS,iCAAiC;AAC1C,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,MAAM,SAAS,aAAa,MAAM,EAAE,M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AA0B;AAE9B,UAAI,QAAQ,YAAY,QAAQ,cAAc;AAC5C,kCAA0B;AAAA,MAC5B,WAAW,QAAQ,aAAa,QAAW;AAEzC,cAAM,gBAAgB,MAAM,KAAK,IAAI,IAAI,QAAQ,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC;AAC7G,cAAM,gBAAgB,KAAK,KAAK,YAAY;AAC5C,cAAM,gBAAgB,cAAc,SAAS,aAAa,KAAK,cAAc,SAAS,OAAO,KAAK,EAAE,EAAE,YAAY,CAAC;AACnH,YAAI,CAAC,eAAe;AAClB,oCAA0B;AAAA,QAC5B;AAAA,MACF;AAEA,UAAI,CAAC,yBAAyB;AAC5B,cAAM,YAAY,cAAc,SAAS;AACzC,YAAI,YAAY,UAAU;AACxB,gBAAM,IAAI,cAAc,KAAK;AAAA,YAC3B,OAAO,UAAU,8CAA8C,6DAA6D,EAAE,UAAU,KAAK,KAAK,CAAC;AAAA,UACrJ,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -95,7 +95,7 @@ __decorateClass([
95
95
  PrimaryKey({ type: "uuid", defaultRaw: "gen_random_uuid()" })
96
96
  ], UserSidebarPreference.prototype, "id", 2);
97
97
  __decorateClass([
98
- ManyToOne(() => User)
98
+ ManyToOne(() => User, { deleteRule: "cascade" })
99
99
  ], UserSidebarPreference.prototype, "user", 2);
100
100
  __decorateClass([
101
101
  Property({ name: "tenant_id", type: "uuid", nullable: true })
@@ -163,7 +163,7 @@ __decorateClass([
163
163
  PrimaryKey({ type: "uuid", defaultRaw: "gen_random_uuid()" })
164
164
  ], SidebarVariant.prototype, "id", 2);
165
165
  __decorateClass([
166
- ManyToOne(() => User)
166
+ ManyToOne(() => User, { deleteRule: "cascade" })
167
167
  ], SidebarVariant.prototype, "user", 2);
168
168
  __decorateClass([
169
169
  Property({ name: "tenant_id", type: "uuid", nullable: true })