@open-mercato/enterprise 0.8.1-develop.7296.1.2111d779db → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/modules/agent_orchestrator/api/processes/[id]/executions/route.js +2 -1
  2. package/dist/modules/agent_orchestrator/api/processes/[id]/executions/route.js.map +2 -2
  3. package/dist/modules/agent_orchestrator/i18n/de.json +2 -1
  4. package/dist/modules/agent_orchestrator/i18n/en.json +2 -1
  5. package/dist/modules/agent_orchestrator/i18n/es.json +2 -1
  6. package/dist/modules/agent_orchestrator/i18n/ko.json +2 -1
  7. package/dist/modules/agent_orchestrator/i18n/pl.json +2 -1
  8. package/dist/modules/agent_orchestrator/lib/identity/agentPrincipalService.js +33 -28
  9. package/dist/modules/agent_orchestrator/lib/identity/agentPrincipalService.js.map +2 -2
  10. package/dist/modules/record_locks/i18n/de.json +1 -0
  11. package/dist/modules/record_locks/i18n/en.json +1 -0
  12. package/dist/modules/record_locks/i18n/es.json +1 -0
  13. package/dist/modules/record_locks/i18n/ko.json +1 -0
  14. package/dist/modules/record_locks/i18n/pl.json +1 -0
  15. package/dist/modules/security/notifications.js +4 -0
  16. package/dist/modules/security/notifications.js.map +2 -2
  17. package/dist/modules/sso/lib/errors.js +15 -1
  18. package/dist/modules/sso/lib/errors.js.map +2 -2
  19. package/dist/modules/sso/services/accountLinkingService.js +77 -26
  20. package/dist/modules/sso/services/accountLinkingService.js.map +2 -2
  21. package/dist/modules/sso/services/ssoService.js +9 -1
  22. package/dist/modules/sso/services/ssoService.js.map +2 -2
  23. package/package.json +10 -11
  24. package/src/modules/agent_orchestrator/api/processes/[id]/executions/route.ts +2 -1
  25. package/src/modules/agent_orchestrator/i18n/de.json +2 -1
  26. package/src/modules/agent_orchestrator/i18n/en.json +2 -1
  27. package/src/modules/agent_orchestrator/i18n/es.json +2 -1
  28. package/src/modules/agent_orchestrator/i18n/ko.json +2 -1
  29. package/src/modules/agent_orchestrator/i18n/pl.json +2 -1
  30. package/src/modules/agent_orchestrator/lib/identity/agentPrincipalService.ts +37 -31
  31. package/src/modules/record_locks/i18n/de.json +1 -0
  32. package/src/modules/record_locks/i18n/en.json +1 -0
  33. package/src/modules/record_locks/i18n/es.json +1 -0
  34. package/src/modules/record_locks/i18n/ko.json +1 -0
  35. package/src/modules/record_locks/i18n/pl.json +1 -0
  36. package/src/modules/security/notifications.ts +4 -0
  37. package/src/modules/sso/lib/errors.ts +20 -0
  38. package/src/modules/sso/services/accountLinkingService.ts +90 -29
  39. package/src/modules/sso/services/ssoService.ts +8 -1
@@ -4,9 +4,11 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
4
4
  import { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'
5
5
  import { SsoConfig, SsoIdentity, SsoRoleGrant, ScimToken } from '../data/entities'
6
6
  import { emitSsoEvent } from '../events'
7
- import { EmailNotVerifiedError } from '../lib/errors'
7
+ import { EmailNotVerifiedError, SsoRolesRevokedError } from '../lib/errors'
8
8
  import type { SsoIdentityPayload } from '../lib/types'
9
9
  import { createLogger } from '@open-mercato/shared/lib/logger'
10
+ import { conflict } from '@open-mercato/shared/lib/crud/errors'
11
+ import { lockUserRoleWriterAuthorizationState } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'
10
12
 
11
13
  const logger = createLogger('sso').child({ component: 'account-linking' })
12
14
 
@@ -193,14 +195,25 @@ export class AccountLinkingService {
193
195
  const hasMappings = config.appRoleMappings && Object.keys(config.appRoleMappings).length > 0
194
196
  if (!hasMappings) return
195
197
 
196
- await this.syncMappedRoles(em, user, config, tenantId, idpGroups)
197
-
198
- const hasAnySsoRole = await em.findOne(SsoRoleGrant, {
199
- userId: user.id,
200
- ssoConfigId: config.id,
201
- })
198
+ const synchronize = async (transactionalEm: EntityManager): Promise<boolean> => {
199
+ const managedUser = typeof transactionalEm.getReference === 'function'
200
+ ? transactionalEm.getReference(User, String(user.id))
201
+ : user
202
+ await this.syncMappedRoles(transactionalEm, managedUser, config, tenantId, idpGroups)
203
+ const remainingGrant = await transactionalEm.findOne(SsoRoleGrant, {
204
+ userId: user.id,
205
+ ssoConfigId: config.id,
206
+ })
207
+ return remainingGrant !== null
208
+ }
209
+ const hasAnySsoRole = typeof em.isInTransaction === 'function' && em.isInTransaction()
210
+ ? await synchronize(em)
211
+ : await em.transactional(synchronize)
202
212
  if (!hasAnySsoRole) {
203
- throw new Error('No roles could be resolved from IdP groups — login denied. Configure role mappings or ensure the IdP sends matching group claims.')
213
+ throw new SsoRolesRevokedError(
214
+ String(user.id),
215
+ 'No roles could be resolved from IdP groups — login denied. Configure role mappings or ensure the IdP sends matching group claims.',
216
+ )
204
217
  }
205
218
  }
206
219
 
@@ -218,31 +231,56 @@ export class AccountLinkingService {
218
231
  const resolvedTenantId = tenantId || user.tenantId || ''
219
232
  if (!resolvedTenantId) return
220
233
 
221
- const allRoles = await em.find(Role, { tenantId: resolvedTenantId, deletedAt: null } as FilterQuery<Role>)
222
- const roleByNormalizedName = new Map<string, Role>()
223
- for (const role of allRoles) {
224
- const normalized = normalizeToken(role.name)
225
- if (normalized) roleByNormalizedName.set(normalized, role)
226
- }
227
-
228
- // Resolve desired role IDs from IdP groups using merged mappings
229
234
  const desiredRoleNames = resolveRoleNamesFromIdpGroups(idpGroups, config.appRoleMappings)
230
- const desiredRoleIds = new Set<string>()
231
- for (const roleName of desiredRoleNames) {
232
- const role = roleByNormalizedName.get(roleName)
233
- if (role) desiredRoleIds.add(role.id)
234
- }
235
+ let allRoles = await em.find(Role, {
236
+ tenantId: resolvedTenantId,
237
+ deletedAt: null,
238
+ } as FilterQuery<Role>)
239
+ let desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)
235
240
 
236
241
  // Query current SSO grants for this user+config
237
- const existingGrants = await em.find(SsoRoleGrant, {
242
+ let existingGrants = await em.find(SsoRoleGrant, {
238
243
  userId: user.id,
239
244
  ssoConfigId: config.id,
240
245
  })
246
+ let allUserRoles = await em.find(UserRole, { user: user.id } as FilterQuery<UserRole>)
247
+ const lockedRoleIds = new Set([
248
+ ...desiredRoleIds,
249
+ ...existingGrants.map((grant) => grant.roleId),
250
+ ...allUserRoles
251
+ .filter((userRole) => userRole.deletedAt)
252
+ .map((userRole) => String(userRole.role?.id ?? userRole.role)),
253
+ ])
254
+ await lockUserRoleWriterAuthorizationState(em, {
255
+ userIds: [String(user.id)],
256
+ roleIds: Array.from(lockedRoleIds),
257
+ })
258
+ allRoles = await em.find(Role, {
259
+ tenantId: resolvedTenantId,
260
+ deletedAt: null,
261
+ } as FilterQuery<Role>, { refresh: true })
262
+ existingGrants = await em.find(SsoRoleGrant, {
263
+ userId: user.id,
264
+ ssoConfigId: config.id,
265
+ }, { refresh: true })
266
+ allUserRoles = await em.find(
267
+ UserRole,
268
+ { user: user.id } as FilterQuery<UserRole>,
269
+ { refresh: true },
270
+ )
271
+
272
+ desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)
241
273
  const existingGrantedRoleIds = new Set(existingGrants.map((g) => g.roleId))
242
274
 
243
275
  // Compute diff
244
276
  const toAdd = [...desiredRoleIds].filter((id) => !existingGrantedRoleIds.has(id))
245
277
  const toRemove = existingGrants.filter((g) => !desiredRoleIds.has(g.roleId))
278
+ const softDeletedUserRoles = allUserRoles.filter((userRole) => userRole.deletedAt)
279
+ assertRoleMutationFootprintWasLocked([
280
+ ...desiredRoleIds,
281
+ ...toRemove.map((grant) => grant.roleId),
282
+ ...softDeletedUserRoles.map((userRole) => String(userRole.role?.id ?? userRole.role)),
283
+ ], lockedRoleIds)
246
284
 
247
285
  // Add new roles
248
286
  for (const roleId of toAdd) {
@@ -273,14 +311,11 @@ export class AccountLinkingService {
273
311
  }
274
312
 
275
313
  // Clean up orphaned soft-deleted UserRole rows (ghost rows from previous soft-delete logic)
276
- const allUserRoles = await em.find(UserRole, { user: user.id } as FilterQuery<UserRole>)
277
- for (const ur of allUserRoles) {
278
- if (ur.deletedAt) {
279
- em.remove(ur)
280
- }
314
+ for (const userRole of softDeletedUserRoles) {
315
+ em.remove(userRole)
281
316
  }
282
317
 
283
- if (toAdd.length > 0 || toRemove.length > 0 || allUserRoles.some((ur) => ur.deletedAt)) {
318
+ if (toAdd.length > 0 || toRemove.length > 0 || softDeletedUserRoles.length > 0) {
284
319
  await em.flush()
285
320
  }
286
321
  }
@@ -294,8 +329,34 @@ export class AccountLinkingService {
294
329
  if (existingLink) return
295
330
 
296
331
  const userRole = em.create(UserRole, { user, role, createdAt: new Date() })
297
- await em.persist(userRole).flush()
332
+ em.persist(userRole)
333
+ }
334
+ }
335
+
336
+ function assertRoleMutationFootprintWasLocked(
337
+ roleIds: Iterable<string>,
338
+ lockedRoleIds: ReadonlySet<string>,
339
+ ): void {
340
+ for (const roleId of roleIds) {
341
+ if (!lockedRoleIds.has(roleId)) {
342
+ throw conflict('[internal] Authorization state changed while acquiring its lock footprint')
343
+ }
344
+ }
345
+ }
346
+
347
+ function resolveActiveRoleIds(roles: Role[], desiredRoleNames: string[]): Set<string> {
348
+ const roleByNormalizedName = new Map<string, Role>()
349
+ for (const role of roles) {
350
+ const normalized = normalizeToken(role.name)
351
+ if (normalized) roleByNormalizedName.set(normalized, role)
352
+ }
353
+
354
+ const desiredRoleIds = new Set<string>()
355
+ for (const roleName of desiredRoleNames) {
356
+ const role = roleByNormalizedName.get(roleName)
357
+ if (role) desiredRoleIds.add(role.id)
298
358
  }
359
+ return desiredRoleIds
299
360
  }
300
361
 
301
362
  function resolveRoleNamesFromIdpGroups(
@@ -9,6 +9,7 @@ import type { SsoProviderRegistry } from '../lib/registry'
9
9
  import type { AccountLinkingService } from './accountLinkingService'
10
10
  import { encryptStateCookie, decryptStateCookie, createFlowState } from '../lib/state-cookie'
11
11
  import { emitSsoEvent } from '../events'
12
+ import { isSsoRolesRevokedError } from '../lib/errors'
12
13
  import type { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'
13
14
  import { createLogger } from '@open-mercato/shared/lib/logger'
14
15
 
@@ -122,7 +123,13 @@ export class SsoService {
122
123
  })
123
124
 
124
125
  const tenantId = config.tenantId ?? ''
125
- const { user } = await this.accountLinkingService.resolveUser(config, idpPayload, tenantId)
126
+ let user: Awaited<ReturnType<AccountLinkingService['resolveUser']>>['user']
127
+ try {
128
+ ;({ user } = await this.accountLinkingService.resolveUser(config, idpPayload, tenantId))
129
+ } catch (err) {
130
+ if (isSsoRolesRevokedError(err)) await this.rbacService.invalidateUserCache(err.userId)
131
+ throw err
132
+ }
126
133
 
127
134
  await this.rbacService.invalidateUserCache(String(user.id))
128
135