@open-mercato/enterprise 0.10.1-develop.7796.1.f2868e5c62 → 0.10.1-develop.7797.1.f0365b4031

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.
@@ -1,2 +1,2 @@
1
- [build:enterprise] found 699 entry points
1
+ [build:enterprise] found 703 entry points
2
2
  [build:enterprise] built successfully
@@ -1,4 +1,4 @@
1
- import { asClass, asValue } from "awilix";
1
+ import { asClass, asFunction, asValue } from "awilix";
2
2
  import { SsoProviderRegistry } from "./lib/registry.js";
3
3
  import { OidcProvider } from "./lib/oidc-provider.js";
4
4
  import { SsoService } from "./services/ssoService.js";
@@ -7,10 +7,12 @@ import { SsoConfigService } from "./services/ssoConfigService.js";
7
7
  import { HrdService } from "./services/hrdService.js";
8
8
  import { ScimTokenService } from "./services/scimTokenService.js";
9
9
  import { ScimService } from "./services/scimService.js";
10
+ import { SsoAuthService } from "./services/ssoAuthService.js";
10
11
  function register(container) {
11
12
  const registry = new SsoProviderRegistry();
12
13
  registry.register(new OidcProvider());
13
14
  container.register({
15
+ authService: asFunction(({ em }) => new SsoAuthService(em)).scoped().proxy(),
14
16
  ssoProviderRegistry: asValue(registry),
15
17
  ssoService: asClass(SsoService).scoped(),
16
18
  accountLinkingService: asClass(AccountLinkingService).scoped(),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/sso/di.ts"],
4
- "sourcesContent": ["import { asClass, asValue } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { SsoProviderRegistry } from './lib/registry'\nimport { OidcProvider } from './lib/oidc-provider'\nimport { SsoService } from './services/ssoService'\nimport { AccountLinkingService } from './services/accountLinkingService'\nimport { SsoConfigService } from './services/ssoConfigService'\nimport { HrdService } from './services/hrdService'\nimport { ScimTokenService } from './services/scimTokenService'\nimport { ScimService } from './services/scimService'\n\nexport function register(container: AppContainer) {\n const registry = new SsoProviderRegistry()\n registry.register(new OidcProvider())\n\n container.register({\n ssoProviderRegistry: asValue(registry),\n ssoService: asClass(SsoService).scoped(),\n accountLinkingService: asClass(AccountLinkingService).scoped(),\n ssoConfigService: asClass(SsoConfigService).scoped(),\n hrdService: asClass(HrdService).scoped(),\n scimTokenService: asClass(ScimTokenService).scoped(),\n scimService: asClass(ScimService).scoped(),\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS,eAAe;AAEjC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAErB,SAAS,SAAS,WAAyB;AAChD,QAAM,WAAW,IAAI,oBAAoB;AACzC,WAAS,SAAS,IAAI,aAAa,CAAC;AAEpC,YAAU,SAAS;AAAA,IACjB,qBAAqB,QAAQ,QAAQ;AAAA,IACrC,YAAY,QAAQ,UAAU,EAAE,OAAO;AAAA,IACvC,uBAAuB,QAAQ,qBAAqB,EAAE,OAAO;AAAA,IAC7D,kBAAkB,QAAQ,gBAAgB,EAAE,OAAO;AAAA,IACnD,YAAY,QAAQ,UAAU,EAAE,OAAO;AAAA,IACvC,kBAAkB,QAAQ,gBAAgB,EAAE,OAAO;AAAA,IACnD,aAAa,QAAQ,WAAW,EAAE,OAAO;AAAA,EAC3C,CAAC;AACH;",
4
+ "sourcesContent": ["import { asClass, asFunction, asValue } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { SsoProviderRegistry } from './lib/registry'\nimport { OidcProvider } from './lib/oidc-provider'\nimport { SsoService } from './services/ssoService'\nimport { AccountLinkingService } from './services/accountLinkingService'\nimport { SsoConfigService } from './services/ssoConfigService'\nimport { HrdService } from './services/hrdService'\nimport { ScimTokenService } from './services/scimTokenService'\nimport { ScimService } from './services/scimService'\nimport { SsoAuthService } from './services/ssoAuthService'\n\nexport function register(container: AppContainer) {\n const registry = new SsoProviderRegistry()\n registry.register(new OidcProvider())\n\n container.register({\n authService: asFunction(({ em }: { em: EntityManager }) => new SsoAuthService(em)).scoped().proxy(),\n ssoProviderRegistry: asValue(registry),\n ssoService: asClass(SsoService).scoped(),\n accountLinkingService: asClass(AccountLinkingService).scoped(),\n ssoConfigService: asClass(SsoConfigService).scoped(),\n hrdService: asClass(HrdService).scoped(),\n scimTokenService: asClass(ScimTokenService).scoped(),\n scimService: asClass(ScimService).scoped(),\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS,YAAY,eAAe;AAG7C,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAExB,SAAS,SAAS,WAAyB;AAChD,QAAM,WAAW,IAAI,oBAAoB;AACzC,WAAS,SAAS,IAAI,aAAa,CAAC;AAEpC,YAAU,SAAS;AAAA,IACjB,aAAa,WAAW,CAAC,EAAE,GAAG,MAA6B,IAAI,eAAe,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM;AAAA,IAClG,qBAAqB,QAAQ,QAAQ;AAAA,IACrC,YAAY,QAAQ,UAAU,EAAE,OAAO;AAAA,IACvC,uBAAuB,QAAQ,qBAAqB,EAAE,OAAO;AAAA,IAC7D,kBAAkB,QAAQ,gBAAgB,EAAE,OAAO;AAAA,IACnD,YAAY,QAAQ,UAAU,EAAE,OAAO;AAAA,IACvC,kBAAkB,QAAQ,gBAAgB,EAAE,OAAO;AAAA,IACnD,aAAa,QAAQ,WAAW,EAAE,OAAO;AAAA,EAC3C,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,55 @@
1
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
2
+ import { Organization } from "@open-mercato/core/modules/directory/data/entities";
3
+ import { SsoConfig, SsoUserDeactivation } from "../data/entities.js";
4
+ async function isSsoUserDeactivated(em, scope) {
5
+ if (!scope.organizationId) return false;
6
+ const deactivation = await findOneWithDecryption(
7
+ em,
8
+ SsoUserDeactivation,
9
+ {
10
+ userId: scope.userId,
11
+ tenantId: scope.tenantId,
12
+ organizationId: scope.organizationId,
13
+ reactivatedAt: null,
14
+ ...scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}
15
+ },
16
+ {},
17
+ { tenantId: scope.tenantId, organizationId: scope.organizationId }
18
+ );
19
+ if (deactivation) return true;
20
+ if (!scope.tenantId) return false;
21
+ const legacyDeactivation = await findOneWithDecryption(
22
+ em,
23
+ SsoUserDeactivation,
24
+ {
25
+ userId: scope.userId,
26
+ tenantId: null,
27
+ organizationId: scope.organizationId,
28
+ reactivatedAt: null,
29
+ ...scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}
30
+ },
31
+ {},
32
+ { tenantId: scope.tenantId, organizationId: scope.organizationId }
33
+ );
34
+ if (!legacyDeactivation) return false;
35
+ const organization = await findOneWithDecryption(
36
+ em,
37
+ Organization,
38
+ { id: scope.organizationId, tenant: scope.tenantId },
39
+ { fields: ["id"] },
40
+ { tenantId: scope.tenantId, organizationId: scope.organizationId }
41
+ );
42
+ if (!organization) return false;
43
+ const config = await findOneWithDecryption(
44
+ em,
45
+ SsoConfig,
46
+ { id: legacyDeactivation.ssoConfigId, organizationId: scope.organizationId, tenantId: null },
47
+ { fields: ["id"] },
48
+ { tenantId: null, organizationId: scope.organizationId }
49
+ );
50
+ return config !== null;
51
+ }
52
+ export {
53
+ isSsoUserDeactivated
54
+ };
55
+ //# sourceMappingURL=deactivation.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/sso/lib/deactivation.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { SsoConfig, SsoUserDeactivation } from '../data/entities'\n\ntype DeactivationScope = {\n userId: string\n tenantId: string | null\n organizationId: string | null\n ssoConfigId?: string\n}\n\nexport async function isSsoUserDeactivated(em: EntityManager, scope: DeactivationScope): Promise<boolean> {\n if (!scope.organizationId) return false\n\n const deactivation = await findOneWithDecryption(\n em,\n SsoUserDeactivation,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n reactivatedAt: null,\n ...(scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}),\n },\n {},\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (deactivation) return true\n if (!scope.tenantId) return false\n\n const legacyDeactivation = await findOneWithDecryption(\n em, SsoUserDeactivation,\n {\n userId: scope.userId,\n tenantId: null,\n organizationId: scope.organizationId,\n reactivatedAt: null,\n ...(scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}),\n },\n {},\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!legacyDeactivation) return false\n\n const organization = await findOneWithDecryption(\n em, Organization,\n { id: scope.organizationId, tenant: scope.tenantId },\n { fields: ['id'] },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!organization) return false\n\n const config = await findOneWithDecryption(\n em, SsoConfig,\n { id: legacyDeactivation.ssoConfigId, organizationId: scope.organizationId, tenantId: null },\n { fields: ['id'] },\n { tenantId: null, organizationId: scope.organizationId },\n )\n return config !== null\n}\n"],
5
+ "mappings": "AACA,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,WAAW,2BAA2B;AAS/C,eAAsB,qBAAqB,IAAmB,OAA4C;AACxG,MAAI,CAAC,MAAM,eAAgB,QAAO;AAElC,QAAM,eAAe,MAAM;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,MACE,QAAQ,MAAM;AAAA,MACd,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,eAAe;AAAA,MACf,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,IAChE;AAAA,IACA,CAAC;AAAA,IACD,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,MAAI,aAAc,QAAO;AACzB,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,qBAAqB,MAAM;AAAA,IAC/B;AAAA,IAAI;AAAA,IACJ;AAAA,MACE,QAAQ,MAAM;AAAA,MACd,UAAU;AAAA,MACV,gBAAgB,MAAM;AAAA,MACtB,eAAe;AAAA,MACf,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,IAChE;AAAA,IACA,CAAC;AAAA,IACD,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,MAAI,CAAC,mBAAoB,QAAO;AAEhC,QAAM,eAAe,MAAM;AAAA,IACzB;AAAA,IAAI;AAAA,IACJ,EAAE,IAAI,MAAM,gBAAgB,QAAQ,MAAM,SAAS;AAAA,IACnD,EAAE,QAAQ,CAAC,IAAI,EAAE;AAAA,IACjB,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,MAAI,CAAC,aAAc,QAAO;AAE1B,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IAAI;AAAA,IACJ,EAAE,IAAI,mBAAmB,aAAa,gBAAgB,MAAM,gBAAgB,UAAU,KAAK;AAAA,IAC3F,EAAE,QAAQ,CAAC,IAAI,EAAE;AAAA,IACjB,EAAE,UAAU,MAAM,gBAAgB,MAAM,eAAe;AAAA,EACzD;AACA,SAAO,WAAW;AACpB;",
6
+ "names": []
7
+ }
@@ -7,6 +7,7 @@ import { EmailNotVerifiedError, SsoRolesRevokedError } from "../lib/errors.js";
7
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
8
8
  import { conflict } from "@open-mercato/shared/lib/crud/errors";
9
9
  import { lockUserRoleWriterAuthorizationState } from "@open-mercato/core/modules/auth/lib/authorizationStateLocks";
10
+ import { isSsoUserDeactivated } from "../lib/deactivation.js";
10
11
  const logger = createLogger("sso").child({ component: "account-linking" });
11
12
  class AccountLinkingService {
12
13
  constructor(em) {
@@ -60,6 +61,7 @@ class AccountLinkingService {
60
61
  await this.em.flush();
61
62
  return null;
62
63
  }
64
+ await this.requireActiveUser(user.id, ssoConfigId, tenantId, organizationId);
63
65
  identity.lastLoginAt = /* @__PURE__ */ new Date();
64
66
  await this.em.flush();
65
67
  return { user, identity };
@@ -81,6 +83,7 @@ class AccountLinkingService {
81
83
  { tenantId, organizationId: config.organizationId }
82
84
  );
83
85
  if (!user) return null;
86
+ await this.requireActiveUser(user.id, config.id, tenantId, config.organizationId);
84
87
  const now = /* @__PURE__ */ new Date();
85
88
  const identity = this.em.create(SsoIdentity, {
86
89
  tenantId,
@@ -105,6 +108,11 @@ class AccountLinkingService {
105
108
  }).catch((eventError) => logger.error("SSO event emit failed", { err: eventError }));
106
109
  return { user, identity };
107
110
  }
111
+ async requireActiveUser(userId, ssoConfigId, tenantId, organizationId, em = this.em) {
112
+ if (await isSsoUserDeactivated(em, { userId, ssoConfigId, tenantId: tenantId || null, organizationId })) {
113
+ throw new Error("[internal] SSO identity is deactivated");
114
+ }
115
+ }
108
116
  async jitProvision(config, idpPayload, tenantId) {
109
117
  return this.em.transactional(async (txEm) => {
110
118
  const user = txEm.create(User, {
@@ -191,6 +199,7 @@ class AccountLinkingService {
191
199
  userIds: [String(user.id)],
192
200
  roleIds: Array.from(lockedRoleIds)
193
201
  });
202
+ await this.requireActiveUser(user.id, config.id, resolvedTenantId, config.organizationId, em);
194
203
  allRoles = await em.find(Role, {
195
204
  tenantId: resolvedTenantId,
196
205
  deletedAt: null
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sso/services/accountLinkingService.ts"],
4
- "sourcesContent": ["import { EntityManager, type FilterQuery, type RequiredEntityData } from '@mikro-orm/postgresql'\nimport { User, UserRole, Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { SsoConfig, SsoIdentity, SsoRoleGrant, ScimToken } from '../data/entities'\nimport { emitSsoEvent } from '../events'\nimport { EmailNotVerifiedError, SsoRolesRevokedError } from '../lib/errors'\nimport type { SsoIdentityPayload } from '../lib/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { conflict } from '@open-mercato/shared/lib/crud/errors'\nimport { lockUserRoleWriterAuthorizationState } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\n\nconst logger = createLogger('sso').child({ component: 'account-linking' })\n\nexport class AccountLinkingService {\n constructor(private em: EntityManager) {}\n\n async resolveUser(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity }> {\n const existing = await this.findExistingLink(config.id, idpPayload.subject, tenantId, config.organizationId)\n if (existing) {\n await this.assignRolesFromSso(this.em, existing.user, config, tenantId, idpPayload.groups)\n return existing\n }\n\n if (idpPayload.emailVerified !== true) {\n throw new EmailNotVerifiedError('IdP did not verify the email claim \u2014 cannot link or provision account')\n }\n\n const emailDomain = idpPayload.email.split('@')[1]?.toLowerCase()\n if (!emailDomain || !config.allowedDomains.some((d) => d.toLowerCase() === emailDomain)) {\n throw new Error('Email domain is not in the allowed domains for this SSO configuration')\n }\n\n const emailLinked = config.autoLinkByEmail\n ? await this.linkByEmail(config, idpPayload, tenantId)\n : null\n if (emailLinked) {\n await this.assignRolesFromSso(this.em, emailLinked.user, config, tenantId, idpPayload.groups)\n return emailLinked\n }\n\n if (config.jitEnabled) {\n const scimActive = await this.em.count(ScimToken, { ssoConfigId: config.id, isActive: true }) > 0\n if (scimActive) {\n throw new Error('JIT provisioning is disabled because SCIM directory sync is active')\n }\n return this.jitProvision(config, idpPayload, tenantId)\n }\n\n throw new Error('No matching user found and JIT provisioning is disabled')\n }\n\n private async findExistingLink(\n ssoConfigId: string,\n idpSubject: string,\n tenantId: string,\n organizationId: string,\n ): Promise<{ user: User; identity: SsoIdentity } | null> {\n const identity = await findOneWithDecryption(\n this.em,\n SsoIdentity,\n { ssoConfigId, idpSubject, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n if (!identity) return null\n\n const user = await findOneWithDecryption(\n this.em,\n User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n if (!user) {\n identity.deletedAt = new Date()\n await this.em.flush()\n return null\n }\n\n identity.lastLoginAt = new Date()\n await this.em.flush()\n\n return { user, identity }\n }\n\n private async linkByEmail(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity } | null> {\n const emailHash = computeEmailHash(idpPayload.email)\n const user = await findOneWithDecryption(\n this.em,\n User,\n {\n organizationId: config.organizationId,\n deletedAt: null,\n $or: [\n { email: idpPayload.email },\n { emailHash },\n ],\n } as FilterQuery<User>,\n {},\n { tenantId, organizationId: config.organizationId },\n )\n if (!user) return null\n\n const now = new Date()\n const identity = this.em.create(SsoIdentity, {\n tenantId,\n organizationId: config.organizationId,\n ssoConfigId: config.id,\n userId: user.id,\n idpSubject: idpPayload.subject,\n idpEmail: idpPayload.email,\n idpName: idpPayload.name ?? null,\n idpGroups: idpPayload.groups ?? [],\n provisioningMethod: 'manual',\n firstLoginAt: now,\n lastLoginAt: now,\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await this.em.persist(identity).flush()\n\n void emitSsoEvent('sso.identity.linked', {\n id: identity.id,\n tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return { user, identity }\n }\n\n private async jitProvision(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity }> {\n return this.em.transactional(async (txEm) => {\n const user = txEm.create(User, {\n tenantId,\n organizationId: config.organizationId,\n email: idpPayload.email,\n emailHash: computeEmailHash(idpPayload.email),\n name: idpPayload.name ?? null,\n passwordHash: null,\n isConfirmed: true,\n createdAt: new Date(),\n })\n await txEm.persist(user).flush()\n\n await this.assignRolesFromSso(txEm, user, config, tenantId, idpPayload.groups)\n\n const now = new Date()\n const identity = txEm.create(SsoIdentity, {\n tenantId,\n organizationId: config.organizationId,\n ssoConfigId: config.id,\n userId: user.id,\n idpSubject: idpPayload.subject,\n idpEmail: idpPayload.email,\n idpName: idpPayload.name ?? null,\n idpGroups: idpPayload.groups ?? [],\n provisioningMethod: 'jit',\n firstLoginAt: now,\n lastLoginAt: now,\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await txEm.persist(identity).flush()\n\n void emitSsoEvent('sso.identity.created', {\n id: identity.id,\n tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return { user, identity }\n })\n }\n\n private async assignRolesFromSso(\n em: EntityManager,\n user: User,\n config: SsoConfig,\n tenantId: string,\n idpGroups?: string[],\n ): Promise<void> {\n const hasMappings = config.appRoleMappings && Object.keys(config.appRoleMappings).length > 0\n if (!hasMappings) return\n\n const synchronize = async (transactionalEm: EntityManager): Promise<boolean> => {\n const managedUser = typeof transactionalEm.getReference === 'function'\n ? transactionalEm.getReference(User, String(user.id))\n : user\n await this.syncMappedRoles(transactionalEm, managedUser, config, tenantId, idpGroups)\n const remainingGrant = await transactionalEm.findOne(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n })\n return remainingGrant !== null\n }\n const hasAnySsoRole = typeof em.isInTransaction === 'function' && em.isInTransaction()\n ? await synchronize(em)\n : await em.transactional(synchronize)\n if (!hasAnySsoRole) {\n throw new SsoRolesRevokedError(\n String(user.id),\n 'No roles could be resolved from IdP groups \u2014 login denied. Configure role mappings or ensure the IdP sends matching group claims.',\n )\n }\n }\n\n /**\n * Sync/replace SSO-sourced roles: on each login, SSO-managed roles are replaced\n * with what the IdP sends, while manually-assigned roles are preserved.\n */\n private async syncMappedRoles(\n em: EntityManager,\n user: User,\n config: SsoConfig,\n tenantId: string,\n idpGroups?: string[],\n ): Promise<void> {\n const resolvedTenantId = tenantId || user.tenantId || ''\n if (!resolvedTenantId) return\n\n const desiredRoleNames = resolveRoleNamesFromIdpGroups(idpGroups, config.appRoleMappings)\n let allRoles = await em.find(Role, {\n tenantId: resolvedTenantId,\n deletedAt: null,\n } as FilterQuery<Role>)\n let desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)\n\n // Query current SSO grants for this user+config\n let existingGrants = await em.find(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n })\n let allUserRoles = await em.find(UserRole, { user: user.id } as FilterQuery<UserRole>)\n const lockedRoleIds = new Set([\n ...desiredRoleIds,\n ...existingGrants.map((grant) => grant.roleId),\n ...allUserRoles\n .filter((userRole) => userRole.deletedAt)\n .map((userRole) => String(userRole.role?.id ?? userRole.role)),\n ])\n await lockUserRoleWriterAuthorizationState(em, {\n userIds: [String(user.id)],\n roleIds: Array.from(lockedRoleIds),\n })\n allRoles = await em.find(Role, {\n tenantId: resolvedTenantId,\n deletedAt: null,\n } as FilterQuery<Role>, { refresh: true })\n existingGrants = await em.find(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n }, { refresh: true })\n allUserRoles = await em.find(\n UserRole,\n { user: user.id } as FilterQuery<UserRole>,\n { refresh: true },\n )\n\n desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)\n const existingGrantedRoleIds = new Set(existingGrants.map((g) => g.roleId))\n\n // Compute diff\n const toAdd = [...desiredRoleIds].filter((id) => !existingGrantedRoleIds.has(id))\n const toRemove = existingGrants.filter((g) => !desiredRoleIds.has(g.roleId))\n const softDeletedUserRoles = allUserRoles.filter((userRole) => userRole.deletedAt)\n assertRoleMutationFootprintWasLocked([\n ...desiredRoleIds,\n ...toRemove.map((grant) => grant.roleId),\n ...softDeletedUserRoles.map((userRole) => String(userRole.role?.id ?? userRole.role)),\n ], lockedRoleIds)\n\n // Add new roles\n for (const roleId of toAdd) {\n const role = allRoles.find((r) => r.id === roleId)\n if (!role) continue\n await this.ensureUserRole(em, user, role)\n const grant = em.create(SsoRoleGrant, {\n tenantId: resolvedTenantId,\n organizationId: config.organizationId,\n userId: user.id,\n roleId,\n ssoConfigId: config.id,\n } as RequiredEntityData<SsoRoleGrant>)\n em.persist(grant)\n }\n\n // Remove stale SSO-sourced roles\n for (const grant of toRemove) {\n const userRole = await em.findOne(UserRole, {\n user: user.id,\n role: grant.roleId,\n deletedAt: null,\n } as FilterQuery<UserRole>)\n if (userRole) {\n em.remove(userRole)\n }\n em.remove(grant)\n }\n\n // Clean up orphaned soft-deleted UserRole rows (ghost rows from previous soft-delete logic)\n for (const userRole of softDeletedUserRoles) {\n em.remove(userRole)\n }\n\n if (toAdd.length > 0 || toRemove.length > 0 || softDeletedUserRoles.length > 0) {\n await em.flush()\n }\n }\n\n private async ensureUserRole(em: EntityManager, user: User, role: Role): Promise<void> {\n const existingLink = await em.findOne(UserRole, {\n user: user.id,\n role: role.id,\n deletedAt: null,\n } as FilterQuery<UserRole>)\n if (existingLink) return\n\n const userRole = em.create(UserRole, { user, role, createdAt: new Date() })\n em.persist(userRole)\n }\n}\n\nfunction assertRoleMutationFootprintWasLocked(\n roleIds: Iterable<string>,\n lockedRoleIds: ReadonlySet<string>,\n): void {\n for (const roleId of roleIds) {\n if (!lockedRoleIds.has(roleId)) {\n throw conflict('[internal] Authorization state changed while acquiring its lock footprint')\n }\n }\n}\n\nfunction resolveActiveRoleIds(roles: Role[], desiredRoleNames: string[]): Set<string> {\n const roleByNormalizedName = new Map<string, Role>()\n for (const role of roles) {\n const normalized = normalizeToken(role.name)\n if (normalized) roleByNormalizedName.set(normalized, role)\n }\n\n const desiredRoleIds = new Set<string>()\n for (const roleName of desiredRoleNames) {\n const role = roleByNormalizedName.get(roleName)\n if (role) desiredRoleIds.add(role.id)\n }\n return desiredRoleIds\n}\n\nfunction resolveRoleNamesFromIdpGroups(\n idpGroups?: string[],\n configMappings?: Record<string, string>,\n): string[] {\n if (!Array.isArray(idpGroups) || idpGroups.length === 0) return []\n\n const normalizedGroups = idpGroups\n .map((group) => normalizeToken(group))\n .filter((group): group is string => group !== null)\n if (normalizedGroups.length === 0) return []\n\n const mergedMappings = loadMergedMappings(configMappings)\n const roleNames = new Set<string>()\n\n for (const group of normalizedGroups) {\n const mapped = mergedMappings.get(group)\n if (!mapped?.length) continue\n\n for (const role of mapped) roleNames.add(role)\n }\n\n return Array.from(roleNames)\n}\n\nfunction loadMergedMappings(configMappings?: Record<string, string>): Map<string, string[]> {\n const mappings = new Map<string, string[]>()\n\n if (configMappings && Object.keys(configMappings).length > 0) {\n for (const [group, roleName] of Object.entries(configMappings)) {\n const normalizedGroup = normalizeToken(group)\n if (!normalizedGroup) continue\n const normalizedRole = normalizeToken(roleName)\n if (!normalizedRole) continue\n mappings.set(normalizedGroup, [normalizedRole])\n }\n }\n\n return mappings\n}\n\nfunction normalizeToken(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const normalized = value.trim().toLowerCase()\n return normalized.length > 0 ? normalized : null\n}\n"],
5
- "mappings": "AACA,SAAS,MAAM,UAAU,YAAY;AACrC,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAoB,aAAa,cAAc,iBAAiB;AAChE,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,4BAA4B;AAE5D,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,4CAA4C;AAErD,MAAM,SAAS,aAAa,KAAK,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAElE,MAAM,sBAAsB;AAAA,EACjC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AA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;AAC9C,UAAI,CAAC,eAAgB;AACrB,eAAS,IAAI,iBAAiB,CAAC,cAAc,CAAC;AAAA,IAChD;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,eAAe,OAA+B;AACrD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,aAAa,MAAM,KAAK,EAAE,YAAY;AAC5C,SAAO,WAAW,SAAS,IAAI,aAAa;AAC9C;",
4
+ "sourcesContent": ["import { EntityManager, type FilterQuery, type RequiredEntityData } from '@mikro-orm/postgresql'\nimport { User, UserRole, Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { SsoConfig, SsoIdentity, SsoRoleGrant, ScimToken } from '../data/entities'\nimport { emitSsoEvent } from '../events'\nimport { EmailNotVerifiedError, SsoRolesRevokedError } from '../lib/errors'\nimport type { SsoIdentityPayload } from '../lib/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { conflict } from '@open-mercato/shared/lib/crud/errors'\nimport { lockUserRoleWriterAuthorizationState } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\nimport { isSsoUserDeactivated } from '../lib/deactivation'\n\nconst logger = createLogger('sso').child({ component: 'account-linking' })\n\nexport class AccountLinkingService {\n constructor(private em: EntityManager) {}\n\n async resolveUser(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity }> {\n const existing = await this.findExistingLink(config.id, idpPayload.subject, tenantId, config.organizationId)\n if (existing) {\n await this.assignRolesFromSso(this.em, existing.user, config, tenantId, idpPayload.groups)\n return existing\n }\n\n if (idpPayload.emailVerified !== true) {\n throw new EmailNotVerifiedError('IdP did not verify the email claim \u2014 cannot link or provision account')\n }\n\n const emailDomain = idpPayload.email.split('@')[1]?.toLowerCase()\n if (!emailDomain || !config.allowedDomains.some((d) => d.toLowerCase() === emailDomain)) {\n throw new Error('Email domain is not in the allowed domains for this SSO configuration')\n }\n\n const emailLinked = config.autoLinkByEmail\n ? await this.linkByEmail(config, idpPayload, tenantId)\n : null\n if (emailLinked) {\n await this.assignRolesFromSso(this.em, emailLinked.user, config, tenantId, idpPayload.groups)\n return emailLinked\n }\n\n if (config.jitEnabled) {\n const scimActive = await this.em.count(ScimToken, { ssoConfigId: config.id, isActive: true }) > 0\n if (scimActive) {\n throw new Error('JIT provisioning is disabled because SCIM directory sync is active')\n }\n return this.jitProvision(config, idpPayload, tenantId)\n }\n\n throw new Error('No matching user found and JIT provisioning is disabled')\n }\n\n private async findExistingLink(\n ssoConfigId: string,\n idpSubject: string,\n tenantId: string,\n organizationId: string,\n ): Promise<{ user: User; identity: SsoIdentity } | null> {\n const identity = await findOneWithDecryption(\n this.em,\n SsoIdentity,\n { ssoConfigId, idpSubject, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n if (!identity) return null\n\n const user = await findOneWithDecryption(\n this.em,\n User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n if (!user) {\n identity.deletedAt = new Date()\n await this.em.flush()\n return null\n }\n\n await this.requireActiveUser(user.id, ssoConfigId, tenantId, organizationId)\n\n identity.lastLoginAt = new Date()\n await this.em.flush()\n\n return { user, identity }\n }\n\n private async linkByEmail(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity } | null> {\n const emailHash = computeEmailHash(idpPayload.email)\n const user = await findOneWithDecryption(\n this.em,\n User,\n {\n organizationId: config.organizationId,\n deletedAt: null,\n $or: [\n { email: idpPayload.email },\n { emailHash },\n ],\n } as FilterQuery<User>,\n {},\n { tenantId, organizationId: config.organizationId },\n )\n if (!user) return null\n\n await this.requireActiveUser(user.id, config.id, tenantId, config.organizationId)\n\n const now = new Date()\n const identity = this.em.create(SsoIdentity, {\n tenantId,\n organizationId: config.organizationId,\n ssoConfigId: config.id,\n userId: user.id,\n idpSubject: idpPayload.subject,\n idpEmail: idpPayload.email,\n idpName: idpPayload.name ?? null,\n idpGroups: idpPayload.groups ?? [],\n provisioningMethod: 'manual',\n firstLoginAt: now,\n lastLoginAt: now,\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await this.em.persist(identity).flush()\n\n void emitSsoEvent('sso.identity.linked', {\n id: identity.id,\n tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return { user, identity }\n }\n\n private async requireActiveUser(\n userId: string,\n ssoConfigId: string,\n tenantId: string,\n organizationId: string,\n em: EntityManager = this.em,\n ): Promise<void> {\n if (await isSsoUserDeactivated(em, { userId, ssoConfigId, tenantId: tenantId || null, organizationId })) {\n throw new Error('[internal] SSO identity is deactivated')\n }\n }\n\n private async jitProvision(\n config: SsoConfig,\n idpPayload: SsoIdentityPayload,\n tenantId: string,\n ): Promise<{ user: User; identity: SsoIdentity }> {\n return this.em.transactional(async (txEm) => {\n const user = txEm.create(User, {\n tenantId,\n organizationId: config.organizationId,\n email: idpPayload.email,\n emailHash: computeEmailHash(idpPayload.email),\n name: idpPayload.name ?? null,\n passwordHash: null,\n isConfirmed: true,\n createdAt: new Date(),\n })\n await txEm.persist(user).flush()\n\n await this.assignRolesFromSso(txEm, user, config, tenantId, idpPayload.groups)\n\n const now = new Date()\n const identity = txEm.create(SsoIdentity, {\n tenantId,\n organizationId: config.organizationId,\n ssoConfigId: config.id,\n userId: user.id,\n idpSubject: idpPayload.subject,\n idpEmail: idpPayload.email,\n idpName: idpPayload.name ?? null,\n idpGroups: idpPayload.groups ?? [],\n provisioningMethod: 'jit',\n firstLoginAt: now,\n lastLoginAt: now,\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await txEm.persist(identity).flush()\n\n void emitSsoEvent('sso.identity.created', {\n id: identity.id,\n tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return { user, identity }\n })\n }\n\n private async assignRolesFromSso(\n em: EntityManager,\n user: User,\n config: SsoConfig,\n tenantId: string,\n idpGroups?: string[],\n ): Promise<void> {\n const hasMappings = config.appRoleMappings && Object.keys(config.appRoleMappings).length > 0\n if (!hasMappings) return\n\n const synchronize = async (transactionalEm: EntityManager): Promise<boolean> => {\n const managedUser = typeof transactionalEm.getReference === 'function'\n ? transactionalEm.getReference(User, String(user.id))\n : user\n await this.syncMappedRoles(transactionalEm, managedUser, config, tenantId, idpGroups)\n const remainingGrant = await transactionalEm.findOne(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n })\n return remainingGrant !== null\n }\n const hasAnySsoRole = typeof em.isInTransaction === 'function' && em.isInTransaction()\n ? await synchronize(em)\n : await em.transactional(synchronize)\n if (!hasAnySsoRole) {\n throw new SsoRolesRevokedError(\n String(user.id),\n 'No roles could be resolved from IdP groups \u2014 login denied. Configure role mappings or ensure the IdP sends matching group claims.',\n )\n }\n }\n\n /**\n * Sync/replace SSO-sourced roles: on each login, SSO-managed roles are replaced\n * with what the IdP sends, while manually-assigned roles are preserved.\n */\n private async syncMappedRoles(\n em: EntityManager,\n user: User,\n config: SsoConfig,\n tenantId: string,\n idpGroups?: string[],\n ): Promise<void> {\n const resolvedTenantId = tenantId || user.tenantId || ''\n if (!resolvedTenantId) return\n\n const desiredRoleNames = resolveRoleNamesFromIdpGroups(idpGroups, config.appRoleMappings)\n let allRoles = await em.find(Role, {\n tenantId: resolvedTenantId,\n deletedAt: null,\n } as FilterQuery<Role>)\n let desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)\n\n // Query current SSO grants for this user+config\n let existingGrants = await em.find(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n })\n let allUserRoles = await em.find(UserRole, { user: user.id } as FilterQuery<UserRole>)\n const lockedRoleIds = new Set([\n ...desiredRoleIds,\n ...existingGrants.map((grant) => grant.roleId),\n ...allUserRoles\n .filter((userRole) => userRole.deletedAt)\n .map((userRole) => String(userRole.role?.id ?? userRole.role)),\n ])\n await lockUserRoleWriterAuthorizationState(em, {\n userIds: [String(user.id)],\n roleIds: Array.from(lockedRoleIds),\n })\n await this.requireActiveUser(user.id, config.id, resolvedTenantId, config.organizationId, em)\n allRoles = await em.find(Role, {\n tenantId: resolvedTenantId,\n deletedAt: null,\n } as FilterQuery<Role>, { refresh: true })\n existingGrants = await em.find(SsoRoleGrant, {\n userId: user.id,\n ssoConfigId: config.id,\n }, { refresh: true })\n allUserRoles = await em.find(\n UserRole,\n { user: user.id } as FilterQuery<UserRole>,\n { refresh: true },\n )\n\n desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames)\n const existingGrantedRoleIds = new Set(existingGrants.map((g) => g.roleId))\n\n // Compute diff\n const toAdd = [...desiredRoleIds].filter((id) => !existingGrantedRoleIds.has(id))\n const toRemove = existingGrants.filter((g) => !desiredRoleIds.has(g.roleId))\n const softDeletedUserRoles = allUserRoles.filter((userRole) => userRole.deletedAt)\n assertRoleMutationFootprintWasLocked([\n ...desiredRoleIds,\n ...toRemove.map((grant) => grant.roleId),\n ...softDeletedUserRoles.map((userRole) => String(userRole.role?.id ?? userRole.role)),\n ], lockedRoleIds)\n\n // Add new roles\n for (const roleId of toAdd) {\n const role = allRoles.find((r) => r.id === roleId)\n if (!role) continue\n await this.ensureUserRole(em, user, role)\n const grant = em.create(SsoRoleGrant, {\n tenantId: resolvedTenantId,\n organizationId: config.organizationId,\n userId: user.id,\n roleId,\n ssoConfigId: config.id,\n } as RequiredEntityData<SsoRoleGrant>)\n em.persist(grant)\n }\n\n // Remove stale SSO-sourced roles\n for (const grant of toRemove) {\n const userRole = await em.findOne(UserRole, {\n user: user.id,\n role: grant.roleId,\n deletedAt: null,\n } as FilterQuery<UserRole>)\n if (userRole) {\n em.remove(userRole)\n }\n em.remove(grant)\n }\n\n // Clean up orphaned soft-deleted UserRole rows (ghost rows from previous soft-delete logic)\n for (const userRole of softDeletedUserRoles) {\n em.remove(userRole)\n }\n\n if (toAdd.length > 0 || toRemove.length > 0 || softDeletedUserRoles.length > 0) {\n await em.flush()\n }\n }\n\n private async ensureUserRole(em: EntityManager, user: User, role: Role): Promise<void> {\n const existingLink = await em.findOne(UserRole, {\n user: user.id,\n role: role.id,\n deletedAt: null,\n } as FilterQuery<UserRole>)\n if (existingLink) return\n\n const userRole = em.create(UserRole, { user, role, createdAt: new Date() })\n em.persist(userRole)\n }\n}\n\nfunction assertRoleMutationFootprintWasLocked(\n roleIds: Iterable<string>,\n lockedRoleIds: ReadonlySet<string>,\n): void {\n for (const roleId of roleIds) {\n if (!lockedRoleIds.has(roleId)) {\n throw conflict('[internal] Authorization state changed while acquiring its lock footprint')\n }\n }\n}\n\nfunction resolveActiveRoleIds(roles: Role[], desiredRoleNames: string[]): Set<string> {\n const roleByNormalizedName = new Map<string, Role>()\n for (const role of roles) {\n const normalized = normalizeToken(role.name)\n if (normalized) roleByNormalizedName.set(normalized, role)\n }\n\n const desiredRoleIds = new Set<string>()\n for (const roleName of desiredRoleNames) {\n const role = roleByNormalizedName.get(roleName)\n if (role) desiredRoleIds.add(role.id)\n }\n return desiredRoleIds\n}\n\nfunction resolveRoleNamesFromIdpGroups(\n idpGroups?: string[],\n configMappings?: Record<string, string>,\n): string[] {\n if (!Array.isArray(idpGroups) || idpGroups.length === 0) return []\n\n const normalizedGroups = idpGroups\n .map((group) => normalizeToken(group))\n .filter((group): group is string => group !== null)\n if (normalizedGroups.length === 0) return []\n\n const mergedMappings = loadMergedMappings(configMappings)\n const roleNames = new Set<string>()\n\n for (const group of normalizedGroups) {\n const mapped = mergedMappings.get(group)\n if (!mapped?.length) continue\n\n for (const role of mapped) roleNames.add(role)\n }\n\n return Array.from(roleNames)\n}\n\nfunction loadMergedMappings(configMappings?: Record<string, string>): Map<string, string[]> {\n const mappings = new Map<string, string[]>()\n\n if (configMappings && Object.keys(configMappings).length > 0) {\n for (const [group, roleName] of Object.entries(configMappings)) {\n const normalizedGroup = normalizeToken(group)\n if (!normalizedGroup) continue\n const normalizedRole = normalizeToken(roleName)\n if (!normalizedRole) continue\n mappings.set(normalizedGroup, [normalizedRole])\n }\n }\n\n return mappings\n}\n\nfunction normalizeToken(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const normalized = value.trim().toLowerCase()\n return normalized.length > 0 ? normalized : null\n}\n"],
5
+ "mappings": "AACA,SAAS,MAAM,UAAU,YAAY;AACrC,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAoB,aAAa,cAAc,iBAAiB;AAChE,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,4BAA4B;AAE5D,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,4CAA4C;AACrD,SAAS,4BAA4B;AAErC,MAAM,SAAS,aAAa,KAAK,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAElE,MAAM,sBAAsB;AAAA,EACjC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,YACJ,QACA,YACA,UACgD;AAChD,UAAM,WAAW,MAAM,KAAK,iBAAiB,OAAO,IAAI,WAAW,SAAS,UAAU,OAAO,cAAc;AAC3G,QAAI,UAAU;AACZ,YAAM,KAAK,mBAAmB,KAAK,IAAI,SAAS,MAAM,QAAQ,UAAU,WAAW,MAAM;AACzF,aAAO;AAAA,IACT;AAEA,QAAI,WAAW,kBAAkB,MAAM;AACrC,YAAM,IAAI,sBAAsB,4EAAuE;AAAA,IACzG;AAEA,UAAM,cAAc,WAAW,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,YAAY;AAChE,QAAI,CAAC,eAAe,CAAC,OAAO,eAAe,KAAK,CAAC,MAAM,EAAE,YAAY,MAAM,WAAW,GAAG;AACvF,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAEA,UAAM,cAAc,OAAO,kBACvB,MAAM,KAAK,YAAY,QAAQ,YAAY,QAAQ,IACnD;AACJ,QAAI,aAA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AAM,KAAK,EAAE,YAAY;AAC5C,SAAO,WAAW,SAAS,IAAI,aAAa;AAC9C;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,6 @@
1
1
  import { User, Session } from "@open-mercato/core/modules/auth/data/entities";
2
2
  import { computeEmailHash } from "@open-mercato/core/modules/auth/lib/emailHash";
3
+ import { lockAuthorizationUserRows } from "@open-mercato/core/modules/auth/lib/authorizationStateLocks";
3
4
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
4
5
  import { SsoIdentity, SsoUserDeactivation, ScimProvisioningLog } from "../data/entities.js";
5
6
  import { toScimUserResource, fromScimUserPayload } from "../lib/scim-mapper.js";
@@ -272,59 +273,54 @@ class ScimService {
272
273
  }
273
274
  }
274
275
  async deactivateUser(userId, scope) {
275
- await this.em.transactional(async (txEm) => {
276
- let deactivation = await txEm.findOne(SsoUserDeactivation, {
276
+ return this.em.transactional((txEm) => this.deactivateUserInTransaction(txEm, userId, scope));
277
+ }
278
+ async deactivateUserInTransaction(txEm, userId, scope) {
279
+ await lockAuthorizationUserRows(txEm, [userId]);
280
+ let deactivation = await findOneWithDecryption(
281
+ txEm,
282
+ SsoUserDeactivation,
283
+ { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },
284
+ { refresh: true },
285
+ { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId }
286
+ );
287
+ if (deactivation) {
288
+ deactivation.deactivatedAt = /* @__PURE__ */ new Date();
289
+ deactivation.reactivatedAt = null;
290
+ } else {
291
+ deactivation = txEm.create(SsoUserDeactivation, {
292
+ tenantId: scope.tenantId ?? null,
293
+ organizationId: scope.organizationId,
277
294
  userId,
278
- ssoConfigId: scope.ssoConfigId
295
+ ssoConfigId: scope.ssoConfigId,
296
+ deactivatedAt: /* @__PURE__ */ new Date()
279
297
  });
280
- if (deactivation) {
281
- deactivation.deactivatedAt = /* @__PURE__ */ new Date();
282
- deactivation.reactivatedAt = null;
283
- } else {
284
- deactivation = txEm.create(SsoUserDeactivation, {
285
- tenantId: scope.tenantId ?? null,
286
- organizationId: scope.organizationId,
287
- userId,
288
- ssoConfigId: scope.ssoConfigId,
289
- deactivatedAt: /* @__PURE__ */ new Date()
290
- });
291
- txEm.persist(deactivation);
292
- }
293
- const sessionWhere = { user: userId };
294
- await txEm.nativeDelete(Session, sessionWhere);
295
- });
298
+ txEm.persist(deactivation);
299
+ }
300
+ const sessionWhere = { user: userId };
301
+ await txEm.nativeDelete(Session, sessionWhere);
302
+ return deactivation;
296
303
  }
297
304
  async reactivateUser(userId, scope) {
298
- const deactivation = await this.em.findOne(SsoUserDeactivation, {
299
- userId,
300
- ssoConfigId: scope.ssoConfigId
305
+ await this.em.transactional(async (txEm) => {
306
+ await lockAuthorizationUserRows(txEm, [userId]);
307
+ const deactivation = await findOneWithDecryption(
308
+ txEm,
309
+ SsoUserDeactivation,
310
+ { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },
311
+ { refresh: true },
312
+ { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId }
313
+ );
314
+ if (deactivation && !deactivation.reactivatedAt) {
315
+ deactivation.reactivatedAt = /* @__PURE__ */ new Date();
316
+ }
301
317
  });
302
- if (deactivation && !deactivation.reactivatedAt) {
303
- deactivation.reactivatedAt = /* @__PURE__ */ new Date();
304
- await this.em.flush();
305
- }
306
318
  }
307
319
  async createDeactivation(userId, scope) {
308
- const deactivation = this.em.create(SsoUserDeactivation, {
309
- tenantId: scope.tenantId ?? null,
310
- organizationId: scope.organizationId,
311
- userId,
312
- ssoConfigId: scope.ssoConfigId,
313
- deactivatedAt: /* @__PURE__ */ new Date()
314
- });
315
- await this.em.persist(deactivation).flush();
316
- return deactivation;
320
+ return this.deactivateUser(userId, scope);
317
321
  }
318
322
  async createDeactivationTx(txEm, userId, scope) {
319
- const deactivation = txEm.create(SsoUserDeactivation, {
320
- tenantId: scope.tenantId ?? null,
321
- organizationId: scope.organizationId,
322
- userId,
323
- ssoConfigId: scope.ssoConfigId,
324
- deactivatedAt: /* @__PURE__ */ new Date()
325
- });
326
- await txEm.persist(deactivation).flush();
327
- return deactivation;
323
+ return this.deactivateUserInTransaction(txEm, userId, scope);
328
324
  }
329
325
  async log(scope, operation, resourceId, externalId, responseStatus, errorMessage) {
330
326
  const entry = this.em.create(ScimProvisioningLog, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sso/services/scimService.ts"],
4
- "sourcesContent": ["import { EntityManager, type FilterQuery, type RequiredEntityData } from '@mikro-orm/postgresql'\nimport { User, Session } from '@open-mercato/core/modules/auth/data/entities'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { SsoIdentity, SsoUserDeactivation, ScimProvisioningLog } from '../data/entities'\nimport { toScimUserResource, fromScimUserPayload, type ScimUserResource, type ScimUserPayload } from '../lib/scim-mapper'\nimport { coerceBoolean } from '../lib/scim-utils'\nimport { parseScimFilter, scimFilterToWhere } from '../lib/scim-filter'\nimport { buildListResponse } from '../lib/scim-response'\nimport type { ScimScope } from '../api/scim/context'\nimport type { ScimPatchOperation } from '../lib/scim-patch'\n\nexport class ScimService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n payload: Record<string, unknown>,\n scope: ScimScope,\n baseUrl: string,\n ): Promise<{ resource: ScimUserResource; status: number }> {\n const parsed = fromScimUserPayload(payload)\n const email = parsed.email ?? parsed.userName\n if (!email) {\n throw new ScimServiceError(400, 'userName or emails[0].value is required')\n }\n\n // Idempotency: if externalId already exists for this config, return existing\n if (parsed.externalId) {\n const existingIdentity = await this.em.findOne(SsoIdentity, {\n ssoConfigId: scope.ssoConfigId,\n externalId: parsed.externalId,\n deletedAt: null,\n })\n if (existingIdentity) {\n const existingUser = await findOneWithDecryption(\n this.em, User,\n { id: existingIdentity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (existingUser) {\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: existingUser.id, ssoConfigId: scope.ssoConfigId,\n })\n await this.log(scope, 'CREATE', existingIdentity.id, parsed.externalId, 200)\n return {\n resource: toScimUserResource(existingUser, existingIdentity, baseUrl, deactivation),\n status: 200,\n }\n }\n }\n }\n\n // Check if user already exists by email\n const emailHash = computeEmailHash(email)\n const where: FilterQuery<User> = {\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: [{ email }, { emailHash }],\n }\n const existingUser = await findOneWithDecryption(\n this.em, User,\n where,\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n\n if (existingUser) {\n // Check if already linked to this SSO config\n const existingLink = await this.em.findOne(SsoIdentity, {\n ssoConfigId: scope.ssoConfigId,\n userId: existingUser.id,\n deletedAt: null,\n })\n if (existingLink) {\n throw new ScimServiceError(409, `User with email ${email} is already linked to this SSO configuration`)\n }\n\n // Auto-link: create SsoIdentity for existing user\n const now = new Date()\n const identity = this.em.create(SsoIdentity, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n userId: existingUser.id,\n idpSubject: parsed.externalId ?? email,\n idpEmail: email,\n idpName: buildDisplayName(parsed),\n idpGroups: [],\n externalId: parsed.externalId ?? null,\n provisioningMethod: 'scim',\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await this.em.persist(identity).flush()\n\n const deactivation = parsed.active === false\n ? await this.createDeactivation(existingUser.id, scope)\n : null\n\n await this.log(scope, 'CREATE', identity.id, parsed.externalId, 201)\n return {\n resource: toScimUserResource(existingUser, identity, baseUrl, deactivation),\n status: 201,\n }\n }\n\n // Create new user + identity\n return this.em.transactional(async (txEm) => {\n const user = txEm.create(User, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n email,\n emailHash: computeEmailHash(email),\n name: buildDisplayName(parsed) ?? undefined,\n passwordHash: null,\n isConfirmed: true,\n createdAt: new Date(),\n })\n await txEm.persist(user).flush()\n\n const now = new Date()\n const identity = txEm.create(SsoIdentity, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n userId: user.id,\n idpSubject: parsed.externalId ?? email,\n idpEmail: email,\n idpName: buildDisplayName(parsed),\n idpGroups: [],\n externalId: parsed.externalId ?? null,\n provisioningMethod: 'scim',\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await txEm.persist(identity).flush()\n\n const deactivation = parsed.active === false\n ? await this.createDeactivationTx(txEm, user.id, scope)\n : null\n\n await this.logTx(txEm, scope, 'CREATE', identity.id, parsed.externalId, 201)\n return {\n resource: toScimUserResource(user, identity, baseUrl, deactivation),\n status: 201,\n }\n })\n }\n\n async getUser(scimId: string, scope: ScimScope, baseUrl: string): Promise<ScimUserResource> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n const user = await findOneWithDecryption(\n this.em, User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (!user) throw new ScimServiceError(404, 'User not found')\n\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: user.id, ssoConfigId: scope.ssoConfigId,\n })\n\n return toScimUserResource(user, identity, baseUrl, deactivation)\n }\n\n async listUsers(\n filter: string | null,\n startIndex: number,\n count: number,\n scope: ScimScope,\n baseUrl: string,\n ): Promise<Record<string, unknown>> {\n const conditions = parseScimFilter(filter)\n const where = scimFilterToWhere(conditions, scope.ssoConfigId, scope.organizationId)\n\n const offset = Math.max(0, startIndex - 1)\n const [identities, total] = await this.em.findAndCount(SsoIdentity, where, {\n orderBy: { createdAt: 'asc' },\n limit: count,\n offset,\n })\n\n const userIds = identities.map((i) => i.userId)\n\n const users = userIds.length > 0\n ? await findWithDecryption(\n this.em, User,\n { id: { $in: userIds }, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n : []\n const userMap = new Map(users.map((u) => [u.id, u]))\n\n const deactivations = userIds.length > 0\n ? await this.em.find(SsoUserDeactivation, {\n userId: { $in: userIds }, ssoConfigId: scope.ssoConfigId,\n })\n : []\n const deactivationMap = new Map(deactivations.map((d) => [d.userId, d]))\n\n const resources: ScimUserResource[] = []\n for (const identity of identities) {\n const user = userMap.get(identity.userId)\n if (!user) continue\n\n const deactivation = deactivationMap.get(user.id) ?? null\n resources.push(toScimUserResource(user, identity, baseUrl, deactivation))\n }\n\n return buildListResponse(resources, total, startIndex, resources.length)\n }\n\n async patchUser(\n scimId: string,\n operations: ScimPatchOperation[],\n scope: ScimScope,\n baseUrl: string,\n ): Promise<ScimUserResource> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n const user = await findOneWithDecryption(\n this.em, User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (!user) throw new ScimServiceError(404, 'User not found')\n\n for (const op of operations) {\n const normalizedOp = op.op.toLowerCase()\n if (normalizedOp === 'replace' || normalizedOp === 'add') {\n this.applyPatchValue(user, identity, op.path, op.value)\n }\n // 'remove' operations on optional fields \u2014 set to null\n if (normalizedOp === 'remove' && op.path) {\n this.applyPatchValue(user, identity, op.path, null)\n }\n }\n\n // Handle active status changes\n const activeOp = operations.find((op) =>\n op.path?.toLowerCase() === 'active' ||\n (!op.path && op.value && typeof op.value === 'object' && 'active' in (op.value as Record<string, unknown>)),\n )\n\n if (activeOp) {\n const activeValue = activeOp.path\n ? coerceBoolean(activeOp.value)\n : coerceBoolean((activeOp.value as Record<string, unknown>).active)\n\n if (activeValue === false) {\n await this.deactivateUser(user.id, scope)\n } else if (activeValue === true) {\n await this.reactivateUser(user.id, scope)\n }\n }\n\n await this.em.flush()\n\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: user.id, ssoConfigId: scope.ssoConfigId,\n })\n\n await this.log(scope, 'PATCH', identity.id, identity.externalId, 200)\n return toScimUserResource(user, identity, baseUrl, deactivation)\n }\n\n async deleteUser(scimId: string, scope: ScimScope): Promise<void> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n await this.deactivateUser(identity.userId, scope)\n await this.log(scope, 'DELETE', identity.id, identity.externalId, 204)\n }\n\n private applyPatchValue(\n user: User,\n identity: SsoIdentity,\n path: string | undefined,\n value: unknown,\n ): void {\n if (!path) {\n // No path means value is an object with attribute keys\n if (value && typeof value === 'object') {\n const obj = value as Record<string, unknown>\n for (const [key, val] of Object.entries(obj)) {\n this.applyPatchValue(user, identity, key, val)\n }\n }\n return\n }\n\n const normalizedPath = path.toLowerCase()\n switch (normalizedPath) {\n case 'displayname':\n user.name = (value as string) || undefined\n identity.idpName = (value as string) ?? null\n break\n case 'name.givenname': {\n const currentParts = (user.name ?? '').split(' ')\n currentParts[0] = (value as string) ?? ''\n user.name = currentParts.join(' ').trim() || undefined\n break\n }\n case 'name.familyname': {\n const currentParts = (user.name ?? '').split(' ')\n const given = currentParts[0] ?? ''\n user.name = value ? `${given} ${value}`.trim() : given || undefined\n break\n }\n case 'username':\n identity.idpEmail = (value as string) ?? identity.idpEmail\n break\n case 'externalid':\n identity.externalId = (value as string) ?? null\n break\n case 'active':\n // Handled separately via deactivation logic\n break\n }\n }\n\n private async deactivateUser(userId: string, scope: ScimScope): Promise<void> {\n await this.em.transactional(async (txEm) => {\n let deactivation = await txEm.findOne(SsoUserDeactivation, {\n userId, ssoConfigId: scope.ssoConfigId,\n })\n\n if (deactivation) {\n deactivation.deactivatedAt = new Date()\n deactivation.reactivatedAt = null\n } else {\n deactivation = txEm.create(SsoUserDeactivation, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n userId,\n ssoConfigId: scope.ssoConfigId,\n deactivatedAt: new Date(),\n } as RequiredEntityData<SsoUserDeactivation>)\n txEm.persist(deactivation)\n }\n\n // Revoke all active sessions atomically with the deactivation upsert\n const sessionWhere: FilterQuery<Session> = { user: userId }\n await txEm.nativeDelete(Session, sessionWhere)\n })\n }\n\n private async reactivateUser(userId: string, scope: ScimScope): Promise<void> {\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId, ssoConfigId: scope.ssoConfigId,\n })\n if (deactivation && !deactivation.reactivatedAt) {\n deactivation.reactivatedAt = new Date()\n await this.em.flush()\n }\n }\n\n private async createDeactivation(userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {\n const deactivation = this.em.create(SsoUserDeactivation, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n userId,\n ssoConfigId: scope.ssoConfigId,\n deactivatedAt: new Date(),\n } as RequiredEntityData<SsoUserDeactivation>)\n await this.em.persist(deactivation).flush()\n return deactivation\n }\n\n private async createDeactivationTx(txEm: EntityManager, userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {\n const deactivation = txEm.create(SsoUserDeactivation, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n userId,\n ssoConfigId: scope.ssoConfigId,\n deactivatedAt: new Date(),\n } as RequiredEntityData<SsoUserDeactivation>)\n await txEm.persist(deactivation).flush()\n return deactivation\n }\n\n private async log(\n scope: ScimScope,\n operation: string,\n resourceId: string | null | undefined,\n externalId: string | null | undefined,\n responseStatus: number,\n errorMessage?: string,\n ): Promise<void> {\n const entry = this.em.create(ScimProvisioningLog, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n operation,\n resourceType: 'User',\n resourceId: resourceId ?? null,\n scimExternalId: externalId ?? null,\n responseStatus,\n errorMessage: errorMessage ?? null,\n } as RequiredEntityData<ScimProvisioningLog>)\n await this.em.persist(entry).flush()\n }\n\n private async logTx(\n txEm: EntityManager,\n scope: ScimScope,\n operation: string,\n resourceId: string | null | undefined,\n externalId: string | null | undefined,\n responseStatus: number,\n ): Promise<void> {\n const entry = txEm.create(ScimProvisioningLog, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n operation,\n resourceType: 'User',\n resourceId: resourceId ?? null,\n scimExternalId: externalId ?? null,\n responseStatus,\n } as RequiredEntityData<ScimProvisioningLog>)\n await txEm.persist(entry).flush()\n }\n}\n\nfunction buildDisplayName(parsed: ScimUserPayload): string | null {\n if (parsed.displayName) return parsed.displayName\n const parts = [parsed.givenName, parsed.familyName].filter(Boolean)\n return parts.length > 0 ? parts.join(' ') : null\n}\n\nexport class ScimServiceError extends Error {\n constructor(\n public readonly statusCode: number,\n message: string,\n ) {\n super(message)\n this.name = 'ScimServiceError'\n }\n}\n"],
5
- "mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,wBAAwB;AACjC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,aAAa,qBAAqB,2BAA2B;AACtE,SAAS,oBAAoB,2BAAwE;AACrG,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB,yBAAyB;AACnD,SAAS,yBAAyB;AAI3B,MAAM,YAAY;AAAA,EACvB,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,WACJ,SACA,OACA,SACyD;AACzD,UAAM,SAAS,oBAAoB,OAAO;AAC1C,UAAM,QAAQ,OAAO,SAAS,OAAO;AACrC,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,iBAAiB,KAAK,yCAAyC;AAAA,IAC3E;AAGA,QAAI,OAAO,YAAY;AACrB,YAAM,mBAAmB,MA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cAAc;AAAA,MAC9B;AAAA,IACF,CAA4C;AAC5C,UAAM,KAAK,QAAQ,KAAK,EAAE,MAAM;AAAA,EAClC;AACF;AAEA,SAAS,iBAAiB,QAAwC;AAChE,MAAI,OAAO,YAAa,QAAO,OAAO;AACtC,QAAM,QAAQ,CAAC,OAAO,WAAW,OAAO,UAAU,EAAE,OAAO,OAAO;AAClE,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,GAAG,IAAI;AAC9C;AAEO,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YACkB,YAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AACF;",
4
+ "sourcesContent": ["import { EntityManager, type FilterQuery, type RequiredEntityData } from '@mikro-orm/postgresql'\nimport { User, Session } from '@open-mercato/core/modules/auth/data/entities'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { lockAuthorizationUserRows } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { SsoIdentity, SsoUserDeactivation, ScimProvisioningLog } from '../data/entities'\nimport { toScimUserResource, fromScimUserPayload, type ScimUserResource, type ScimUserPayload } from '../lib/scim-mapper'\nimport { coerceBoolean } from '../lib/scim-utils'\nimport { parseScimFilter, scimFilterToWhere } from '../lib/scim-filter'\nimport { buildListResponse } from '../lib/scim-response'\nimport type { ScimScope } from '../api/scim/context'\nimport type { ScimPatchOperation } from '../lib/scim-patch'\n\nexport class ScimService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n payload: Record<string, unknown>,\n scope: ScimScope,\n baseUrl: string,\n ): Promise<{ resource: ScimUserResource; status: number }> {\n const parsed = fromScimUserPayload(payload)\n const email = parsed.email ?? parsed.userName\n if (!email) {\n throw new ScimServiceError(400, 'userName or emails[0].value is required')\n }\n\n // Idempotency: if externalId already exists for this config, return existing\n if (parsed.externalId) {\n const existingIdentity = await this.em.findOne(SsoIdentity, {\n ssoConfigId: scope.ssoConfigId,\n externalId: parsed.externalId,\n deletedAt: null,\n })\n if (existingIdentity) {\n const existingUser = await findOneWithDecryption(\n this.em, User,\n { id: existingIdentity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (existingUser) {\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: existingUser.id, ssoConfigId: scope.ssoConfigId,\n })\n await this.log(scope, 'CREATE', existingIdentity.id, parsed.externalId, 200)\n return {\n resource: toScimUserResource(existingUser, existingIdentity, baseUrl, deactivation),\n status: 200,\n }\n }\n }\n }\n\n // Check if user already exists by email\n const emailHash = computeEmailHash(email)\n const where: FilterQuery<User> = {\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: [{ email }, { emailHash }],\n }\n const existingUser = await findOneWithDecryption(\n this.em, User,\n where,\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n\n if (existingUser) {\n // Check if already linked to this SSO config\n const existingLink = await this.em.findOne(SsoIdentity, {\n ssoConfigId: scope.ssoConfigId,\n userId: existingUser.id,\n deletedAt: null,\n })\n if (existingLink) {\n throw new ScimServiceError(409, `User with email ${email} is already linked to this SSO configuration`)\n }\n\n // Auto-link: create SsoIdentity for existing user\n const now = new Date()\n const identity = this.em.create(SsoIdentity, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n userId: existingUser.id,\n idpSubject: parsed.externalId ?? email,\n idpEmail: email,\n idpName: buildDisplayName(parsed),\n idpGroups: [],\n externalId: parsed.externalId ?? null,\n provisioningMethod: 'scim',\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await this.em.persist(identity).flush()\n\n const deactivation = parsed.active === false\n ? await this.createDeactivation(existingUser.id, scope)\n : null\n\n await this.log(scope, 'CREATE', identity.id, parsed.externalId, 201)\n return {\n resource: toScimUserResource(existingUser, identity, baseUrl, deactivation),\n status: 201,\n }\n }\n\n // Create new user + identity\n return this.em.transactional(async (txEm) => {\n const user = txEm.create(User, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n email,\n emailHash: computeEmailHash(email),\n name: buildDisplayName(parsed) ?? undefined,\n passwordHash: null,\n isConfirmed: true,\n createdAt: new Date(),\n })\n await txEm.persist(user).flush()\n\n const now = new Date()\n const identity = txEm.create(SsoIdentity, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n userId: user.id,\n idpSubject: parsed.externalId ?? email,\n idpEmail: email,\n idpName: buildDisplayName(parsed),\n idpGroups: [],\n externalId: parsed.externalId ?? null,\n provisioningMethod: 'scim',\n createdAt: now,\n updatedAt: now,\n } as RequiredEntityData<SsoIdentity>)\n await txEm.persist(identity).flush()\n\n const deactivation = parsed.active === false\n ? await this.createDeactivationTx(txEm, user.id, scope)\n : null\n\n await this.logTx(txEm, scope, 'CREATE', identity.id, parsed.externalId, 201)\n return {\n resource: toScimUserResource(user, identity, baseUrl, deactivation),\n status: 201,\n }\n })\n }\n\n async getUser(scimId: string, scope: ScimScope, baseUrl: string): Promise<ScimUserResource> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n const user = await findOneWithDecryption(\n this.em, User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (!user) throw new ScimServiceError(404, 'User not found')\n\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: user.id, ssoConfigId: scope.ssoConfigId,\n })\n\n return toScimUserResource(user, identity, baseUrl, deactivation)\n }\n\n async listUsers(\n filter: string | null,\n startIndex: number,\n count: number,\n scope: ScimScope,\n baseUrl: string,\n ): Promise<Record<string, unknown>> {\n const conditions = parseScimFilter(filter)\n const where = scimFilterToWhere(conditions, scope.ssoConfigId, scope.organizationId)\n\n const offset = Math.max(0, startIndex - 1)\n const [identities, total] = await this.em.findAndCount(SsoIdentity, where, {\n orderBy: { createdAt: 'asc' },\n limit: count,\n offset,\n })\n\n const userIds = identities.map((i) => i.userId)\n\n const users = userIds.length > 0\n ? await findWithDecryption(\n this.em, User,\n { id: { $in: userIds }, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n : []\n const userMap = new Map(users.map((u) => [u.id, u]))\n\n const deactivations = userIds.length > 0\n ? await this.em.find(SsoUserDeactivation, {\n userId: { $in: userIds }, ssoConfigId: scope.ssoConfigId,\n })\n : []\n const deactivationMap = new Map(deactivations.map((d) => [d.userId, d]))\n\n const resources: ScimUserResource[] = []\n for (const identity of identities) {\n const user = userMap.get(identity.userId)\n if (!user) continue\n\n const deactivation = deactivationMap.get(user.id) ?? null\n resources.push(toScimUserResource(user, identity, baseUrl, deactivation))\n }\n\n return buildListResponse(resources, total, startIndex, resources.length)\n }\n\n async patchUser(\n scimId: string,\n operations: ScimPatchOperation[],\n scope: ScimScope,\n baseUrl: string,\n ): Promise<ScimUserResource> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n const user = await findOneWithDecryption(\n this.em, User,\n { id: identity.userId, deletedAt: null },\n {},\n { tenantId: scope.tenantId ?? '', organizationId: scope.organizationId },\n )\n if (!user) throw new ScimServiceError(404, 'User not found')\n\n for (const op of operations) {\n const normalizedOp = op.op.toLowerCase()\n if (normalizedOp === 'replace' || normalizedOp === 'add') {\n this.applyPatchValue(user, identity, op.path, op.value)\n }\n // 'remove' operations on optional fields \u2014 set to null\n if (normalizedOp === 'remove' && op.path) {\n this.applyPatchValue(user, identity, op.path, null)\n }\n }\n\n // Handle active status changes\n const activeOp = operations.find((op) =>\n op.path?.toLowerCase() === 'active' ||\n (!op.path && op.value && typeof op.value === 'object' && 'active' in (op.value as Record<string, unknown>)),\n )\n\n if (activeOp) {\n const activeValue = activeOp.path\n ? coerceBoolean(activeOp.value)\n : coerceBoolean((activeOp.value as Record<string, unknown>).active)\n\n if (activeValue === false) {\n await this.deactivateUser(user.id, scope)\n } else if (activeValue === true) {\n await this.reactivateUser(user.id, scope)\n }\n }\n\n await this.em.flush()\n\n const deactivation = await this.em.findOne(SsoUserDeactivation, {\n userId: user.id, ssoConfigId: scope.ssoConfigId,\n })\n\n await this.log(scope, 'PATCH', identity.id, identity.externalId, 200)\n return toScimUserResource(user, identity, baseUrl, deactivation)\n }\n\n async deleteUser(scimId: string, scope: ScimScope): Promise<void> {\n const identity = await this.em.findOne(SsoIdentity, {\n id: scimId,\n ssoConfigId: scope.ssoConfigId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!identity) throw new ScimServiceError(404, 'User not found')\n\n await this.deactivateUser(identity.userId, scope)\n await this.log(scope, 'DELETE', identity.id, identity.externalId, 204)\n }\n\n private applyPatchValue(\n user: User,\n identity: SsoIdentity,\n path: string | undefined,\n value: unknown,\n ): void {\n if (!path) {\n // No path means value is an object with attribute keys\n if (value && typeof value === 'object') {\n const obj = value as Record<string, unknown>\n for (const [key, val] of Object.entries(obj)) {\n this.applyPatchValue(user, identity, key, val)\n }\n }\n return\n }\n\n const normalizedPath = path.toLowerCase()\n switch (normalizedPath) {\n case 'displayname':\n user.name = (value as string) || undefined\n identity.idpName = (value as string) ?? null\n break\n case 'name.givenname': {\n const currentParts = (user.name ?? '').split(' ')\n currentParts[0] = (value as string) ?? ''\n user.name = currentParts.join(' ').trim() || undefined\n break\n }\n case 'name.familyname': {\n const currentParts = (user.name ?? '').split(' ')\n const given = currentParts[0] ?? ''\n user.name = value ? `${given} ${value}`.trim() : given || undefined\n break\n }\n case 'username':\n identity.idpEmail = (value as string) ?? identity.idpEmail\n break\n case 'externalid':\n identity.externalId = (value as string) ?? null\n break\n case 'active':\n // Handled separately via deactivation logic\n break\n }\n }\n\n private async deactivateUser(userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {\n return this.em.transactional((txEm) => this.deactivateUserInTransaction(txEm, userId, scope))\n }\n\n private async deactivateUserInTransaction(\n txEm: EntityManager,\n userId: string,\n scope: ScimScope,\n ): Promise<SsoUserDeactivation> {\n await lockAuthorizationUserRows(txEm, [userId])\n let deactivation = await findOneWithDecryption(\n txEm, SsoUserDeactivation,\n { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },\n { refresh: true },\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId },\n )\n if (deactivation) {\n deactivation.deactivatedAt = new Date()\n deactivation.reactivatedAt = null\n } else {\n deactivation = txEm.create(SsoUserDeactivation, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n userId,\n ssoConfigId: scope.ssoConfigId,\n deactivatedAt: new Date(),\n } as RequiredEntityData<SsoUserDeactivation>)\n txEm.persist(deactivation)\n }\n const sessionWhere: FilterQuery<Session> = { user: userId }\n await txEm.nativeDelete(Session, sessionWhere)\n return deactivation\n }\n\n private async reactivateUser(userId: string, scope: ScimScope): Promise<void> {\n await this.em.transactional(async (txEm) => {\n await lockAuthorizationUserRows(txEm, [userId])\n const deactivation = await findOneWithDecryption(\n txEm, SsoUserDeactivation,\n { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },\n { refresh: true },\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId },\n )\n if (deactivation && !deactivation.reactivatedAt) {\n deactivation.reactivatedAt = new Date()\n }\n })\n }\n\n private async createDeactivation(userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {\n return this.deactivateUser(userId, scope)\n }\n\n private async createDeactivationTx(txEm: EntityManager, userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {\n return this.deactivateUserInTransaction(txEm, userId, scope)\n }\n\n private async log(\n scope: ScimScope,\n operation: string,\n resourceId: string | null | undefined,\n externalId: string | null | undefined,\n responseStatus: number,\n errorMessage?: string,\n ): Promise<void> {\n const entry = this.em.create(ScimProvisioningLog, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n operation,\n resourceType: 'User',\n resourceId: resourceId ?? null,\n scimExternalId: externalId ?? null,\n responseStatus,\n errorMessage: errorMessage ?? null,\n } as RequiredEntityData<ScimProvisioningLog>)\n await this.em.persist(entry).flush()\n }\n\n private async logTx(\n txEm: EntityManager,\n scope: ScimScope,\n operation: string,\n resourceId: string | null | undefined,\n externalId: string | null | undefined,\n responseStatus: number,\n ): Promise<void> {\n const entry = txEm.create(ScimProvisioningLog, {\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n ssoConfigId: scope.ssoConfigId,\n operation,\n resourceType: 'User',\n resourceId: resourceId ?? null,\n scimExternalId: externalId ?? null,\n responseStatus,\n } as RequiredEntityData<ScimProvisioningLog>)\n await txEm.persist(entry).flush()\n }\n}\n\nfunction buildDisplayName(parsed: ScimUserPayload): string | null {\n if (parsed.displayName) return parsed.displayName\n const parts = [parsed.givenName, parsed.familyName].filter(Boolean)\n return parts.length > 0 ? parts.join(' ') : null\n}\n\nexport class ScimServiceError extends Error {\n constructor(\n public readonly statusCode: number,\n message: string,\n ) {\n super(message)\n this.name = 'ScimServiceError'\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;AAC1C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,aAAa,qBAAqB,2BAA2B;AACtE,SAAS,oBAAoB,2BAAwE;AACrG,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB,yBAAyB;AACnD,SAAS,yBAAyB;AAI3B,MAAM,YAAY;AAAA,EACvB,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,WACJ,SAC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,QAAQ,KAAK,EAAE,MAAM;AAAA,EACrC;AAAA,EAEA,MAAc,MACZ,MACA,OACA,WACA,YACA,YACA,gBACe;AACf,UAAM,QAAQ,KAAK,OAAO,qBAAqB;AAAA,MAC7C,UAAU,MAAM,YAAY;AAAA,MAC5B,gBAAgB,MAAM;AAAA,MACtB,aAAa,MAAM;AAAA,MACnB;AAAA,MACA,cAAc;AAAA,MACd,YAAY,cAAc;AAAA,MAC1B,gBAAgB,cAAc;AAAA,MAC9B;AAAA,IACF,CAA4C;AAC5C,UAAM,KAAK,QAAQ,KAAK,EAAE,MAAM;AAAA,EAClC;AACF;AAEA,SAAS,iBAAiB,QAAwC;AAChE,MAAI,OAAO,YAAa,QAAO,OAAO;AACtC,QAAM,QAAQ,CAAC,OAAO,WAAW,OAAO,UAAU,EAAE,OAAO,OAAO;AAClE,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,GAAG,IAAI;AAC9C;AAEO,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YACkB,YAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AACF;",
6
6
  "names": ["existingUser"]
7
7
  }
@@ -0,0 +1,46 @@
1
+ import { User } from "@open-mercato/core/modules/auth/data/entities";
2
+ import { AuthService } from "@open-mercato/core/modules/auth/services/authService";
3
+ import { AuthSessionRejectedError } from "@open-mercato/core/modules/auth/lib/sessionEligibility";
4
+ import { lockAuthorizationUserRows } from "@open-mercato/core/modules/auth/lib/authorizationStateLocks";
5
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
6
+ import { isSsoUserDeactivated } from "../lib/deactivation.js";
7
+ class SsoAuthService extends AuthService {
8
+ constructor(ssoEm) {
9
+ super(ssoEm);
10
+ this.ssoEm = ssoEm;
11
+ }
12
+ async verifyPassword(user, password) {
13
+ const verified = await super.verifyPassword(user, password);
14
+ if (!verified || !user) return false;
15
+ return !await isSsoUserDeactivated(this.ssoEm, {
16
+ userId: user.id,
17
+ tenantId: user.tenantId ?? null,
18
+ organizationId: user.organizationId ?? null
19
+ });
20
+ }
21
+ async createSession(user, expiresAt, scope) {
22
+ return this.ssoEm.transactional(async (txEm) => {
23
+ await lockAuthorizationUserRows(txEm, [user.id]);
24
+ const currentUser = await findOneWithDecryption(
25
+ txEm,
26
+ User,
27
+ { id: user.id, tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null, deletedAt: null },
28
+ { refresh: true },
29
+ { tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null }
30
+ );
31
+ if (!currentUser || await isSsoUserDeactivated(txEm, {
32
+ userId: user.id,
33
+ tenantId: scope ? scope.tenantId : currentUser.tenantId ?? null,
34
+ organizationId: scope ? scope.organizationId : currentUser.organizationId ?? null,
35
+ ...scope ? { ssoConfigId: scope.ssoConfigId } : {}
36
+ })) {
37
+ throw new AuthSessionRejectedError();
38
+ }
39
+ return this.createSessionWithEntityManager(txEm, currentUser, expiresAt);
40
+ });
41
+ }
42
+ }
43
+ export {
44
+ SsoAuthService
45
+ };
46
+ //# sourceMappingURL=ssoAuthService.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/sso/services/ssoAuthService.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User, type Session } from '@open-mercato/core/modules/auth/data/entities'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { AuthSessionRejectedError } from '@open-mercato/core/modules/auth/lib/sessionEligibility'\nimport { lockAuthorizationUserRows } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isSsoUserDeactivated } from '../lib/deactivation'\n\ntype SsoSessionScope = {\n tenantId: string | null\n organizationId: string\n ssoConfigId: string\n}\n\nexport class SsoAuthService extends AuthService {\n constructor(private ssoEm: EntityManager) {\n super(ssoEm)\n }\n\n override async verifyPassword(user: User | null, password: string): Promise<boolean> {\n const verified = await super.verifyPassword(user, password)\n if (!verified || !user) return false\n\n return !await isSsoUserDeactivated(this.ssoEm, {\n userId: user.id,\n tenantId: user.tenantId ?? null,\n organizationId: user.organizationId ?? null,\n })\n }\n\n override async createSession(\n user: User,\n expiresAt: Date,\n scope?: SsoSessionScope,\n ): Promise<{ session: Session; token: string }> {\n return this.ssoEm.transactional(async (txEm) => {\n await lockAuthorizationUserRows(txEm, [user.id])\n const currentUser = await findOneWithDecryption(\n txEm, User,\n { id: user.id, tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null, deletedAt: null },\n { refresh: true },\n { tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null },\n )\n if (!currentUser || await isSsoUserDeactivated(txEm, {\n userId: user.id,\n tenantId: scope ? scope.tenantId : currentUser.tenantId ?? null,\n organizationId: scope ? scope.organizationId : currentUser.organizationId ?? null,\n ...(scope ? { ssoConfigId: scope.ssoConfigId } : {}),\n })) {\n throw new AuthSessionRejectedError()\n }\n return this.createSessionWithEntityManager(txEm, currentUser, expiresAt)\n })\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,YAA0B;AACnC,SAAS,mBAAmB;AAC5B,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AAQ9B,MAAM,uBAAuB,YAAY;AAAA,EAC9C,YAAoB,OAAsB;AACxC,UAAM,KAAK;AADO;AAAA,EAEpB;AAAA,EAEA,MAAe,eAAe,MAAmB,UAAoC;AACnF,UAAM,WAAW,MAAM,MAAM,eAAe,MAAM,QAAQ;AAC1D,QAAI,CAAC,YAAY,CAAC,KAAM,QAAO;AAE/B,WAAO,CAAC,MAAM,qBAAqB,KAAK,OAAO;AAAA,MAC7C,QAAQ,KAAK;AAAA,MACb,UAAU,KAAK,YAAY;AAAA,MAC3B,gBAAgB,KAAK,kBAAkB;AAAA,IACzC,CAAC;AAAA,EACH;AAAA,EAEA,MAAe,cACb,MACA,WACA,OAC8C;AAC9C,WAAO,KAAK,MAAM,cAAc,OAAO,SAAS;AAC9C,YAAM,0BAA0B,MAAM,CAAC,KAAK,EAAE,CAAC;AAC/C,YAAM,cAAc,MAAM;AAAA,QACxB;AAAA,QAAM;AAAA,QACN,EAAE,IAAI,KAAK,IAAI,UAAU,KAAK,YAAY,MAAM,gBAAgB,KAAK,kBAAkB,MAAM,WAAW,KAAK;AAAA,QAC7G,EAAE,SAAS,KAAK;AAAA,QAChB,EAAE,UAAU,KAAK,YAAY,MAAM,gBAAgB,KAAK,kBAAkB,KAAK;AAAA,MACjF;AACA,UAAI,CAAC,eAAe,MAAM,qBAAqB,MAAM;AAAA,QACnD,QAAQ,KAAK;AAAA,QACb,UAAU,QAAQ,MAAM,WAAW,YAAY,YAAY;AAAA,QAC3D,gBAAgB,QAAQ,MAAM,iBAAiB,YAAY,kBAAkB;AAAA,QAC7E,GAAI,QAAQ,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,MACpD,CAAC,GAAG;AACF,cAAM,IAAI,yBAAyB;AAAA,MACrC;AACA,aAAO,KAAK,+BAA+B,MAAM,aAAa,SAAS;AAAA,IACzE,CAAC;AAAA,EACH;AACF;",
6
+ "names": []
7
+ }
@@ -97,7 +97,11 @@ class SsoService {
97
97
  await this.authService.updateLastLoginAt(user);
98
98
  const days = Number(process.env.REMEMBER_ME_DAYS || "30");
99
99
  const sessionExpiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1e3);
100
- const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt);
100
+ const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt, {
101
+ tenantId: config.tenantId ?? null,
102
+ organizationId: config.organizationId,
103
+ ssoConfigId: config.id
104
+ });
101
105
  const token = signJwt({
102
106
  sub: String(user.id),
103
107
  sid: String(session.id),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sso/services/ssoService.ts"],
4
- "sourcesContent": ["import crypto from 'node:crypto'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport type { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { SsoConfig } from '../data/entities'\nimport type { SsoProviderRegistry } from '../lib/registry'\nimport type { AccountLinkingService } from './accountLinkingService'\nimport { encryptStateCookie, decryptStateCookie, createFlowState } from '../lib/state-cookie'\nimport { emitSsoEvent } from '../events'\nimport { isSsoRolesRevokedError } from '../lib/errors'\nimport type { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sso').child({ component: 'service' })\n\nexport class SsoService {\n constructor(\n private em: EntityManager,\n private ssoProviderRegistry: SsoProviderRegistry,\n private accountLinkingService: AccountLinkingService,\n private tenantEncryptionService: TenantDataEncryptionService,\n private authService: AuthService,\n private rbacService: RbacService,\n ) {}\n\n async findConfigByEmail(email: string): Promise<SsoConfig | null> {\n const domain = email.split('@')[1]?.toLowerCase()\n if (!domain) return null\n\n const configs = await findWithDecryption(\n this.em,\n SsoConfig,\n { isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n const matches = configs.filter((c) => c.allowedDomains.some((d) => d.toLowerCase() === domain))\n return matches.length === 1 ? matches[0]! : null\n }\n\n async initiateLogin(\n configId: string,\n returnUrl: string,\n redirectUri: string,\n ): Promise<{ redirectUrl: string; stateCookie: string }> {\n const config = await findOneWithDecryption(\n this.em,\n SsoConfig,\n { id: configId, isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n if (!config) throw new Error('SSO configuration not found or inactive')\n\n const provider = this.ssoProviderRegistry.resolve(config.protocol)\n if (!provider) throw new Error(`No provider registered for protocol: ${config.protocol}`)\n\n const clientSecret = await this.decryptClientSecret(config)\n\n const { state } = createFlowState({ configId, returnUrl })\n\n void emitSsoEvent('sso.login.initiated', {\n tenantId: config.tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n const authUrl = await provider.buildAuthUrl(config, {\n state: state.state,\n nonce: state.nonce,\n redirectUri,\n codeVerifier: state.codeVerifier,\n clientSecret,\n })\n\n const stateCookie = encryptStateCookie(state)\n return { redirectUrl: authUrl, stateCookie }\n }\n\n async handleOidcCallback(\n callbackParams: Record<string, string>,\n stateCookie: string,\n redirectUri: string,\n ): Promise<{\n token: string\n sessionToken: string\n sessionExpiresAt: Date\n redirectUrl: string\n tenantId: string | null\n organizationId: string\n }> {\n const flowState = decryptStateCookie(stateCookie)\n if (!flowState) throw new Error('Invalid or expired SSO state')\n\n const receivedState = Buffer.from(callbackParams.state || '')\n const expectedState = Buffer.from(flowState.state)\n if (receivedState.length !== expectedState.length || !crypto.timingSafeEqual(receivedState, expectedState)) {\n throw new Error('State mismatch \u2014 possible CSRF attack')\n }\n\n const config = await findOneWithDecryption(\n this.em,\n SsoConfig,\n { id: flowState.configId, isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n if (!config) throw new Error('SSO configuration no longer active')\n\n const provider = this.ssoProviderRegistry.resolve(config.protocol)\n if (!provider) throw new Error(`No provider for protocol: ${config.protocol}`)\n\n const clientSecret = await this.decryptClientSecret(config)\n\n const idpPayload = await provider.handleCallback(config, {\n callbackParams,\n redirectUri,\n expectedState: flowState.state,\n expectedNonce: flowState.nonce,\n codeVerifier: flowState.codeVerifier,\n clientSecret,\n })\n\n const tenantId = config.tenantId ?? ''\n let user: Awaited<ReturnType<AccountLinkingService['resolveUser']>>['user']\n try {\n ;({ user } = await this.accountLinkingService.resolveUser(config, idpPayload, tenantId))\n } catch (err) {\n if (isSsoRolesRevokedError(err)) await this.rbacService.invalidateUserCache(err.userId)\n throw err\n }\n\n await this.rbacService.invalidateUserCache(String(user.id))\n\n const roles = await this.authService.getUserRoles(user, tenantId || null)\n\n await this.authService.updateLastLoginAt(user)\n\n const days = Number(process.env.REMEMBER_ME_DAYS || '30')\n const sessionExpiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000)\n const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt)\n\n const token = signJwt({\n sub: String(user.id),\n sid: String(session.id),\n tenantId: tenantId || null,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles,\n })\n\n void emitSsoEvent('sso.login.completed', {\n id: String(user.id),\n tenantId: config.tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return {\n token,\n sessionToken: sessionRefreshToken,\n sessionExpiresAt,\n redirectUrl: flowState.returnUrl || '/backend',\n tenantId: config.tenantId ?? null,\n organizationId: config.organizationId,\n }\n }\n\n private async decryptClientSecret(config: SsoConfig): Promise<string | undefined> {\n if (!config.clientSecretEnc) return undefined\n\n const decrypted = await this.tenantEncryptionService.decryptEntityPayload(\n config.id,\n { clientSecretEnc: config.clientSecretEnc },\n config.tenantId,\n config.organizationId,\n )\n return (decrypted.clientSecretEnc as string) ?? undefined\n }\n}\n"],
5
- "mappings": "AAAA,OAAO,YAAY;AAEnB,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,eAAe;AAGxB,SAAS,iBAAiB;AAG1B,SAAS,oBAAoB,oBAAoB,uBAAuB;AACxE,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,KAAK,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAE1D,MAAM,WAAW;AAAA,EACtB,YACU,IACA,qBACA,uBACA,yBACA,aACA,aACR;AANQ;AACA;AACA;AACA;AACA;AACA;AAAA,EACP;AAAA,EAEH,MAAM,kBAAkB,OAA0C;AAChE,UAAM,SAAS,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,YAAY;AAChD,QAAI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{ findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport type { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { SsoConfig } from '../data/entities'\nimport type { SsoProviderRegistry } from '../lib/registry'\nimport type { AccountLinkingService } from './accountLinkingService'\nimport type { SsoAuthService } from './ssoAuthService'\nimport { encryptStateCookie, decryptStateCookie, createFlowState } from '../lib/state-cookie'\nimport { emitSsoEvent } from '../events'\nimport { isSsoRolesRevokedError } from '../lib/errors'\nimport type { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sso').child({ component: 'service' })\n\nexport class SsoService {\n constructor(\n private em: EntityManager,\n private ssoProviderRegistry: SsoProviderRegistry,\n private accountLinkingService: AccountLinkingService,\n private tenantEncryptionService: TenantDataEncryptionService,\n private authService: AuthService & Pick<SsoAuthService, 'createSession'>,\n private rbacService: RbacService,\n ) {}\n\n async findConfigByEmail(email: string): Promise<SsoConfig | null> {\n const domain = email.split('@')[1]?.toLowerCase()\n if (!domain) return null\n\n const configs = await findWithDecryption(\n this.em,\n SsoConfig,\n { isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n const matches = configs.filter((c) => c.allowedDomains.some((d) => d.toLowerCase() === domain))\n return matches.length === 1 ? matches[0]! : null\n }\n\n async initiateLogin(\n configId: string,\n returnUrl: string,\n redirectUri: string,\n ): Promise<{ redirectUrl: string; stateCookie: string }> {\n const config = await findOneWithDecryption(\n this.em,\n SsoConfig,\n { id: configId, isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n if (!config) throw new Error('SSO configuration not found or inactive')\n\n const provider = this.ssoProviderRegistry.resolve(config.protocol)\n if (!provider) throw new Error(`No provider registered for protocol: ${config.protocol}`)\n\n const clientSecret = await this.decryptClientSecret(config)\n\n const { state } = createFlowState({ configId, returnUrl })\n\n void emitSsoEvent('sso.login.initiated', {\n tenantId: config.tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n const authUrl = await provider.buildAuthUrl(config, {\n state: state.state,\n nonce: state.nonce,\n redirectUri,\n codeVerifier: state.codeVerifier,\n clientSecret,\n })\n\n const stateCookie = encryptStateCookie(state)\n return { redirectUrl: authUrl, stateCookie }\n }\n\n async handleOidcCallback(\n callbackParams: Record<string, string>,\n stateCookie: string,\n redirectUri: string,\n ): Promise<{\n token: string\n sessionToken: string\n sessionExpiresAt: Date\n redirectUrl: string\n tenantId: string | null\n organizationId: string\n }> {\n const flowState = decryptStateCookie(stateCookie)\n if (!flowState) throw new Error('Invalid or expired SSO state')\n\n const receivedState = Buffer.from(callbackParams.state || '')\n const expectedState = Buffer.from(flowState.state)\n if (receivedState.length !== expectedState.length || !crypto.timingSafeEqual(receivedState, expectedState)) {\n throw new Error('State mismatch \u2014 possible CSRF attack')\n }\n\n const config = await findOneWithDecryption(\n this.em,\n SsoConfig,\n { id: flowState.configId, isActive: true, deletedAt: null },\n {},\n { tenantId: null },\n )\n if (!config) throw new Error('SSO configuration no longer active')\n\n const provider = this.ssoProviderRegistry.resolve(config.protocol)\n if (!provider) throw new Error(`No provider for protocol: ${config.protocol}`)\n\n const clientSecret = await this.decryptClientSecret(config)\n\n const idpPayload = await provider.handleCallback(config, {\n callbackParams,\n redirectUri,\n expectedState: flowState.state,\n expectedNonce: flowState.nonce,\n codeVerifier: flowState.codeVerifier,\n clientSecret,\n })\n\n const tenantId = config.tenantId ?? ''\n let user: Awaited<ReturnType<AccountLinkingService['resolveUser']>>['user']\n try {\n ;({ user } = await this.accountLinkingService.resolveUser(config, idpPayload, tenantId))\n } catch (err) {\n if (isSsoRolesRevokedError(err)) await this.rbacService.invalidateUserCache(err.userId)\n throw err\n }\n\n await this.rbacService.invalidateUserCache(String(user.id))\n\n const roles = await this.authService.getUserRoles(user, tenantId || null)\n\n await this.authService.updateLastLoginAt(user)\n\n const days = Number(process.env.REMEMBER_ME_DAYS || '30')\n const sessionExpiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000)\n const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt, {\n tenantId: config.tenantId ?? null,\n organizationId: config.organizationId,\n ssoConfigId: config.id,\n })\n\n const token = signJwt({\n sub: String(user.id),\n sid: String(session.id),\n tenantId: tenantId || null,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles,\n })\n\n void emitSsoEvent('sso.login.completed', {\n id: String(user.id),\n tenantId: config.tenantId,\n organizationId: config.organizationId,\n }).catch((eventError) => logger.error('SSO event emit failed', { err: eventError }))\n\n return {\n token,\n sessionToken: sessionRefreshToken,\n sessionExpiresAt,\n redirectUrl: flowState.returnUrl || '/backend',\n tenantId: config.tenantId ?? null,\n organizationId: config.organizationId,\n }\n }\n\n private async decryptClientSecret(config: SsoConfig): Promise<string | undefined> {\n if (!config.clientSecretEnc) return undefined\n\n const decrypted = await this.tenantEncryptionService.decryptEntityPayload(\n config.id,\n { clientSecretEnc: config.clientSecretEnc },\n config.tenantId,\n config.organizationId,\n )\n return (decrypted.clientSecretEnc as string) ?? undefined\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,YAAY;AAEnB,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,eAAe;AAGxB,SAAS,iBAAiB;AAI1B,SAAS,oBAAoB,oBAAoB,uBAAuB;AACxE,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,KAAK,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAE1D,MAAM,WAAW;AAAA,EACtB,YACU,IACA,qBACA,uBACA,yBACA,aACA,aACR;AANQ;AACA;AACA;AACA;AACA;AACA;AAAA,EACP;AAAA,EAEH,MAAM,kBAAkB,OAA0C;AAChE,UAAM,SAA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AC1C,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AACA,WAAQ,UAAU,mBAA8B;AAAA,EAClD;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/enterprise",
3
- "version": "0.10.1-develop.7796.1.f2868e5c62",
3
+ "version": "0.10.1-develop.7797.1.f0365b4031",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -70,12 +70,12 @@
70
70
  "@dnd-kit/core": "^6.3.1",
71
71
  "@dnd-kit/sortable": "^10.0.0",
72
72
  "@dnd-kit/utilities": "^3.2.2",
73
- "@open-mercato/ai-assistant": "0.10.1-develop.7796.1.f2868e5c62",
74
- "@open-mercato/core": "0.10.1-develop.7796.1.f2868e5c62",
75
- "@open-mercato/queue": "0.10.1-develop.7796.1.f2868e5c62",
76
- "@open-mercato/scheduler": "0.10.1-develop.7796.1.f2868e5c62",
77
- "@open-mercato/ui": "0.10.1-develop.7796.1.f2868e5c62",
78
- "@open-mercato/web-research": "0.10.1-develop.7796.1.f2868e5c62",
73
+ "@open-mercato/ai-assistant": "0.10.1-develop.7797.1.f0365b4031",
74
+ "@open-mercato/core": "0.10.1-develop.7797.1.f0365b4031",
75
+ "@open-mercato/queue": "0.10.1-develop.7797.1.f0365b4031",
76
+ "@open-mercato/scheduler": "0.10.1-develop.7797.1.f0365b4031",
77
+ "@open-mercato/ui": "0.10.1-develop.7797.1.f0365b4031",
78
+ "@open-mercato/web-research": "0.10.1-develop.7797.1.f0365b4031",
79
79
  "@simplewebauthn/browser": "^13.3.0",
80
80
  "@simplewebauthn/server": "^13.3.2",
81
81
  "@simplewebauthn/types": "^12.0.0",
@@ -87,13 +87,13 @@
87
87
  },
88
88
  "peerDependencies": {
89
89
  "@mikro-orm/core": "^7.0.14",
90
- "@open-mercato/shared": "0.10.1-develop.7796.1.f2868e5c62",
90
+ "@open-mercato/shared": "0.10.1-develop.7797.1.f0365b4031",
91
91
  "react": "^19.0.0",
92
92
  "react-dom": "^19.0.0",
93
93
  "zod": ">=3.23.0"
94
94
  },
95
95
  "devDependencies": {
96
- "@open-mercato/shared": "0.10.1-develop.7796.1.f2868e5c62",
96
+ "@open-mercato/shared": "0.10.1-develop.7797.1.f0365b4031",
97
97
  "@types/jest": "^30.0.0",
98
98
  "@types/react": "^19.2.18",
99
99
  "@types/react-dom": "^19.2.5",
@@ -1,4 +1,5 @@
1
- import { asClass, asValue } from 'awilix'
1
+ import { asClass, asFunction, asValue } from 'awilix'
2
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
3
  import type { AppContainer } from '@open-mercato/shared/lib/di/container'
3
4
  import { SsoProviderRegistry } from './lib/registry'
4
5
  import { OidcProvider } from './lib/oidc-provider'
@@ -8,12 +9,14 @@ import { SsoConfigService } from './services/ssoConfigService'
8
9
  import { HrdService } from './services/hrdService'
9
10
  import { ScimTokenService } from './services/scimTokenService'
10
11
  import { ScimService } from './services/scimService'
12
+ import { SsoAuthService } from './services/ssoAuthService'
11
13
 
12
14
  export function register(container: AppContainer) {
13
15
  const registry = new SsoProviderRegistry()
14
16
  registry.register(new OidcProvider())
15
17
 
16
18
  container.register({
19
+ authService: asFunction(({ em }: { em: EntityManager }) => new SsoAuthService(em)).scoped().proxy(),
17
20
  ssoProviderRegistry: asValue(registry),
18
21
  ssoService: asClass(SsoService).scoped(),
19
22
  accountLinkingService: asClass(AccountLinkingService).scoped(),
@@ -0,0 +1,61 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
3
+ import { Organization } from '@open-mercato/core/modules/directory/data/entities'
4
+ import { SsoConfig, SsoUserDeactivation } from '../data/entities'
5
+
6
+ type DeactivationScope = {
7
+ userId: string
8
+ tenantId: string | null
9
+ organizationId: string | null
10
+ ssoConfigId?: string
11
+ }
12
+
13
+ export async function isSsoUserDeactivated(em: EntityManager, scope: DeactivationScope): Promise<boolean> {
14
+ if (!scope.organizationId) return false
15
+
16
+ const deactivation = await findOneWithDecryption(
17
+ em,
18
+ SsoUserDeactivation,
19
+ {
20
+ userId: scope.userId,
21
+ tenantId: scope.tenantId,
22
+ organizationId: scope.organizationId,
23
+ reactivatedAt: null,
24
+ ...(scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}),
25
+ },
26
+ {},
27
+ { tenantId: scope.tenantId, organizationId: scope.organizationId },
28
+ )
29
+ if (deactivation) return true
30
+ if (!scope.tenantId) return false
31
+
32
+ const legacyDeactivation = await findOneWithDecryption(
33
+ em, SsoUserDeactivation,
34
+ {
35
+ userId: scope.userId,
36
+ tenantId: null,
37
+ organizationId: scope.organizationId,
38
+ reactivatedAt: null,
39
+ ...(scope.ssoConfigId ? { ssoConfigId: scope.ssoConfigId } : {}),
40
+ },
41
+ {},
42
+ { tenantId: scope.tenantId, organizationId: scope.organizationId },
43
+ )
44
+ if (!legacyDeactivation) return false
45
+
46
+ const organization = await findOneWithDecryption(
47
+ em, Organization,
48
+ { id: scope.organizationId, tenant: scope.tenantId },
49
+ { fields: ['id'] },
50
+ { tenantId: scope.tenantId, organizationId: scope.organizationId },
51
+ )
52
+ if (!organization) return false
53
+
54
+ const config = await findOneWithDecryption(
55
+ em, SsoConfig,
56
+ { id: legacyDeactivation.ssoConfigId, organizationId: scope.organizationId, tenantId: null },
57
+ { fields: ['id'] },
58
+ { tenantId: null, organizationId: scope.organizationId },
59
+ )
60
+ return config !== null
61
+ }
@@ -9,6 +9,7 @@ import type { SsoIdentityPayload } from '../lib/types'
9
9
  import { createLogger } from '@open-mercato/shared/lib/logger'
10
10
  import { conflict } from '@open-mercato/shared/lib/crud/errors'
11
11
  import { lockUserRoleWriterAuthorizationState } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'
12
+ import { isSsoUserDeactivated } from '../lib/deactivation'
12
13
 
13
14
  const logger = createLogger('sso').child({ component: 'account-linking' })
14
15
 
@@ -82,6 +83,8 @@ export class AccountLinkingService {
82
83
  return null
83
84
  }
84
85
 
86
+ await this.requireActiveUser(user.id, ssoConfigId, tenantId, organizationId)
87
+
85
88
  identity.lastLoginAt = new Date()
86
89
  await this.em.flush()
87
90
 
@@ -110,6 +113,8 @@ export class AccountLinkingService {
110
113
  )
111
114
  if (!user) return null
112
115
 
116
+ await this.requireActiveUser(user.id, config.id, tenantId, config.organizationId)
117
+
113
118
  const now = new Date()
114
119
  const identity = this.em.create(SsoIdentity, {
115
120
  tenantId,
@@ -137,6 +142,18 @@ export class AccountLinkingService {
137
142
  return { user, identity }
138
143
  }
139
144
 
145
+ private async requireActiveUser(
146
+ userId: string,
147
+ ssoConfigId: string,
148
+ tenantId: string,
149
+ organizationId: string,
150
+ em: EntityManager = this.em,
151
+ ): Promise<void> {
152
+ if (await isSsoUserDeactivated(em, { userId, ssoConfigId, tenantId: tenantId || null, organizationId })) {
153
+ throw new Error('[internal] SSO identity is deactivated')
154
+ }
155
+ }
156
+
140
157
  private async jitProvision(
141
158
  config: SsoConfig,
142
159
  idpPayload: SsoIdentityPayload,
@@ -255,6 +272,7 @@ export class AccountLinkingService {
255
272
  userIds: [String(user.id)],
256
273
  roleIds: Array.from(lockedRoleIds),
257
274
  })
275
+ await this.requireActiveUser(user.id, config.id, resolvedTenantId, config.organizationId, em)
258
276
  allRoles = await em.find(Role, {
259
277
  tenantId: resolvedTenantId,
260
278
  deletedAt: null,
@@ -1,6 +1,7 @@
1
1
  import { EntityManager, type FilterQuery, type RequiredEntityData } from '@mikro-orm/postgresql'
2
2
  import { User, Session } from '@open-mercato/core/modules/auth/data/entities'
3
3
  import { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'
4
+ import { lockAuthorizationUserRows } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'
4
5
  import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
5
6
  import { SsoIdentity, SsoUserDeactivation, ScimProvisioningLog } from '../data/entities'
6
7
  import { toScimUserResource, fromScimUserPayload, type ScimUserResource, type ScimUserPayload } from '../lib/scim-mapper'
@@ -341,64 +342,61 @@ export class ScimService {
341
342
  }
342
343
  }
343
344
 
344
- private async deactivateUser(userId: string, scope: ScimScope): Promise<void> {
345
- await this.em.transactional(async (txEm) => {
346
- let deactivation = await txEm.findOne(SsoUserDeactivation, {
347
- userId, ssoConfigId: scope.ssoConfigId,
348
- })
349
-
350
- if (deactivation) {
351
- deactivation.deactivatedAt = new Date()
352
- deactivation.reactivatedAt = null
353
- } else {
354
- deactivation = txEm.create(SsoUserDeactivation, {
355
- tenantId: scope.tenantId ?? null,
356
- organizationId: scope.organizationId,
357
- userId,
358
- ssoConfigId: scope.ssoConfigId,
359
- deactivatedAt: new Date(),
360
- } as RequiredEntityData<SsoUserDeactivation>)
361
- txEm.persist(deactivation)
362
- }
345
+ private async deactivateUser(userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {
346
+ return this.em.transactional((txEm) => this.deactivateUserInTransaction(txEm, userId, scope))
347
+ }
363
348
 
364
- // Revoke all active sessions atomically with the deactivation upsert
365
- const sessionWhere: FilterQuery<Session> = { user: userId }
366
- await txEm.nativeDelete(Session, sessionWhere)
367
- })
349
+ private async deactivateUserInTransaction(
350
+ txEm: EntityManager,
351
+ userId: string,
352
+ scope: ScimScope,
353
+ ): Promise<SsoUserDeactivation> {
354
+ await lockAuthorizationUserRows(txEm, [userId])
355
+ let deactivation = await findOneWithDecryption(
356
+ txEm, SsoUserDeactivation,
357
+ { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },
358
+ { refresh: true },
359
+ { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId },
360
+ )
361
+ if (deactivation) {
362
+ deactivation.deactivatedAt = new Date()
363
+ deactivation.reactivatedAt = null
364
+ } else {
365
+ deactivation = txEm.create(SsoUserDeactivation, {
366
+ tenantId: scope.tenantId ?? null,
367
+ organizationId: scope.organizationId,
368
+ userId,
369
+ ssoConfigId: scope.ssoConfigId,
370
+ deactivatedAt: new Date(),
371
+ } as RequiredEntityData<SsoUserDeactivation>)
372
+ txEm.persist(deactivation)
373
+ }
374
+ const sessionWhere: FilterQuery<Session> = { user: userId }
375
+ await txEm.nativeDelete(Session, sessionWhere)
376
+ return deactivation
368
377
  }
369
378
 
370
379
  private async reactivateUser(userId: string, scope: ScimScope): Promise<void> {
371
- const deactivation = await this.em.findOne(SsoUserDeactivation, {
372
- userId, ssoConfigId: scope.ssoConfigId,
380
+ await this.em.transactional(async (txEm) => {
381
+ await lockAuthorizationUserRows(txEm, [userId])
382
+ const deactivation = await findOneWithDecryption(
383
+ txEm, SsoUserDeactivation,
384
+ { userId, ssoConfigId: scope.ssoConfigId, organizationId: scope.organizationId, tenantId: scope.tenantId ?? null },
385
+ { refresh: true },
386
+ { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId },
387
+ )
388
+ if (deactivation && !deactivation.reactivatedAt) {
389
+ deactivation.reactivatedAt = new Date()
390
+ }
373
391
  })
374
- if (deactivation && !deactivation.reactivatedAt) {
375
- deactivation.reactivatedAt = new Date()
376
- await this.em.flush()
377
- }
378
392
  }
379
393
 
380
394
  private async createDeactivation(userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {
381
- const deactivation = this.em.create(SsoUserDeactivation, {
382
- tenantId: scope.tenantId ?? null,
383
- organizationId: scope.organizationId,
384
- userId,
385
- ssoConfigId: scope.ssoConfigId,
386
- deactivatedAt: new Date(),
387
- } as RequiredEntityData<SsoUserDeactivation>)
388
- await this.em.persist(deactivation).flush()
389
- return deactivation
395
+ return this.deactivateUser(userId, scope)
390
396
  }
391
397
 
392
398
  private async createDeactivationTx(txEm: EntityManager, userId: string, scope: ScimScope): Promise<SsoUserDeactivation> {
393
- const deactivation = txEm.create(SsoUserDeactivation, {
394
- tenantId: scope.tenantId ?? null,
395
- organizationId: scope.organizationId,
396
- userId,
397
- ssoConfigId: scope.ssoConfigId,
398
- deactivatedAt: new Date(),
399
- } as RequiredEntityData<SsoUserDeactivation>)
400
- await txEm.persist(deactivation).flush()
401
- return deactivation
399
+ return this.deactivateUserInTransaction(txEm, userId, scope)
402
400
  }
403
401
 
404
402
  private async log(
@@ -0,0 +1,55 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import { User, type Session } from '@open-mercato/core/modules/auth/data/entities'
3
+ import { AuthService } from '@open-mercato/core/modules/auth/services/authService'
4
+ import { AuthSessionRejectedError } from '@open-mercato/core/modules/auth/lib/sessionEligibility'
5
+ import { lockAuthorizationUserRows } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'
6
+ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
7
+ import { isSsoUserDeactivated } from '../lib/deactivation'
8
+
9
+ type SsoSessionScope = {
10
+ tenantId: string | null
11
+ organizationId: string
12
+ ssoConfigId: string
13
+ }
14
+
15
+ export class SsoAuthService extends AuthService {
16
+ constructor(private ssoEm: EntityManager) {
17
+ super(ssoEm)
18
+ }
19
+
20
+ override async verifyPassword(user: User | null, password: string): Promise<boolean> {
21
+ const verified = await super.verifyPassword(user, password)
22
+ if (!verified || !user) return false
23
+
24
+ return !await isSsoUserDeactivated(this.ssoEm, {
25
+ userId: user.id,
26
+ tenantId: user.tenantId ?? null,
27
+ organizationId: user.organizationId ?? null,
28
+ })
29
+ }
30
+
31
+ override async createSession(
32
+ user: User,
33
+ expiresAt: Date,
34
+ scope?: SsoSessionScope,
35
+ ): Promise<{ session: Session; token: string }> {
36
+ return this.ssoEm.transactional(async (txEm) => {
37
+ await lockAuthorizationUserRows(txEm, [user.id])
38
+ const currentUser = await findOneWithDecryption(
39
+ txEm, User,
40
+ { id: user.id, tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null, deletedAt: null },
41
+ { refresh: true },
42
+ { tenantId: user.tenantId ?? null, organizationId: user.organizationId ?? null },
43
+ )
44
+ if (!currentUser || await isSsoUserDeactivated(txEm, {
45
+ userId: user.id,
46
+ tenantId: scope ? scope.tenantId : currentUser.tenantId ?? null,
47
+ organizationId: scope ? scope.organizationId : currentUser.organizationId ?? null,
48
+ ...(scope ? { ssoConfigId: scope.ssoConfigId } : {}),
49
+ })) {
50
+ throw new AuthSessionRejectedError()
51
+ }
52
+ return this.createSessionWithEntityManager(txEm, currentUser, expiresAt)
53
+ })
54
+ }
55
+ }
@@ -7,6 +7,7 @@ import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacS
7
7
  import { SsoConfig } from '../data/entities'
8
8
  import type { SsoProviderRegistry } from '../lib/registry'
9
9
  import type { AccountLinkingService } from './accountLinkingService'
10
+ import type { SsoAuthService } from './ssoAuthService'
10
11
  import { encryptStateCookie, decryptStateCookie, createFlowState } from '../lib/state-cookie'
11
12
  import { emitSsoEvent } from '../events'
12
13
  import { isSsoRolesRevokedError } from '../lib/errors'
@@ -21,7 +22,7 @@ export class SsoService {
21
22
  private ssoProviderRegistry: SsoProviderRegistry,
22
23
  private accountLinkingService: AccountLinkingService,
23
24
  private tenantEncryptionService: TenantDataEncryptionService,
24
- private authService: AuthService,
25
+ private authService: AuthService & Pick<SsoAuthService, 'createSession'>,
25
26
  private rbacService: RbacService,
26
27
  ) {}
27
28
 
@@ -139,7 +140,11 @@ export class SsoService {
139
140
 
140
141
  const days = Number(process.env.REMEMBER_ME_DAYS || '30')
141
142
  const sessionExpiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
142
- const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt)
143
+ const { session, token: sessionRefreshToken } = await this.authService.createSession(user, sessionExpiresAt, {
144
+ tenantId: config.tenantId ?? null,
145
+ organizationId: config.organizationId,
146
+ ssoConfigId: config.id,
147
+ })
143
148
 
144
149
  const token = signJwt({
145
150
  sub: String(user.id),