@open-mercato/enterprise 0.6.6-develop.5612.1.d382eb2f33 → 0.6.6-develop.5617.1.62538c48ca

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/modules/security/api/i18n.js +3 -0
  2. package/dist/modules/security/api/i18n.js.map +2 -2
  3. package/dist/modules/security/api/mfa/prepare/route.js +6 -1
  4. package/dist/modules/security/api/mfa/prepare/route.js.map +2 -2
  5. package/dist/modules/security/api/mfa/verify/route.js +7 -1
  6. package/dist/modules/security/api/mfa/verify/route.js.map +2 -2
  7. package/dist/modules/security/api/sudo/prepare/route.js +6 -1
  8. package/dist/modules/security/api/sudo/prepare/route.js.map +2 -2
  9. package/dist/modules/security/api/users/mfa/compliance/route.js +4 -2
  10. package/dist/modules/security/api/users/mfa/compliance/route.js.map +2 -2
  11. package/dist/modules/security/commands/createEnforcementPolicy.js +6 -4
  12. package/dist/modules/security/commands/createEnforcementPolicy.js.map +2 -2
  13. package/dist/modules/security/commands/deleteEnforcementPolicy.js +6 -4
  14. package/dist/modules/security/commands/deleteEnforcementPolicy.js.map +2 -2
  15. package/dist/modules/security/commands/resetUserMfa.js +11 -4
  16. package/dist/modules/security/commands/resetUserMfa.js.map +2 -2
  17. package/dist/modules/security/commands/updateEnforcementPolicy.js +6 -4
  18. package/dist/modules/security/commands/updateEnforcementPolicy.js.map +2 -2
  19. package/dist/modules/security/i18n/de.json +3 -0
  20. package/dist/modules/security/i18n/en.json +3 -0
  21. package/dist/modules/security/i18n/es.json +3 -0
  22. package/dist/modules/security/i18n/pl.json +3 -0
  23. package/dist/modules/security/services/MfaAdminService.js +42 -8
  24. package/dist/modules/security/services/MfaAdminService.js.map +2 -2
  25. package/dist/modules/security/services/MfaEnforcementService.js +57 -7
  26. package/dist/modules/security/services/MfaEnforcementService.js.map +2 -2
  27. package/dist/modules/security/services/MfaVerificationService.js +15 -6
  28. package/dist/modules/security/services/MfaVerificationService.js.map +2 -2
  29. package/dist/modules/security/services/SudoChallengeService.js +26 -4
  30. package/dist/modules/security/services/SudoChallengeService.js.map +2 -2
  31. package/package.json +5 -5
  32. package/src/modules/security/api/i18n.ts +3 -0
  33. package/src/modules/security/api/mfa/prepare/route.ts +6 -1
  34. package/src/modules/security/api/mfa/verify/route.ts +7 -1
  35. package/src/modules/security/api/sudo/prepare/route.ts +6 -1
  36. package/src/modules/security/api/users/mfa/compliance/route.ts +6 -3
  37. package/src/modules/security/commands/createEnforcementPolicy.ts +7 -5
  38. package/src/modules/security/commands/deleteEnforcementPolicy.ts +10 -5
  39. package/src/modules/security/commands/resetUserMfa.ts +12 -5
  40. package/src/modules/security/commands/updateEnforcementPolicy.ts +10 -5
  41. package/src/modules/security/i18n/de.json +3 -0
  42. package/src/modules/security/i18n/en.json +3 -0
  43. package/src/modules/security/i18n/es.json +3 -0
  44. package/src/modules/security/i18n/pl.json +3 -0
  45. package/src/modules/security/services/MfaAdminService.ts +101 -8
  46. package/src/modules/security/services/MfaEnforcementService.ts +174 -7
  47. package/src/modules/security/services/MfaVerificationService.ts +58 -4
  48. package/src/modules/security/services/SudoChallengeService.ts +31 -6
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/security/services/SudoChallengeService.ts"],
4
- "sourcesContent": ["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n dedupeSudoTargets,\n getSecuritySudoTargetEntries,\n type SecuritySudoTarget,\n} from '../lib/module-security-registry'\nimport {\n ChallengeMethod,\n SudoChallengeConfig,\n SudoChallengeMethodUsed,\n SudoSession,\n} from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type {\n SudoConfigInput,\n SudoConfigUpdateInput,\n} from '../data/validators'\nimport type { PasswordService } from './PasswordService'\nimport type { MfaService } from './MfaService'\nimport type { MfaVerificationService } from './MfaVerificationService'\nimport { sudoTargets as defaultSudoTargets } from '../security.sudo'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SudoMethod = 'password' | 'mfa'\n\nexport type SudoAvailableMethod = {\n type: string\n label: string\n icon: string\n}\n\nexport type SudoProtectionResolution = {\n protected: boolean\n config?: SudoChallengeConfig\n}\n\nconst signedSudoTokenPayloadSchema = z.object({\n sid: z.string(),\n sub: z.string(),\n tid: z.string().nullable(),\n oid: z.string().nullable(),\n tgt: z.string(),\n exp: z.number(),\n})\n\ntype SignedSudoTokenPayload = z.infer<typeof signedSudoTokenPayloadSchema>\n\ntype UserScope = {\n id: string\n tenantId: string | null\n organizationId: string | null\n}\n\nexport type SudoAuthScope = {\n tenantId: string | null\n organizationId?: string | null\n isSuperAdmin?: boolean\n}\n\ntype DeveloperDefaultPayload = {\n targetIdentifier: string\n label?: string | null\n ttlSeconds?: number\n challengeMethod?: ChallengeMethod\n}\n\nexport class SudoChallengeServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'SudoChallengeServiceError'\n }\n}\n\nexport class SudoChallengeService {\n constructor(\n private readonly em: EntityManager,\n private readonly passwordService: PasswordService,\n private readonly mfaService: MfaService,\n private readonly mfaVerificationService: MfaVerificationService,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async listConfigs(scope?: SudoAuthScope): Promise<SudoChallengeConfig[]> {\n await this.ensureDeveloperDefaultsRegistered()\n const filter: FilterQuery<SudoChallengeConfig> = { deletedAt: null }\n if (scope && !scope.isSuperAdmin) {\n if (!scope.tenantId) return []\n ;(filter as Record<string, unknown>).$or = [\n { tenantId: scope.tenantId },\n { tenantId: null },\n ]\n }\n return this.em.find(\n SudoChallengeConfig,\n filter,\n {\n orderBy: {\n targetIdentifier: 'asc',\n tenantId: 'asc',\n organizationId: 'asc',\n createdAt: 'asc',\n },\n },\n )\n }\n\n async getConfigById(id: string, scope?: SudoAuthScope): Promise<SudoChallengeConfig | null> {\n await this.ensureDeveloperDefaultsRegistered()\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) return null\n if (scope && !this.isConfigVisibleToScope(config, scope)) return null\n return config\n }\n\n async isProtected(\n targetIdentifier: string,\n tenantId?: string | null,\n organizationId?: string | null,\n ): Promise<SudoProtectionResolution> {\n await this.ensureDeveloperDefaultsRegistered()\n\n const candidates = await this.em.find(SudoChallengeConfig, {\n targetIdentifier,\n deletedAt: null,\n })\n\n const resolved = candidates\n .filter((config) => this.matchesScope(config, tenantId ?? null, organizationId ?? null))\n .sort((left, right) => this.compareConfigPriority(left, right, tenantId ?? null, organizationId ?? null))[0]\n\n if (!resolved || !resolved.isEnabled) {\n return { protected: false }\n }\n\n return { protected: true, config: resolved }\n }\n\n async initiate(\n userId: string,\n targetIdentifier: string,\n options?: { tenantId?: string | null; organizationId?: string | null },\n ): Promise<{\n required: boolean\n sessionId?: string\n method?: SudoMethod\n availableMfaMethods?: SudoAvailableMethod[]\n expiresAt?: Date\n }> {\n const protection = await this.isProtected(\n targetIdentifier,\n options?.tenantId ?? null,\n options?.organizationId ?? null,\n )\n\n if (!protection.protected || !protection.config) {\n return { required: false }\n }\n\n const user = await this.findUserScope(userId)\n if (!user?.tenantId) {\n throw new SudoChallengeServiceError('User not found', 404)\n }\n\n const userMethods = await this.mfaService.getUserMethods(userId)\n const method = this.resolveChallengeMethod(protection.config.challengeMethod, userMethods.length)\n\n let sessionToken = randomBytes(16).toString('hex')\n let availableMfaMethods: SudoAvailableMethod[] | undefined\n if (method === 'mfa') {\n const challenge = await this.mfaVerificationService.createChallenge(userId)\n sessionToken = challenge.challengeId\n availableMfaMethods = challenge.availableMethods\n }\n\n const expiresAt = new Date(Date.now() + this.securityConfig.sudo.pendingChallengeTtlMs)\n const session = this.em.create(SudoSession, {\n userId,\n tenantId: user.tenantId,\n sessionToken,\n challengeMethod: method,\n expiresAt,\n createdAt: new Date(),\n })\n this.em.persist(session)\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.challenged', {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n targetIdentifier,\n method,\n })\n\n return {\n required: true,\n sessionId: session.id,\n method,\n availableMfaMethods,\n expiresAt,\n }\n }\n\n async prepare(\n sessionId: string,\n methodType: string,\n request?: Request,\n ): Promise<{ clientData?: Record<string, unknown> }> {\n const session = await this.getPendingSession(sessionId)\n if (session.challengeMethod !== 'mfa') {\n throw new SudoChallengeServiceError('This sudo session does not require MFA', 400)\n }\n return this.mfaVerificationService.prepareChallenge(session.sessionToken, methodType, { request })\n }\n\n async verify(\n sessionId: string,\n methodType: string,\n payload: unknown,\n options: {\n expectedUserId?: string\n tenantId?: string | null\n organizationId?: string | null\n targetIdentifier: string\n },\n request?: Request,\n ): Promise<{ sudoToken: string; expiresAt: Date }> {\n const session = await this.getPendingSession(sessionId)\n if (options.expectedUserId && session.userId !== options.expectedUserId) {\n throw new SudoChallengeServiceError('Sudo challenge user mismatch', 403)\n }\n const user = await this.findUserScope(session.userId)\n if (!user?.tenantId) {\n throw new SudoChallengeServiceError('User not found', 404)\n }\n\n const scopeTenantId = options.tenantId !== undefined ? options.tenantId : user.tenantId\n const scopeOrganizationId = options.organizationId !== undefined ? options.organizationId : user.organizationId\n const protection = await this.isProtected(\n options.targetIdentifier,\n scopeTenantId,\n scopeOrganizationId,\n )\n if (!protection.protected || !protection.config) {\n throw new SudoChallengeServiceError('Sudo protection is not configured for this target', 404)\n }\n\n let verified = false\n let methodUsed: string = methodType\n if (session.challengeMethod === 'password') {\n const password = this.readPassword(payload)\n verified = await this.passwordService.verifyPassword(session.userId, password)\n methodUsed = SudoChallengeMethodUsed.PASSWORD\n } else {\n verified = await this.mfaVerificationService.verifyChallenge(session.sessionToken, methodType, payload, { request })\n }\n\n if (!verified) {\n await emitSecurityEvent('security.sudo.failed', {\n userId: session.userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n targetIdentifier: options.targetIdentifier,\n method: methodUsed,\n })\n throw new SudoChallengeServiceError('Unable to verify sudo challenge', 401)\n }\n\n const ttlSeconds = this.normalizeTtl(protection.config.ttlSeconds)\n const expiresAt = new Date(Date.now() + ttlSeconds * 1000)\n const sudoToken = this.signToken({\n sid: session.id,\n sub: session.userId,\n tid: scopeTenantId,\n oid: scopeOrganizationId,\n tgt: options.targetIdentifier,\n exp: expiresAt.getTime(),\n })\n\n session.sessionToken = sudoToken\n session.challengeMethod = methodUsed\n session.expiresAt = expiresAt\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.verified', {\n userId: session.userId,\n tenantId: scopeTenantId,\n organizationId: scopeOrganizationId,\n targetIdentifier: options.targetIdentifier,\n method: methodUsed,\n expiresAt: expiresAt.toISOString(),\n })\n\n return { sudoToken, expiresAt }\n }\n\n async validateToken(\n token: string,\n targetIdentifier: string,\n options?: {\n expectedUserId?: string\n tenantId?: string | null\n organizationId?: string | null\n },\n ): Promise<boolean> {\n if (!token) return false\n const payload = this.readSignedToken(token)\n if (!payload) return false\n if (payload.exp <= Date.now()) return false\n if (payload.tgt !== targetIdentifier) return false\n if (options?.expectedUserId && payload.sub !== options.expectedUserId) return false\n if (options?.tenantId !== undefined && payload.tid !== (options.tenantId ?? null)) return false\n if (options?.organizationId !== undefined && payload.oid !== (options.organizationId ?? null)) return false\n\n const session = await this.em.findOne(SudoSession, {\n id: payload.sid,\n userId: payload.sub,\n sessionToken: token,\n } as FilterQuery<SudoSession>)\n\n return Boolean(session && session.expiresAt.getTime() > Date.now())\n }\n\n async createConfig(\n input: SudoConfigInput,\n configuredBy: string,\n scope?: SudoAuthScope,\n ): Promise<SudoChallengeConfig> {\n await this.ensureDeveloperDefaultsRegistered()\n const inputTenantId = input.tenantId ?? null\n const inputOrganizationId = input.organizationId ?? null\n this.validateScope(inputTenantId, inputOrganizationId)\n if (scope) this.assertWriteScope(inputTenantId, inputOrganizationId, scope)\n await this.ensureUniqueConfig(input.targetIdentifier, inputTenantId, inputOrganizationId)\n\n const config = this.em.create(SudoChallengeConfig, {\n tenantId: inputTenantId,\n organizationId: inputOrganizationId,\n label: input.label ?? null,\n targetIdentifier: input.targetIdentifier,\n isEnabled: input.isEnabled,\n ttlSeconds: this.normalizeTtl(input.ttlSeconds),\n challengeMethod: input.challengeMethod,\n configuredBy,\n isDeveloperDefault: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n this.em.persist(config)\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.created', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n configuredBy,\n })\n\n return config\n }\n\n async updateConfig(\n id: string,\n input: SudoConfigUpdateInput,\n configuredBy: string,\n scope?: SudoAuthScope,\n ): Promise<SudoChallengeConfig> {\n await this.ensureDeveloperDefaultsRegistered()\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (scope) {\n this.assertWriteScope(config.tenantId ?? null, config.organizationId ?? null, scope)\n if (config.isDeveloperDefault && !scope.isSuperAdmin) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n\n const nextTenantId = input.tenantId !== undefined ? input.tenantId ?? null : config.tenantId ?? null\n const nextOrganizationId = input.organizationId !== undefined ? input.organizationId ?? null : config.organizationId ?? null\n const nextTargetIdentifier = input.targetIdentifier ?? config.targetIdentifier\n this.validateScope(nextTenantId, nextOrganizationId)\n if (scope) this.assertWriteScope(nextTenantId, nextOrganizationId, scope)\n await this.ensureUniqueConfig(nextTargetIdentifier, nextTenantId, nextOrganizationId, config.id)\n\n if (input.tenantId !== undefined) config.tenantId = input.tenantId ?? null\n if (input.organizationId !== undefined) config.organizationId = input.organizationId ?? null\n if (input.label !== undefined) config.label = input.label ?? null\n if (input.targetIdentifier !== undefined) config.targetIdentifier = input.targetIdentifier\n if (input.isEnabled !== undefined) config.isEnabled = input.isEnabled\n if (input.ttlSeconds !== undefined) config.ttlSeconds = this.normalizeTtl(input.ttlSeconds)\n if (input.challengeMethod !== undefined) config.challengeMethod = input.challengeMethod\n config.configuredBy = configuredBy\n config.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.updated', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n configuredBy,\n })\n\n return config\n }\n\n async deleteConfig(id: string, scope?: SudoAuthScope): Promise<void> {\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (scope) {\n this.assertWriteScope(config.tenantId ?? null, config.organizationId ?? null, scope)\n if (config.isDeveloperDefault && !scope.isSuperAdmin) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n config.deletedAt = new Date()\n config.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.deleted', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n })\n }\n\n async registerDeveloperDefault(\n input: DeveloperDefaultPayload,\n ): Promise<void> {\n const existing = await this.em.findOne(SudoChallengeConfig, {\n targetIdentifier: input.targetIdentifier,\n tenantId: null,\n organizationId: null,\n isDeveloperDefault: true,\n })\n\n if (existing) {\n existing.isEnabled = true\n existing.deletedAt = null\n existing.ttlSeconds = this.normalizeTtl(input.ttlSeconds)\n existing.challengeMethod = input.challengeMethod ?? ChallengeMethod.AUTO\n existing.updatedAt = new Date()\n await this.em.flush()\n return\n }\n\n const config = this.em.create(SudoChallengeConfig, {\n tenantId: null,\n organizationId: null,\n label: input.label ?? null,\n targetIdentifier: input.targetIdentifier,\n isEnabled: true,\n isDeveloperDefault: true,\n ttlSeconds: this.normalizeTtl(input.ttlSeconds),\n challengeMethod: input.challengeMethod ?? ChallengeMethod.AUTO,\n configuredBy: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n this.em.persist(config)\n await this.em.flush()\n }\n\n async cleanupExpired(): Promise<number> {\n return this.em.nativeDelete(SudoSession, {\n expiresAt: { $lte: new Date() },\n })\n }\n\n private async ensureDeveloperDefaultsRegistered(): Promise<void> {\n const registryEntries = getSecuritySudoTargetEntries()\n const registryTargets = registryEntries.flatMap((entry) => entry.targets ?? [])\n const fallbackTargets = registryEntries.length === 0 ? defaultSudoTargets : []\n\n for (const target of dedupeSudoTargets([\n ...registryTargets,\n ...fallbackTargets,\n ])) {\n await this.registerDeveloperDefault(this.readDeveloperDefault(target))\n }\n }\n\n private readDeveloperDefault(target: SecuritySudoTarget): DeveloperDefaultPayload {\n return {\n targetIdentifier: target.identifier,\n label: target.label ?? null,\n ttlSeconds: target.ttlSeconds,\n challengeMethod: this.toChallengeMethod(target.challengeMethod),\n }\n }\n\n private async ensureUniqueConfig(\n targetIdentifier: string,\n tenantId: string | null,\n organizationId: string | null,\n ignoreId?: string,\n ): Promise<void> {\n const existing = await this.em.findOne(SudoChallengeConfig, {\n targetIdentifier,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (existing && existing.id !== ignoreId) {\n throw new SudoChallengeServiceError('A sudo configuration for this target and scope already exists', 409)\n }\n }\n\n private validateScope(tenantId: string | null, organizationId: string | null): void {\n if (organizationId && !tenantId) {\n throw new SudoChallengeServiceError('Organization-scoped sudo config requires a tenant', 400)\n }\n }\n\n private isConfigVisibleToScope(config: SudoChallengeConfig, scope: SudoAuthScope): boolean {\n if (scope.isSuperAdmin) return true\n if (!scope.tenantId) return false\n const configTenantId = config.tenantId ?? null\n if (configTenantId === null) return true\n return configTenantId === scope.tenantId\n }\n\n private assertWriteScope(\n targetTenantId: string | null,\n targetOrganizationId: string | null,\n scope: SudoAuthScope,\n ): void {\n if (scope.isSuperAdmin) return\n if (!scope.tenantId) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if ((targetTenantId ?? null) !== scope.tenantId) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (\n scope.organizationId !== undefined\n && scope.organizationId !== null\n && targetOrganizationId !== null\n && targetOrganizationId !== scope.organizationId\n ) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n\n private resolveChallengeMethod(\n configuredMethod: ChallengeMethod,\n availableMfaMethodCount: number,\n ): SudoMethod {\n if (this.securityConfig.mfa.emergencyBypass) {\n return 'password'\n }\n if (configuredMethod === ChallengeMethod.PASSWORD) return 'password'\n if (configuredMethod === ChallengeMethod.MFA) {\n if (availableMfaMethodCount === 0) {\n throw new SudoChallengeServiceError('This sudo target requires MFA, but no MFA methods are configured', 400)\n }\n return 'mfa'\n }\n return availableMfaMethodCount > 0 ? 'mfa' : 'password'\n }\n\n private matchesScope(config: SudoChallengeConfig, tenantId: string | null, organizationId: string | null): boolean {\n if (config.organizationId) {\n return config.organizationId === organizationId && config.tenantId === tenantId\n }\n if (config.tenantId) {\n return config.tenantId === tenantId\n }\n return true\n }\n\n private compareConfigPriority(\n left: SudoChallengeConfig,\n right: SudoChallengeConfig,\n tenantId: string | null,\n organizationId: string | null,\n ): number {\n const leftScore = this.getScopePriority(left, tenantId, organizationId)\n const rightScore = this.getScopePriority(right, tenantId, organizationId)\n if (leftScore !== rightScore) return leftScore - rightScore\n if (left.isDeveloperDefault !== right.isDeveloperDefault) {\n return left.isDeveloperDefault ? 1 : -1\n }\n return right.updatedAt.getTime() - left.updatedAt.getTime()\n }\n\n private getScopePriority(\n config: SudoChallengeConfig,\n tenantId: string | null,\n organizationId: string | null,\n ): number {\n if (config.organizationId === organizationId && config.tenantId === tenantId) return 0\n if (!config.organizationId && config.tenantId === tenantId) return 1\n if (!config.organizationId && !config.tenantId && !config.isDeveloperDefault) return 2\n if (!config.organizationId && !config.tenantId && config.isDeveloperDefault) return 3\n return 4\n }\n\n private async getPendingSession(sessionId: string): Promise<SudoSession> {\n const session = await this.em.findOne(SudoSession, { id: sessionId })\n if (!session) {\n throw new SudoChallengeServiceError('Sudo challenge session not found', 404)\n }\n if (session.expiresAt.getTime() <= Date.now()) {\n throw new SudoChallengeServiceError('Sudo challenge session expired', 400)\n }\n return session\n }\n\n private async findUserScope(userId: string): Promise<UserScope | null> {\n const user = await findOneWithDecryption(\n this.em,\n User,\n { id: userId, deletedAt: null },\n undefined,\n {},\n )\n\n if (!user) return null\n return {\n id: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n }\n }\n\n private normalizeTtl(value?: number | null): number {\n const rawValue = value ?? this.securityConfig.sudo.defaultTtlSeconds\n return Math.min(\n Math.max(rawValue, this.securityConfig.sudo.minTtlSeconds),\n this.securityConfig.sudo.maxTtlSeconds,\n )\n }\n\n private readPassword(payload: unknown): string {\n if (!payload || typeof payload !== 'object') {\n throw new SudoChallengeServiceError('Password is required', 400)\n }\n const maybePassword = (payload as Record<string, unknown>).password\n if (typeof maybePassword !== 'string' || maybePassword.trim().length === 0) {\n throw new SudoChallengeServiceError('Password is required', 400)\n }\n return maybePassword\n }\n\n private signToken(payload: SignedSudoTokenPayload): string {\n const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url')\n const signature = createHmac('sha256', this.getSudoSecret()).update(encodedPayload).digest('base64url')\n return `${encodedPayload}.${signature}`\n }\n\n private readSignedToken(token: string): SignedSudoTokenPayload | null {\n const [encodedPayload, signature] = token.split('.')\n if (!encodedPayload || !signature) return null\n\n const expected = createHmac('sha256', this.getSudoSecret()).update(encodedPayload).digest('base64url')\n const signatureBuffer = Buffer.from(signature)\n const expectedBuffer = Buffer.from(expected)\n if (signatureBuffer.length !== expectedBuffer.length) return null\n if (!timingSafeEqual(signatureBuffer, expectedBuffer)) return null\n\n try {\n const parsed = signedSudoTokenPayloadSchema.safeParse(\n JSON.parse(Buffer.from(encodedPayload, 'base64url').toString('utf8')),\n )\n if (!parsed.success) return null\n return parsed.data\n } catch {\n return null\n }\n }\n\n private getSudoSecret(): string {\n return process.env.OM_SECURITY_SUDO_SECRET\n ?? process.env.AUTH_JWT_SECRET\n ?? process.env.JWT_SECRET\n ?? 'open-mercato-sudo-secret'\n }\n\n private toChallengeMethod(\n method: SecuritySudoTarget['challengeMethod'],\n ): ChallengeMethod | undefined {\n switch (method) {\n case 'password':\n return ChallengeMethod.PASSWORD\n case 'mfa':\n return ChallengeMethod.MFA\n case 'auto':\n default:\n return ChallengeMethod.AUTO\n }\n }\n}\n\nexport default SudoChallengeService\n"],
5
- "mappings": "AAAA,SAAS,YAAY,aAAa,uBAAuB;AACzD,SAAS,SAAS;AAElB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAQlC,SAAS,eAAe,0BAA0B;AAElD,SAAS,gCAAgC;AAezC,MAAM,+BAA+B,EAAE,OAAO;AAAA,EAC5C,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA,EACzB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA,EACzB,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO;AAChB,CAAC;AAuBM,MAAM,kCAAkC,MAAM;AAAA,EACnD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,qBAAqB;AAAA,EAChC,YACmB,IACA,iBACA,YACA,wBACA,iBAAuC,yBAAyB,GACjF;AALiB;AACA;AACA;AACA;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,YAAY,OAAuD;AACvE,UAAM,KAAK,kCAAkC;AAC7C,UAAM,SAA2C,EAAE,WAAW,KAAK;AACnE,QAAI,SAAS,CAAC,MAAM,cAAc;AAChC,UAAI,CAAC,MAAM,SAAU,QAAO,CAAC;AAC5B,MAAC,OAAmC,MAAM;AAAA,Q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AAQ,IAAI,cACZ;AAAA,EACP;AAAA,EAEQ,kBACN,QAC6B;AAC7B,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,eAAO,gBAAgB;AAAA,MACzB,KAAK;AACH,eAAO,gBAAgB;AAAA,MACzB,KAAK;AAAA,MACL;AACE,eAAO,gBAAgB;AAAA,IAC3B;AAAA,EACF;AACF;AAEA,IAAO,+BAAQ;",
4
+ "sourcesContent": ["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n dedupeSudoTargets,\n getSecuritySudoTargetEntries,\n type SecuritySudoTarget,\n} from '../lib/module-security-registry'\nimport {\n ChallengeMethod,\n SudoChallengeConfig,\n SudoChallengeMethodUsed,\n SudoSession,\n} from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type {\n SudoConfigInput,\n SudoConfigUpdateInput,\n} from '../data/validators'\nimport type { PasswordService } from './PasswordService'\nimport type { MfaService } from './MfaService'\nimport type { MfaVerificationService } from './MfaVerificationService'\nimport { sudoTargets as defaultSudoTargets } from '../security.sudo'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SudoMethod = 'password' | 'mfa'\n\nexport type SudoAvailableMethod = {\n type: string\n label: string\n icon: string\n}\n\nexport type SudoProtectionResolution = {\n protected: boolean\n config?: SudoChallengeConfig\n}\n\nconst signedSudoTokenPayloadSchema = z.object({\n sid: z.string(),\n sub: z.string(),\n tid: z.string().nullable(),\n oid: z.string().nullable(),\n tgt: z.string(),\n exp: z.number(),\n})\n\ntype SignedSudoTokenPayload = z.infer<typeof signedSudoTokenPayloadSchema>\n\ntype UserScope = {\n id: string\n tenantId: string | null\n organizationId: string | null\n}\n\nexport type SudoAuthScope = {\n tenantId: string | null\n organizationId?: string | null\n isSuperAdmin?: boolean\n}\n\ntype DeveloperDefaultPayload = {\n targetIdentifier: string\n label?: string | null\n ttlSeconds?: number\n challengeMethod?: ChallengeMethod\n}\n\nfunction readTrimmedEnv(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed ? trimmed : undefined\n}\n\nexport class SudoChallengeServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'SudoChallengeServiceError'\n }\n}\n\nexport class SudoChallengeService {\n constructor(\n private readonly em: EntityManager,\n private readonly passwordService: PasswordService,\n private readonly mfaService: MfaService,\n private readonly mfaVerificationService: MfaVerificationService,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async listConfigs(scope?: SudoAuthScope): Promise<SudoChallengeConfig[]> {\n await this.ensureDeveloperDefaultsRegistered()\n const filter: FilterQuery<SudoChallengeConfig> = { deletedAt: null }\n if (scope && !scope.isSuperAdmin) {\n if (!scope.tenantId) return []\n ;(filter as Record<string, unknown>).$or = [\n { tenantId: scope.tenantId },\n { tenantId: null },\n ]\n }\n return this.em.find(\n SudoChallengeConfig,\n filter,\n {\n orderBy: {\n targetIdentifier: 'asc',\n tenantId: 'asc',\n organizationId: 'asc',\n createdAt: 'asc',\n },\n },\n )\n }\n\n async getConfigById(id: string, scope?: SudoAuthScope): Promise<SudoChallengeConfig | null> {\n await this.ensureDeveloperDefaultsRegistered()\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) return null\n if (scope && !this.isConfigVisibleToScope(config, scope)) return null\n return config\n }\n\n async isProtected(\n targetIdentifier: string,\n tenantId?: string | null,\n organizationId?: string | null,\n ): Promise<SudoProtectionResolution> {\n await this.ensureDeveloperDefaultsRegistered()\n\n const candidates = await this.em.find(SudoChallengeConfig, {\n targetIdentifier,\n deletedAt: null,\n })\n\n const resolved = candidates\n .filter((config) => this.matchesScope(config, tenantId ?? null, organizationId ?? null))\n .sort((left, right) => this.compareConfigPriority(left, right, tenantId ?? null, organizationId ?? null))[0]\n\n if (!resolved || !resolved.isEnabled) {\n return { protected: false }\n }\n\n return { protected: true, config: resolved }\n }\n\n async initiate(\n userId: string,\n targetIdentifier: string,\n options?: { tenantId?: string | null; organizationId?: string | null },\n ): Promise<{\n required: boolean\n sessionId?: string\n method?: SudoMethod\n availableMfaMethods?: SudoAvailableMethod[]\n expiresAt?: Date\n }> {\n const protection = await this.isProtected(\n targetIdentifier,\n options?.tenantId ?? null,\n options?.organizationId ?? null,\n )\n\n if (!protection.protected || !protection.config) {\n return { required: false }\n }\n\n const user = await this.findUserScope(userId)\n if (!user?.tenantId) {\n throw new SudoChallengeServiceError('User not found', 404)\n }\n\n const userMethods = await this.mfaService.getUserMethods(userId)\n const method = this.resolveChallengeMethod(protection.config.challengeMethod, userMethods.length)\n\n let sessionToken = randomBytes(16).toString('hex')\n let availableMfaMethods: SudoAvailableMethod[] | undefined\n if (method === 'mfa') {\n const challenge = await this.mfaVerificationService.createChallenge(userId)\n sessionToken = challenge.challengeId\n availableMfaMethods = challenge.availableMethods\n }\n\n const expiresAt = new Date(Date.now() + this.securityConfig.sudo.pendingChallengeTtlMs)\n const session = this.em.create(SudoSession, {\n userId,\n tenantId: user.tenantId,\n sessionToken,\n challengeMethod: method,\n expiresAt,\n createdAt: new Date(),\n })\n this.em.persist(session)\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.challenged', {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n targetIdentifier,\n method,\n })\n\n return {\n required: true,\n sessionId: session.id,\n method,\n availableMfaMethods,\n expiresAt,\n }\n }\n\n async prepare(\n sessionId: string,\n methodType: string,\n options: { expectedUserId?: string } = {},\n request?: Request,\n ): Promise<{ clientData?: Record<string, unknown> }> {\n const session = await this.getPendingSession(sessionId)\n if (options.expectedUserId && session.userId !== options.expectedUserId) {\n throw new SudoChallengeServiceError('Sudo challenge user mismatch', 403)\n }\n if (session.challengeMethod !== 'mfa') {\n throw new SudoChallengeServiceError('This sudo session does not require MFA', 400)\n }\n return this.mfaVerificationService.prepareChallenge(\n session.sessionToken,\n methodType,\n { request },\n { userId: session.userId },\n )\n }\n\n async verify(\n sessionId: string,\n methodType: string,\n payload: unknown,\n options: {\n expectedUserId?: string\n tenantId?: string | null\n organizationId?: string | null\n targetIdentifier: string\n },\n request?: Request,\n ): Promise<{ sudoToken: string; expiresAt: Date }> {\n const session = await this.getPendingSession(sessionId)\n if (options.expectedUserId && session.userId !== options.expectedUserId) {\n throw new SudoChallengeServiceError('Sudo challenge user mismatch', 403)\n }\n const user = await this.findUserScope(session.userId)\n if (!user?.tenantId) {\n throw new SudoChallengeServiceError('User not found', 404)\n }\n\n const scopeTenantId = options.tenantId !== undefined ? options.tenantId : user.tenantId\n const scopeOrganizationId = options.organizationId !== undefined ? options.organizationId : user.organizationId\n const protection = await this.isProtected(\n options.targetIdentifier,\n scopeTenantId,\n scopeOrganizationId,\n )\n if (!protection.protected || !protection.config) {\n throw new SudoChallengeServiceError('Sudo protection is not configured for this target', 404)\n }\n\n let verified = false\n let methodUsed: string = methodType\n if (session.challengeMethod === 'password') {\n const password = this.readPassword(payload)\n verified = await this.passwordService.verifyPassword(session.userId, password)\n methodUsed = SudoChallengeMethodUsed.PASSWORD\n } else {\n verified = await this.mfaVerificationService.verifyChallenge(\n session.sessionToken,\n methodType,\n payload,\n { request },\n { userId: session.userId },\n )\n }\n\n if (!verified) {\n await emitSecurityEvent('security.sudo.failed', {\n userId: session.userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n targetIdentifier: options.targetIdentifier,\n method: methodUsed,\n })\n throw new SudoChallengeServiceError('Unable to verify sudo challenge', 401)\n }\n\n const ttlSeconds = this.normalizeTtl(protection.config.ttlSeconds)\n const expiresAt = new Date(Date.now() + ttlSeconds * 1000)\n const sudoToken = this.signToken({\n sid: session.id,\n sub: session.userId,\n tid: scopeTenantId,\n oid: scopeOrganizationId,\n tgt: options.targetIdentifier,\n exp: expiresAt.getTime(),\n })\n\n session.sessionToken = sudoToken\n session.challengeMethod = methodUsed\n session.expiresAt = expiresAt\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.verified', {\n userId: session.userId,\n tenantId: scopeTenantId,\n organizationId: scopeOrganizationId,\n targetIdentifier: options.targetIdentifier,\n method: methodUsed,\n expiresAt: expiresAt.toISOString(),\n })\n\n return { sudoToken, expiresAt }\n }\n\n async validateToken(\n token: string,\n targetIdentifier: string,\n options?: {\n expectedUserId?: string\n tenantId?: string | null\n organizationId?: string | null\n },\n ): Promise<boolean> {\n if (!token) return false\n const payload = this.readSignedToken(token)\n if (!payload) return false\n if (payload.exp <= Date.now()) return false\n if (payload.tgt !== targetIdentifier) return false\n if (options?.expectedUserId && payload.sub !== options.expectedUserId) return false\n if (options?.tenantId !== undefined && payload.tid !== (options.tenantId ?? null)) return false\n if (options?.organizationId !== undefined && payload.oid !== (options.organizationId ?? null)) return false\n\n const session = await this.em.findOne(SudoSession, {\n id: payload.sid,\n userId: payload.sub,\n sessionToken: token,\n } as FilterQuery<SudoSession>)\n\n return Boolean(session && session.expiresAt.getTime() > Date.now())\n }\n\n async createConfig(\n input: SudoConfigInput,\n configuredBy: string,\n scope?: SudoAuthScope,\n ): Promise<SudoChallengeConfig> {\n await this.ensureDeveloperDefaultsRegistered()\n const inputTenantId = input.tenantId ?? null\n const inputOrganizationId = input.organizationId ?? null\n this.validateScope(inputTenantId, inputOrganizationId)\n if (scope) this.assertWriteScope(inputTenantId, inputOrganizationId, scope)\n await this.ensureUniqueConfig(input.targetIdentifier, inputTenantId, inputOrganizationId)\n\n const config = this.em.create(SudoChallengeConfig, {\n tenantId: inputTenantId,\n organizationId: inputOrganizationId,\n label: input.label ?? null,\n targetIdentifier: input.targetIdentifier,\n isEnabled: input.isEnabled,\n ttlSeconds: this.normalizeTtl(input.ttlSeconds),\n challengeMethod: input.challengeMethod,\n configuredBy,\n isDeveloperDefault: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n this.em.persist(config)\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.created', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n configuredBy,\n })\n\n return config\n }\n\n async updateConfig(\n id: string,\n input: SudoConfigUpdateInput,\n configuredBy: string,\n scope?: SudoAuthScope,\n ): Promise<SudoChallengeConfig> {\n await this.ensureDeveloperDefaultsRegistered()\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (scope) {\n this.assertWriteScope(config.tenantId ?? null, config.organizationId ?? null, scope)\n if (config.isDeveloperDefault && !scope.isSuperAdmin) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n\n const nextTenantId = input.tenantId !== undefined ? input.tenantId ?? null : config.tenantId ?? null\n const nextOrganizationId = input.organizationId !== undefined ? input.organizationId ?? null : config.organizationId ?? null\n const nextTargetIdentifier = input.targetIdentifier ?? config.targetIdentifier\n this.validateScope(nextTenantId, nextOrganizationId)\n if (scope) this.assertWriteScope(nextTenantId, nextOrganizationId, scope)\n await this.ensureUniqueConfig(nextTargetIdentifier, nextTenantId, nextOrganizationId, config.id)\n\n if (input.tenantId !== undefined) config.tenantId = input.tenantId ?? null\n if (input.organizationId !== undefined) config.organizationId = input.organizationId ?? null\n if (input.label !== undefined) config.label = input.label ?? null\n if (input.targetIdentifier !== undefined) config.targetIdentifier = input.targetIdentifier\n if (input.isEnabled !== undefined) config.isEnabled = input.isEnabled\n if (input.ttlSeconds !== undefined) config.ttlSeconds = this.normalizeTtl(input.ttlSeconds)\n if (input.challengeMethod !== undefined) config.challengeMethod = input.challengeMethod\n config.configuredBy = configuredBy\n config.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.updated', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n configuredBy,\n })\n\n return config\n }\n\n async deleteConfig(id: string, scope?: SudoAuthScope): Promise<void> {\n const config = await this.em.findOne(SudoChallengeConfig, { id, deletedAt: null })\n if (!config) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (scope) {\n this.assertWriteScope(config.tenantId ?? null, config.organizationId ?? null, scope)\n if (config.isDeveloperDefault && !scope.isSuperAdmin) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n config.deletedAt = new Date()\n config.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.sudo.config.deleted', {\n id: config.id,\n targetIdentifier: config.targetIdentifier,\n })\n }\n\n async registerDeveloperDefault(\n input: DeveloperDefaultPayload,\n ): Promise<void> {\n const existing = await this.em.findOne(SudoChallengeConfig, {\n targetIdentifier: input.targetIdentifier,\n tenantId: null,\n organizationId: null,\n isDeveloperDefault: true,\n })\n\n if (existing) {\n existing.isEnabled = true\n existing.deletedAt = null\n existing.ttlSeconds = this.normalizeTtl(input.ttlSeconds)\n existing.challengeMethod = input.challengeMethod ?? ChallengeMethod.AUTO\n existing.updatedAt = new Date()\n await this.em.flush()\n return\n }\n\n const config = this.em.create(SudoChallengeConfig, {\n tenantId: null,\n organizationId: null,\n label: input.label ?? null,\n targetIdentifier: input.targetIdentifier,\n isEnabled: true,\n isDeveloperDefault: true,\n ttlSeconds: this.normalizeTtl(input.ttlSeconds),\n challengeMethod: input.challengeMethod ?? ChallengeMethod.AUTO,\n configuredBy: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n this.em.persist(config)\n await this.em.flush()\n }\n\n async cleanupExpired(): Promise<number> {\n return this.em.nativeDelete(SudoSession, {\n expiresAt: { $lte: new Date() },\n })\n }\n\n private async ensureDeveloperDefaultsRegistered(): Promise<void> {\n const registryEntries = getSecuritySudoTargetEntries()\n const registryTargets = registryEntries.flatMap((entry) => entry.targets ?? [])\n const fallbackTargets = registryEntries.length === 0 ? defaultSudoTargets : []\n\n for (const target of dedupeSudoTargets([\n ...registryTargets,\n ...fallbackTargets,\n ])) {\n await this.registerDeveloperDefault(this.readDeveloperDefault(target))\n }\n }\n\n private readDeveloperDefault(target: SecuritySudoTarget): DeveloperDefaultPayload {\n return {\n targetIdentifier: target.identifier,\n label: target.label ?? null,\n ttlSeconds: target.ttlSeconds,\n challengeMethod: this.toChallengeMethod(target.challengeMethod),\n }\n }\n\n private async ensureUniqueConfig(\n targetIdentifier: string,\n tenantId: string | null,\n organizationId: string | null,\n ignoreId?: string,\n ): Promise<void> {\n const existing = await this.em.findOne(SudoChallengeConfig, {\n targetIdentifier,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (existing && existing.id !== ignoreId) {\n throw new SudoChallengeServiceError('A sudo configuration for this target and scope already exists', 409)\n }\n }\n\n private validateScope(tenantId: string | null, organizationId: string | null): void {\n if (organizationId && !tenantId) {\n throw new SudoChallengeServiceError('Organization-scoped sudo config requires a tenant', 400)\n }\n }\n\n private isConfigVisibleToScope(config: SudoChallengeConfig, scope: SudoAuthScope): boolean {\n if (scope.isSuperAdmin) return true\n if (!scope.tenantId) return false\n const configTenantId = config.tenantId ?? null\n if (configTenantId === null) return true\n return configTenantId === scope.tenantId\n }\n\n private assertWriteScope(\n targetTenantId: string | null,\n targetOrganizationId: string | null,\n scope: SudoAuthScope,\n ): void {\n if (scope.isSuperAdmin) return\n if (!scope.tenantId) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if ((targetTenantId ?? null) !== scope.tenantId) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n if (\n scope.organizationId !== undefined\n && scope.organizationId !== null\n && targetOrganizationId !== null\n && targetOrganizationId !== scope.organizationId\n ) {\n throw new SudoChallengeServiceError('Sudo configuration not found', 404)\n }\n }\n\n private resolveChallengeMethod(\n configuredMethod: ChallengeMethod,\n availableMfaMethodCount: number,\n ): SudoMethod {\n if (this.securityConfig.mfa.emergencyBypass) {\n return 'password'\n }\n if (configuredMethod === ChallengeMethod.PASSWORD) return 'password'\n if (configuredMethod === ChallengeMethod.MFA) {\n if (availableMfaMethodCount === 0) {\n throw new SudoChallengeServiceError('This sudo target requires MFA, but no MFA methods are configured', 400)\n }\n return 'mfa'\n }\n return availableMfaMethodCount > 0 ? 'mfa' : 'password'\n }\n\n private matchesScope(config: SudoChallengeConfig, tenantId: string | null, organizationId: string | null): boolean {\n if (config.organizationId) {\n return config.organizationId === organizationId && config.tenantId === tenantId\n }\n if (config.tenantId) {\n return config.tenantId === tenantId\n }\n return true\n }\n\n private compareConfigPriority(\n left: SudoChallengeConfig,\n right: SudoChallengeConfig,\n tenantId: string | null,\n organizationId: string | null,\n ): number {\n const leftScore = this.getScopePriority(left, tenantId, organizationId)\n const rightScore = this.getScopePriority(right, tenantId, organizationId)\n if (leftScore !== rightScore) return leftScore - rightScore\n if (left.isDeveloperDefault !== right.isDeveloperDefault) {\n return left.isDeveloperDefault ? 1 : -1\n }\n return right.updatedAt.getTime() - left.updatedAt.getTime()\n }\n\n private getScopePriority(\n config: SudoChallengeConfig,\n tenantId: string | null,\n organizationId: string | null,\n ): number {\n if (config.organizationId === organizationId && config.tenantId === tenantId) return 0\n if (!config.organizationId && config.tenantId === tenantId) return 1\n if (!config.organizationId && !config.tenantId && !config.isDeveloperDefault) return 2\n if (!config.organizationId && !config.tenantId && config.isDeveloperDefault) return 3\n return 4\n }\n\n private async getPendingSession(sessionId: string): Promise<SudoSession> {\n const session = await this.em.findOne(SudoSession, { id: sessionId })\n if (!session) {\n throw new SudoChallengeServiceError('Sudo challenge session not found', 404)\n }\n if (session.expiresAt.getTime() <= Date.now()) {\n throw new SudoChallengeServiceError('Sudo challenge session expired', 400)\n }\n return session\n }\n\n private async findUserScope(userId: string): Promise<UserScope | null> {\n const user = await findOneWithDecryption(\n this.em,\n User,\n { id: userId, deletedAt: null },\n undefined,\n {},\n )\n\n if (!user) return null\n return {\n id: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n }\n }\n\n private normalizeTtl(value?: number | null): number {\n const rawValue = value ?? this.securityConfig.sudo.defaultTtlSeconds\n return Math.min(\n Math.max(rawValue, this.securityConfig.sudo.minTtlSeconds),\n this.securityConfig.sudo.maxTtlSeconds,\n )\n }\n\n private readPassword(payload: unknown): string {\n if (!payload || typeof payload !== 'object') {\n throw new SudoChallengeServiceError('Password is required', 400)\n }\n const maybePassword = (payload as Record<string, unknown>).password\n if (typeof maybePassword !== 'string' || maybePassword.trim().length === 0) {\n throw new SudoChallengeServiceError('Password is required', 400)\n }\n return maybePassword\n }\n\n private signToken(payload: SignedSudoTokenPayload): string {\n const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url')\n const signature = createHmac('sha256', this.getSudoSecret()).update(encodedPayload).digest('base64url')\n return `${encodedPayload}.${signature}`\n }\n\n private readSignedToken(token: string): SignedSudoTokenPayload | null {\n const [encodedPayload, signature] = token.split('.')\n if (!encodedPayload || !signature) return null\n\n const expected = createHmac('sha256', this.getSudoSecret()).update(encodedPayload).digest('base64url')\n const signatureBuffer = Buffer.from(signature)\n const expectedBuffer = Buffer.from(expected)\n if (signatureBuffer.length !== expectedBuffer.length) return null\n if (!timingSafeEqual(signatureBuffer, expectedBuffer)) return null\n\n try {\n const parsed = signedSudoTokenPayloadSchema.safeParse(\n JSON.parse(Buffer.from(encodedPayload, 'base64url').toString('utf8')),\n )\n if (!parsed.success) return null\n return parsed.data\n } catch {\n return null\n }\n }\n\n private getSudoSecret(): string {\n const secret =\n readTrimmedEnv(process.env.OM_SECURITY_SUDO_SECRET)\n ?? readTrimmedEnv(process.env.AUTH_JWT_SECRET)\n ?? readTrimmedEnv(process.env.AUTH_SECRET)\n ?? readTrimmedEnv(process.env.JWT_SECRET)\n if (secret) return secret\n throw new Error(\n 'Sudo step-up tokens require OM_SECURITY_SUDO_SECRET, AUTH_JWT_SECRET, AUTH_SECRET, or JWT_SECRET to be set.',\n )\n }\n\n private toChallengeMethod(\n method: SecuritySudoTarget['challengeMethod'],\n ): ChallengeMethod | undefined {\n switch (method) {\n case 'password':\n return ChallengeMethod.PASSWORD\n case 'mfa':\n return ChallengeMethod.MFA\n case 'auto':\n default:\n return ChallengeMethod.AUTO\n }\n }\n}\n\nexport default SudoChallengeService\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,aAAa,uBAAuB;AACzD,SAAS,SAAS;AAElB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAQlC,SAAS,eAAe,0BAA0B;AAElD,SAAS,gCAAgC;AAezC,MAAM,+BAA+B,EAAE,OAAO;AAAA,EAC5C,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA,EACzB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA,EACzB,KAAK,EAAE,OAAO;AAAA,EACd,KAAK,EAAE,OAAO;AAChB,CAAC;AAuBD,SAAS,eAAe,OAA+C;AACrE,QAAM,UAAU,OAAO,KAAK;AAC5B,SAAO,UAAU,UAAU;AAC7B;AAEO,MAAM,kCAAkC,MAAM;AAAA,EACnD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,qBAAqB;AAAA,EAChC,YACmB,IACA,iBACA,YACA,wBACA,iBAAuC,yBAAyB,GACjF;AALiB;AACA;AACA;AACA;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,YAAY,OAAuD;AACvE,UAAM,KAAK,kCAAkC;AAC7C,UAAM,SAA2C,EAAE,WAAW,KAAK;AACnE,QAAI,SAAS,CAAC,MAAM,cAAc;AAChC,UAAI,CAAC,MAAM,SAAU,QAAO,CAAC;AAC5B,MAAC,OAAmC,MAAM;AAAA,QACzC,EAAE,UAAU,MAAM,SAAS;AAAA,QAC3B,EAAE,UAAU,KAAK;AAAA,MACnB;AAAA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AAC,OAAO,QAAS,QAAO;AAC5B,aAAO,OAAO;AAAA,IAChB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,gBAAwB;AAC9B,UAAM,SACJ,eAAe,QAAQ,IAAI,uBAAuB,KAC/C,eAAe,QAAQ,IAAI,eAAe,KAC1C,eAAe,QAAQ,IAAI,WAAW,KACtC,eAAe,QAAQ,IAAI,UAAU;AAC1C,QAAI,OAAQ,QAAO;AACnB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,kBACN,QAC6B;AAC7B,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,eAAO,gBAAgB;AAAA,MACzB,KAAK;AACH,eAAO,gBAAgB;AAAA,MACzB,KAAK;AAAA,MACL;AACE,eAAO,gBAAgB;AAAA,IAC3B;AAAA,EACF;AACF;AAEA,IAAO,+BAAQ;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/enterprise",
3
- "version": "0.6.6-develop.5612.1.d382eb2f33",
3
+ "version": "0.6.6-develop.5617.1.62538c48ca",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
@@ -64,8 +64,8 @@
64
64
  }
65
65
  },
66
66
  "dependencies": {
67
- "@open-mercato/core": "0.6.6-develop.5612.1.d382eb2f33",
68
- "@open-mercato/ui": "0.6.6-develop.5612.1.d382eb2f33",
67
+ "@open-mercato/core": "0.6.6-develop.5617.1.62538c48ca",
68
+ "@open-mercato/ui": "0.6.6-develop.5617.1.62538c48ca",
69
69
  "@simplewebauthn/browser": "^13.3.0",
70
70
  "@simplewebauthn/server": "^13.3.1",
71
71
  "@simplewebauthn/types": "^12.0.0",
@@ -75,12 +75,12 @@
75
75
  "qrcode": "^1.5.4"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.6.6-develop.5612.1.d382eb2f33",
78
+ "@open-mercato/shared": "0.6.6-develop.5617.1.62538c48ca",
79
79
  "react": "^19.0.0",
80
80
  "react-dom": "^19.0.0"
81
81
  },
82
82
  "devDependencies": {
83
- "@open-mercato/shared": "0.6.6-develop.5612.1.d382eb2f33",
83
+ "@open-mercato/shared": "0.6.6-develop.5617.1.62538c48ca",
84
84
  "@types/jest": "^30.0.0",
85
85
  "@types/react": "^19.2.17",
86
86
  "@types/react-dom": "^19.2.3",
@@ -22,6 +22,8 @@ const exactMessageMap = new Map<string, MessageDescriptor>([
22
22
  ['Sudo config not found', { key: 'security.api.errors.sudoConfigurationNotFound', fallback: 'Sudo configuration not found.' }],
23
23
  ['Sudo configuration not found', { key: 'security.api.errors.sudoConfigurationNotFound', fallback: 'Sudo configuration not found.' }],
24
24
  ['Tenant context is required.', { key: 'security.api.errors.tenantContextRequired', fallback: 'Tenant context is required.' }],
25
+ ['Cross-tenant access denied.', { key: 'security.api.errors.crossTenantAccessDenied', fallback: 'Cross-tenant access denied.' }],
26
+ ['Tenant not found', { key: 'security.api.errors.tenantNotFound', fallback: 'Tenant not found.' }],
25
27
  ['MFA pending token is required.', { key: 'security.api.errors.mfaPendingTokenRequired', fallback: 'MFA pending token is required.' }],
26
28
  ['challengeId and methodType are required.', { key: 'security.api.errors.challengeIdAndMethodTypeRequired', fallback: 'challengeId and methodType are required.' }],
27
29
  ['setupId is required.', { key: 'security.api.errors.setupIdRequired', fallback: 'setupId is required.' }],
@@ -46,6 +48,7 @@ const exactMessageMap = new Map<string, MessageDescriptor>([
46
48
  ['MFA challenge already verified', { key: 'security.api.errors.mfaChallengeAlreadyVerified', fallback: 'MFA challenge was already verified.' }],
47
49
  ['MFA challenge expired', { key: 'security.api.errors.mfaChallengeExpired', fallback: 'MFA challenge expired.' }],
48
50
  ['Enforcement policy not found', { key: 'security.api.errors.enforcementPolicyNotFound', fallback: 'Enforcement policy not found.' }],
51
+ ['Insufficient scope for enforcement policy', { key: 'security.api.errors.enforcementInsufficientScope', fallback: 'Insufficient scope for enforcement policy.' }],
49
52
  ['Enforcement policy already exists for this scope', { key: 'security.api.errors.enforcementPolicyAlreadyExistsForScope', fallback: 'An enforcement policy already exists for this scope.' }],
50
53
  ['scopeId is required for tenant and organisation scopes', { key: 'security.api.errors.enforcementScopeIdRequired', fallback: 'scopeId is required for tenant and organisation scopes.' }],
51
54
  ["organisation scopeId must use '<tenantId>:<organizationId>' format", { key: 'security.api.errors.enforcementOrganizationScopeFormat', fallback: "Organisation scopeId must use '<tenantId>:<organizationId>' format." }],
@@ -34,7 +34,12 @@ export async function POST(req: Request) {
34
34
  }
35
35
 
36
36
  try {
37
- const prepared = await context.mfaVerificationService.prepareChallenge(challengeId, methodType, { request: req })
37
+ const prepared = await context.mfaVerificationService.prepareChallenge(
38
+ challengeId,
39
+ methodType,
40
+ { request: req },
41
+ { userId: context.auth.sub },
42
+ )
38
43
  return NextResponse.json({ ok: true, ...(prepared.clientData ? { clientData: prepared.clientData } : {}) })
39
44
  } catch (error) {
40
45
  return await mapMfaError(error)
@@ -37,7 +37,13 @@ export async function POST(req: Request) {
37
37
  }
38
38
 
39
39
  try {
40
- const verified = await context.mfaVerificationService.verifyChallenge(challengeId, methodType, payload, { request: req })
40
+ const verified = await context.mfaVerificationService.verifyChallenge(
41
+ challengeId,
42
+ methodType,
43
+ payload,
44
+ { request: req },
45
+ { userId: context.auth.sub },
46
+ )
41
47
  if (!verified) {
42
48
  return securityApiError(401, 'Invalid MFA verification code.')
43
49
  }
@@ -30,7 +30,12 @@ export async function POST(req: Request) {
30
30
  }
31
31
 
32
32
  try {
33
- const result = await context.sudoChallengeService.prepare(parsed.data.sessionId, parsed.data.methodType, req)
33
+ const result = await context.sudoChallengeService.prepare(
34
+ parsed.data.sessionId,
35
+ parsed.data.methodType,
36
+ { expectedUserId: context.auth.sub },
37
+ req,
38
+ )
34
39
  return NextResponse.json(result)
35
40
  } catch (error) {
36
41
  return await mapSudoError(error)
@@ -8,6 +8,7 @@ import {
8
8
  mapSecurityUsersError,
9
9
  resolveSecurityUsersContext,
10
10
  } from '../../_shared'
11
+ import type { MfaAdminAuthScope } from '../../../../services/MfaAdminService'
11
12
 
12
13
  const querySchema = z.object({
13
14
  tenantId: z.string().uuid().optional(),
@@ -48,10 +49,12 @@ export async function GET(req: Request) {
48
49
  return securityApiError(400, 'Tenant context is required.')
49
50
  }
50
51
  const isSuperAdmin = await resolveIsSuperAdmin({ auth: context.auth, container: context.container })
51
- const items = await context.mfaAdminService.bulkComplianceCheck(tenantId, {
52
- tenantId: context.auth.tenantId ?? null,
52
+ const scope: MfaAdminAuthScope = {
53
+ tenantId: (context.auth.tenantId as string | null | undefined) ?? null,
54
+ organizationId: (context.auth.orgId as string | null | undefined) ?? null,
53
55
  isSuperAdmin,
54
- })
56
+ }
57
+ const items = await context.mfaAdminService.bulkComplianceCheck(tenantId, scope)
55
58
  return NextResponse.json({ items })
56
59
  } catch (error) {
57
60
  return await mapSecurityUsersError(error)
@@ -4,7 +4,7 @@ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
4
4
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
5
5
  import { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'
6
6
  import { enforcementPolicySchema } from '../data/validators'
7
- import type { MfaEnforcementService } from '../services/MfaEnforcementService'
7
+ import type { MfaEnforcementAuthScope, MfaEnforcementService } from '../services/MfaEnforcementService'
8
8
 
9
9
  export const commandId = 'security.enforcement.create'
10
10
 
@@ -36,11 +36,13 @@ registerCommand({
36
36
 
37
37
  const enforcementService = ctx.container.resolve<MfaEnforcementService>('mfaEnforcementService')
38
38
  const isSuperAdmin = await resolveIsSuperAdmin({ auth: ctx.auth, container: ctx.container })
39
+ const scope: MfaEnforcementAuthScope = {
40
+ tenantId: (ctx.auth.tenantId as string | null | undefined) ?? null,
41
+ organizationId: (ctx.auth.orgId as string | null | undefined) ?? null,
42
+ isSuperAdmin,
43
+ }
39
44
  try {
40
- const policy = await enforcementService.createPolicy(parsed.data, ctx.auth.sub, {
41
- tenantId: ctx.auth.tenantId ?? null,
42
- isSuperAdmin,
43
- })
45
+ const policy = await enforcementService.createPolicy(parsed.data, ctx.auth.sub, scope)
44
46
  return { id: policy.id }
45
47
  } catch (error) {
46
48
  if (isEnforcementServiceError(error)) {
@@ -3,7 +3,10 @@ import { registerCommand } from '@open-mercato/shared/lib/commands'
3
3
  import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
4
4
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
5
5
  import { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'
6
- import type { MfaEnforcementService } from '../services/MfaEnforcementService'
6
+ import type {
7
+ MfaEnforcementAuthScope,
8
+ MfaEnforcementService,
9
+ } from '../services/MfaEnforcementService'
7
10
 
8
11
  export const commandId = 'security.enforcement.delete'
9
12
 
@@ -37,11 +40,13 @@ registerCommand({
37
40
 
38
41
  const enforcementService = ctx.container.resolve<MfaEnforcementService>('mfaEnforcementService')
39
42
  const isSuperAdmin = await resolveIsSuperAdmin({ auth: ctx.auth, container: ctx.container })
43
+ const scope: MfaEnforcementAuthScope = {
44
+ tenantId: (ctx.auth.tenantId as string | null | undefined) ?? null,
45
+ organizationId: (ctx.auth.orgId as string | null | undefined) ?? null,
46
+ isSuperAdmin,
47
+ }
40
48
  try {
41
- await enforcementService.deletePolicy(parsed.data.id, {
42
- tenantId: ctx.auth.tenantId ?? null,
43
- isSuperAdmin,
44
- })
49
+ await enforcementService.deletePolicy(parsed.data.id, scope)
45
50
  return { ok: true as const }
46
51
  } catch (error) {
47
52
  if (isEnforcementServiceError(error)) {
@@ -3,7 +3,7 @@ import { registerCommand } from '@open-mercato/shared/lib/commands'
3
3
  import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
4
4
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
5
5
  import { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'
6
- import type { MfaAdminService } from '../services/MfaAdminService'
6
+ import type { MfaAdminAuthScope, MfaAdminService } from '../services/MfaAdminService'
7
7
 
8
8
  export const commandId = 'security.admin.mfa.reset'
9
9
 
@@ -38,11 +38,18 @@ registerCommand({
38
38
 
39
39
  const mfaAdminService = ctx.container.resolve<MfaAdminService>('mfaAdminService')
40
40
  const isSuperAdmin = await resolveIsSuperAdmin({ auth: ctx.auth, container: ctx.container })
41
+ const scope: MfaAdminAuthScope = {
42
+ tenantId: (ctx.auth.tenantId as string | null | undefined) ?? null,
43
+ organizationId: (ctx.auth.orgId as string | null | undefined) ?? null,
44
+ isSuperAdmin,
45
+ }
41
46
  try {
42
- await mfaAdminService.resetUserMfa(ctx.auth.sub, parsed.data.userId, parsed.data.reason, {
43
- tenantId: ctx.auth.tenantId ?? null,
44
- isSuperAdmin,
45
- })
47
+ await mfaAdminService.resetUserMfa(
48
+ ctx.auth.sub,
49
+ parsed.data.userId,
50
+ parsed.data.reason,
51
+ scope,
52
+ )
46
53
  return { ok: true as const }
47
54
  } catch (error) {
48
55
  if (isMfaAdminServiceError(error)) {
@@ -4,7 +4,10 @@ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
4
4
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
5
5
  import { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'
6
6
  import { updateEnforcementPolicySchema } from '../data/validators'
7
- import type { MfaEnforcementService } from '../services/MfaEnforcementService'
7
+ import type {
8
+ MfaEnforcementAuthScope,
9
+ MfaEnforcementService,
10
+ } from '../services/MfaEnforcementService'
8
11
 
9
12
  export const commandId = 'security.enforcement.update'
10
13
 
@@ -39,11 +42,13 @@ registerCommand({
39
42
 
40
43
  const enforcementService = ctx.container.resolve<MfaEnforcementService>('mfaEnforcementService')
41
44
  const isSuperAdmin = await resolveIsSuperAdmin({ auth: ctx.auth, container: ctx.container })
45
+ const scope: MfaEnforcementAuthScope = {
46
+ tenantId: (ctx.auth.tenantId as string | null | undefined) ?? null,
47
+ organizationId: (ctx.auth.orgId as string | null | undefined) ?? null,
48
+ isSuperAdmin,
49
+ }
42
50
  try {
43
- await enforcementService.updatePolicy(parsed.data.id, parsed.data.data, ctx.auth.sub, {
44
- tenantId: ctx.auth.tenantId ?? null,
45
- isSuperAdmin,
46
- })
51
+ await enforcementService.updatePolicy(parsed.data.id, parsed.data.data, ctx.auth.sub, scope)
47
52
  return { ok: true as const }
48
53
  } catch (error) {
49
54
  if (isEnforcementServiceError(error)) {
@@ -224,10 +224,12 @@
224
224
  "security.api.errors.adminIdRequired": "Eine Administrator-ID ist erforderlich.",
225
225
  "security.api.errors.challengeIdAndMethodTypeRequired": "challengeId und methodType sind erforderlich.",
226
226
  "security.api.errors.codeRequired": "code ist erforderlich.",
227
+ "security.api.errors.crossTenantAccessDenied": "Tenantübergreifender Zugriff verweigert.",
227
228
  "security.api.errors.emailOtpDestinationMissing": "Bei der E-Mail-OTP-Methode fehlt die Ziel-E-Mail-Adresse.",
228
229
  "security.api.errors.emailOtpDestinationRequired": "E-Mail-OTP kann ohne Ziel-E-Mail-Adresse nicht konfiguriert werden.",
229
230
  "security.api.errors.emailOtpSetupSessionExpired": "Die E-Mail-OTP-Einrichtungssitzung ist abgelaufen.",
230
231
  "security.api.errors.emailOtpSetupSessionNotFound": "Die E-Mail-OTP-Einrichtungssitzung wurde nicht gefunden.",
232
+ "security.api.errors.enforcementInsufficientScope": "Unzureichende Berechtigung für diese Enforcement-Richtlinie.",
231
233
  "security.api.errors.enforcementOrganizationScopeFormat": "Die Organisations-scopeId muss das Format '<tenantId>:<organizationId>' verwenden.",
232
234
  "security.api.errors.enforcementOrganizationScopeIdsRequired": "tenantId und organizationId sind für den Organisationsbereich erforderlich.",
233
235
  "security.api.errors.enforcementPolicyAlreadyExistsForScope": "Für diesen Geltungsbereich existiert bereits eine Enforcement-Richtlinie.",
@@ -282,6 +284,7 @@
282
284
  "security.api.errors.sudoVerifyFailed": "Die Sudo-Challenge konnte nicht verifiziert werden.",
283
285
  "security.api.errors.tenantContextRequired": "Ein Tenant-Kontext ist erforderlich.",
284
286
  "security.api.errors.tenantIdRequired": "Eine Tenant-ID ist erforderlich.",
287
+ "security.api.errors.tenantNotFound": "Tenant nicht gefunden.",
285
288
  "security.api.errors.totpSetupSessionExpired": "Die TOTP-Einrichtungssitzung ist abgelaufen.",
286
289
  "security.api.errors.totpSetupSessionNotFound": "Die TOTP-Einrichtungssitzung wurde nicht gefunden.",
287
290
  "security.api.errors.userIdRequired": "Eine Benutzer-ID ist erforderlich.",
@@ -224,10 +224,12 @@
224
224
  "security.api.errors.adminIdRequired": "Admin ID is required.",
225
225
  "security.api.errors.challengeIdAndMethodTypeRequired": "challengeId and methodType are required.",
226
226
  "security.api.errors.codeRequired": "code is required.",
227
+ "security.api.errors.crossTenantAccessDenied": "Cross-tenant access denied.",
227
228
  "security.api.errors.emailOtpDestinationMissing": "The email OTP method is missing a destination email address.",
228
229
  "security.api.errors.emailOtpDestinationRequired": "Unable to configure email OTP without a destination email address.",
229
230
  "security.api.errors.emailOtpSetupSessionExpired": "Email OTP setup session expired.",
230
231
  "security.api.errors.emailOtpSetupSessionNotFound": "Email OTP setup session not found.",
232
+ "security.api.errors.enforcementInsufficientScope": "Insufficient scope for enforcement policy.",
231
233
  "security.api.errors.enforcementOrganizationScopeFormat": "Organisation scopeId must use '<tenantId>:<organizationId>' format.",
232
234
  "security.api.errors.enforcementOrganizationScopeIdsRequired": "tenantId and organizationId are required for organisation scope.",
233
235
  "security.api.errors.enforcementPolicyAlreadyExistsForScope": "An enforcement policy already exists for this scope.",
@@ -282,6 +284,7 @@
282
284
  "security.api.errors.sudoVerifyFailed": "Unable to verify the sudo challenge.",
283
285
  "security.api.errors.tenantContextRequired": "Tenant context is required.",
284
286
  "security.api.errors.tenantIdRequired": "Tenant ID is required.",
287
+ "security.api.errors.tenantNotFound": "Tenant not found.",
285
288
  "security.api.errors.totpSetupSessionExpired": "TOTP setup session expired.",
286
289
  "security.api.errors.totpSetupSessionNotFound": "TOTP setup session not found.",
287
290
  "security.api.errors.userIdRequired": "User ID is required.",
@@ -224,10 +224,12 @@
224
224
  "security.api.errors.adminIdRequired": "Se requiere el ID del administrador.",
225
225
  "security.api.errors.challengeIdAndMethodTypeRequired": "challengeId y methodType son obligatorios.",
226
226
  "security.api.errors.codeRequired": "code es obligatorio.",
227
+ "security.api.errors.crossTenantAccessDenied": "Acceso entre inquilinos denegado.",
227
228
  "security.api.errors.emailOtpDestinationMissing": "Al método OTP por correo le falta una dirección de correo de destino.",
228
229
  "security.api.errors.emailOtpDestinationRequired": "No se puede configurar OTP por correo electrónico sin una dirección de correo de destino.",
229
230
  "security.api.errors.emailOtpSetupSessionExpired": "La sesión de configuración de OTP por correo ha expirado.",
230
231
  "security.api.errors.emailOtpSetupSessionNotFound": "No se encontró la sesión de configuración de OTP por correo.",
232
+ "security.api.errors.enforcementInsufficientScope": "Permisos insuficientes para esta política de aplicación.",
231
233
  "security.api.errors.enforcementOrganizationScopeFormat": "El scopeId de organización debe usar el formato '<tenantId>:<organizationId>'.",
232
234
  "security.api.errors.enforcementOrganizationScopeIdsRequired": "tenantId y organizationId son obligatorios para el alcance de organización.",
233
235
  "security.api.errors.enforcementPolicyAlreadyExistsForScope": "Ya existe una política de cumplimiento para este alcance.",
@@ -282,6 +284,7 @@
282
284
  "security.api.errors.sudoVerifyFailed": "No se pudo verificar el desafío sudo.",
283
285
  "security.api.errors.tenantContextRequired": "Se requiere el contexto del tenant.",
284
286
  "security.api.errors.tenantIdRequired": "Se requiere el ID del tenant.",
287
+ "security.api.errors.tenantNotFound": "Tenant no encontrado.",
285
288
  "security.api.errors.totpSetupSessionExpired": "La sesión de configuración de TOTP ha expirado.",
286
289
  "security.api.errors.totpSetupSessionNotFound": "No se encontró la sesión de configuración de TOTP.",
287
290
  "security.api.errors.userIdRequired": "Se requiere el ID del usuario.",
@@ -224,10 +224,12 @@
224
224
  "security.api.errors.adminIdRequired": "Identyfikator administratora jest wymagany.",
225
225
  "security.api.errors.challengeIdAndMethodTypeRequired": "Pola challengeId i methodType są wymagane.",
226
226
  "security.api.errors.codeRequired": "Pole code jest wymagane.",
227
+ "security.api.errors.crossTenantAccessDenied": "Dostęp międzytenantowy został zablokowany.",
227
228
  "security.api.errors.emailOtpDestinationMissing": "W metodzie OTP e-mail brakuje docelowego adresu e-mail.",
228
229
  "security.api.errors.emailOtpDestinationRequired": "Nie można skonfigurować OTP e-mail bez docelowego adresu e-mail.",
229
230
  "security.api.errors.emailOtpSetupSessionExpired": "Sesja konfiguracji OTP e-mail wygasła.",
230
231
  "security.api.errors.emailOtpSetupSessionNotFound": "Nie znaleziono sesji konfiguracji OTP e-mail.",
232
+ "security.api.errors.enforcementInsufficientScope": "Niewystarczające uprawnienia do tej polityki wymuszania.",
231
233
  "security.api.errors.enforcementOrganizationScopeFormat": "Pole scopeId dla organizacji musi mieć format '<tenantId>:<organizationId>'.",
232
234
  "security.api.errors.enforcementOrganizationScopeIdsRequired": "Pola tenantId i organizationId są wymagane dla zakresu organizacji.",
233
235
  "security.api.errors.enforcementPolicyAlreadyExistsForScope": "Polityka egzekwowania dla tego zakresu już istnieje.",
@@ -282,6 +284,7 @@
282
284
  "security.api.errors.sudoVerifyFailed": "Nie udało się zweryfikować wyzwania sudo.",
283
285
  "security.api.errors.tenantContextRequired": "Kontekst tenantu jest wymagany.",
284
286
  "security.api.errors.tenantIdRequired": "Identyfikator tenantu jest wymagany.",
287
+ "security.api.errors.tenantNotFound": "Tenant nie został znaleziony.",
285
288
  "security.api.errors.totpSetupSessionExpired": "Sesja konfiguracji TOTP wygasła.",
286
289
  "security.api.errors.totpSetupSessionNotFound": "Nie znaleziono sesji konfiguracji TOTP.",
287
290
  "security.api.errors.userIdRequired": "Identyfikator użytkownika jest wymagany.",